diff --git a/cli/wicd-cli.py b/cli/wicd-cli.py index 277bf3d..be4886f 100755 --- a/cli/wicd-cli.py +++ b/cli/wicd-cli.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 -""" Scriptable command-line interface. """ +"""Scriptable command-line interface.""" # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or @@ -17,9 +17,11 @@ # MA 02110-1301, USA. import optparse +import sys + import dbus import dbus.service -import sys + from wicd import misc from wicd.translations import _ @@ -52,13 +54,13 @@ try: 'org.wicd.daemon.config' ) except dbus.DBusException: - print(('Error: Could not connect to the daemon. ' + \ - 'Please make sure it is running.')) + print('Error: Could not connect to the daemon. Please make sure it is ' + 'running.') sys.exit(3) if not daemon: - print(('Error connecting to wicd via D-Bus. ' + \ - 'Please make sure the wicd service is running.')) + print('Error connecting to wicd via D-Bus. Please make sure the wicd ' + 'service is running.') sys.exit(3) parser = optparse.OptionParser() @@ -71,25 +73,26 @@ parser.add_option('--name', '-m') parser.add_option('--scan', '-S', default=False, action='store_true') parser.add_option('--save', '-w', default=False, action='store_true') parser.add_option('--list-networks', '-l', default=False, action='store_true') -parser.add_option('--network-details', '-d', default=False, action='store_true') +parser.add_option('--network-details', '-d', default=False, + action='store_true') parser.add_option('--disconnect', '-x', default=False, action='store_true') parser.add_option('--connect', '-c', default=False, action='store_true') parser.add_option('--list-encryption-types', '-e', default=False, - action='store_true') + action='store_true') # short options for these aren't great. parser.add_option('--wireless', '-y', default=False, action='store_true') parser.add_option('--wired', '-z', default=False, action='store_true') parser.add_option('--load-profile', '-o', default=False, action='store_true') parser.add_option('--status', '-i', default=False, - action='store_true') # -i(nfo) + action='store_true') # -i(nfo) options, arguments = parser.parse_args() op_performed = False if not (options.wireless or options.wired) and not options.status: - print(("Please use --wireless or --wired to specify " + \ - "the type of connection to operate on.")) + print("Please use --wireless or --wired to specify the type of " + "connection to operate on.") if options.status: status, info = daemon.GetConnectionStatus() @@ -109,46 +112,47 @@ if options.status: print((_('Connection type') + ': ' + conn_type)) if status == misc.WIRELESS: strength = daemon.FormatSignalForPrinting(info[2]) - print((_('Connected to $A at $B (IP: $C)') \ - .replace('$A', info[1]) \ - .replace('$B', strength) \ - .replace('$C', info[0]))) - print((_('Network ID: $A') \ - .replace('$A', info[3]))) + print(_('Connected to $A at $B (IP: $C)') + .replace('$A', info[1]) + .replace('$B', strength) + .replace('$C', info[0])) + print(_('Network ID: $A').replace('$A', info[3])) else: - print((_('Connected to wired network (IP: $A)') \ - .replace('$A', info[0]))) + print(_('Connected to wired network (IP: $A)') + .replace('$A', info[0])) else: if status == misc.CONNECTING: if info[0] == 'wired': - print((_('Connecting to wired network.'))) + print(_('Connecting to wired network.')) elif info[0] == 'wireless': - print((_('Connecting to wireless network "$A".') \ - .replace('$A', info[1]))) + print(_('Connecting to wireless network "$A".') + .replace('$A', info[1])) op_performed = True -# functions + def is_valid_wireless_network_id(network_id): - """ Check if it's a valid wireless network. '""" - if not (network_id >= 0 \ - and network_id < wireless.GetNumberOfNetworks()): + """Check if it's a valid wireless network.""" + if not (network_id >= 0 and + network_id < wireless.GetNumberOfNetworks()): print('Invalid wireless network identifier.') sys.exit(1) + def is_valid_wired_network_id(network_id): - """ Check if it's a valid wired network. '""" + """Check if it's a valid wired network. """ num = len(wired.GetWiredProfileList()) - if not (network_id < num and \ - network_id >= 0): + if not (network_id < num and network_id >= 0): print('Invalid wired network identifier.') sys.exit(4) + def is_valid_wired_network_profile(profile_name): - """ Check if it's a valid wired network profile. '""" - if not profile_name in wired.GetWiredProfileList(): + """Check if it's a valid wired network profile. """ + if profile_name not in wired.GetWiredProfileList(): print('Profile of that name does not exist.') sys.exit(5) + if options.scan and options.wireless: # synchronized scan wireless.Scan(True) @@ -163,10 +167,11 @@ if options.list_networks: if options.wireless: print('#\tBSSID\t\t\tChannel\tESSID') for network_id in range(0, wireless.GetNumberOfNetworks()): - print(('%s\t%s\t%s\t%s' % (network_id, - wireless.GetWirelessProperty(network_id, 'bssid'), - wireless.GetWirelessProperty(network_id, 'channel'), - wireless.GetWirelessProperty(network_id, 'essid')))) + print('%s\t%s\t%s\t%s' % + (network_id, + wireless.GetWirelessProperty(network_id, 'bssid'), + wireless.GetWirelessProperty(network_id, 'channel'), + wireless.GetWirelessProperty(network_id, 'essid'))) elif options.wired: print('#\tProfile name') i = 0 @@ -186,22 +191,22 @@ if options.network_details: # we're connected to a network, print IP print(("IP: %s" % wireless.GetWirelessIP(0))) - print(("Essid: %s" % wireless.GetWirelessProperty(network_id, "essid"))) - print(("Bssid: %s" % wireless.GetWirelessProperty(network_id, "bssid"))) + print("Essid: %s" % wireless.GetWirelessProperty(network_id, "essid")) + print("Bssid: %s" % wireless.GetWirelessProperty(network_id, "bssid")) if wireless.GetWirelessProperty(network_id, "encryption"): print("Encryption: On") - print(("Encryption Method: %s" % \ - wireless.GetWirelessProperty(network_id, "encryption_method"))) + print("Encryption Method: %s" % + wireless.GetWirelessProperty(network_id, + "encryption_method")) else: print("Encryption: Off") - print(("Quality: %s" % \ - wireless.GetWirelessProperty(network_id, "quality"))) - print(("Mode: %s" % \ - wireless.GetWirelessProperty(network_id, "mode"))) - print(("Channel: %s" % \ - wireless.GetWirelessProperty(network_id, "channel"))) - print(("Bit Rates: %s" % \ - wireless.GetWirelessProperty(network_id, "bitrates"))) + print("Quality: %s" % + wireless.GetWirelessProperty(network_id, "quality")) + print("Mode: %s" % wireless.GetWirelessProperty(network_id, "mode")) + print("Channel: %s" % + wireless.GetWirelessProperty(network_id, "channel")) + print("Bit Rates: %s" % + wireless.GetWirelessProperty(network_id, "bitrates")) op_performed = True # network properties @@ -216,11 +221,11 @@ if options.network_property: network_id = wireless.GetCurrentNetworkID(0) is_valid_wireless_network_id(network_id) if not options.set_to: - print((wireless.GetWirelessProperty(network_id, - options.network_property))) + print(wireless.GetWirelessProperty(network_id, + options.network_property)) else: - wireless.SetWirelessProperty(network_id, \ - options.network_property, options.set_to) + wireless.SetWirelessProperty(network_id, options.network_property, + options.set_to) elif options.wired: if not options.set_to: print((wired.GetWiredProperty(options.network_property))) @@ -232,13 +237,13 @@ if options.disconnect: daemon.Disconnect() if options.wireless: if wireless.GetCurrentNetworkID(0) > -1: - print(("Disconnecting from %s on %s" % \ - (wireless.GetCurrentNetwork(0), - wireless.DetectWirelessInterface()))) + print("Disconnecting from %s on %s" % + (wireless.GetCurrentNetwork(0), + wireless.DetectWirelessInterface())) elif options.wired: if wired.CheckPluggedIn(): - print(("Disconnecting from wired connection on %s" % \ - wired.DetectWiredInterface())) + print("Disconnecting from wired connection on %s" % + wired.DetectWiredInterface()) op_performed = True if options.connect: @@ -247,16 +252,16 @@ if options.connect: is_valid_wireless_network_id(options.network) name = wireless.GetWirelessProperty(options.network, 'essid') encryption = wireless.GetWirelessProperty(options.network, 'enctype') - print(("Connecting to %s with %s on %s" % (name, encryption, - wireless.DetectWirelessInterface()))) + print("Connecting to %s with %s on %s" % + (name, encryption, wireless.DetectWirelessInterface())) wireless.ConnectWireless(options.network) check = wireless.CheckIfWirelessConnecting status = wireless.CheckWirelessConnectingStatus message = wireless.CheckWirelessConnectingMessage elif options.wired: - print(("Connecting to wired connection on %s" % \ - wired.DetectWiredInterface())) + print("Connecting to wired connection on %s" % + wired.DetectWiredInterface()) wired.ConnectWired() check = wired.CheckIfWiredConnecting @@ -273,8 +278,8 @@ if options.connect: while check(): next_ = status() if next_ != last: - # avoid a race condition where status is updated to "done" after - # the loop check + # avoid a race condition where status is updated to "done" + # after the loop check if next_ == "done": break print((message())) @@ -284,14 +289,16 @@ if options.connect: exit_status = 6 op_performed = True + def str_properties(prop): - """ Pretty print optional and required properties. """ + """Pretty print optional and required properties.""" if len(prop) == 0: return "None" else: tmp = [(x[0], x[1].replace('_', ' ')) for x in type['required']] return ', '.join("%s (%s)" % (x, y) for x, y in tmp) + if options.wireless and options.list_encryption_types: et = misc.LoadEncryptionMethods() # print 'Installed encryption templates:' @@ -302,7 +309,7 @@ if options.wireless and options.list_encryption_types: print((' Req: %s' % str_properties(t['required']))) print('---') # don't print optionals (yet) - #print ' Opt: %s' % str_properties(type['optional']) + # print ' Opt: %s' % str_properties(type['optional']) i += 1 op_performed = True @@ -318,4 +325,3 @@ if not op_performed: print("No operations performed.") sys.exit(exit_status) - diff --git a/curses/configscript_curses.py b/curses/configscript_curses.py index fa8832f..088ef40 100644 --- a/curses/configscript_curses.py +++ b/curses/configscript_curses.py @@ -23,16 +23,17 @@ Also recycles a lot of configscript.py, too. :-) # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. +import sys +import os + +import urwid +import urwid.curses_display + from wicd.translations import _ from configscript import write_scripts, get_script_info from configscript import none_to_blank, blank_to_none -import urwid -import urwid.curses_display -import sys -import os - ui = None frame = None pre_entry = None @@ -42,20 +43,18 @@ post_disconnect_entry = None def main(argv): - """ Main function. """ + """Main function.""" global ui, frame if len(argv) < 2: print('Network id to configure is missing, aborting.') sys.exit(1) ui = urwid.curses_display.Screen() - ui.register_palette([ - ('body', 'default', 'default'), - ('focus', 'dark magenta', 'light gray'), - ('editcp', 'default', 'default', 'standout'), - ('editbx', 'light gray', 'dark blue'), - ('editfc', 'white', 'dark blue', 'bold'), - ]) + ui.register_palette([('body', 'default', 'default'), + ('focus', 'dark magenta', 'light gray'), + ('editcp', 'default', 'default', 'standout'), + ('editbx', 'light gray', 'dark blue'), + ('editfc', 'white', 'dark blue', 'bold')]) network = argv[1] network_type = argv[2] @@ -70,69 +69,69 @@ def main(argv): global pre_entry, post_entry, pre_disconnect_entry, post_disconnect_entry pre_entry = urwid.AttrWrap(urwid.Edit(pre_entry_t, - none_to_blank(script_info.get('pre_entry'))), - 'editbx', 'editfc') + none_to_blank(script_info. + get('pre_entry'))), + 'editbx', 'editfc') post_entry = urwid.AttrWrap(urwid.Edit(post_entry_t, - none_to_blank(script_info.get('post_entry'))), - 'editbx', 'editfc') + none_to_blank(script_info. + get('post_entry'))), + 'editbx', 'editfc') - pre_disconnect_entry = urwid.AttrWrap(urwid.Edit(pre_disconnect_entry_t, - none_to_blank(script_info.get('pre_disconnect_entry'))), + pre_disconnect_entry = urwid.AttrWrap( + urwid.Edit(pre_disconnect_entry_t, + none_to_blank(script_info.get('pre_disconnect_entry'))), 'editbx', 'editfc') - post_disconnect_entry = urwid.AttrWrap(urwid.Edit(post_disconnect_entry_t, - none_to_blank(script_info.get('post_disconnect_entry'))), + post_disconnect_entry = urwid.AttrWrap( + urwid.Edit(post_disconnect_entry_t, + none_to_blank(script_info.get('post_disconnect_entry'))), 'editbx', 'editfc') # The buttons - ok_button = urwid.AttrWrap( - urwid.Button(_('OK'), ok_callback), - 'body', 'focus' - ) - cancel_button = urwid.AttrWrap( - urwid.Button(_('Cancel'), cancel_callback), - 'body', 'focus' - ) + ok_button = urwid.AttrWrap(urwid.Button(_('OK'), ok_callback), 'body', + 'focus') + cancel_button = urwid.AttrWrap(urwid.Button(_('Cancel'), cancel_callback), + 'body', 'focus') button_cols = urwid.Columns([ok_button, cancel_button], dividechars=1) lbox = urwid.Pile([('fixed', 2, urwid.Filler(pre_entry)), - #('fixed', urwid.Filler(blank), 1), + # ('fixed', urwid.Filler(blank), 1), ('fixed', 2, urwid.Filler(post_entry)), ('fixed', 2, urwid.Filler(pre_disconnect_entry)), ('fixed', 2, urwid.Filler(post_disconnect_entry)), - #blank, blank, blank, blank, blank, - urwid.Filler(button_cols, 'bottom') - ]) + # blank, blank, blank, blank, blank, + urwid.Filler(button_cols, 'bottom')]) frame = urwid.Frame(lbox) result = ui.run_wrapper(run) if result: script_info["pre_entry"] = blank_to_none(pre_entry.get_edit_text()) script_info["post_entry"] = blank_to_none(post_entry.get_edit_text()) - script_info["pre_disconnect_entry"] = \ - blank_to_none(pre_disconnect_entry.get_edit_text()) - script_info["post_disconnect_entry"] = \ - blank_to_none(post_disconnect_entry.get_edit_text()) + script_info["pre_disconnect_entry"] = blank_to_none( + pre_disconnect_entry.get_edit_text()) + script_info["post_disconnect_entry"] = blank_to_none( + post_disconnect_entry.get_edit_text()) write_scripts(network, network_type, script_info) + OK_PRESSED = False CANCEL_PRESSED = False def ok_callback(button_object, user_data=None): - """ Callback. """ + """Callback.""" global OK_PRESSED OK_PRESSED = True def cancel_callback(button_object, user_data=None): - """ Callback. """ + """Callback.""" global CANCEL_PRESSED CANCEL_PRESSED = True def run(): - """ Run the UI. """ + """Run the UI.""" dim = ui.get_cols_rows() ui.set_mouse_tracking() @@ -147,7 +146,7 @@ def run(): if "esc" in keys or 'Q' in keys: return False for k in keys: - #Send key to underlying widget: + # Send key to underlying widget: if urwid.is_mouse_event(k): event, button, col, row = k frame.mouse_event(dim, event, button, col, row, focus=True) @@ -159,6 +158,7 @@ def run(): if OK_PRESSED or 'meta enter' in keys: return True + if __name__ == '__main__': if os.getuid() != 0: print("Root privileges are required to configure scripts. Exiting.") diff --git a/curses/curses_misc.py b/curses/curses_misc.py index 65a3971..06f5220 100644 --- a/curses/curses_misc.py +++ b/curses/curses_misc.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 # -* coding: utf-8 -*- -""" curses_misc.py: Module for various widgets that are used throughout +"""curses_misc.py: Module for various widgets that are used throughout wicd-curses. """ @@ -51,7 +51,7 @@ class SelText(urwid.Text): class NSelListBox(urwid.ListBox): - """ Non-selectable ListBox. """ + """Non-selectable ListBox.""" def selectable(self): return False @@ -69,7 +69,7 @@ class DynWrap(urwid.AttrWrap): """ # pylint: disable-msg=W0231 def __init__(self, w, sensitive=True, attrs=('editbx', 'editnfc'), - focus_attr='editfc'): + focus_attr='editfc'): self._attrs = attrs self._sensitive = sensitive @@ -82,11 +82,11 @@ class DynWrap(urwid.AttrWrap): self.__super.__init__(w, cur_attr, focus_attr) def get_sensitive(self): - """ Getter for sensitive property. """ + """Getter for sensitive property.""" return self._sensitive def set_sensitive(self, state): - """ Setter for sensitive property. """ + """Setter for sensitive property.""" if state: self.set_attr(self._attrs[0]) else: @@ -95,11 +95,11 @@ class DynWrap(urwid.AttrWrap): property(get_sensitive, set_sensitive) def get_attrs(self): - """ Getter for attrs property. """ + """Getter for attrs property.""" return self._attrs def set_attrs(self, attrs): - """ Setter for attrs property. """ + """Setter for attrs property.""" self._attrs = attrs property(get_attrs, set_attrs) @@ -108,10 +108,10 @@ class DynWrap(urwid.AttrWrap): class DynEdit(DynWrap): - """ Edit DynWrap'ed to the most common specifications. """ + """Edit DynWrap'ed to the most common specifications.""" # pylint: disable-msg=W0231 def __init__(self, caption='', edit_text='', sensitive=True, - attrs=('editbx', 'editnfc'), focus_attr='editfc'): + attrs=('editbx', 'editnfc'), focus_attr='editfc'): caption = ('editcp', caption + ': ') edit = urwid.Edit(caption, edit_text) # pylint: disable-msg=E1101 @@ -119,10 +119,10 @@ class DynEdit(DynWrap): class DynIntEdit(DynWrap): - """ IntEdit DynWrap'ed to the most common specifications. """ + """IntEdit DynWrap'ed to the most common specifications.""" # pylint: disable-msg=W0231 def __init__(self, caption='', edit_text='', sensitive=True, - attrs=('editbx', 'editnfc'), focus_attr='editfc'): + attrs=('editbx', 'editnfc'), focus_attr='editfc'): caption = ('editcp', caption + ':') edit = urwid.IntEdit(caption, edit_text) # pylint: disable-msg=E1101 @@ -130,20 +130,20 @@ class DynIntEdit(DynWrap): class DynRadioButton(DynWrap): - """ RadioButton DynWrap'ed to the most common specifications. """ + """RadioButton DynWrap'ed to the most common specifications.""" # pylint: disable-msg=W0231 def __init__(self, group, label, state='first True', on_state_change=None, - user_data=None, sensitive=True, attrs=('body', 'editnfc'), - focus_attr='body'): - #caption = ('editcp', caption + ':') + user_data=None, sensitive=True, attrs=('body', 'editnfc'), + focus_attr='body'): + # caption = ('editcp', caption + ':') button = urwid.RadioButton(group, label, state, on_state_change, - user_data) + user_data) # pylint: disable-msg=E1101 self.__super.__init__(button, sensitive, attrs, focus_attr) class MaskingEditException(Exception): - """ Custom exception. """ + """Custom exception.""" pass @@ -159,31 +159,31 @@ class MaskingEdit(urwid.Edit): """ # pylint: disable-msg=W0231 def __init__(self, caption="", edit_text="", multiline=False, align='left', - wrap='space', allow_tab=False, edit_pos=None, layout=None, - mask_mode="always", mask_char='*'): + wrap='space', allow_tab=False, edit_pos=None, layout=None, + mask_mode="always", mask_char='*'): self.mask_mode = mask_mode if len(mask_char) > 1: - raise MaskingEditException('Masks of more than one character are' + - ' not supported!') + raise MaskingEditException('Masks of more than one character are ' + 'not supported!') self.mask_char = mask_char # pylint: disable-msg=E1101 self.__super.__init__(caption, edit_text, multiline, align, wrap, - allow_tab, edit_pos, layout) + allow_tab, edit_pos, layout) def get_caption(self): - """ Return caption. """ + """Return caption.""" return self.caption def get_mask_mode(self): - """ Getter for mask_mode property. """ + """Getter for mask_mode property.""" return self.mask_mode def set_mask_mode(self, mode): - """ Setter for mask_mode property.""" + """Setter for mask_mode property.""" self.mask_mode = mode def get_masked_text(self): - """ Get masked out text. """ + """Get masked out text.""" return self.mask_char * len(self.get_edit_text()) def render(self, xxx_todo_changeme, focus=False): @@ -195,8 +195,8 @@ class MaskingEdit(urwid.Edit): if self.mask_mode == "off" or (self.mask_mode == 'no_focus' and focus): # pylint: disable-msg=E1101 canv = self.__super.render((maxcol, ), focus) - # The cache messes this thing up, because I am totally changing what - # is displayed. + # The cache messes this thing up, because I am totally changing + # what is displayed. self._invalidate() return canv @@ -226,9 +226,10 @@ class TabColumns(urwid.WidgetWrap): # FIXME Make the bottom_part optional # pylint: disable-msg=W0231 def __init__(self, tab_str, tab_wid, title, bottom_part=None, - attr=('body', 'focus'), attrsel='tab active', attrtitle='header'): - #self.bottom_part = bottom_part - #title_wid = urwid.Text((attrtitle, title), align='right') + attr=('body', 'focus'), attrsel='tab active', + attrtitle='header'): + # self.bottom_part = bottom_part + # title_wid = urwid.Text((attrtitle, title), align='right') column_list = [] for w in tab_str: text, trash = w.get_text() @@ -238,31 +239,31 @@ class TabColumns(urwid.WidgetWrap): self.tab_map = dict(list(zip(tab_str, tab_wid))) self.active_tab = tab_str[0] self.columns = urwid.Columns(column_list, dividechars=1) - #walker = urwid.SimpleListWalker([self.columns, tab_wid[0]]) - #self.listbox = urwid.ListBox(walker) + # walker = urwid.SimpleListWalker([self.columns, tab_wid[0]]) + # self.listbox = urwid.ListBox(walker) self.gen_pile(tab_wid[0], True) self.frame = urwid.Frame(self.pile) # pylint: disable-msg=E1101 self.__super.__init__(self.frame) def gen_pile(self, lbox, firstrun=False): - """ Make the pile in the middle. """ - self.pile = urwid.Pile([ - ('fixed', 1, urwid.Filler(self.columns, 'top')), - urwid.Filler(lbox, 'top', height=('relative', 99)), - #('fixed', 1, urwid.Filler(self.bottom_part, 'bottom')) - ]) + """Make the pile in the middle.""" + self.pile = urwid.Pile([('fixed', 1, + urwid.Filler(self.columns, 'top')), + urwid.Filler(lbox, 'top', + height=('relative', 99))]) + # ('fixed', 1, urwid.Filler(self.bottom_part, 'bottom'))]) if not firstrun: self.frame.set_body(self.pile) self._w = self.frame self._invalidate() def selectable(self): - """ Return whether the widget is selectable. """ + """Return whether the widget is selectable.""" return True def keypress(self, size, key): - """ Handle keypresses. """ + """Handle keypresses.""" # If the key is page up or page down, move focus to the tabs and call # left or right on the tabs. if key == "page up" or key == "page down": @@ -285,7 +286,7 @@ class TabColumns(urwid.WidgetWrap): return key def mouse_event(self, size, event, button, x, y, focus): - """ Handle mouse events. """ + """Handle mouse events.""" wid = self.pile.get_focus().get_body() if wid == self.columns: self.active_tab.set_attr('body') @@ -299,7 +300,7 @@ class TabColumns(urwid.WidgetWrap): class ComboBoxException(Exception): - """ Custom exception. """ + """Custom exception.""" pass @@ -314,39 +315,40 @@ class ComboBox(urwid.WidgetWrap): class ComboSpace(urwid.WidgetWrap): """The actual menu-like space that comes down from the ComboBox""" # pylint: disable-msg=W0231 - def __init__(self, l, body, ui, show_first, pos=(0, 0), - attr=('body', 'focus')): + def __init__(self, data, body, ui, show_first, pos=(0, 0), + attr=('body', 'focus')): """ body : parent widget - l : stuff to include in the combobox + data : stuff to include in the combobox ui : the screen show_first: index of the element in the list to pick first pos : a tuple of (row,col) where to put the list attr : a tuple of (attr_no_focus,attr_focus) """ - #Calculate width and height of the menu widget: - height = len(l) + # Calculate width and height of the menu widget: + height = len(data) width = 0 - for entry in l: + for entry in data: if len(entry) > width: width = len(entry) content = [urwid.AttrWrap(SelText(w), attr[0], attr[1]) - for w in l] + for w in data] self._listbox = urwid.ListBox(content) self._listbox.set_focus(show_first) - overlay = urwid.Overlay(self._listbox, body, ('fixed left', pos[0]), - width + 2, ('fixed top', pos[1]), height) + overlay = urwid.Overlay(self._listbox, body, + ('fixed left', pos[0]), width + 2, + ('fixed top', pos[1]), height) # pylint: disable-msg=E1101 self.__super.__init__(overlay) def show(self, ui, display): - """ Show widget. """ + """Show widget.""" dim = ui.get_cols_rows() keys = True - #Event loop: + # Event loop: while True: if keys: ui.draw_screen(dim, self.render(dim, True)) @@ -363,19 +365,19 @@ class ComboBox(urwid.WidgetWrap): return text for k in keys: - #Send key to underlying widget: + # Send key to underlying widget: self._w.keypress(dim, k) - #def get_size(self): + # def get_size(self): # pylint: disable-msg=W0231 - def __init__(self, label='', l=None, attrs=('body', 'editnfc'), - focus_attr='focus', use_enter=True, focus=0, callback=None, - user_args=None): + def __init__(self, label='', data=None, attrs=('body', 'editnfc'), + focus_attr='focus', use_enter=True, focus=0, callback=None, + user_args=None): """ label : bit of text that preceeds the combobox. If it is "", then ignore it - l : stuff to include in the combobox + data : stuff to include in the combobox body : parent widget ui : the screen row : where this object is to be found onscreen @@ -388,15 +390,15 @@ class ComboBox(urwid.WidgetWrap): self.label = urwid.Text(label) self.attrs = attrs self.focus_attr = focus_attr - if l is None: - l = [] - self.list = l + if data is None: + data = [] + self.list = data s, trash = self.label.get_text() self.overlay = None self.cbox = DynWrap(SelText(self.DOWN_ARROW), attrs=attrs, - focus_attr=focus_attr) + focus_attr=focus_attr) # Unicode will kill me sooner or later. if label != '': w = urwid.Columns( @@ -424,12 +426,12 @@ class ComboBox(urwid.WidgetWrap): self.ui = None self.row = None - def set_list(self, l): - """ Populate widget list. """ - self.list = l + def set_list(self, data): + """Populate widget list.""" + self.list = data def set_focus(self, index): - """ Set widget focus. """ + """Set widget focus.""" if urwid.VERSION < (1, 1, 0): self.focus = index else: @@ -447,11 +449,11 @@ class ComboBox(urwid.WidgetWrap): self.overlay._listbox.set_focus(index) def rebuild_combobox(self): - """ Rebuild combobox. """ + """Rebuild combobox.""" self.build_combobox(self.parent, self.ui, self.row) def build_combobox(self, parent, ui, row): - """ Build combobox. """ + """Build combobox.""" s, trash = self.label.get_text() if urwid.VERSION < (1, 1, 0): @@ -460,16 +462,16 @@ class ComboBox(urwid.WidgetWrap): index = self._w.focus_position # pylint: disable-msg=E1103 self.cbox = DynWrap(SelText([self.list[index] + self.DOWN_ARROW]), - attrs=self.attrs, focus_attr=self.focus_attr) + attrs=self.attrs, focus_attr=self.focus_attr) if str != '': w = urwid.Columns([('fixed', len(s), self.label), self.cbox], - dividechars=1) + dividechars=1) self.overlay = self.ComboSpace(self.list, parent, ui, index, - pos=(len(s) + 1, row)) + pos=(len(s) + 1, row)) else: w = urwid.Columns([self.cbox]) self.overlay = self.ComboSpace(self.list, parent, ui, index, - pos=(0, row)) + pos=(0, row)) self._w = w self._invalidate() @@ -479,7 +481,7 @@ class ComboBox(urwid.WidgetWrap): # If we press space or enter, be a combo box! def keypress(self, size, key): - """ Handle keypresses. """ + """Handle keypresses.""" activate = key == ' ' if self.use_enter: activate = activate or key == 'enter' @@ -490,43 +492,43 @@ class ComboBox(urwid.WidgetWrap): retval = self.overlay.show(self.ui, self.parent) if retval is not None: self.set_focus(self.list.index(retval)) - #self.cbox.set_w(SelText(retval+' vvv')) + # self.cbox.set_w(SelText(retval+' vvv')) if self.callback is not None: self.callback(self, self.overlay._listbox.get_focus()[1], - self.user_args) + self.user_args) return self._w.keypress(size, key) def selectable(self): - """ Return whether the widget is selectable. """ + """Return whether the widget is selectable.""" return self.cbox.selectable() def get_focus(self): - """ Return widget focus. """ + """Return widget focus.""" if self.overlay: return self.overlay._listbox.get_focus() else: if urwid.VERSION < (1, 1, 0): return None, self.focus else: - return None, self._w.focus_position # pylint: disable-msg=E1103 + return None, self._w.focus_position def get_sensitive(self): - """ Return widget sensitivity. """ + """Return widget sensitivity.""" return self.cbox.get_sensitive() def set_sensitive(self, state): - """ Set widget sensitivity. """ + """Set widget sensitivity.""" self.cbox.set_sensitive(state) # This is a h4x3d copy of some of the code in Ian Ward's dialog.py example. class DialogExit(Exception): - """ Custom exception. """ + """Custom exception.""" pass class Dialog2(urwid.WidgetWrap): - """ Base class for other dialogs. """ + """Base class for other dialogs.""" def __init__(self, text, height, width, body=None): self.buttons = None @@ -553,28 +555,28 @@ class Dialog2(urwid.WidgetWrap): # buttons: tuple of name,exitcode def add_buttons(self, buttons): - """ Add buttons. """ - l = [] + """Add buttons.""" + data = [] maxlen = 0 for name, exitcode in buttons: b = urwid.Button(name, self.button_press) b.exitcode = exitcode b = urwid.AttrWrap(b, 'body', 'focus') - l.append(b) + data.append(b) maxlen = max(len(name), maxlen) maxlen += 4 # because of '< ... >' - self.buttons = urwid.GridFlow(l, maxlen, 3, 1, 'center') + self.buttons = urwid.GridFlow(data, maxlen, 3, 1, 'center') self.frame.footer = urwid.Pile([ urwid.Divider(), self.buttons ], focus_item=1) def button_press(self, button): - """ Handle button press. """ + """Handle button press.""" raise DialogExit(button.exitcode) def run(self, ui, parent): - """ Run the UI. """ + """Run the UI.""" ui.set_mouse_tracking() size = ui.get_cols_rows() overlay = urwid.Overlay( @@ -597,7 +599,7 @@ class Dialog2(urwid.WidgetWrap): if check_mouse_event(k): event, button, col, row = k overlay.mouse_event(size, event, button, col, row, - focus=True) + focus=True) else: if k == 'window resize': size = ui.get_cols_rows() @@ -610,20 +612,20 @@ class Dialog2(urwid.WidgetWrap): return self.on_exit(e.args[0]) def on_exit(self, exitcode): - """ Handle dialog exit. """ + """Handle dialog exit.""" return exitcode, "" def unhandled_key(self, size, key): - """ Handle keypresses. """ + """Handle keypresses.""" pass class TextDialog(Dialog2): - """ Simple dialog with text and "OK" button. """ + """Simple dialog with text and "OK" button.""" def __init__(self, text, height, width, header=None, align='left', - buttons=(_('OK'), 1)): - l = [urwid.Text(text)] - body = urwid.ListBox(l) + buttons=(_('OK'), 1)): + data = [urwid.Text(text)] + body = urwid.ListBox(data) body = urwid.AttrWrap(body, 'body') Dialog2.__init__(self, header, height + 2, width + 2, body) @@ -633,7 +635,7 @@ class TextDialog(Dialog2): self.add_buttons([buttons]) def unhandled_key(self, size, k): - """ Handle keys. """ + """Handle keys.""" if k in ('up', 'page up', 'down', 'page down'): self.frame.set_focus('body') self.view.keypress(size, k) @@ -641,7 +643,7 @@ class TextDialog(Dialog2): class InputDialog(Dialog2): - """ Simple dialog with text and entry. """ + """Simple dialog with text and entry.""" def __init__(self, text, height, width, ok_name=_('OK'), edit_text=''): self.edit = urwid.Edit(wrap='clip', edit_text=edit_text) body = urwid.ListBox([self.edit]) @@ -653,7 +655,7 @@ class InputDialog(Dialog2): self.add_buttons([(ok_name, 0), (_('Cancel'), -1)]) def unhandled_key(self, size, k): - """ Handle keys. """ + """Handle keys.""" if k in ('up', 'page up'): self.frame.set_focus('body') if k in ('down', 'page down'): @@ -664,12 +666,12 @@ class InputDialog(Dialog2): self.view.keypress(size, k) def on_exit(self, exitcode): - """ Handle dialog exit. """ + """Handle dialog exit.""" return exitcode, self.edit.get_edit_text() class ClickCols(urwid.WidgetWrap): - """ Clickable menubar. """ + """Clickable menubar.""" # pylint: disable-msg=W0231 def __init__(self, items, callback=None, args=None): cols = urwid.Columns(items) @@ -679,27 +681,29 @@ class ClickCols(urwid.WidgetWrap): self.args = args def mouse_event(self, size, event, button, x, y, focus): - """ Handle mouse events. """ + """Handle mouse events.""" if event == "mouse press": - # The keypress dealie in wicd-curses.py expects a list of keystrokes + # The keypress dealie in wicd-curses.py expects a list of + # keystrokes self.callback([self.args]) class OptCols(urwid.WidgetWrap): - """ Htop-style menubar on the bottom of the screen. """ + """Htop-style menubar on the bottom of the screen.""" # tuples = [(key,desc)], on_event gets passed a key # attrs = (attr_key,attr_desc) # handler = function passed the key of the "button" pressed # mentions of 'left' and right will be converted to <- and -> respectively # pylint: disable-msg=W0231 - def __init__(self, tuples, handler, attrs=('body', 'infobar'), debug=False): + def __init__(self, tuples, handler, attrs=('body', 'infobar'), + debug=False): # Find the longest string. Keys for this bar should be no greater than # 2 characters long (e.g., -> for left) - #maxlen = 6 - #for i in tuples: - # newmax = len(i[0])+len(i[1]) - # if newmax > maxlen: - # maxlen = newmax + # maxlen = 6 + # for i in tuples: + # newmax = len(i[0])+len(i[1]) + # if newmax > maxlen: + # maxlen = newmax # Construct the texts textList = [] @@ -719,7 +723,7 @@ class OptCols(urwid.WidgetWrap): else: callback = handler args = cmd[0] - #self.callbacks.append(cmd[2]) + # self.callbacks.append(cmd[2]) col = ClickCols([ ('fixed', len(key) + 1, urwid.Text((attrs[0], key + ':'))), urwid.AttrWrap(urwid.Text(cmd[1]), attrs[1])], @@ -736,10 +740,10 @@ class OptCols(urwid.WidgetWrap): self.__super.__init__(cols) def debugClick(self, args): - """ Debug clicks. """ + """Debug clicks.""" self.debug.set_text(args) def mouse_event(self, size, event, button, x, y, focus): - """ Handle mouse events. """ + """Handle mouse events.""" # Widgets are evenly long (as of current), so... return self._w.mouse_event(size, event, button, x, y, focus) diff --git a/curses/netentry_curses.py b/curses/netentry_curses.py index 1803a16..647481b 100644 --- a/curses/netentry_curses.py +++ b/curses/netentry_curses.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 """ - netentry_curses -- everyone's favorite networks settings dialogs... in text - form! +netentry_curses -- everyone's favorite networks settings dialogs... in text +form! """ # Copyright (C) 2009 Andrew Psaltis @@ -20,6 +20,7 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. +import os import urwid from curses_misc import DynWrap, MaskingEdit, ComboBox, error @@ -27,7 +28,6 @@ import wicd.misc as misc from wicd.misc import noneToString, stringToNone, noneToBlankString, to_bool from wicd.translations import language, _ -import os daemon = None wired = None @@ -36,7 +36,7 @@ wireless = None # Call this first! def dbus_init(dbus_ifaces): - """ Initialize DBus interfaces. """ + """Initialize DBus interfaces.""" global daemon, wired, wireless daemon = dbus_ifaces['daemon'] wired = dbus_ifaces['wired'] @@ -47,10 +47,10 @@ class AdvancedSettingsDialog(urwid.WidgetWrap): """ Settings dialog. - Both the wired and the wireless settings preferences dialogs use some of the - same fields. - This will be used to produce the individual network settings dialogs way far - below. + Both the wired and the wireless settings preferences dialogs use some of + the same fields. + This will be used to produce the individual network settings dialogs way + far below. """ # pylint: disable-msg=W0231 def __init__(self): @@ -84,28 +84,20 @@ class AdvancedSettingsDialog(urwid.WidgetWrap): cancel_t = _('Cancel') ok_t = _('OK') - self.static_ip_cb = urwid.CheckBox(static_ip_t, - on_state_change=self.static_ip_toggle) + self.static_ip_cb = urwid.CheckBox( + static_ip_t, on_state_change=self.static_ip_toggle) self.ip_edit = DynWrap(urwid.Edit(ip_t), False) self.netmask_edit = DynWrap(urwid.Edit(netmask_t), False) self.gateway_edit = DynWrap(urwid.Edit(gateway_t), False) self.static_dns_cb = DynWrap( urwid.CheckBox(use_static_dns_t, on_state_change=self.dns_toggle), - True, - ('body', 'editnfc'), - None - ) + True, ('body', 'editnfc'), None) self.global_dns_cb = DynWrap( urwid.CheckBox(use_global_dns_t, on_state_change=self.dns_toggle), - False, - ('body', 'editnfc'), - None - ) - self.checkb_cols = urwid.Columns([ - self.static_dns_cb, - self.global_dns_cb - ]) + False, ('body', 'editnfc'), None) + self.checkb_cols = urwid.Columns([self.static_dns_cb, + self.global_dns_cb]) self.dns_dom_edit = DynWrap(urwid.Edit(dns_dom_t), False) self.search_dom_edit = DynWrap(urwid.Edit(search_dom_t), False) self.dns1 = DynWrap(urwid.Edit(dns1_t), False) @@ -113,10 +105,8 @@ class AdvancedSettingsDialog(urwid.WidgetWrap): self.dns3 = DynWrap(urwid.Edit(dns3_t), False) self.use_dhcp_h = urwid.CheckBox( - use_dhcp_h_t, - False, - on_state_change=self.use_dhcp_h_toggle - ) + use_dhcp_h_t, False, + on_state_change=self.use_dhcp_h_toggle) self.dhcp_h = DynWrap(urwid.Edit(dhcp_h_t), False) _blank = urwid.Text('') @@ -144,11 +134,11 @@ class AdvancedSettingsDialog(urwid.WidgetWrap): self.__super.__init__(self._frame) def use_dhcp_h_toggle(self, checkb, new_state, user_data=None): - """ Set sensitivity of widget. """ + """Set sensitivity of widget.""" self.dhcp_h.set_sensitive(new_state) def static_ip_toggle(self, checkb, new_state, user_data=None): - """ Set sensitivity of widget. """ + """Set sensitivity of widget.""" for w in [self.ip_edit, self.netmask_edit, self.gateway_edit]: w.set_sensitive(new_state) self.static_dns_cb.set_state(new_state) @@ -159,7 +149,7 @@ class AdvancedSettingsDialog(urwid.WidgetWrap): self.checkb_cols.set_focus(self.static_dns_cb) def dns_toggle(self, checkb, new_state, user_data=None): - """ Set sensitivity of widget. """ + """Set sensitivity of widget.""" if checkb == self.static_dns_cb.get_w(): for w in [ self.dns_dom_edit, @@ -174,17 +164,17 @@ class AdvancedSettingsDialog(urwid.WidgetWrap): self.global_dns_cb.set_sensitive(new_state) # use_global_dns_cb is DynWrapped if checkb == self.global_dns_cb.get_w(): - for w in [self.dns_dom_edit, self.search_dom_edit, - self.dns1, self.dns2, self.dns3 ]: + for w in [self.dns_dom_edit, self.search_dom_edit, self.dns1, + self.dns2, self.dns3]: w.set_sensitive(not new_state) def set_net_prop(self, option, value): - """ Set network property. MUST BE OVERRIDEN. """ + """Set network property. MUST BE OVERRIDEN.""" raise NotImplementedError # Code totally yanked from netentry.py def save_settings(self): - """ Save settings common to wired and wireless settings dialogs. """ + """Save settings common to wired and wireless settings dialogs.""" if self.static_ip_cb.get_state(): for i in [ self.ip_edit, @@ -195,9 +185,9 @@ class AdvancedSettingsDialog(urwid.WidgetWrap): self.set_net_prop("ip", noneToString(self.ip_edit.get_edit_text())) self.set_net_prop("netmask", - noneToString(self.netmask_edit.get_edit_text())) + noneToString(self.netmask_edit.get_edit_text())) self.set_net_prop("gateway", - noneToString(self.gateway_edit.get_edit_text())) + noneToString(self.gateway_edit.get_edit_text())) else: self.set_net_prop("ip", '') self.set_net_prop("netmask", '') @@ -217,14 +207,15 @@ class AdvancedSettingsDialog(urwid.WidgetWrap): ]: i.set_edit_text(i.get_edit_text().strip()) self.set_net_prop('dns_domain', - noneToString(self.dns_dom_edit.get_edit_text())) + noneToString(self.dns_dom_edit.get_edit_text())) self.set_net_prop("search_domain", - noneToString(self.search_dom_edit.get_edit_text())) + noneToString(self.search_dom_edit + .get_edit_text())) self.set_net_prop("dns1", noneToString(self.dns1.get_edit_text())) self.set_net_prop("dns2", noneToString(self.dns2.get_edit_text())) self.set_net_prop("dns3", noneToString(self.dns3.get_edit_text())) - elif self.static_dns_cb.get_state() and \ - self.global_dns_cb.get_state(): + elif (self.static_dns_cb.get_state() and + self.global_dns_cb.get_state()): self.set_net_prop('use_static_dns', True) self.set_net_prop('use_global_dns', True) else: @@ -240,20 +231,20 @@ class AdvancedSettingsDialog(urwid.WidgetWrap): # Prevent comboboxes from dying. def ready_widgets(self, ui, body): - """ Build comboboxes. """ + """Build comboboxes.""" self.ui = ui self.body = body self.encryption_combo.build_combobox(body, ui, 14) self.change_encrypt_method() def combo_on_change(self, combobox, new_index, user_data=None): - """ Handle change of item in the combobox. """ + """Handle change of item in the combobox.""" self.change_encrypt_method() # More or less ripped from netentry.py def change_encrypt_method(self): - """ Change encrypt method based on combobox. """ - #self.lbox_encrypt = urwid.ListBox() + """Change encrypt method based on combobox.""" + # self.lbox_encrypt = urwid.ListBox() self.encryption_info = {} wid, ID = self.encryption_combo.get_focus() methods = self.encrypt_types @@ -288,36 +279,35 @@ class AdvancedSettingsDialog(urwid.WidgetWrap): wired.GetWiredProperty(field[0]))) else: edit.set_edit_text(noneToBlankString( - wireless.GetWirelessProperty(self.networkid, field[0]))) + wireless.GetWirelessProperty(self.networkid, + field[0]))) - #FIXME: This causes the entire pile to light up upon use. + # FIXME: This causes the entire pile to light up upon use. # Make this into a listbox? - self.pile_encrypt = DynWrap( - urwid.Pile(theList), - attrs=('editbx', 'editnfc') - ) + self.pile_encrypt = DynWrap(urwid.Pile(theList), + attrs=('editbx', 'editnfc')) self.pile_encrypt.set_sensitive(self.encryption_chkbox.get_state()) - self._w.body.body.insert(self._w.body.body.__len__(), self.pile_encrypt) - #self._w.body.body.append(self.pile_encrypt) + self._w.body.body.insert(self._w.body.body.__len__(), + self.pile_encrypt) + # self._w.body.body.append(self.pile_encrypt) def encryption_toggle(self, chkbox, new_state, user_data=None): - """ Set sensitivity of widget. """ + """Set sensitivity of widget.""" self.encryption_combo.set_sensitive(new_state) self.pile_encrypt.set_sensitive(new_state) class WiredSettingsDialog(AdvancedSettingsDialog): - """ Settings dialog for wired interface. """ + """Settings dialog for wired interface.""" def __init__(self, name, parent): AdvancedSettingsDialog.__init__(self) self.wired = True self.set_default = urwid.CheckBox( - _('Use as default profile (overwrites any previous default)') - ) - #self.cur_default = + _('Use as default profile (overwrites any previous default)')) + # self.cur_default = # Add widgets to listbox self._w.body.body.append(self.set_default) @@ -347,11 +337,11 @@ class WiredSettingsDialog(AdvancedSettingsDialog): self.set_values() def set_net_prop(self, option, value): - """ Set network property. """ + """Set network property.""" wired.SetWiredProperty(option, value) def set_values(self): - """ Load saved values. """ + """Load saved values.""" self.ip_edit.set_edit_text(self.format_entry("ip")) self.netmask_edit.set_edit_text(self.format_entry("netmask")) self.gateway_edit.set_edit_text(self.format_entry("gateway")) @@ -375,19 +365,19 @@ class WiredSettingsDialog(AdvancedSettingsDialog): self.set_default.set_state(to_bool(wired.GetWiredProperty("default"))) # Throw the encryption stuff into a list - l = [] + combo_items = [] activeID = -1 # Set the menu to this item when we are done for x, enc_type in enumerate(self.encrypt_types): - l.append(enc_type['name']) + combo_items.append(enc_type['name']) if enc_type['type'] == wired.GetWiredProperty("enctype"): activeID = x - self.encryption_combo.set_list(l) + self.encryption_combo.set_list(combo_items) self.encryption_combo.set_focus(activeID) if wired.GetWiredProperty("encryption_enabled"): self.encryption_chkbox.set_state(True, do_callback=False) self.encryption_combo.set_sensitive(True) - #self.lbox_encrypt_info.set_sensitive(True) + # self.lbox_encrypt_info.set_sensitive(True) else: self.encryption_combo.set_focus(0) self.encryption_combo.set_sensitive(False) @@ -405,7 +395,7 @@ class WiredSettingsDialog(AdvancedSettingsDialog): self.dhcp_h.set_edit_text(str(dhcphname)) def save_settings(self): - """ Save settings to disk. """ + """Save settings to disk.""" # Check encryption info if self.encryption_chkbox.get_state(): encrypt_info = self.encryption_info @@ -430,7 +420,7 @@ class WiredSettingsDialog(AdvancedSettingsDialog): for entry_key, entry_info in list(encrypt_info.items()): self.set_net_prop(entry_key, noneToString(entry_info[0]. - get_edit_text())) + get_edit_text())) else: self.set_net_prop("enctype", "None") self.set_net_prop("encryption_enabled", False) @@ -447,7 +437,7 @@ 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 prerun(self, ui, dim, display): @@ -455,7 +445,7 @@ class WiredSettingsDialog(AdvancedSettingsDialog): class WirelessSettingsDialog(AdvancedSettingsDialog): - """ Settings dialog for wireless interfaces. """ + """Settings dialog for wireless interfaces.""" def __init__(self, networkID, parent): AdvancedSettingsDialog.__init__(self) self.wired = False @@ -502,17 +492,21 @@ class WirelessSettingsDialog(AdvancedSettingsDialog): self.encrypt_types = misc.LoadEncryptionMethods() self.set_values() - title = _('Configuring preferences for wireless network "$A" ($B)'). \ - replace('$A', wireless.GetWirelessProperty(networkID, 'essid')). \ - replace('$B', wireless.GetWirelessProperty(networkID, 'bssid')) + title = (_('Configuring preferences for wireless network "$A" ($B)') + .replace('$A', wireless.GetWirelessProperty(networkID, + 'essid')) + .replace('$B', wireless.GetWirelessProperty(networkID, + 'bssid'))) self._w.header = urwid.Text(('header', title), align='right') 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.ip_edit.set_edit_text(self.format_entry(networkID, "ip")) - self.netmask_edit.set_edit_text(self.format_entry(networkID, "netmask")) - self.gateway_edit.set_edit_text(self.format_entry(networkID, "gateway")) + self.netmask_edit.set_edit_text(self.format_entry(networkID, + "netmask")) + self.gateway_edit.set_edit_text(self.format_entry(networkID, + "gateway")) self.global_dns_cb.set_state( bool(wireless.GetWirelessProperty(networkID, 'use_global_dns'))) @@ -547,32 +541,29 @@ class WirelessSettingsDialog(AdvancedSettingsDialog): to_bool(self.format_entry(networkID, 'allow_lower_bitrates')) ) - #self.reset_static_checkboxes() + # self.reset_static_checkboxes() self.encryption_chkbox.set_state( bool(wireless.GetWirelessProperty(networkID, 'encryption')), do_callback=False) self.global_settings_chkbox.set_state( - bool(wireless.GetWirelessProperty( - networkID, - 'use_settings_globally') - ) - ) + bool(wireless.GetWirelessProperty(networkID, + 'use_settings_globally'))) # Throw the encryption stuff into a list - l = [] + combo_items = [] activeID = -1 # Set the menu to this item when we are done for x, enc_type in enumerate(self.encrypt_types): - l.append(enc_type['name']) - if enc_type['type'] == \ - wireless.GetWirelessProperty(networkID, "enctype"): + combo_items.append(enc_type['name']) + if enc_type['type'] == wireless.GetWirelessProperty(networkID, + "enctype"): activeID = x - self.encryption_combo.set_list(l) + self.encryption_combo.set_list(combo_items) self.encryption_combo.set_focus(activeID) if activeID != -1: self.encryption_chkbox.set_state(True, do_callback=False) self.encryption_combo.set_sensitive(True) - #self.lbox_encrypt_info.set_sensitive(True) + # self.lbox_encrypt_info.set_sensitive(True) else: self.encryption_combo.set_focus(0) @@ -587,16 +578,17 @@ class WirelessSettingsDialog(AdvancedSettingsDialog): self.dhcp_h.set_edit_text(str(dhcphname)) 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 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)) # Ripped from netentry.py def save_settings(self): - """ Save settings to disk. """ + """Save settings to disk.""" # Check encryption info if self.encryption_chkbox.get_state(): encrypt_info = self.encryption_info @@ -607,29 +599,21 @@ class WirelessSettingsDialog(AdvancedSettingsDialog): ) # Make sure all required fields are filled in. for entry_info in list(encrypt_info.values()): - if entry_info[0].get_edit_text() == "" \ - and entry_info[1] == 'required': - error( - self.ui, - self.parent, - "%s (%s)" % ( - _('Required encryption information is missing.'), - entry_info[0].get_caption()[0:-2] - ) - ) + if (entry_info[0].get_edit_text() == "" and + entry_info[1] == 'required'): + error(self.ui, self.parent, "%s (%s)" % + (_('Required encryption information is missing.'), + entry_info[0].get_caption()[0:-2])) return False for entry_key, entry_info in list(encrypt_info.items()): self.set_net_prop(entry_key, noneToString(entry_info[0]. - get_edit_text())) - elif not self.encryption_chkbox.get_state() and \ - wireless.GetWirelessProperty(self.networkid, "encryption"): + get_edit_text())) + elif (not self.encryption_chkbox.get_state() and + wireless.GetWirelessProperty(self.networkid, "encryption")): # Encrypt checkbox is off, but the network needs it. - error( - self.ui, - self.parent, - _('This network requires encryption to be enabled.') - ) + error(self.ui, self.parent, + _('This network requires encryption to be enabled.')) return False else: self.set_net_prop("enctype", "None") @@ -657,7 +641,7 @@ class WirelessSettingsDialog(AdvancedSettingsDialog): return True def ready_widgets(self, ui, body): - """ Build comboboxes. """ + """Build comboboxes.""" AdvancedSettingsDialog.ready_widgets(self, ui, body) self.ui = ui self.body = body diff --git a/curses/prefs_curses.py b/curses/prefs_curses.py index ecef28c..0d3e172 100644 --- a/curses/prefs_curses.py +++ b/curses/prefs_curses.py @@ -32,7 +32,7 @@ wired = None class PrefsDialog(urwid.WidgetWrap): - """ Preferences dialog. """ + """Preferences dialog.""" # pylint: disable-msg=W0231 def __init__(self, body, pos, ui, dbus=None): global daemon, wireless, wired @@ -48,14 +48,15 @@ class PrefsDialog(urwid.WidgetWrap): width, height = ui.get_cols_rows() height -= 3 - #width = 80 - #height = 20 + # width = 80 + # height = 20 # Stuff that goes at the top header0_t = _('General Settings') header1_t = _('External Programs') header2_t = _('Advanced Settings') - self.header0 = urwid.AttrWrap(SelText(header0_t), 'tab active', 'focus') + self.header0 = urwid.AttrWrap(SelText(header0_t), 'tab active', + 'focus') self.header1 = urwid.AttrWrap(SelText(header1_t), 'body', 'focus') self.header2 = urwid.AttrWrap(SelText(header2_t), 'body', 'focus') title = ('Preferences') @@ -63,9 +64,7 @@ class PrefsDialog(urwid.WidgetWrap): # Blank line _blank = urwid.Text('') - #### - #### Text in the widgets - #### + # Text in the widgets # General Settings net_cat_t = ('header', ('Network Interfaces')) @@ -90,7 +89,7 @@ class PrefsDialog(urwid.WidgetWrap): auto_reconn_cat_t = ('header', _('Automatic Reconnection')) auto_reconn_t = _('Automatically reconnect on connection loss') - #### External Programs + # External Programs automatic_t = _('Automatic (recommended)') dhcp_header_t = ('header', _('DHCP Client')) @@ -108,12 +107,12 @@ class PrefsDialog(urwid.WidgetWrap): flush1_t = 'ip' flush2_t = 'route' - #### Advanced Settings + # Advanced Settings wpa_cat_t = ('header', _('WPA Supplicant')) wpa_t = ('editcp', 'Driver:') wpa_list = [] - wpa_warn_t = ('important', - _('You should almost always use wext as the WPA supplicant driver')) + wpa_warn_t = ('important', _('You should almost always use wext as ' + 'the WPA supplicant driver')) backend_cat_t = ('header', _('Backend')) backend_t = _('Backend') + ':' @@ -124,12 +123,10 @@ class PrefsDialog(urwid.WidgetWrap): wless_cat_t = ('header', _('Wireless Interface')) use_dbm_t = _('Use dBm to measure signal strength') - verify_ap_t = \ - _('Ping static gateways after connecting to verify association') + verify_ap_t = _('Ping static gateways after connecting to verify ' + 'association') - #### - #### UI Widgets - #### + # UI Widgets # General Settings self.net_cat = urwid.Text(net_cat_t) @@ -142,10 +139,9 @@ class PrefsDialog(urwid.WidgetWrap): # Default the global DNS settings to off. They will be reenabled later # if so required. global_dns_state = False - self.global_dns_checkb = urwid.CheckBox(global_dns_t, - global_dns_state, - on_state_change=self.global_dns_trigger - ) + self.global_dns_checkb = urwid.CheckBox(global_dns_t, global_dns_state, + on_state_change=self. + global_dns_trigger) self.search_dom = DynWrap(urwid.Edit(search_dom_t), global_dns_state) self.dns_dom = DynWrap(urwid.Edit(dns_dom_t), global_dns_state) self.dns1 = DynWrap(urwid.Edit(dns1_t), global_dns_state) @@ -156,9 +152,12 @@ class PrefsDialog(urwid.WidgetWrap): self.wired_auto_l = [] self.wired_auto_cat = urwid.Text(wired_auto_cat_t) - self.wired_auto_1 = urwid.RadioButton(self.wired_auto_l, wired_auto_1_t) - self.wired_auto_2 = urwid.RadioButton(self.wired_auto_l, wired_auto_2_t) - self.wired_auto_3 = urwid.RadioButton(self.wired_auto_l, wired_auto_3_t) + self.wired_auto_1 = urwid.RadioButton(self.wired_auto_l, + wired_auto_1_t) + self.wired_auto_2 = urwid.RadioButton(self.wired_auto_l, + wired_auto_2_t) + self.wired_auto_3 = urwid.RadioButton(self.wired_auto_l, + wired_auto_2_t) self.auto_reconn_cat = urwid.Text(auto_reconn_cat_t) self.auto_reconn_checkb = urwid.CheckBox(auto_reconn_t) @@ -180,7 +179,8 @@ class PrefsDialog(urwid.WidgetWrap): self.auto_reconn_checkb ]) - #### External Programs tab + # External Programs tab + automatic_t = _('Automatic (recommended)') self.dhcp_header = urwid.Text(dhcp_header_t) @@ -223,7 +223,8 @@ class PrefsDialog(urwid.WidgetWrap): self.flush0, self.flush1, self.flush2 ]) - #### Advanced settings + # Advanced settings + self.wpa_cat = urwid.Text(wpa_cat_t) self.wpa_cbox = ComboBox(wpa_t) self.wpa_warn = urwid.Text(wpa_warn_t) @@ -257,15 +258,16 @@ class PrefsDialog(urwid.WidgetWrap): self.header1: externalLB, self.header2: advancedLB } - #self.load_settings() + + # self.load_settings() self.tabs = TabColumns(headerList, lbList, _('Preferences')) # pylint: disable-msg=E1101 self.__super.__init__(self.tabs) def load_settings(self): - """ Load settings to be used in the dialog. """ - ### General Settings + """Load settings to be used in the dialog.""" + # General Settings # ComboBox does not like dbus.Strings as text markups. My fault. :/ wless_iface = str(daemon.GetWirelessInterface()) wired_iface = str(daemon.GetWiredInterface()) @@ -280,7 +282,8 @@ class PrefsDialog(urwid.WidgetWrap): theDNS = daemon.GetGlobalDNSAddresses() i = 0 - for w in self.dns1, self.dns2, self.dns3, self.dns_dom, self.search_dom: + for w in (self.dns1, self.dns2, self.dns3, self.dns_dom, + self.search_dom): w.set_edit_text(misc.noneToBlankString(theDNS[i])) i += 1 @@ -289,11 +292,11 @@ class PrefsDialog(urwid.WidgetWrap): self.auto_reconn_checkb.set_state(daemon.GetAutoReconnect()) def find_avail(apps): - """ Find available apps. """ + """Find available apps.""" for app in apps[1:]: app.set_sensitive(daemon.GetAppAvailable(app.get_label())) - ### External Programs + # External Programs find_avail(self.dhcp_l) dhcp_method = daemon.GetDHCPClient() self.dhcp_l[dhcp_method].set_state(True) @@ -306,7 +309,7 @@ class PrefsDialog(urwid.WidgetWrap): flush_method = daemon.GetFlushTool() self.flush_l[flush_method].set_state(True) - ### Advanced settings + # Advanced settings # wpa_supplicant janx self.wpadrivers = wireless.GetWpaSupplicantDrivers() self.wpadrivers.append("ralink_legacy") @@ -337,7 +340,7 @@ class PrefsDialog(urwid.WidgetWrap): self.verify_ap_checkb.set_state(daemon.GetShouldVerifyAp()) def save_settings(self): - """ Pushes the selected settings to the daemon. + """Pushes the selected settings to the daemon. This exact order is found in prefs.py""" daemon.SetUseGlobalDNS(self.global_dns_checkb.get_state()) @@ -404,11 +407,12 @@ class PrefsDialog(urwid.WidgetWrap): daemon.SetFlushTool(flush_tool) def global_dns_trigger(self, check_box, new_state, user_data=None): - """ DNS CheckBox callback. """ - for w in self.dns1, self.dns2, self.dns3, self.dns_dom, self.search_dom: + """DNS CheckBox callback.""" + for w in (self.dns1, self.dns2, self.dns3, self.dns_dom, + self.search_dom): w.set_sensitive(new_state) def ready_widgets(self, ui, body): - """ Build comboboxes. """ + """Build comboboxes.""" self.wpa_cbox.build_combobox(body, ui, 4) self.backend_cbox.build_combobox(body, ui, 8) diff --git a/curses/wicd-curses.py b/curses/wicd-curses.py index fd09524..8e2cc56 100644 --- a/curses/wicd-curses.py +++ b/curses/wicd-curses.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 # -* coding: utf-8 -*- -""" wicd-curses. (curses/urwid-based) console interface to wicd +"""wicd-curses. (curses/urwid-based) console interface to wicd Provides a console UI for wicd, so that people with broken X servers can at least get a network connection. Or those who don't like using X and/or GTK. @@ -35,29 +35,20 @@ at least get a network connection. Or those who don't like using X and/or GTK. # Filter out a confusing urwid warning in python 2.6. # This is valid as of urwid version 0.9.8.4 +from optparse import OptionParser +import signal +import sys import warnings -warnings.filterwarnings( - "ignore", - "The popen2 module is deprecated. Use the subprocess module." -) -# UI stuff -import urwid -# DBus communication stuff +import urwid from dbus import DBusException # It took me a while to figure out that I have to use this. from gi.repository import GLib as gobject -# Other important wicd-related stuff from wicd import wpath from wicd import misc from wicd import dbusmanager - -# Internal Python stuff -import sys - -# SIGQUIT signal handling -import signal +from wicd.translations import _ # Curses UIs for other stuff from curses_misc import ComboBox, Dialog2, NSelListBox, SelText, OptCols @@ -67,51 +58,50 @@ from prefs_curses import PrefsDialog import netentry_curses from netentry_curses import WirelessSettingsDialog, WiredSettingsDialog -from optparse import OptionParser - # Stuff about getting the script configurer running -#from grp import getgrgid -#from os import getgroups, system +# from grp import getgrgid +# from os import getgroups, system -#import logging -#import logging.handler +# import logging +# import logging.handler CURSES_REV = wpath.curses_revision # Fix strings in wicd-curses -#from wicd.translations import language -from wicd.translations import _ +# from wicd.translations import language +warnings.filterwarnings( + "ignore", + "The popen2 module is deprecated. Use the subprocess module." +) ui = None loop = None bus = daemon = wireless = wired = None -######################################## -##### SUPPORT CLASSES -######################################## + # Yay for decorators! def wrap_exceptions(func): - """ Decorator to wrap exceptions. """ + """Decorator to wrap exceptions.""" def wrapper(*args, **kargs): try: return func(*args, **kargs) except KeyboardInterrupt: - #gobject.source_remove(redraw_tag) + # gobject.source_remove(redraw_tag) loop.quit() ui.stop() print("\n" + _('Terminated by user'), file=sys.stderr) - #raise + # raise except DBusException: loop.quit() ui.stop() - print("\n" + _('DBus failure! ' - 'This is most likely caused by the wicd daemon ' - 'stopping while wicd-curses is running. ' - 'Please restart the daemon, and then restart wicd-curses.'), file=sys.stderr) + print("\n" + _('DBus failure! This is most likely caused by the ' + 'wicd daemon stopping while wicd-curses is ' + 'running. Please restart the daemon, and then ' + 'restart wicd-curses.'), file=sys.stderr) raise - except: + except Exception: # Quit the loop - #if 'loop' in locals(): + # if 'loop' in locals(): loop.quit() # Zap the screen ui.stop() @@ -133,19 +123,14 @@ def wrap_exceptions(func): return wrapper -######################################## -##### SUPPORT FUNCTIONS -######################################## - # Look familiar? These two functions are clones of functions found in wicd's # gui.py file, except that now set_status is a function passed to them. @wrap_exceptions def check_for_wired(wired_ip, set_status): - """ Determine if wired is active, and if yes, set the status. """ + """Determine if wired is active, and if yes, set the status.""" if wired_ip and wired.CheckPluggedIn(): - set_status( - _('Connected to wired network (IP: $A)').replace('$A',wired_ip) - ) + set_status(_('Connected to wired network (IP: $A)') + .replace('$A', wired_ip)) return True else: return False @@ -153,7 +138,7 @@ def check_for_wired(wired_ip, set_status): @wrap_exceptions def check_for_wireless(iwconfig, wireless_ip, set_status): - """ Determine if wireless is active, and if yes, set the status. """ + """Determine if wireless is active, and if yes, set the status.""" if not wireless_ip: return False @@ -171,10 +156,10 @@ def check_for_wireless(iwconfig, wireless_ip, set_status): return False strength = misc.to_unicode(daemon.FormatSignalForPrinting(strength)) ip = misc.to_unicode(wireless_ip) - set_status(_('Connected to $A at $B (IP: $C)').replace - ('$A', network).replace - ('$B', strength).replace - ('$C', ip)) + set_status(_('Connected to $A at $B (IP: $C)') + .replace('$A', network) + .replace('$B', strength) + .replace('$C', ip)) return True @@ -183,15 +168,15 @@ def check_for_wireless(iwconfig, wireless_ip, set_status): # DBUS interfaces do. :P # Whatever calls this must be exception-wrapped if it is run if the UI is up def gen_network_list(): - """ Generate the list of networks. """ + """Generate the list of networks.""" wiredL = wired.GetWiredProfileList() wlessL = [] # This one makes a list of NetLabels for network_id in range(0, wireless.GetNumberOfNetworks()): - is_active = \ - wireless.GetCurrentSignalStrength("") != 0 and \ - wireless.GetCurrentNetworkID(wireless.GetIwconfig()) == network_id \ - and wireless.GetWirelessIP('') is not None + is_active = (wireless.GetCurrentSignalStrength("") != 0 and + wireless.GetCurrentNetworkID(wireless.GetIwconfig()) == + network_id and + wireless.GetWirelessIP('') is not None) label = NetLabel(network_id, is_active) wlessL.append(label) @@ -199,67 +184,80 @@ def gen_network_list(): def about_dialog(body): - """ About dialog. """ + """About dialog.""" # This looks A LOT better when it is actually displayed. I promise :-). # The ASCII Art "Wicd" was made from the "smslant" font on one of those # online ASCII big text generators. - theText = [ -('green', " /// \\\\\\"), " _ ___ __\n", -('green', " /// \\\\\\"), " | | /| / (_)______/ /\n", -('green', " /// \\\\\\"), " | |/ |/ / / __/ _ / \n", -('green', "/|| // \\\\ ||\\"), " |__/|__/_/\__/\_,_/ \n", -('green', "||| ||"), "(|^|)", ('green', "|| |||"), -" ($VERSION) \n".replace("$VERSION", daemon.Hello()), - -('green', "\\|| \\\\"), " |+| ", ('green', "// ||/ \n"), -('green', " \\\\\\"), " |+| ", ('green', "///"), - " http://launchpad.net/wicd\n", -('green', " \\\\\\"), " |+| ", ('green', "///"), " ", - _('Brought to you by:'), "\n", -('green', " \\\\\\"), " |+| ", ('green', "///"), " * Tom Van Braeckel\n", -" __|+|__ * Adam Blackburn\n", -" ___|+|___ * Dan O'Reilly\n", -" ____|+|____ * Andrew Psaltis\n", -" |-----------| * David Paleino\n"] + theText = [('green', " /// \\\\\\"), + " _ ___ __\n", + ('green', " /// \\\\\\"), + " | | /| / (_)______/ /\n", + ('green', " /// \\\\\\"), + " | |/ |/ / / __/ _ / \n", + ('green', "/|| // \\\\ ||\\"), + " |__/|__/_/\__/\_,_/ \n", + ('green', "||| ||"), "(|^|)", ('green', "|| |||"), + " ($VERSION) \n".replace("$VERSION", + daemon.Hello()), + ('green', "\\|| \\\\"), " |+| ", ('green', "// ||/ \n"), + ('green', " \\\\\\"), " |+| ", ('green', "///"), + " http://launchpad.net/wicd\n", + ('green', " \\\\\\"), " |+| ", ('green', "///"), " ", + _('Brought to you by:'), "\n", + ('green', " \\\\\\"), " |+| ", + ('green', "///"), " * Tom Van Braeckel\n", + " __|+|__ * Adam Blackburn\n", + " ___|+|___ * Dan O'Reilly\n", + " ____|+|____ * Andrew Psaltis\n", + " |-----------| * David Paleino\n"] about = TextDialog(theText, 18, 55, header=('header', _('About Wicd'))) about.run(ui, body) # Modeled after htop's help def help_dialog(body): - """ Help dialog. """ + """Help dialog.""" textT = urwid.Text(('header', _('wicd-curses help')), 'right') textSH = urwid.Text([ 'This is ', ('blue', 'wicd-curses-' + CURSES_REV), ' using wicd ', str(daemon.Hello()), '\n' ]) - textH = urwid.Text([ -_('For more detailed help, consult the wicd-curses(8) man page.') + "\n", -('bold', '->'), ' and ', ('bold', '<-'), -" are the right and left arrows respectively.\n" - ]) + textH = urwid.Text([_('For more detailed help, consult the wicd-curses(8) ' + 'man page.') + "\n", ('bold', '->'), ' and ', + ('bold', '<-'), " are the right and left arrows " + "respectively.\n"]) - text1 = urwid.Text([ -('bold', ' H h ?'), ": " + _('Display this help dialog') + "\n", -('bold', 'enter C'), ": " + _('Connect to selected network') + "\n", -('bold', ' D'), ": " + _('Disconnect from all networks') + "\n", -('bold', ' ESC'), ": " + _('Stop a connection in progress') + "\n", -('bold', ' F5 R'), ": " + _('Refresh network list') + "\n", -('bold', ' P'), ": " + _('Preferences dialog') + "\n", - ]) - text2 = urwid.Text([ -('bold', ' I'), ": " + _('Scan for hidden networks') + "\n", -('bold', ' S'), ": " + _('Select scripts') + "\n", -('bold', ' O'), ": " + _('Set up Ad-hoc network') + "\n", -('bold', ' X'), ": " + _('Remove settings for saved networks') + "\n", -('bold', ' ->'), ": " + _('Configure selected network') + "\n", -('bold', ' A'), ": " + _("Display 'about' dialog") + "\n", -('bold', ' F8 q Q'), ": " + _('Quit wicd-curses') + "\n", - ]) + text1 = urwid.Text([('bold', ' H h ?'), + ": " + _('Display this help dialog') + "\n", + ('bold', 'enter C'), + ": " + _('Connect to selected network') + "\n", + ('bold', ' D'), + ": " + _('Disconnect from all networks') + "\n", + ('bold', ' ESC'), + ": " + _('Stop a connection in progress') + "\n", + ('bold', ' F5 R'), + ": " + _('Refresh network list') + "\n", + ('bold', ' P'), + ": " + _('Preferences dialog') + "\n"]) + text2 = urwid.Text([('bold', ' I'), + ": " + _('Scan for hidden networks') + "\n", + ('bold', ' S'), + ": " + _('Select scripts') + "\n", + ('bold', ' O'), + ": " + _('Set up Ad-hoc network') + "\n", + ('bold', ' X'), + ": " + _('Remove settings for saved networks') + "\n", + ('bold', ' ->'), + ": " + _('Configure selected network') + "\n", + ('bold', ' A'), + ": " + _("Display 'about' dialog") + "\n", + ('bold', ' F8 q Q'), + ": " + _('Quit wicd-curses') + "\n"]) textF = urwid.Text(_('Press any key to return.')) - #textJ = urwid.Text(('important', 'Nobody expects the Spanish Inquisition!')) + # textJ = urwid.Text(('important', + # 'Nobody expects the Spanish Inquisition!')) blank = urwid.Text('') @@ -291,7 +289,7 @@ _('For more detailed help, consult the wicd-curses(8) man page.') + "\n", def run_configscript(parent, netname, nettype): - """ Run configuration script. """ + """Run configuration script.""" configfile = wpath.etc + netname + '-settings.conf' if nettype != 'wired': header = 'profile' @@ -301,59 +299,62 @@ def run_configscript(parent, netname, nettype): profname = nettype else: profname = wireless.GetWirelessProperty(int(netname), 'bssid') - theText = [ -_('To avoid various complications, wicd-curses does not support directly ' -'editing the scripts. However, you can edit them manually. First, (as root), ' -'open the "$A" config file, and look for the section labeled by the $B in ' -'question. In this case, this is:'). -replace('$A', configfile).replace('$B', header), -"\n\n[" + profname + "]\n\n", -_('You can also configure the wireless networks by looking for the "[]" ' -'field in the config file.'), -_('Once there, you can adjust (or add) the "beforescript", "afterscript", ' -'"predisconnectscript" and "postdisconnectscript" variables as needed, to ' -'change the preconnect, postconnect, predisconnect and postdisconnect scripts ' -'respectively. Note that you will be specifying the full path to the scripts ' -'- not the actual script contents. You will need to add/edit the script ' -'contents separately. Refer to the wicd manual page for more information.') - ] + theText = [_('To avoid various complications, wicd-curses does not ' + 'support directly editing the scripts. However, you can ' + 'edit them manually. First, (as root), open the "$A" config ' + 'file, and look for the section labeled by the $B in ' + 'question. In this case, this is:') + .replace('$A', configfile) + .replace('$B', header), + "\n\n[" + profname + "]\n\n", + _('You can also configure the wireless networks by looking ' + 'for the "[]" field in the config file.'), + _('Once there, you can adjust (or add) the "beforescript", ' + '"afterscript", "predisconnectscript" and ' + '"postdisconnectscript" variables as needed, to change the ' + 'preconnect, postconnect, predisconnect and postdisconnect ' + 'scripts respectively. Note that you will be specifying ' + 'the full path to the scripts - not the actual script ' + 'contents. You will need to add/edit the script contents ' + 'separately. Refer to the wicd manual page for more ' + 'information.')] dialog = TextDialog(theText, 20, 80) dialog.run(ui, parent) # This code works with many distributions, but not all of them. So, to # limit complications, it has been deactivated. If you want to run it, # be my guest. Be sure to deactivate the above stuff first. - #loop.quit() - #ui.stop() - #argv = netname + ' ' +nettype + # loop.quit() + # ui.stop() + # argv = netname + ' ' +nettype - ##cmd = '/usr/lib/configscript_curses.py '+argv - #cmd = wpath.lib+'configscript_curses.py '+argv - ## Check whether we can sudo. Hopefully this is complete - #glist = [] - #for i in getgroups(): - #glist.append(getgrgid(i)[0]) - #if 'root' in glist: - #precmd = '' - #precmdargv = '' - #postcmd = '' - #elif 'admin' in glist or 'wheel' in glist or 'sudo' in glist: - #precmd = 'sudo' - #precmdargv = '' - #postcmd = '' - #else: - #precmd = 'su' - #precmdargv = ' -c "' - #postcmd = '"' - #print "Calling command: " + precmd + precmdargv + cmd + postcmd - #sys.stdout.flush() - #system(precmd+precmdargv+cmd+postcmd) - #raw_input("Press enter!") - #main() + # #cmd = '/usr/lib/configscript_curses.py '+argv + # cmd = wpath.lib+'configscript_curses.py '+argv + # # Check whether we can sudo. Hopefully this is complete + # glist = [] + # for i in getgroups(): + # glist.append(getgrgid(i)[0]) + # if 'root' in glist: + # precmd = '' + # precmdargv = '' + # postcmd = '' + # elif 'admin' in glist or 'wheel' in glist or 'sudo' in glist: + # precmd = 'sudo' + # precmdargv = '' + # postcmd = '' + # else: + # precmd = 'su' + # precmdargv = ' -c "' + # postcmd = '"' + # print "Calling command: " + precmd + precmdargv + cmd + postcmd + # sys.stdout.flush() + # system(precmd+precmdargv+cmd+postcmd) + # raw_input("Press enter!") + # main() def gen_list_header(): - """ Generate header. """ + """Generate header.""" if daemon.GetSignalDisplayType() == 0: # Allocate 25 cols for the ESSID name essidgap = 25 @@ -363,17 +364,15 @@ def gen_list_header(): return 'C %s %*s %9s %17s %6s %s' % \ ('STR ', essidgap, 'ESSID', 'ENCRYPT', 'BSSID', 'MODE', 'CHNL') -""" Some people use CTRL-\ to quit the application (SIGQUIT) """ + def handle_sigquit(signal_number, stack_frame): + """Some people use CTRL-\ to quit the application (SIGQUIT)""" loop.quit() ui.stop() -######################################## -##### URWID SUPPORT CLASSES -######################################## class NetLabel(urwid.WidgetWrap): - """ Wireless network label. """ + """Wireless network label.""" # pylint: disable-msg=W0231 def __init__(self, i, is_active): # Pick which strength measure to use based on what the daemon says @@ -417,15 +416,15 @@ class NetLabel(urwid.WidgetWrap): self.__super.__init__(w) def selectable(self): - """ Return whether the widget is selectable. """ + """Return whether the widget is selectable.""" return True def keypress(self, size, key): - """ Handle keypresses. """ + """Handle keypresses.""" return self._w.keypress(size, key) def connect(self): - """ Execute connection. """ + """Execute connection.""" wireless.ConnectWireless(self.id) @@ -434,22 +433,22 @@ class WiredComboBox(ComboBox): list : the list of wired network profiles. The rest is self-explanitory. """ # pylint: disable-msg=W0231 - def __init__(self, l): + def __init__(self, wired_list): self.ADD_PROFILE = '---' + _('Add a new profile') + '---' # pylint: disable-msg=E1101 self.__super.__init__(use_enter=False) self.theList = [] - self.set_list(l) + self.set_list(wired_list) - def set_list(self, l): - """ Set contents of the combobox. """ - self.theList = l + def set_list(self, wired_list): + """Set contents of the combobox.""" + self.theList = wired_list i = 0 wiredL = [] is_active = \ wireless.GetWirelessIP('') is None and \ wired.GetWiredIP('') is not None - for profile in l: + for profile in wired_list: theString = '%4s %25s' % (i, profile) # Tag if no wireless IP present, and wired one is if is_active: @@ -469,15 +468,13 @@ class WiredComboBox(ComboBox): wired.ReadWiredNetworkProfile(self.get_selected_profile()) def keypress(self, size, key): - """ Handle keypresses. """ + """Handle keypresses.""" prev_focus = self.get_focus()[1] key = ComboBox.keypress(self, size, key) if key == ' ': if self.get_focus()[1] == len(self.list) - 1: - dialog = InputDialog( - ('header', _('Add a new wired profile')), - 7, 30 - ) + dialog = InputDialog(('header', _('Add a new wired profile')), + 7, 30) exitcode, name = dialog.run(ui, self.parent) if exitcode == 0: name = name.strip() @@ -494,12 +491,9 @@ class WiredComboBox(ComboBox): wired.ReadWiredNetworkProfile(self.get_selected_profile()) if key == 'delete': if len(self.theList) == 1: - error( - self.ui, - self.parent, - _('wicd-curses does not support deleting the last wired ' - 'profile. Try renaming it ("F2")') - ) + error(self.ui, self.parent, + _('wicd-curses does not support deleting the last ' + 'wired profile. Try renaming it ("F2")')) return key wired.DeleteWiredNetworkProfile(self.get_selected_profile()) # Return to the top of the list if something is deleted. @@ -536,7 +530,7 @@ class WiredComboBox(ComboBox): class AdHocDialog(Dialog2): - """ Dialog2 that initiates an Ad-Hoc network connection. """ + """Dialog2 that initiates an Ad-Hoc network connection.""" def __init__(self): essid_t = _('ESSID') ip_t = _('IP') @@ -551,8 +545,8 @@ class AdHocDialog(Dialog2): self.key_edit = DynEdit(key_t, sensitive=False) self.use_ics_chkb = urwid.CheckBox(use_ics_t) - self.use_encrypt_chkb = urwid.CheckBox(use_encrypt_t, - on_state_change=self.encrypt_callback) + self.use_encrypt_chkb = urwid.CheckBox( + use_encrypt_t, on_state_change=self.encrypt_callback) blank = urwid.Text('') @@ -561,9 +555,9 @@ class AdHocDialog(Dialog2): self.ip_edit.set_edit_text("169.254.12.10") self.channel_edit.set_edit_text("3") - l = [self.essid_edit, self.ip_edit, self.channel_edit, blank, - self.use_ics_chkb, self.use_encrypt_chkb, self.key_edit] - body = urwid.ListBox(l) + lb = [self.essid_edit, self.ip_edit, self.channel_edit, blank, + self.use_ics_chkb, self.use_encrypt_chkb, self.key_edit] + body = urwid.ListBox(lb) header = ('header', _('Create an Ad-Hoc Network')) Dialog2.__init__(self, header, 15, 50, body) @@ -571,11 +565,11 @@ class AdHocDialog(Dialog2): self.frame.set_focus('body') def encrypt_callback(self, chkbox, new_state, user_info=None): - """ Set widget sensitivity. """ + """Set widget sensitivity.""" self.key_edit.set_sensitive(new_state) def unhandled_key(self, size, k): - """ Handle keypresses. """ + """Handle keypresses.""" if k in ('up', 'page up'): self.frame.set_focus('body') if k in ('down', 'page down'): @@ -587,7 +581,7 @@ class AdHocDialog(Dialog2): self.view.keypress(size, k) def on_exit(self, exitcode): - """ Handle dialog exit. """ + """Handle dialog exit.""" data = (self.essid_edit.get_edit_text(), self.ip_edit.get_edit_text().strip(), self.channel_edit.get_edit_text(), @@ -599,7 +593,7 @@ class AdHocDialog(Dialog2): # TODO class ForgetDialog(Dialog2): - """ Dialog2 that removes/forgets a network. """ + """Dialog2 that removes/forgets a network.""" def __init__(self): self.to_remove = dict(essid=[], bssid=[]) @@ -608,7 +602,7 @@ class ForgetDialog(Dialog2): 'listbar' ) title = urwid.Text(_('Please select the networks to forget')) - l = [title, header] + lb = [title, header] for entry in wireless.GetSavedWirelessNetworks(): label = '%20s %20s' if entry[1] != 'None': @@ -623,8 +617,8 @@ class ForgetDialog(Dialog2): on_state_change=self.update_to_remove, user_data=data ) - l.append(cb) - body = urwid.ListBox(l) + lb.append(cb) + body = urwid.ListBox(lb) header = ('header', _('List of saved networks')) Dialog2.__init__(self, header, 15, 50, body) @@ -632,7 +626,7 @@ class ForgetDialog(Dialog2): self.frame.set_focus('body') def update_to_remove(self, widget, checked, data): - """ Update list of removable networks. """ + """Update list of removable networks.""" if checked: self.to_remove['essid'].append(data[0]) self.to_remove['bssid'].append(data[1]) @@ -641,7 +635,7 @@ class ForgetDialog(Dialog2): self.to_remove['bssid'].remove(data[1]) def unhandled_key(self, size, k): - """ Handle unhandled keys. """ + """Handle unhandled keys.""" if k in ('up', 'page up'): self.frame.set_focus('body') if k in ('down', 'page down'): @@ -653,13 +647,10 @@ class ForgetDialog(Dialog2): self.view.keypress(size, k) def on_exit(self, exitcode): - """ Handle dialog exit. """ + """Handle dialog exit.""" return exitcode, self.to_remove -######################################## -##### APPLICATION INTERFACE CLASS -######################################## # The Whole Shebang class appGUI(): """The UI itself, all glory belongs to it!""" @@ -686,7 +677,8 @@ class appGUI(): self.WIRED_IDX = 1 self.WLESS_IDX = 3 - header = urwid.AttrWrap(urwid.Text(self.TITLE, align='right'), 'header') + header = urwid.AttrWrap(urwid.Text(self.TITLE, align='right'), + 'header') self.wiredH = urwid.Filler(urwid.Text(_('Wired Networks'))) self.list_header = urwid.AttrWrap( urwid.Text(gen_list_header()), 'listbar' @@ -713,19 +705,17 @@ class appGUI(): self.update_netlist(force_check=True, firstrun=True) # Keymappings proposed by nanotube in #wicd - keys = [ - ('H', _('Help'), None), - ('right', _('Config'), None), - #(' ', ' ', None), - ('K', _('RfKill'), None), - ('C', _('Connect'), None), - ('D', _('Disconn'), None), - ('R', _('Refresh'), None), - ('P', _('Prefs'), None), - ('I', _('Hidden'), None), - ('A', _('About'), None), - ('Q', _('Quit'), loop.quit) - ] + keys = [('H', _('Help'), None), + ('right', _('Config'), None), + # (' ', ' ', None), + ('K', _('RfKill'), None), + ('C', _('Connect'), None), + ('D', _('Disconn'), None), + ('R', _('Refresh'), None), + ('P', _('Prefs'), None), + ('I', _('Hidden'), None), + ('A', _('About'), None), + ('Q', _('Quit'), loop.quit)] self.primaryCols = OptCols(keys, self.handle_keys) self.status_label = urwid.AttrWrap(urwid.Text(''), 'important') @@ -745,7 +735,8 @@ class appGUI(): self.prev_state = False self.connecting = False self.screen_locked = False - self.do_diag_lock = False # Whether the screen is locked beneath a dialog + # Whether the screen is locked beneath a dialog + self.do_diag_lock = False self.diag_type = 'none' # The type of dialog that is up self.scanning = False @@ -753,28 +744,24 @@ class appGUI(): self.update_status() - #self.max_wait = ui.max_wait + # self.max_wait = ui.max_wait def doScan(self, sync=False): - """ Start wireless scan. """ + """Start wireless scan.""" self.scanning = True wireless.Scan(False) def init_other_optcols(self): - """ Init "tabbed" preferences dialog. """ - self.prefCols = OptCols([ - ('S', _('Save')), - ('page up', _('Tab Left'), ), - ('page down', _('Tab Right')), - ('esc', _('Cancel')) - ], self.handle_keys) - self.confCols = OptCols([ - ('S', _('Save')), - ('esc', _('Cancel')) - ], self.handle_keys) + """Init "tabbed" preferences dialog.""" + self.prefCols = OptCols([('S', _('Save')), + ('page up', _('Tab Left'), ), + ('page down', _('Tab Right')), + ('esc', _('Cancel'))], self.handle_keys) + self.confCols = OptCols([('S', _('Save')), + ('esc', _('Cancel'))], self.handle_keys) def lock_screen(self): - """ Lock the screen. """ + """Lock the screen.""" if self.diag_type == 'pref': self.do_diag_lock = True return True @@ -783,7 +770,7 @@ class appGUI(): self.update_ui() def unlock_screen(self): - """ Unlock the screen. """ + """Unlock the screen.""" if self.do_diag_lock: self.do_diag_lock = False return True @@ -794,7 +781,7 @@ class appGUI(): self.update_ui() def raise_hidden_network_dialog(self): - """ Show hidden network dialog. """ + """Show hidden network dialog.""" dialog = InputDialog( ('header', _('Select Hidden Network ESSID')), 7, 30, _('Scan') @@ -824,15 +811,15 @@ class appGUI(): where = None else: where = self.thePile.get_focus().get_focus()[1] - #where = self.wlessLB.get_focus()[1] + # where = self.wlessLB.get_focus()[1] self.focusloc = [wlessorwired, where] # Be clunky until I get to a later stage of development. # Update the list of networks. Usually called by DBus. @wrap_exceptions def update_netlist(self, state=None, x=None, force_check=False, - firstrun=False): - """ Update the list of networks. """ + firstrun=False): + """Update the list of networks.""" # Don't even try to do this if we are running a dialog if self.diag: return @@ -872,8 +859,10 @@ class appGUI(): get_body().set_focus(self.focusloc[1]) else: if self.wlessLB != self.no_wlan: - # Set the focus to the last selected item, but never past the length of the list - self.thePile.get_focus().set_focus(min(self.focusloc[1], len(wlessL) - 1)) + # Set the focus to the last selected item, but never + # past the length of the list + self.thePile.get_focus().set_focus( + min(self .focusloc[1], len(wlessL) - 1)) else: self.thePile.set_focus(self.wiredCB) else: @@ -886,8 +875,10 @@ class appGUI(): if self.focusloc[1] is None: self.focusloc[1] = 0 if self.wlessLB != self.no_wlan: - # Set the focus to the last selected item, but never past the length of the list - self.wlessLB.set_focus(min(self.focusloc[1], len(wlessL) - 1)) + # Set the focus to the last selected item, but never past + # the length of the list + self.wlessLB.set_focus(min(self.focusloc[1], + len(wlessL) - 1)) self.prev_state = state if not firstrun: @@ -896,13 +887,11 @@ class appGUI(): if wired.GetDefaultWiredNetwork() is not None: self.wiredCB.get_body().set_focus( wired.GetWiredProfileList().index( - wired.GetDefaultWiredNetwork() - ) - ) + wired.GetDefaultWiredNetwork())) @wrap_exceptions def update_status(self): - """ Update the footer / statusbar. """ + """Update the footer / statusbar.""" wired_connecting = wired.CheckIfWiredConnecting() wireless_connecting = wireless.CheckIfWirelessConnecting() self.connecting = wired_connecting or wireless_connecting @@ -921,7 +910,7 @@ class appGUI(): else: iwconfig = '' if check_for_wireless(iwconfig, wireless.GetWirelessIP(""), - self.set_status): + self.set_status): return True else: self.set_status(_('Not connected')) @@ -929,7 +918,7 @@ class appGUI(): return True def set_connecting_status(self, fast): - """ Set connecting status. """ + """Set connecting status.""" wired_connecting = wired.CheckIfWiredConnecting() wireless_connecting = wireless.CheckIfWirelessConnecting() if wireless_connecting: @@ -941,14 +930,14 @@ class appGUI(): stat = wireless.CheckWirelessConnectingMessage() return self.set_status("%s: %s" % (essid, stat), True) if wired_connecting: - return self.set_status(_('Wired Network') + - ': ' + wired.CheckWiredConnectingMessage(), True) + return self.set_status(_('Wired Network') + ': ' + + wired.CheckWiredConnectingMessage(), True) else: self.conn_status = False return False def set_status(self, text, from_idle=False): - """ Set the status text. """ + """Set the status text.""" # Set the status text, usually called by the update_status method # from_idle : a check to see if we are being called directly from the # mainloop @@ -975,22 +964,22 @@ class appGUI(): return True def dbus_scan_finished(self): - """ Handle DBus scan finish. """ + """Handle DBus scan finish.""" # I'm pretty sure that I'll need this later. - #if not self.connecting: - # gobject.idle_add(self.refresh_networks, None, False, None) + # if not self.connecting: + # gobject.idle_add(self.refresh_networks, None, False, None) self.unlock_screen() self.scanning = False def dbus_scan_started(self): - """ Handle DBus scan start. """ + """Handle DBus scan start.""" self.scanning = True if self.diag_type == 'conf': self.restore_primary() self.lock_screen() def restore_primary(self): - """ Restore screen. """ + """Restore screen.""" self.diag_type = 'none' if self.do_diag_lock or self.scanning: self.frame.set_body(self.screen_locker) @@ -1002,12 +991,12 @@ class appGUI(): self.update_ui() def handle_keys(self, keys): - """ Handle keys. """ + """Handle keys.""" if not self.diag: # Handle keystrokes if "f8" in keys or 'Q' in keys or 'q' in keys: loop.quit() - #return False + # return False if "f5" in keys or 'R' in keys: self.lock_screen() self.doScan() @@ -1065,7 +1054,8 @@ class appGUI(): ) self.pref.load_settings() self.pref.ready_widgets(ui, self.frame) - self.frame.set_footer(urwid.Pile([self.prefCols, self.footer2])) + self.frame.set_footer(urwid.Pile([self.prefCols, + self.footer2])) self.diag = self.pref self.diag_type = 'pref' self.frame.set_body(self.diag) @@ -1091,7 +1081,7 @@ class appGUI(): run_configscript(self.frame, netname, nettype) if "O" in keys: exitcode, data = AdHocDialog().run(ui, self.frame) - #data = (essid,ip,channel,use_ics,use_encrypt,key_edit) + # data = (essid,ip,channel,use_ics,use_encrypt,key_edit) if exitcode == 1: wireless.CreateAdHocNetwork( data[0], @@ -1106,11 +1096,12 @@ class appGUI(): exitcode, data = ForgetDialog().run(ui, self.frame) if exitcode == 1: text = _('Are you sure you want to discard settings for ' - 'the selected networks?') + 'the selected networks?') text += '\n\n' + '\n'.join(data['essid']) - confirm, trash = TextDialog(text, 20, 50, - buttons=[(_('OK'), 1), (_('Cancel'), -1)], - ).run(ui, self.frame) + confirm, trash = TextDialog( + text, 20, 50, + buttons=[(_('OK'), 1), + (_('Cancel'), -1)],).run(ui, self.frame) if confirm == 1: for x in data['bssid']: wireless.DeleteWirelessNetwork(x) @@ -1127,12 +1118,13 @@ class appGUI(): continue k = self.frame.keypress(self.size, k) if self.diag: - if k == 'esc' or k == 'q' or k == 'Q': + if k == 'esc' or k == 'q' or k == 'Q': self.restore_primary() break # F10 has been changed to S to avoid using function keys, # which are often caught by the terminal emulator. - # But F10 still works, because it doesn't hurt and some users might be used to it. + # But F10 still works, because it doesn't hurt and some users + # might be used to it. if k == 'f10' or k == 'S' or k == 's': self.diag.save_settings() self.restore_primary() @@ -1142,14 +1134,14 @@ class appGUI(): continue def call_update_ui(self, source, cb_condition): - """ Update UI. """ + """Update UI.""" self.update_ui(True) return True # Redraw the screen @wrap_exceptions def update_ui(self, from_key=False): - """ Redraw the screen. """ + """Redraw the screen.""" if not ui._started: return False @@ -1163,11 +1155,11 @@ class appGUI(): # Get the input data if self.update_tag is not None: gobject.source_remove(self.update_tag) - #if from_key: + # if from_key: return False def connect(self, nettype, networkid, networkentry=None): - """ Initiates the connection process in the daemon. """ + """Initiates the connection process in the daemon.""" if nettype == "wireless": wireless.ConnectWireless(networkid) elif nettype == "wired": @@ -1175,21 +1167,18 @@ class appGUI(): self.update_status() -######################################## -##### INITIALIZATION FUNCTIONS -######################################## def main(): - """ Main function. """ + """Main function.""" global ui, dlogger # We are not python. misc.RenameProcess('wicd-curses') ui = urwid.raw_display.Screen() - #if options.debug: - # dlogger = logging.getLogger("Debug") - # dlogger.setLevel(logging.DEBUG) - # dlogger.debug("wicd-curses debug logging started") + # if options.debug: + # dlogger = logging.getLogger("Debug") + # dlogger.setLevel(logging.DEBUG) + # dlogger.debug("wicd-curses debug logging started") # Default Color scheme. # Other potential color schemes can be found at: @@ -1216,7 +1205,8 @@ def main(): ('red', 'dark red', 'default'), ('bold', 'white', 'black', 'bold') ]) - # Handle SIGQUIT correctly (otherwise urwid leaves the terminal in a bad state) + # Handle SIGQUIT correctly (otherwise urwid leaves the terminal in a bad + # state) signal.signal(signal.SIGQUIT, handle_sigquit) # This is a wrapper around a function that calls another a function that # is a wrapper around a infinite loop. Fun. @@ -1226,7 +1216,7 @@ def main(): @wrap_exceptions def run(): - """ Run the UI. """ + """Run the UI.""" global loop loop = gobject.MainLoop() @@ -1254,52 +1244,51 @@ def run(): # Mostly borrowed from gui.py def setup_dbus(force=True): - """ Initialize DBus. """ + """Initialize DBus.""" global bus, daemon, wireless, wired try: dbusmanager.connect_to_dbus() except DBusException: - print(_("Can't connect to the daemon, trying to start it automatically..."), file=sys.stderr) + print(_("Can't connect to the daemon, trying to start it " + "automatically..."), file=sys.stderr) try: - bus = dbusmanager.get_bus() - dbus_ifaces = dbusmanager.get_dbus_ifaces() - daemon = dbus_ifaces['daemon'] - wireless = dbus_ifaces['wireless'] - wired = dbus_ifaces['wired'] + bus = dbusmanager.get_bus() + dbus_ifaces = dbusmanager.get_dbus_ifaces() + daemon = dbus_ifaces['daemon'] + wireless = dbus_ifaces['wireless'] + wired = dbus_ifaces['wired'] except DBusException: - print(_("Can't automatically start the daemon, this error is fatal..."), file=sys.stderr) + print(_("Can't automatically start the daemon, this error is " + "fatal..."), file=sys.stderr) if not daemon: - print('Error connecting to wicd via D-Bus. ' \ - 'Please make sure the wicd service is running.') + print('Error connecting to wicd via D-Bus.\nPlease make sure the ' + 'wicd service is running.') sys.exit(3) netentry_curses.dbus_init(dbus_ifaces) return True + setup_dbus() -######################################## -##### MAIN ENTRY POINT -######################################## + if __name__ == '__main__': try: - parser = OptionParser( - version="wicd-curses-%s (using wicd %s)" % - (CURSES_REV, daemon.Hello()), - prog="wicd-curses" - ) + parser = OptionParser(version="wicd-curses-%s (using wicd %s)" % + (CURSES_REV, daemon.Hello()), + prog="wicd-curses") except Exception as e: if "DBus.Error.AccessDenied" in e.get_dbus_name(): print(_('ERROR: wicd-curses was denied access to the wicd daemon: ' - 'please check that your user is in the "$A" group.'). \ - replace('$A', '\033[1;34m' + wpath.wicd_group + '\033[0m')) + 'please check that your user is in the "$A" group.') + .replace('$A', '\033[1;34m' + wpath.wicd_group + '\033[0m')) sys.exit(1) else: raise - #parser.add_option("-d", "--debug", action="store_true", dest='debug', - # help="enable logging of wicd-curses (currently does nothing)") + # parser.add_option("-d", "--debug", action="store_true", dest='debug', + # help="enable logging of wicd-curses (currently does nothing)") (options, args) = parser.parse_args() main() diff --git a/gtk/configscript.py b/gtk/configscript.py index 085f1c7..0544fa0 100644 --- a/gtk/configscript.py +++ b/gtk/configscript.py @@ -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) diff --git a/gtk/gui.py b/gtk/gui.py index 8f40622..75aaf49 100644 --- a/gtk/gui.py +++ b/gtk/gui.py @@ -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. diff --git a/gtk/guiutil.py b/gtk/guiutil.py index 820aae9..6fefa55 100644 --- a/gtk/guiutil.py +++ b/gtk/guiutil.py @@ -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) diff --git a/gtk/netentry.py b/gtk/netentry.py index 06ce1c5..2e0701c 100644 --- a/gtk/netentry.py +++ b/gtk/netentry.py @@ -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 . # +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("&", "&"). \ replace("<", "<"). \ replace(">", ">"). \ @@ -1069,11 +1070,11 @@ class WirelessNetworkEntry(NetworkEntry): replace('"', """) 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)) diff --git a/gtk/prefs.py b/gtk/prefs.py index adf8368..d293a60 100644 --- a/gtk/prefs.py +++ b/gtk/prefs.py @@ -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 . # +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()]]) diff --git a/gtk/wicd-client.py b/gtk/wicd-client.py index fdd6186..adc2682 100644 --- a/gtk/wicd-client.py +++ b/gtk/wicd-client.py @@ -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 . # -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", "" + wpath.wicd_group + "") - ) - #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", "%s" % + 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. diff --git a/in/wicd=wpath.py.in b/in/wicd=wpath.py.in index 17bbb73..257ddc4 100755 --- a/in/wicd=wpath.py.in +++ b/in/wicd=wpath.py.in @@ -1,9 +1,8 @@ -""" Path configuration and functions for the wicd daemon and gui clients. +"""Path configuration and functions for the wicd daemon and gui clients. chdir() -- Change directory to the location of the current file. """ - import os # The path containing the wpath.py file. @@ -90,6 +89,7 @@ no_install_cli = %NO_INSTALL_CLI% no_install_gnome_shell_extensions = %NO_INSTALL_GNOME_SHELL_EXTENSIONS% no_use_notifications = %NO_USE_NOTIFICATIONS% + def chdir(f): """Change directory to the location of the specified file. diff --git a/setup.py b/setup.py index d4a68c0..fc892ab 100755 --- a/setup.py +++ b/setup.py @@ -16,16 +16,15 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . # +from glob import glob +import os +import re +import shutil +import subprocess from distutils.core import setup, Command from distutils.command.build import build as _build from distutils.command.install import install as _install -import os -import re -import sys -import shutil -import subprocess -from glob import glob # Be sure to keep this updated! # VERSIONNUMBER @@ -46,8 +45,9 @@ os.chdir(os.path.abspath(os.path.split(__file__)[0])) try: if os.path.exists('.bzr') and os.system('bzr > /dev/null 2>&1') == 0: try: - os.system('bzr version-info --python > vcsinfo.py && 2to3-2.7 -w vcsinfo.py') - except: + os.system('bzr version-info --python > vcsinfo.py && 2to3-2.7 ' + '-w vcsinfo.py') + except Exception: pass import vcsinfo REVISION_NUM = vcsinfo.version_info['revno'] @@ -55,6 +55,7 @@ except Exception as e: print('failed to find revision number:') print(e) + class build(_build): sub_commands = _build.sub_commands + [('compile_translations', None)] @@ -64,9 +65,10 @@ class build(_build): except ImportError: self.run_command('configure') import wpath - #raise Exception, 'Please run "./setup.py configure" first.' + # raise Exception, 'Please run "./setup.py configure" first.' _build.run(self) + class configure(Command): description = "configure the paths that Wicd will be installed to" @@ -87,21 +89,31 @@ class configure(Command): ('curses=', None, 'set the curses UI directory'), ('gtk=', None, 'set the GTK UI directory'), ('cli=', None, 'set the CLI directory'), - ('gnome-shell-extensions=', None, 'set the Gnome Shell Extensions directory'), + ('gnome-shell-extensions=', None, 'set the Gnome Shell Extensions ' + 'directory'), ('networks=', None, 'set the encryption configuration directory'), ('log=', None, 'set the log directory'), - ('resume=', None, 'set the directory the resume from suspend script is stored in'), - ('suspend=', None, 'set the directory the suspend script is stored in'), - ('pmutils=', None, 'set the directory the pm-utils hooks are stored in'), + ('resume=', None, 'set the directory the resume from suspend script ' + 'is stored in'), + ('suspend=', None, 'set the directory the suspend script is stored ' + 'in'), + ('pmutils=', None, 'set the directory the pm-utils hooks are stored ' + 'in'), ('dbus=', None, 'set the directory the dbus config file is stored in'), - ('dbus-service=', None, 'set the directory where the dbus services config files are stored in'), - ('systemd=', None, 'set the directory where the systemd system services config files are stored in'), - ('logrotate=', None, 'set the directory where the logrotate configuration files are stored in'), + ('dbus-service=', None, 'set the directory where the dbus services ' + 'config files are stored in'), + ('systemd=', None, 'set the directory where the systemd system ' + 'services config files are stored in'), + ('logrotate=', None, 'set the directory where the logrotate ' + 'configuration files are stored in'), ('desktop=', None, 'set the directory the .desktop file is stored in'), - ('icons=', None, "set the base directory for the .desktop file's icons"), - ('translations=', None, 'set the directory translations are stored in'), - ('autostart=', None, 'set the directory that will be autostarted on desktop login'), - ('varlib=',None , 'set the path for wicd\'s variable state data'), + ('icons=', None, "set the base directory for the .desktop file's " + "icons"), + ('translations=', None, 'set the directory translations are stored ' + 'in'), + ('autostart=', None, 'set the directory that will be autostarted on ' + 'desktop login'), + ('varlib=', None, 'set the path for wicd\'s variable state data'), ('init=', None, 'set the directory for the init file'), ('docdir=', None, 'set the directory for the documentation'), ('mandir=', None, 'set the directory for the man pages'), @@ -116,7 +128,8 @@ class configure(Command): ('initfile=', None, 'set the init file to use'), ('initfilename=', None, "set the name of the init file (don't use)"), ('wicdgroup=', None, "set the name of the group used for wicd"), - ('distro=', None, 'set the distribution for which wicd will be installed'), + ('distro=', None, 'set the distribution for which wicd will be ' + 'installed'), ('loggroup=', None, 'the group the log file belongs to'), ('logperms=', None, 'the log file permissions'), @@ -124,17 +137,21 @@ class configure(Command): ('no-install-init', None, "do not install the init file"), ('no-install-man', None, 'do not install the man files'), ('no-install-i18n', None, 'do not install translation files'), - ('no-install-i18n-man', None, 'do not install the translated man files'), + ('no-install-i18n-man', None, 'do not install the translated man ' + 'files'), ('no-install-kde', None, 'do not install the kde autostart file'), - ('no-install-acpi', None, 'do not install the suspend.d and resume.d acpi scripts'), + ('no-install-acpi', None, 'do not install the suspend.d and resume.d ' + 'acpi scripts'), ('no-install-pmutils', None, 'do not install the pm-utils hooks'), - ('no-install-docs', None, 'do not install the auxiliary documentation'), + ('no-install-docs', None, 'do not install the auxiliary ' + 'documentation'), ('no-install-ncurses', None, 'do not install the ncurses client'), ('no-install-cli', None, 'do not install the command line executable'), ('no-install-gtk', None, 'do not install the gtk client'), - ('no-install-gnome-shell-extensions', None, 'do not install the Gnome Shell extension'), - ('no-use-notifications', None, 'do not ever allow the use of libnotify notifications') - ] + ('no-install-gnome-shell-extensions', None, 'do not install the Gnome ' + 'Shell extension'), + ('no-use-notifications', None, 'do not ever allow the use of ' + 'libnotify notifications')] def initialize_options(self): self.lib = '/usr/lib/wicd/' @@ -202,9 +219,9 @@ class configure(Command): self.ddistro = 'debian' elif os.path.exists('/etc/arch-release'): self.ddistro = 'arch' - elif os.path.exists('/etc/slackware-version') or \ - os.path.exists('/etc/slamd64-version') or \ - os.path.exists('/etc/bluewhite64-version'): + elif (os.path.exists('/etc/slackware-version') or + os.path.exists('/etc/slamd64-version') or + os.path.exists('/etc/bluewhite64-version')): self.ddistro = 'slackware' elif os.path.exists('/etc/pld-release'): self.ddistro = 'pld' @@ -214,12 +231,13 @@ class configure(Command): self.distro = 'lunar' else: self.ddistro = 'FAIL' - #self.no_install_init = True - #self.distro_detect_failed = True - print('WARNING: Unable to detect the distribution in use. ' + \ - 'If you have specified --distro or --init and --initfile, configure will continue. ' + \ - 'Please report this warning, along with the name of your ' + \ - 'distribution, to the wicd developers.') + # self.no_install_init = True + # self.distro_detect_failed = True + print('WARNING: Unable to detect the distribution in use.\n' + 'If you have specified --distro or --init and --initfile, ' + 'configure will continue.\nPlease report this warning, ' + 'along with the name of your distribution, to the wicd ' + 'developers.') # Try to get the pm-utils sleep hooks directory from pkg-config and # the kde prefix from kde-config @@ -228,33 +246,42 @@ class configure(Command): # If we don't get anything from *-config, or it didn't run properly, # or the path is not a proper absolute path, raise an error try: - pmtemp = subprocess.Popen(["pkg-config", "--variable=pm_sleephooks", + pmtemp = subprocess.Popen(["pkg-config", + "--variable=pm_sleephooks", "pm-utils"], stdout=subprocess.PIPE) - returncode = pmtemp.wait() # let it finish, and get the exit code - pmutils_candidate = str(pmtemp.stdout.readline().strip()) # read stdout + returncode = pmtemp.wait() # let it finish, and get the exit code + # read stdout + pmutils_candidate = str(pmtemp.stdout.readline().strip()) if len(pmutils_candidate) == 0 or returncode != 0 or \ not os.path.isabs(pmutils_candidate): raise ValueError else: self.pmutils = pmutils_candidate except (OSError, ValueError, FileNotFoundError): - pass # use our default + pass # use our default try: - kdetemp = subprocess.Popen(["kde-config","--prefix"], stdout=subprocess.PIPE) - returncode = kdetemp.wait() # let it finish, and get the exit code - kdedir_candidate = str(kdetemp.stdout.readline().strip()) # read stdout - if len(kdedir_candidate) == 0 or returncode != 0 or \ - not os.path.isabs(kdedir_candidate): + kdetemp = subprocess.Popen(["kde-config", "--prefix"], + stdout=subprocess.PIPE) + # let it finish, and get the exit code + returncode = kdetemp.wait() + # read stdout + kdedir_candidate = str(kdetemp.stdout.readline().strip()) + if (len(kdedir_candidate) == 0 or + returncode != 0 or + not os.path.isabs(kdedir_candidate)): raise ValueError else: self.kdedir = kdedir_candidate + '/share/autostart' except (OSError, ValueError, FileNotFoundError): # If kde-config isn't present, we'll check for kde-4.x try: - kde4temp = subprocess.Popen(["kde4-config","--prefix"], stdout=subprocess.PIPE) - returncode = kde4temp.wait() # let it finish, and get the exit code - kde4dir_candidate = str(kde4temp.stdout.readline().strip()) # read stdout + kde4temp = subprocess.Popen(["kde4-config", "--prefix"], + stdout=subprocess.PIPE) + # let it finish, and get the exit code + returncode = kde4temp.wait() + # read stdout + kde4dir_candidate = str(kde4temp.stdout.readline().strip()) if len(kde4dir_candidate) == 0 or returncode != 0 or \ not os.path.isabs(kde4dir_candidate): raise ValueError @@ -266,7 +293,7 @@ class configure(Command): # on the user's system self.no_install_kde = True # If the assumption above turns out to be wrong, do this: - #pass # use our default + # pass # use our default self.python = '/usr/bin/python3' self.pidfile = '/var/run/wicd/wicd.pid' @@ -309,11 +336,12 @@ class configure(Command): elif self.distro in ['crux']: self.init = '/etc/rc.d/' elif self.distro in ['lunar']: - self.init='/etc/init.d/' + self.init = '/etc/init.d/' self.initfile = 'init/lunar/wicd' - else : + else: if self.distro == 'auto': - print("NOTICE: Automatic distro detection found: " + self.ddistro + ", retrying with that...") + print("NOTICE: Automatic distro detection found: %s, retrying " + "with that..." % self.ddistro) self.distro = self.ddistro self.distro_check() else: @@ -321,13 +349,13 @@ class configure(Command): self.no_install_init = True self.distro_detect_failed = True - def finalize_options(self): self.distro_check() if self.distro_detect_failed and not self.no_install_init and \ 'FAIL' in [self.init, self.initfile]: - print('ERROR: Failed to detect distro. Configure cannot continue. ' + \ - 'Please specify --init and --initfile to continue with configuration.') + print('ERROR: Failed to detect distro. Configure cannot ' + 'continue.\nPlease specify --init and --initfile to ' + 'continue with configuration.') # loop through the argument definitions in user_options for argument in self.user_options: @@ -354,7 +382,8 @@ class configure(Command): cur_arg = argument[0][:-1] cur_arg_value = getattr(self, cur_arg.replace('-', '_')) print("%s is %s" % (cur_arg, cur_arg_value)) - values.append((cur_arg, getattr(self, cur_arg.replace('-','_')))) + values.append((cur_arg, getattr(self, cur_arg.replace('-', + '_')))) else: cur_arg = argument[0] cur_arg_value = getattr(self, cur_arg.replace('-', '_')) @@ -364,20 +393,21 @@ class configure(Command): print('Replacing values in template files...') for item in os.listdir('in'): if item.endswith('.in'): - print('Replacing values in',item, end=' ') - original_name = os.path.join('in',item) + print('Replacing values in', item, end=' ') + original_name = os.path.join('in', item) item_in = open(original_name, 'r') - final_name = item[:-3].replace('=','/') + final_name = item[:-3].replace('=', '/') parent_dir = os.path.dirname(final_name) if parent_dir and not os.path.exists(parent_dir): - print('(mkdir %s)'%parent_dir, end=' ') + print('(mkdir %s)' % parent_dir, end=' ') os.makedirs(parent_dir) print(final_name) item_out = open(final_name, 'w') for line in item_in.readlines(): for item, value in values: - line = line.replace('%' + str(item.upper().replace('-','_')) + \ - '%', str(value)) + line = line.replace('%' + str(item.upper()) + .replace('-', '_') + '%', + str(value)) # other things to replace that aren't arguments line = line.replace('%VERSION%', str(VERSION_NUM)) @@ -406,9 +436,9 @@ class clear_generated(Command): print('Removing completed template files...') for item in os.listdir('in'): if item.endswith('.in'): - print('Removing completed',item, end=' ') - original_name = os.path.join('in',item) - final_name = item[:-3].replace('=','/') + print('Removing completed', item, end=' ') + original_name = os.path.join('in', item) + final_name = item[:-3].replace('=', '/') print(final_name, '...', end=' ') if os.path.exists(final_name): os.remove(final_name) @@ -420,6 +450,7 @@ class clear_generated(Command): shutil.rmtree('translations/') os.makedirs('translations/') + class install(_install): def run(self): try: @@ -428,7 +459,7 @@ class install(_install): self.run_command('build') import wpath - print("Using init file",(wpath.init, wpath.initfile)) + print("Using init file", wpath.init, wpath.initfile) data.extend([ (wpath.dbus, ['other/wicd.conf']), (wpath.dbus_service, ['other/org.wicd.daemon.service']), @@ -437,12 +468,14 @@ class install(_install): (wpath.log, [empty_file]), (wpath.etc, ['other/dhclient.conf.template.default']), (wpath.encryption, [('encryption/templates/' + b) for b in - os.listdir('encryption/templates') if not b.startswith('.')]), + os.listdir('encryption/templates') + if not b.startswith('.')]), (wpath.networks, [empty_file]), (wpath.sbin, ['scripts/wicd']), (wpath.daemon, ['wicd/monitor.py', 'wicd/wicd-daemon.py', - 'wicd/suspend.py', 'wicd/autoconnect.py']), - (wpath.backends, ['wicd/backends/be-external.py', 'wicd/backends/be-ioctl.py']), + 'wicd/suspend.py', 'wicd/autoconnect.py']), + (wpath.backends, ['wicd/backends/be-external.py', + 'wicd/backends/be-ioctl.py']), (wpath.scripts, [empty_file]), (wpath.predisconnectscripts, [empty_file]), (wpath.postdisconnectscripts, [empty_file]), @@ -465,21 +498,22 @@ class install(_install): ])) data.append((wpath.autostart, ['other/wicd-tray.desktop'])) if not wpath.no_install_man: - data.append((wpath.mandir + 'man1/', [ 'man/wicd-client.1' ])) + data.append((wpath.mandir + 'man1/', ['man/wicd-client.1'])) for size in os.listdir('icons'): for category in os.listdir(os.path.join('icons', size)): imgdir = os.path.join('icons', size, category) - data.append( - (os.path.join(wpath.icons, size, category), - [(os.path.join(imgdir, f)) for f in os.listdir(imgdir) if not f.startswith('.')]) - ) + data.append((os.path.join(wpath.icons, size, category), + [(os.path.join(imgdir, f)) + for f in os.listdir(imgdir) + if not f.startswith('.')])) for size in os.listdir('images'): for category in os.listdir(os.path.join('images', size)): imgdir = os.path.join('images', size, category) - data.append( - (os.path.join(wpath.images, 'hicolor', size, category), - [(os.path.join(imgdir, f)) for f in os.listdir(imgdir) if not f.startswith('.')]) - ) + data.append((os.path.join(wpath.images, 'hicolor', size, + category), + [(os.path.join(imgdir, f)) + for f in os.listdir(imgdir) + if not f.startswith('.')])) data.append((wpath.pixmaps, ['other/wicd-gtk.xpm'])) if not wpath.no_install_gnome_shell_extensions: data.append( @@ -494,43 +528,51 @@ class install(_install): data.append((wpath.curses, ['curses/configscript_curses.py'])) data.append((wpath.bin, ['scripts/wicd-curses'])) if not wpath.no_install_man: - data.append(( wpath.mandir + 'man8/', ['man/wicd-curses.8'])) + data.append((wpath.mandir + 'man8/', ['man/wicd-curses.8'])) if not wpath.no_install_man and not wpath.no_install_i18n_man: - data.append(( wpath.mandir + 'nl/man8/', ['man/nl/wicd-curses.8'])) + data.append((wpath.mandir + 'nl/man8/', + ['man/nl/wicd-curses.8'])) if not wpath.no_install_docs: - data.append(( wpath.docdir, ['curses/README.curses'])) + data.append((wpath.docdir, ['curses/README.curses'])) if not wpath.no_install_cli: data.append((wpath.cli, ['cli/wicd-cli.py'])) data.append((wpath.bin, ['scripts/wicd-cli'])) if not wpath.no_install_man: - data.append(( wpath.mandir + 'man8/', ['man/wicd-cli.8'])) + data.append((wpath.mandir + 'man8/', ['man/wicd-cli.8'])) if not wpath.no_install_docs: - data.append(( wpath.docdir, ['cli/README.cli'])) + data.append((wpath.docdir, ['cli/README.cli'])) piddir = os.path.dirname(wpath.pidfile) if not piddir.endswith('/'): piddir += '/' if not wpath.no_install_docs: data.append((wpath.docdir, ['INSTALL', 'LICENSE', 'AUTHORS', - 'README', 'CHANGES', ])) + 'README', 'CHANGES', ])) data.append((wpath.varlib, ['other/WHEREAREMYFILES'])) if not wpath.no_install_kde: if not wpath.no_install_gtk: data.append((wpath.kdedir, ['other/wicd-tray.desktop'])) if not wpath.no_install_init: - data.append((wpath.init, [ wpath.initfile ])) + data.append((wpath.init, [wpath.initfile])) if not wpath.no_install_man: data.append((wpath.mandir + 'man8/', ['man/wicd.8'])) - data.append((wpath.mandir + 'man5/', ['man/wicd-manager-settings.conf.5'])) - data.append((wpath.mandir + 'man5/', ['man/wicd-wired-settings.conf.5'])) - data.append((wpath.mandir + 'man5/', ['man/wicd-wireless-settings.conf.5'])) + data.append((wpath.mandir + 'man5/', + ['man/wicd-manager-settings.conf.5'])) + data.append((wpath.mandir + 'man5/', + ['man/wicd-wired-settings.conf.5'])) + data.append((wpath.mandir + 'man5/', + ['man/wicd-wireless-settings.conf.5'])) data.append((wpath.mandir + 'man1/', ['man/wicd-client.1'])) if not wpath.no_install_man and not wpath.no_install_i18n_man: # Dutch translations of the man - data.append((wpath.mandir + 'nl/man8/', ['man/nl/wicd.8' ])) - data.append((wpath.mandir + 'nl/man5/', ['man/nl/wicd-manager-settings.conf.5'])) - data.append((wpath.mandir + 'nl/man5/', ['man/nl/wicd-wired-settings.conf.5'])) - data.append((wpath.mandir + 'nl/man5/', ['man/nl/wicd-wireless-settings.conf.5'])) - data.append((wpath.mandir + 'nl/man1/', ['man/nl/wicd-client.1'])) + data.append((wpath.mandir + 'nl/man8/', ['man/nl/wicd.8'])) + data.append((wpath.mandir + 'nl/man5/', + ['man/nl/wicd-manager-settings.conf.5'])) + data.append((wpath.mandir + 'nl/man5/', + ['man/nl/wicd-wired-settings.conf.5'])) + data.append((wpath.mandir + 'nl/man5/', + ['man/nl/wicd-wireless-settings.conf.5'])) + data.append((wpath.mandir + 'nl/man1/', + ['man/nl/wicd-client.1'])) if not wpath.no_install_acpi: data.append((wpath.resume, ['other/80-wicd-connect.sh'])) data.append((wpath.suspend, ['other/50-wicd-suspend.sh'])) @@ -543,11 +585,13 @@ class install(_install): language = language.replace('translations/', '') print(language, end=' ') data.append((wpath.translations + language + '/LC_MESSAGES/', - ['translations/' + language + '/LC_MESSAGES/wicd.mo'])) + ['translations/' + language + + '/LC_MESSAGES/wicd.mo'])) print() _install.run(self) + class test(Command): description = "run Wicd's unit tests" @@ -565,6 +609,7 @@ class test(Command): print('running tests') tests.run_tests() + class update_message_catalog(Command): description = "update wicd.pot with new strings" @@ -580,6 +625,7 @@ class update_message_catalog(Command): os.system('pybabel extract . -o po/wicd.pot --sort-output') os.system('xgettext -L glade data/wicd.ui -j -o po/wicd.pot') + class update_translations(Command): description = "update po-files with new strings from wicd.pot" @@ -594,7 +640,9 @@ class update_translations(Command): def run(self): for pofile in glob('po/*.po'): lang = pofile.replace('po/', '').replace('.po', '') - os.system('pybabel update -N -o %s -i po/wicd.pot -D wicd -l %s' % (pofile, lang)) + os.system('pybabel update -N -o %s -i po/wicd.pot -D wicd -l %s' % + (pofile, lang)) + class compile_translations(Command): description = 'compile po-files to binary mo' @@ -628,36 +676,44 @@ class compile_translations(Command): lang = pofile.replace('po/', '').replace('.po', '') compile_po = False try: - msgfmt = subprocess.Popen(['msgfmt', '--statistics', pofile, - '-o', '/dev/null'], stderr=subprocess.PIPE) - returncode = msgfmt.wait() # let it finish, and get the exit code + msgfmt = subprocess.Popen(['msgfmt', '--statistics', + pofile, '-o', '/dev/null'], + stderr=subprocess.PIPE) + # let it finish, and get the exit code + returncode = msgfmt.wait() output = msgfmt.stderr.readline().strip().decode('utf-8') if len(output) == 0 or returncode != 0: print(len(output), returncode) raise ValueError else: - m = re.match('(\d+) translated messages(?:, (\d+) fuzzy translation)?(?:, (\d+) untranslated messages)?.', output) + m = re.match(r'(\d+) translated messages(?:, (\d+) ' + r'fuzzy translation)?(?:, (\d+) ' + r'untranslated messages)?.', output) if m: done, fuzzy, missing = m.groups() fuzzy = int(fuzzy) if fuzzy else 0 missing = int(missing) if missing else 0 - completeness = float(done)/(int(done) + missing + fuzzy) + completeness = float(done)/(int(done) + missing + + fuzzy) if completeness >= self.threshold: compile_po = True else: - print('Disabled %s (%s%% < %s%%).' % \ - (lang, completeness*100, self.threshold*100)) + print('Disabled %s (%s%% < %s%%).' % + (lang, completeness*100, + self.threshold*100)) continue except (OSError, ValueError): print('ARGH') if compile_po: os.makedirs('translations/' + lang + '/LC_MESSAGES/') - os.system('pybabel compile -D wicd -i %s -l %s -d translations/' % (pofile, lang)) + os.system('pybabel compile -D wicd -i %s -l %s -d ' + 'translations/' % (pofile, lang)) os.environ['LANG'] = oldlang + class uninstall(Command): description = "remove Wicd using uninstall.sh and install.log" @@ -672,38 +728,35 @@ class uninstall(Command): def run(self): os.system("./uninstall.sh") -py_modules = ['wicd.networking','wicd.misc','wicd.wnettools', - 'wicd.wpath','wicd.dbusmanager', - 'wicd.logfile','wicd.backend','wicd.configmanager', - 'wicd.translations'] -setup( - cmdclass = { - 'build' : build, - 'configure' : configure, - 'install' : install, - 'uninstall' : uninstall, - 'test' : test, - 'clear_generated' : clear_generated, - 'update_message_catalog' : update_message_catalog, - 'update_translations' : update_translations, - 'compile_translations' : compile_translations, - }, - name = "wicd", - version = VERSION_NUM, - description = "A wireless and wired network manager", - long_description = """A complete network connection manager -Wicd supports wired and wireless networks, and capable of -creating and tracking profiles for both. It has a -template-based wireless encryption system, which allows the user -to easily add encryption methods used. It ships with some common -encryption types, such as WPA and WEP. Wicd will automatically -connect at startup to any preferred network within range. -""", - author = "Tom Van Braeckel, Adam Blackburn, Dan O'Reilly, Andrew Psaltis, David Paleino", - author_email = "tomvanbraeckel@gmail.com, compwiz18@gmail.com, oreilldf@gmail.com, ampsaltis@gmail.com, d.paleino@gmail.com", - url = "https://launchpad.net/wicd", - license = "http://www.gnu.org/licenses/old-licenses/gpl-2.0.html", - py_modules = py_modules, - data_files = data, -) +py_modules = ['wicd.networking', 'wicd.misc', 'wicd.wnettools', 'wicd.wpath', + 'wicd.dbusmanager', 'wicd.logfile', 'wicd.backend', + 'wicd.configmanager', 'wicd.translations'] + +setup(cmdclass={'build': build, + 'configure': configure, + 'install': install, + 'uninstall': uninstall, + 'test': test, + 'clear_generated': clear_generated, + 'update_message_catalog': update_message_catalog, + 'update_translations': update_translations, + 'compile_translations': compile_translations}, + name="wicd", + version=VERSION_NUM, + description="A wireless and wired network manager", + long_description="A complete network connection manager Wicd supports " + "wired and wireless networks, and capable of creating and tracking " + "profiles for both. It has a template-based wireless encryption system, " + "which allows the user to easily add encryption methods used. It ships " + "with some common encryption types, such as WPA and WEP. Wicd will " + "automatically connect at startup to any preferred network within " + "range.", + author="Tom Van Braeckel, Adam Blackburn, Dan O'Reilly, Andrew Psaltis, " + "David Paleino", + author_email="tomvanbraeckel@gmail.com, compwiz18@gmail.com, " + "oreilldf@gmail.com, ampsaltis@gmail.com, d.paleino@gmail.com", + url="https://launchpad.net/wicd", + license="http://www.gnu.org/licenses/old-licenses/gpl-2.0.html", + py_modules=py_modules, + data_files=data) diff --git a/tests/testmisc.py b/tests/testmisc.py index 4014dce..31198bb 100644 --- a/tests/testmisc.py +++ b/tests/testmisc.py @@ -4,6 +4,7 @@ import unittest from wicd import misc + class TestMisc(unittest.TestCase): def test_misc_run(self): output = misc.Run(['echo', 'hi']).strip() @@ -25,10 +26,12 @@ class TestMisc(unittest.TestCase): self.assertTrue(misc.IsValidIP('::1')) def test_valid_ip_6(self): - self.assertTrue(misc.IsValidIP('FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF')) + self.assertTrue(misc. + IsValidIP('FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF')) def test_valid_ip_7(self): - self.assertTrue(misc.IsValidIP('2001:0db8:85a3:0000:0000:8a2e:0370:7334')) + self.assertTrue(misc. + IsValidIP('2001:0db8:85a3:0000:0000:8a2e:0370:7334')) def test_invalid_ip_1(self): self.assertFalse(misc.IsValidIP('-10.0.-1.-1')) @@ -46,10 +49,12 @@ class TestMisc(unittest.TestCase): self.assertFalse(misc.IsValidIP('1:')) def test_invalid_ip_6(self): - self.assertFalse(misc.IsValidIP('ZZZZ:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF')) + self.assertFalse(misc. + IsValidIP('ZZZZ:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF')) def test_invalid_ip_7(self): - self.assertFalse(misc.IsValidIP('2001:0db8:85Z3:0000:0000:8a2e:0370:7334')) + self.assertFalse(misc. + IsValidIP('2001:0db8:85Z3:0000:0000:8a2e:0370:7334')) def test_run_valid_regex(self): import re @@ -72,7 +77,7 @@ class TestMisc(unittest.TestCase): def test_to_boolean_true(self): self.assertTrue(misc.to_bool('True')) - def test_to_boolean_true(self): + def test_to_boolean_true_int(self): self.assertTrue(misc.to_bool('1')) def test_noneify_1(self): @@ -137,7 +142,8 @@ class TestMisc(unittest.TestCase): self.assertEqual(misc.to_unicode('abcdef'), 'abcdef') def test_to_unicode_4(self): - self.assertEqual(type(misc.to_unicode('abcdef'.encode('latin-1'))), bytes) + self.assertEqual(type(misc.to_unicode('abcdef'.encode('latin-1'))), + bytes) def test_to_unicode_5(self): self.assertEqual(misc.to_unicode("berkåk"), "berkåk") @@ -163,13 +169,15 @@ class TestMisc(unittest.TestCase): def test_string_to_none_4(self): self.assertEqual(misc.stringToNone('abcdef'), 'abcdef') + def suite(): - suite = unittest.TestSuite() - tests = [] - [ tests.append(test) for test in dir(TestMisc) if test.startswith('test') ] - for test in tests: - suite.addTest(TestMisc(test)) - return suite + suite = unittest.TestSuite() + tests = [] + [tests.append(test) for test in dir(TestMisc) if test.startswith('test')] + for test in tests: + suite.addTest(TestMisc(test)) + return suite + if __name__ == '__main__': - unittest.main() + unittest.main() diff --git a/tests/testwnettools.py b/tests/testwnettools.py index c90956a..257226e 100644 --- a/tests/testwnettools.py +++ b/tests/testwnettools.py @@ -2,71 +2,78 @@ import unittest from unittest import mock from wicd import wnettools -class TestWnettools(unittest.TestCase): - def setUp(self): - self.interface = wnettools.BaseInterface('eth0') - - def test_find_wireless_interface(self): - interfaces = wnettools.GetWirelessInterfaces() - # wlan0 may change depending on your system - #self.assertTrue('wlan0' in interfaces) - self.assertTrue(type(interfaces) == list) - - @mock.patch('wicd.wnettools.os') - @mock.patch('wicd.wnettools.open') - def test_find_wired_interface(self, mock_f, mock_os): - mock_os.listdir.return_value = ['eth0'] - mock_os.path.isdir.return_value = True - mock_f.return_value.readlines.return_value = "1" - interfaces = wnettools.GetWiredInterfaces() - self.assertTrue('eth0' in interfaces) - - @mock.patch('wicd.misc.Run') - def test_wext_is_valid_wpasupplicant_driver(self, mock_syscall): - self.assertTrue(wnettools.IsValidWpaSuppDriver('wext')) - mock_syscall.assert_called_once() - - def test_needs_external_calls_not_implemented(self): - self.assertRaises(NotImplementedError, wnettools.NeedsExternalCalls) - - def test_is_up_boolean(self): - self.assertTrue(type(self.interface.IsUp()) == bool) - def test_enable_debug_mode(self): - self.interface.SetDebugMode(True) - self.assertTrue(self.interface.verbose) - - def test_disable_debug_mode(self): - self.interface.SetDebugMode(False) - self.assertFalse(self.interface.verbose) - - def test_interface_name_sanitation(self): - interface = wnettools.BaseInterface('blahblah; uptime > /tmp/blah | cat') - self.assertEqual(interface.iface, 'blahblahuptimetmpblahcat') - - def test_freq_translation_low(self): - freq = '2.412 GHz' - interface = wnettools.BaseWirelessInterface('wlan0') - self.assertEqual(interface._FreqToChannel(freq), 1) - - def test_freq_translation_high(self): - freq = '2.484 GHz' - interface = wnettools.BaseWirelessInterface('wlan0') - self.assertEqual(interface._FreqToChannel(freq), 14) - - def test_generate_psk(self): - interface = wnettools.BaseWirelessInterface('wlan0') - if 'wlan0' in wnettools.GetWirelessInterfaces(): - psk = interface.GeneratePSK({'essid' : 'Network 1', 'key' : 'arandompassphrase'}) - self.assertEqual(psk, 'd70463014514f4b4ebb8e3aebbdec13f4437ac3a9af084b3433f3710e658a7be') +class TestWnettools(unittest.TestCase): + def setUp(self): + self.interface = wnettools.BaseInterface('eth0') + + def test_find_wireless_interface(self): + interfaces = wnettools.GetWirelessInterfaces() + # wlan0 may change depending on your system + # self.assertTrue('wlan0' in interfaces) + self.assertTrue(type(interfaces) == list) + + @mock.patch('wicd.wnettools.os') + @mock.patch('wicd.wnettools.open') + def test_find_wired_interface(self, mock_f, mock_os): + mock_os.listdir.return_value = ['eth0'] + mock_os.path.isdir.return_value = True + mock_f.return_value.readlines.return_value = "1" + interfaces = wnettools.GetWiredInterfaces() + self.assertTrue('eth0' in interfaces) + + @mock.patch('wicd.misc.Run') + def test_wext_is_valid_wpasupplicant_driver(self, mock_syscall): + self.assertTrue(wnettools.IsValidWpaSuppDriver('wext')) + mock_syscall.assert_called_once() + + def test_needs_external_calls_not_implemented(self): + self.assertRaises(NotImplementedError, wnettools.NeedsExternalCalls) + + def test_is_up_boolean(self): + self.assertTrue(type(self.interface.IsUp()) == bool) + + def test_enable_debug_mode(self): + self.interface.SetDebugMode(True) + self.assertTrue(self.interface.verbose) + + def test_disable_debug_mode(self): + self.interface.SetDebugMode(False) + self.assertFalse(self.interface.verbose) + + def test_interface_name_sanitation(self): + interface = wnettools.BaseInterface('blahblah; uptime > /tmp/blah | ' + 'cat') + self.assertEqual(interface.iface, 'blahblahuptimetmpblahcat') + + def test_freq_translation_low(self): + freq = '2.412 GHz' + interface = wnettools.BaseWirelessInterface('wlan0') + self.assertEqual(interface._FreqToChannel(freq), 1) + + def test_freq_translation_high(self): + freq = '2.484 GHz' + interface = wnettools.BaseWirelessInterface('wlan0') + self.assertEqual(interface._FreqToChannel(freq), 14) + + def test_generate_psk(self): + interface = wnettools.BaseWirelessInterface('wlan0') + if 'wlan0' in wnettools.GetWirelessInterfaces(): + psk = interface.GeneratePSK({'essid': 'Network 1', + 'key': 'arandompassphrase'}) + self.assertEqual(psk, 'd70463014514f4b4ebb8e3aebbdec13f4437ac3a9a' + 'f084b3433f3710e658a7be') + def suite(): - suite = unittest.TestSuite() - tests = [] - [ tests.append(test) for test in dir(TestWnettools) if test.startswith('test') ] - for test in tests: - suite.addTest(TestWnettools(test)) - return suite + suite = unittest.TestSuite() + tests = [] + [tests.append(test) for test in dir(TestWnettools) + if test.startswith('test')] + for test in tests: + suite.addTest(TestWnettools(test)) + return suite + if __name__ == '__main__': - unittest.main() + unittest.main() diff --git a/wicd/__init__.py b/wicd/__init__.py index 9b51119..322d432 100644 --- a/wicd/__init__.py +++ b/wicd/__init__.py @@ -1 +1 @@ -""" WICD core module. """ +"""WICD core module.""" diff --git a/wicd/autoconnect.py b/wicd/autoconnect.py index 7e35878..22cc52a 100644 --- a/wicd/autoconnect.py +++ b/wicd/autoconnect.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 -""" autoconnect -- Triggers an automatic connection attempt. """ +"""autoconnect -- Triggers an automatic connection attempt.""" # # Copyright (C) 2007 - 2009 Adam Blackburn @@ -18,19 +18,18 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . # - -from wicd import dbusmanager +import sys +import time import dbus -import time -import sys - if getattr(dbus, 'version', (0, 0, 0)) < (0, 80, 0): import dbus.glib else: from dbus.mainloop.glib import DBusGMainLoop DBusGMainLoop(set_as_default=True) +from wicd import dbusmanager + try: dbusmanager.connect_to_dbus() daemon = dbusmanager.get_interface('daemon') @@ -40,20 +39,24 @@ except Exception as e: print('Could not connect to daemon.', file=sys.stderr) sys.exit(1) + def handler(*args): - """ No-op handler. """ + """No-op handler.""" pass + + def error_handler(*args): - """ Error handler. """ + """Error handler.""" print('Async error autoconnecting.', file=sys.stderr) sys.exit(3) + if __name__ == '__main__': try: time.sleep(2) daemon.SetSuspend(False) if not daemon.CheckIfConnecting(): - daemon.AutoConnect(True, reply_handler=handler, + daemon.AutoConnect(True, reply_handler=handler, error_handler=error_handler) except Exception as e: print("Exception caught: %s" % str(e), file=sys.stderr) diff --git a/wicd/backend.py b/wicd/backend.py index cbfa0d3..3c96b10 100644 --- a/wicd/backend.py +++ b/wicd/backend.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 -""" Backend manager for wicd. +"""Backend manager for wicd. Manages and loads the pluggable backends for wicd. @@ -29,57 +29,58 @@ import os import wicd.wpath as wpath + def fail(backend_name, reason): - """ Helper to warn the user about failure in loading backend. """ + """Helper to warn the user about failure in loading backend.""" print(("Failed to load backend %s: %s" % (backend_name, reason))) return True class BackendManager(object): - """ Manages, validates, and loads wicd backends. """ + """Manages, validates, and loads wicd backends.""" def __init__(self): - """ Initialize the backend manager. """ + """Initialize the backend manager.""" self.backend_dir = wpath.backends self.__loaded_backend = None def _valid_backend_file(self, be_file): - """ Make sure the backend file is valid. """ - return (os.path.exists(be_file) and + """Make sure the backend file is valid.""" + return (os.path.exists(be_file) and os.path.basename(be_file).startswith("be-") and be_file.endswith(".py")) - + def get_current_backend(self): - """ Returns the name of the loaded backend. """ + """Returns the name of the loaded backend.""" if self.__loaded_backend: return self.__loaded_backend.NAME else: return None - + def get_available_backends(self): - """ Returns a list of all valid backends in the backend directory. """ + """Returns a list of all valid backends in the backend directory.""" be_list = [] for f in os.listdir(self.backend_dir): if self._valid_backend_file(os.path.join(self.backend_dir, f)): be_list.append(f[3:-3]) return be_list or [""] - + def get_update_interval(self): - """ Returns how often in seconds the wicd monitor should update. """ + """Returns how often in seconds the wicd monitor should update.""" if self.__loaded_backend: return self.__loaded_backend.UPDATE_INTERVAL else: return None - + def get_backend_description(self, backend_name): - """ Loads a backend and returns its description. """ + """Loads a backend and returns its description.""" backend = self._load_backend(backend_name) if backend and backend.DESCRIPTION: return backend.DESCRIPTION else: return "No backend data available" - + def _load_backend(self, backend_name): - """ Imports a backend and returns the loaded module. """ + """Imports a backend and returns the loaded module.""" print(('trying to load backend %s' % backend_name)) backend_path = os.path.join(self.backend_dir, 'be-' + backend_name + '.py') @@ -90,9 +91,9 @@ class BackendManager(object): else: fail(backend_name, 'Invalid backend file.') return None - + def _validate_backend(self, backend, backend_name): - """ Ensures that a backend module is valid. """ + """Ensures that a backend module is valid.""" failed = False if not backend.NAME: failed = fail(backend_name, 'Missing NAME attribute.') @@ -105,20 +106,20 @@ class BackendManager(object): if not backend.WirelessInterface: failed = fail(backend_name, "Missing WirelessInterface class.") return failed - + def load_backend(self, backend_name): - """ Load and return a backend module. - + """Load and return a backend module. + Given a backend name be-foo, attempt to load a python module in the backends directory called be-foo.py. The module must include a certain set of classes and variables to be considered valid. - + """ backend = self._load_backend(backend_name) if not backend: return None - + failed = self._validate_backend(backend, backend_name) if failed: return None diff --git a/wicd/backends/__init__.py b/wicd/backends/__init__.py index e3b4204..9032cd8 100644 --- a/wicd/backends/__init__.py +++ b/wicd/backends/__init__.py @@ -1 +1 @@ -""" Backends module. """ +"""Backends module.""" diff --git a/wicd/backends/be-external.py b/wicd/backends/be-external.py index 61e2fb4..8b4679d 100644 --- a/wicd/backends/be-external.py +++ b/wicd/backends/be-external.py @@ -29,9 +29,15 @@ class WirelessInterface() -- Control a wireless network interface. # along with this program. If not, see . # -from wicd.wnettools import GetDefaultGateway, GetWiredInterfaces, \ -GetWirelessInterfaces, IsValidWpaSuppDriver, BaseWirelessInterface, \ -BaseWiredInterface, BaseInterface, GetWpaSupplicantDrivers +from wicd.wnettools import BaseInterface +from wicd.wnettools import BaseWiredInterface +from wicd.wnettools import BaseWirelessInterface +from wicd.wnettools import GetDefaultGateway +from wicd.wnettools import GetWiredInterfaces +from wicd.wnettools import GetWirelessInterfaces +from wicd.wnettools import GetWpaSupplicantDrivers +from wicd.wnettools import IsValidWpaSuppDriver + NAME = "external" UPDATE_INTERVAL = 5 @@ -46,14 +52,14 @@ more stable for some set ups. def NeedsExternalCalls(*args, **kargs): - """ Return True, since this backend uses iwconfig/ifconfig. """ + """Return True, since this backend uses iwconfig/ifconfig.""" return True class Interface(BaseInterface): - """ Control a network interface. """ + """Control a network interface.""" def __init__(self, iface, verbose=False): - """ Initialize the object. + """Initialize the object. Keyword arguments: iface -- the name of the interface @@ -62,12 +68,12 @@ class Interface(BaseInterface): """ BaseInterface.__init__(self, iface, verbose) self.Check() - + class WiredInterface(Interface, BaseWiredInterface): - """ Control a wired network interface. """ + """Control a wired network interface.""" def __init__(self, iface, verbose=False): - """ Initialise the wired network interface class. + """Initialise the wired network interface class. Keyword arguments: iface -- name of the interface @@ -79,9 +85,9 @@ class WiredInterface(Interface, BaseWiredInterface): class WirelessInterface(Interface, BaseWirelessInterface): - """ Control a wireless network interface. """ + """Control a wireless network interface.""" def __init__(self, iface, verbose=False, wpa_driver='wext'): - """ Initialise the wireless network interface class. + """Initialise the wireless network interface class. Keyword arguments: iface -- name of the interface diff --git a/wicd/backends/be-ioctl.py b/wicd/backends/be-ioctl.py index 6dd24c7..79a6d9a 100644 --- a/wicd/backends/be-ioctl.py +++ b/wicd/backends/be-ioctl.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- -""" ioctl Network interface control tools for wicd. +"""ioctl Network interface control tools for wicd. This module implements functions to control and obtain information from network interfaces. It utilizes ioctl calls and python modules to @@ -30,18 +30,33 @@ class WirelessInterface() -- Control a wireless network interface. # along with this program. If not, see . # +import array +import fcntl +import os +import socket +import struct +import time + from wicd import misc from wicd import wpath -from wicd.wnettools import GetDefaultGateway, GetWiredInterfaces, \ -GetWirelessInterfaces, IsValidWpaSuppDriver, BaseWirelessInterface, \ -BaseWiredInterface, BaseInterface, GetWpaSupplicantDrivers, wep_pattern, \ -signaldbm_pattern, neediface +from wicd.wnettools import BaseInterface +from wicd.wnettools import BaseWiredInterface +from wicd.wnettools import BaseWirelessInterface +from wicd.wnettools import GetDefaultGateway +from wicd.wnettools import GetWiredInterfaces +from wicd.wnettools import GetWirelessInterfaces +from wicd.wnettools import GetWpaSupplicantDrivers +from wicd.wnettools import IsValidWpaSuppDriver +from wicd.wnettools import neediface +from wicd.wnettools import signaldbm_pattern +from wicd.wnettools import wep_pattern try: import iwscan IWSCAN_AVAIL = True except ImportError: - print("WARNING: python-iwscan not found, falling back to using iwlist scan.") + print("WARNING: python-iwscan not found, falling back to using iwlist " + "scan.") IWSCAN_AVAIL = False try: import wpactrl @@ -50,14 +65,6 @@ except ImportError: print("WARNING: python-wpactrl not found, falling back to using wpa_cli.") WPACTRL_AVAIL = False -import re -import os -import time -import socket -import fcntl -import struct -import array - NAME = "ioctl" UPDATE_INTERVAL = 4 @@ -90,7 +97,7 @@ SIOCGIFFLAGS = 0x8913 def get_iw_ioctl_result(iface, call): - """ Makes the given ioctl call and returns the results. + """Makes the given ioctl call and returns the results. Keyword arguments: call -- The ioctl call to make @@ -112,15 +119,16 @@ def get_iw_ioctl_result(iface, call): return None return buff.tostring() + def NeedsExternalCalls(*args, **kargs): - """ Return False, since this backend doesn't use any external apps. """ + """Return False, since this backend doesn't use any external apps.""" return False class Interface(BaseInterface): - """ Control a network interface. """ + """Control a network interface.""" def __init__(self, iface, verbose=False): - """ Initialise the object. + """Initialise the object. Keyword arguments: iface -- the name of the interface @@ -132,13 +140,13 @@ class Interface(BaseInterface): self.Check() def CheckWirelessTools(self): - """ Check for the existence needed wireless tools """ + """Check for the existence needed wireless tools""" if not WPACTRL_AVAIL: BaseInterface.CheckWirelessTools(self) @neediface("") def GetIP(self, ifconfig=""): - """ Get the IP address of the interface. + """Get the IP address of the interface. Returns: The IP address of the interface in dotted quad form. @@ -156,7 +164,7 @@ class Interface(BaseInterface): @neediface(False) def IsUp(self, ifconfig=None): - """ Determines if the interface is up. + """Determines if the interface is up. Returns: True if the interface is up, False otherwise. @@ -175,9 +183,9 @@ class Interface(BaseInterface): class WiredInterface(Interface, BaseWiredInterface): - """ Control a wired network interface. """ + """Control a wired network interface.""" def __init__(self, iface, verbose=False): - """ Initialise the wired network interface class. + """Initialise the wired network interface class. Keyword arguments: iface -- name of the interface @@ -189,7 +197,7 @@ class WiredInterface(Interface, BaseWiredInterface): @neediface(False) def GetPluggedIn(self): - """ Get the current physical connection state. + """Get the current physical connection state. The method will first attempt to use ethtool do determine physical connection state. Should ethtool fail to run properly, @@ -201,7 +209,8 @@ class WiredInterface(Interface, BaseWiredInterface): """ if self.ethtool_cmd and self.link_detect in [misc.ETHTOOL, misc.AUTO]: return self._eth_get_plugged_in() - elif self.miitool_cmd and self.link_detect in [misc.MIITOOL, misc.AUTO]: + elif self.miitool_cmd and self.link_detect in [misc.MIITOOL, + misc.AUTO]: return self._mii_get_plugged_in() else: print(('Error: No way of checking for a wired connection. Make' + @@ -209,7 +218,7 @@ class WiredInterface(Interface, BaseWiredInterface): return False def _eth_get_plugged_in(self): - """ Use ethtool to determine the physical connection state. + """Use ethtool to determine the physical connection state. Returns: True if a link is detected, False otherwise. @@ -231,7 +240,7 @@ class WiredInterface(Interface, BaseWiredInterface): return bool(buff.tolist()[1]) def _mii_get_plugged_in(self): - """ Use mii-tool to determine the physical connection state. + """Use mii-tool to determine the physical connection state. Returns: True if a link is detected, False otherwise. @@ -253,25 +262,24 @@ class WiredInterface(Interface, BaseWiredInterface): class WirelessInterface(Interface, BaseWirelessInterface): - """ Control a wireless network interface. """ + """Control a wireless network interface.""" def __init__(self, iface, verbose=False, wpa_driver='wext'): - """ Initialise the wireless network interface class. + """Initialise the wireless network interface class. Keyword arguments: iface -- name of the interface verbose -- print all commands """ - BaseWirelessInterface.__init__(self, iface, verbose, - wpa_driver) + BaseWirelessInterface.__init__(self, iface, verbose, wpa_driver) Interface.__init__(self, iface, verbose) self.scan_iface = None self.CheckWirelessTools() @neediface([]) def GetNetworks(self, essid=None): - """ Get a list of available wireless networks. - + """Get a list of available wireless networks. + NOTE: the essid parameter is not used here, it was added for the iwlist scan for hidden networks. @@ -282,7 +290,7 @@ class WirelessInterface(Interface, BaseWirelessInterface): if not IWSCAN_AVAIL: # Use the slow version if python-iwscan isn't available. return BaseWirelessInterface.GetNetworks(self) - + if not self.scan_iface: try: self.scan_iface = iwscan.WirelessInterface(self.iface) @@ -298,7 +306,7 @@ class WirelessInterface(Interface, BaseWirelessInterface): return [_f for _f in [self._parse_ap(cell) for cell in results] if _f] def _parse_ap(self, cell): - """ Parse a single cell from the python-iwscan list. """ + """Parse a single cell from the python-iwscan list.""" ap = {} try: ap['essid'] = misc.to_unicode(cell['essid']) @@ -306,7 +314,7 @@ class WirelessInterface(Interface, BaseWirelessInterface): print('Unicode problem with the current network essid, ignoring!!') return None - if ap['essid'] in [ "", '']: + if ap['essid'] in ["", '']: ap['essid'] = '' ap['hidden'] = True else: @@ -344,13 +352,14 @@ class WirelessInterface(Interface, BaseWirelessInterface): # quality displayed or it isn't found) if misc.RunRegex(signaldbm_pattern, cell["stats"]): ap['strength'] = misc.RunRegex(signaldbm_pattern, cell["stats"]) - elif self.wpa_driver != RALINK_DRIVER: # This is already set for ralink - ap['strength'] = -1 + # This is already set for ralink + elif self.wpa_driver != RALINK_DRIVER: + ap['strength'] = -1 return ap def _connect_to_wpa_ctrl_iface(self): - """ Connect to the wpa ctrl interface. """ + """Connect to the wpa ctrl interface.""" ctrl_iface = '/var/run/wpa_supplicant' socket_loc = os.path.join(ctrl_iface, self.iface) if os.path.exists(socket_loc): @@ -360,12 +369,12 @@ class WirelessInterface(Interface, BaseWirelessInterface): print(("Couldn't open ctrl_interface: %s" % e)) return None else: - print(("Couldn't find a wpa_supplicant ctrl_interface for iface %s" \ - % self.iface)) + print(f"Couldn't find a wpa_supplicant ctrl_interface for iface " + f"{self.iface}") return None def ValidateAuthentication(self, auth_time): - """ Validate WPA authentication. + """Validate WPA authentication. Validate that the wpa_supplicant authentication process was successful. @@ -384,8 +393,9 @@ class WirelessInterface(Interface, BaseWirelessInterface): """ if not WPACTRL_AVAIL: # If we don't have python-wpactrl, use the slow version. - return BaseWirelessInterface.ValidateAuthentication(self, auth_time) - + return BaseWirelessInterface.ValidateAuthentication(self, + auth_time) + # Right now there's no way to do this for ralink drivers if self.wpa_driver == RALINK_DRIVER: return True @@ -401,16 +411,16 @@ class WirelessInterface(Interface, BaseWirelessInterface): while (time.time() - auth_time) < MAX_TIME: try: status = wpa.request("STATUS").split("\n") - except: + except Exception: print("wpa_supplicant status query failed.") return False if self.verbose: - print(('wpa_supplicant ctrl_interface status query is %s' \ - % str(status))) + print(f'wpa_supplicant ctrl_interface status query is ' + f'{status}') try: - [result] = [l for l in status if l.startswith("wpa_state=")] + [result] = [s for s in status if s.startswith("wpa_state=")] except ValueError: return False @@ -431,7 +441,7 @@ class WirelessInterface(Interface, BaseWirelessInterface): @neediface(False) def StopWPA(self): - """ Terminates wpa_supplicant using its ctrl interface. """ + """Terminates wpa_supplicant using its ctrl interface.""" if not WPACTRL_AVAIL: return BaseWirelessInterface.StopWPA(self) wpa = self._connect_to_wpa_ctrl_iface() @@ -440,7 +450,7 @@ class WirelessInterface(Interface, BaseWirelessInterface): wpa.request("TERMINATE") def _AuthenticateRalinkLegacy(self, network): - """ Authenticate with the specified wireless network. + """Authenticate with the specified wireless network. This function handles Ralink legacy cards that cannot use wpa_supplicant. @@ -449,58 +459,60 @@ class WirelessInterface(Interface, BaseWirelessInterface): network -- dictionary containing network info """ - if network.get('key') != None: - lines = self._GetRalinkInfo() - for x in lines: - info = x.split() - if len(info) < 5: - break - if info[2] == network.get('essid'): - if info[5] == 'WEP' or (info[5] == 'OPEN' and \ - info[4] == 'WEP'): + if network.get('key') is None: + return + + lines = self._GetRalinkInfo() + for x in lines: + info = x.split() + if len(info) < 5: + break + if info[2] == network.get('essid'): + if info[5] == 'WEP' or (info[5] == 'OPEN' and + info[4] == 'WEP'): + print('Setting up WEP') + cmd = ''.join(['iwconfig ', self.iface, ' key ', + network.get('key')]) + if self.verbose: + print(cmd) + misc.Run(cmd) + else: + if info[5] == 'SHARED' and info[4] == 'WEP': print('Setting up WEP') - cmd = ''.join(['iwconfig ', self.iface, ' key ', - network.get('key')]) + auth_mode = 'SHARED' + key_name = 'Key1' + elif info[5] == 'WPA-PSK': + print('Setting up WPA-PSK') + auth_mode = 'WPAPSK' + key_name = 'WPAPSK' + elif info[5] == 'WPA2-PSK': + print('Setting up WPA2-PSK') + auth_mode = 'WPA2PSK' + key_name = 'WPAPSK' + else: + print("Unknown AuthMode, can\'t complete connection " + "process!") + return + + cmd_list = [] + cmd_list.append('NetworkType=' + info[6]) + cmd_list.append('AuthMode=' + auth_mode) + cmd_list.append('EncrypType=' + info[4]) + cmd_list.append('SSID=' + info[2]) + cmd_list.append(key_name + '=' + network.get('key')) + if info[5] == 'SHARED' and info[4] == 'WEP': + cmd_list.append('DefaultKeyID=1') + cmd_list.append('SSID=' + info[2]) + + for cmd in cmd_list: + cmd = 'iwpriv ' + self.iface + ' ' if self.verbose: print(cmd) misc.Run(cmd) - else: - if info[5] == 'SHARED' and info[4] == 'WEP': - print('Setting up WEP') - auth_mode = 'SHARED' - key_name = 'Key1' - elif info[5] == 'WPA-PSK': - print('Setting up WPA-PSK') - auth_mode = 'WPAPSK' - key_name = 'WPAPSK' - elif info[5] == 'WPA2-PSK': - print('Setting up WPA2-PSK') - auth_mode = 'WPA2PSK' - key_name = 'WPAPSK' - else: - print(('Unknown AuthMode, can\'t complete ' + \ - 'connection process!')) - return - - cmd_list = [] - cmd_list.append('NetworkType=' + info[6]) - cmd_list.append('AuthMode=' + auth_mode) - cmd_list.append('EncrypType=' + info[4]) - cmd_list.append('SSID=' + info[2]) - cmd_list.append(key_name + '=' + network.get('key')) - if info[5] == 'SHARED' and info[4] == 'WEP': - cmd_list.append('DefaultKeyID=1') - cmd_list.append('SSID=' + info[2]) - - for cmd in cmd_list: - cmd = 'iwpriv ' + self.iface + ' ' - if self.verbose: - print(cmd) - misc.Run(cmd) @neediface("") def GetBSSID(self, iwconfig=None): - """ Get the MAC address for the interface. """ + """Get the MAC address for the interface.""" data = (self.iface + '\0' * 32)[:32] try: result = fcntl.ioctl(self.sock.fileno(), SIOCGIWAP, data)[16:] @@ -513,7 +525,7 @@ class WirelessInterface(Interface, BaseWirelessInterface): @neediface("") def GetCurrentBitrate(self, iwconfig=None): - """ Get the current bitrate for the interface. """ + """Get the current bitrate for the interface.""" data = (self.iface + '\0' * 32)[:32] fmt = "ihbb" size = struct.calcsize(fmt) @@ -526,19 +538,19 @@ class WirelessInterface(Interface, BaseWirelessInterface): f, e, x, x = struct.unpack(fmt, result[:size]) return "%s %s" % ((f / 1000000), 'Mb/s') - #def GetOperationalMode(self, iwconfig=None): - # """ Get the operational mode for the interface. """ - # TODO: implement me - # return '' + # def GetOperationalMode(self, iwconfig=None): + # """ Get the operational mode for the interface.""" + # TODO: implement me + # return '' - #def GetAvailableAuthMethods(self, iwlistauth=None): - # """ Get the authentication methods for the interface. """ - # TODO: Implement me - # return '' + # def GetAvailableAuthMethods(self, iwlistauth=None): + # """ Get the authentication methods for the interface.""" + # TODO: Implement me + # return '' @neediface(-1) def GetSignalStrength(self, iwconfig=None): - """ Get the signal strength of the current network. + """Get the signal strength of the current network. Returns: The signal strength. @@ -555,7 +567,7 @@ class WirelessInterface(Interface, BaseWirelessInterface): return None def _get_max_strength(self): - """ Gets the maximum possible strength from the wireless driver. """ + """Gets the maximum possible strength from the wireless driver.""" buff = array.array('c', '\0' * 700) addr, length = buff.buffer_info() arg = struct.pack('Pi', addr, length) @@ -576,7 +588,7 @@ class WirelessInterface(Interface, BaseWirelessInterface): @neediface(-100) def GetDBMStrength(self, iwconfig=None): - """ Get the dBm signal strength of the current network. + """Get the dBm signal strength of the current network. Returns: The dBm signal strength. @@ -590,7 +602,7 @@ class WirelessInterface(Interface, BaseWirelessInterface): @neediface("") def GetCurrentNetwork(self, iwconfig=None): - """ Get the essid of the current network. + """Get the essid of the current network. Returns: The current network essid. diff --git a/wicd/configmanager.py b/wicd/configmanager.py index 59b912e..a8c689a 100644 --- a/wicd/configmanager.py +++ b/wicd/configmanager.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 -""" configmanager -- Wicd configuration file manager +"""configmanager -- Wicd configuration file manager Wrapper around ConfigParser for wicd, though it should be reusable for other purposes as well. @@ -25,17 +25,18 @@ reusable for other purposes as well. # along with this program. If not, see . # -import sys, os - -from configparser import RawConfigParser, ParsingError import codecs - -from wicd.misc import Noneify, to_unicode +import configparser +import os +import sys from dbus import Int32 +from wicd.misc import Noneify, to_unicode + + def sanitize_config_file(path): - """ Remove invalid lines from config file. """ + """Remove invalid lines from config file.""" conf = open(path) newconf = '' for line in conf: @@ -46,10 +47,11 @@ def sanitize_config_file(path): conf.write(newconf) conf.close() -class ConfigManager(RawConfigParser): - """ A class that can be used to manage a given configuration file. """ + +class ConfigManager(configparser.RawConfigParser): + """A class that can be used to manage a given configuration file.""" def __init__(self, path, debug=False, mark_whitespace="`'`"): - RawConfigParser.__init__(self) + configparser.RawConfigParser.__init__(self) self.config_file = path self.debug = debug self.mrk_ws = mark_whitespace @@ -57,55 +59,55 @@ class ConfigManager(RawConfigParser): sanitize_config_file(path) try: self.read(path) - except ParsingError: + except configparser.ParsingError: self.write() try: self.read(path) - except ParsingError as p: + except configparser.ParsingError as p: print(("Could not start wicd: %s" % p.message)) sys.exit(1) def __repr__(self): return self.config_file - + def __str__(self): return self.config_file - + def get_config(self): - """ Returns the path to the loaded config file. """ + """Returns the path to the loaded config file.""" return self.config_file - + def set_option(self, section, option, value, write=False): - """ Wrapper around ConfigParser.set + """Wrapper around ConfigParser.set Adds the option to write the config file change right away. Also forces all the values being written to type str, and adds the section the option should be written to if it doesn't exist already. - + """ if not self.has_section(section): self.add_section(section) if isinstance(value, str): value = to_unicode(value) if value.startswith(' ') or value.endswith(' '): - value = "%(ws)s%(value)s%(ws)s" % {"value" : value, - "ws" : self.mrk_ws} - RawConfigParser.set(self, section, str(option), value) + value = "%(ws)s%(value)s%(ws)s" % {"value": value, + "ws": self.mrk_ws} + configparser.RawConfigParser.set(self, section, str(option), value) if write: self.write() def set(self, *args, **kargs): - """ Calls the set_option method. """ + """Calls the set_option method.""" self.set_option(*args, **kargs) - + def get_option(self, section, option, default="__None__"): - """ Wrapper around ConfigParser.get. - + """Wrapper around ConfigParser.get. + Automatically adds any missing sections, adds the ability to write a default value, and if one is provided prints if the default or a previously saved value is returned. - + """ if not self.has_section(section): if default != "__None__": @@ -114,31 +116,29 @@ class ConfigManager(RawConfigParser): return None if self.has_option(section, option): - ret = RawConfigParser.get(self, section, option) - if (isinstance(ret, str) and ret.startswith(self.mrk_ws) - and ret.endswith(self.mrk_ws)): + ret = configparser.RawConfigParser.get(self, section, option) + if (isinstance(ret, str) and ret.startswith(self.mrk_ws) + and ret.endswith(self.mrk_ws)): ret = ret[3:-3] ret = to_unicode(ret) if default: if self.debug: # mask out sensitive information - if option in ['apsk', 'password', 'identity', \ - 'private_key', 'private_key_passwd', \ + if option in ['apsk', 'password', 'identity', + 'private_key', 'private_key_passwd', 'key', 'passphrase']: - print((''.join(['found ', option, \ - ' in configuration *****']))) + print(f'found {option} in configuration *****') else: - print((''.join(['found ', option, ' in configuration ', - str(ret)]))) - else: # Use the default, unless no default was provided + print(f'found {option} in configuration {ret}') + else: # Use the default, unless no default was provided if default != "__None__": - print(('did not find %s in configuration, setting default %s' \ - % (option, str(default)))) + print(f'did not find {option} in configuration, setting ' + f'default {default}') self.set(section, option, str(default), write=True) ret = default else: ret = None - + # Try to intelligently handle the type of the return value. try: if not ret.startswith('0') or len(ret) == 1: @@ -152,52 +152,53 @@ class ConfigManager(RawConfigParser): except OverflowError: ret = str(ret) return to_unicode(ret) - + def get(self, *args, **kargs): - """ Calls the get_option method """ + """Calls the get_option method""" return self.get_option(*args, **kargs) - + def _write_one(self): - """ Writes the loaded config file to disk. """ + """Writes the loaded config file to disk.""" for section in self.sections(): if not section: self.remove_section(section) configfile = open(self.config_file, 'w') - RawConfigParser.write(self, configfile) + configparser.RawConfigParser.write(self, configfile) configfile.close() - + def remove_section(self, section): - """ Wrapper around the ConfigParser.remove_section() method. - + """Wrapper around the ConfigParser.remove_section() method. + This method only calls the ConfigParser.remove_section() method if the section actually exists. - + """ if self.has_section(section): - RawConfigParser.remove_section(self, section) - + configparser.RawConfigParser.remove_section(self, section) + def reload(self): - """ Re-reads the config file, in case it was edited out-of-band. """ + """Re-reads the config file, in case it was edited out-of-band.""" self.read(self.config_file) def read(self, path): - """ Reads the config file specified by 'path' then reads all the + """Reads the config file specified by 'path' then reads all the files in the directory obtained by adding '.d' to 'path'. The files in the '.d' directory are read in normal sorted order and section entries in these files override entries in the main file. """ if os.path.exists(path): - RawConfigParser.readfp(self, codecs.open(path, 'r', 'utf-8')) + configparser.RawConfigParser.readfp(self, codecs.open(path, 'r', + 'utf-8')) path_d = path + ".d" files = [] if os.path.exists(path_d): - files = [ os.path.join(path_d, f) for f in os.listdir(path_d) ] + files = [os.path.join(path_d, f) for f in os.listdir(path_d)] files.sort() for fname in files: - p = RawConfigParser() + p = configparser.RawConfigParser() p.readfp(codecs.open(fname, 'r', 'utf-8')) for section_name in p.sections(): # New files override old, so remove first to avoid @@ -209,9 +210,8 @@ class ConfigManager(RawConfigParser): # Store the filename this section was read from. self.set(section_name, '_filename_', fname) - def _copy_section(self, name): - """ Copy whole section from config file. """ + """Copy whole section from config file.""" p = ConfigManager("", self.debug, self.mrk_ws) p.add_section(name) for (iname, value) in self.items(name): @@ -222,7 +222,7 @@ class ConfigManager(RawConfigParser): return p def write(self, fp=None): - """ Writes the loaded config file to disk. """ + """Writes the loaded config file to disk.""" in_this_file = [] for sname in sorted(self.sections()): fname = self.get_option(sname, '_filename_') @@ -243,4 +243,3 @@ class ConfigManager(RawConfigParser): p.set(sname, iname, value) p.remove_option(sname, '_filename_') p._write_one() - diff --git a/wicd/dbusmanager.py b/wicd/dbusmanager.py index 18a4c5a..567d9c3 100644 --- a/wicd/dbusmanager.py +++ b/wicd/dbusmanager.py @@ -1,6 +1,4 @@ -#!/usr/bin/env python3 - -""" The wicd DBus Manager. +"""The wicd DBus Manager. A module for managing wicd's dbus interfaces. @@ -29,74 +27,81 @@ if getattr(dbus, "version", (0, 0, 0)) < (0, 80, 0): else: from dbus.mainloop.glib import DBusGMainLoop DBusGMainLoop(set_as_default=True) - + DBUS_MANAGER = None - + + def get_dbus_ifaces(): - """ Return available DBus interfaces. """ + """Return available DBus interfaces.""" return DBUS_MANAGER.get_dbus_ifaces() + def get_interface(iface): - """ Return specified interface. """ + """Return specified interface.""" return DBUS_MANAGER.get_interface(iface) + def get_bus(): - """ Return the loaded System Bus. """ + """Return the loaded System Bus.""" return DBUS_MANAGER.get_bus() + def set_mainloop(loop): - """ Set DBus main loop. """ + """Set DBus main loop.""" return DBUS_MANAGER.set_mainloop(loop) + def connect_to_dbus(): - """ Connect to DBus. """ + """Connect to DBus.""" return DBUS_MANAGER.connect_to_dbus() + def threads_init(): - """ Init GLib threads. """ + """Init GLib threads.""" dbus.mainloop.glib.threads_init() class DBusManager(object): - """ Manages the DBus objects used by wicd. """ + """Manages the DBus objects used by wicd.""" def __init__(self): self._bus = dbus.SystemBus() - self._dbus_ifaces = {} - + self._dbus_ifaces = {} + def get_dbus_ifaces(self): - """ Returns a dict of dbus interfaces. """ + """Returns a dict of dbus interfaces.""" if not self._dbus_ifaces: connect_to_dbus() return self._dbus_ifaces - + def get_interface(self, iface): - """ Returns a DBus Interface. """ + """Returns a DBus Interface.""" if not self._dbus_ifaces: connect_to_dbus() return self._dbus_ifaces[iface] - + def get_bus(self): - """ Returns the loaded SystemBus. """ + """Returns the loaded SystemBus.""" return self._bus - + def set_mainloop(self, loop): - """ Set DBus main loop. """ + """Set DBus main loop.""" dbus.set_default_main_loop(loop) - + def connect_to_dbus(self): - """ Connects to wicd's dbus interfaces and loads them into a dict. """ + """Connects to wicd's dbus interfaces and loads them into a dict.""" proxy_obj = self._bus.get_object("org.wicd.daemon", '/org/wicd/daemon') daemon = dbus.Interface(proxy_obj, 'org.wicd.daemon') - + proxy_obj = self._bus.get_object("org.wicd.daemon", '/org/wicd/daemon/wireless') wireless = dbus.Interface(proxy_obj, 'org.wicd.daemon.wireless') - + proxy_obj = self._bus.get_object("org.wicd.daemon", '/org/wicd/daemon/wired') wired = dbus.Interface(proxy_obj, 'org.wicd.daemon.wired') - - self._dbus_ifaces = {"daemon" : daemon, "wireless" : wireless, - "wired" : wired} - + + self._dbus_ifaces = {"daemon": daemon, "wireless": wireless, + "wired": wired} + + DBUS_MANAGER = DBusManager() diff --git a/wicd/logfile.py b/wicd/logfile.py index effe0e1..95f0deb 100644 --- a/wicd/logfile.py +++ b/wicd/logfile.py @@ -1,5 +1,12 @@ -#!/usr/bin/env python3 +""" +Managing logfile rotation. A ManagedLog object is a file-like object that +rotates itself when a maximum size is reached. + +TODO(gryf): how about using standard logging module and let the log rotating +to system tools like logrotate? + +""" # # Copyright (C) 1999-2006 Keith Dart # Copyright (C) 2008-2009 Dan O'Reilly @@ -14,28 +21,23 @@ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. -""" - -Managing logfile rotation. A ManagedLog object is a file-like object that -rotates itself when a maximum size is reached. - -""" - -import sys -import os -import time import io +import os +import sys +import time + class SizeError(IOError): - """ Custom error class. """ + """Custom error class.""" pass + class LogFile(io.FileIO): """LogFile(name, [mode="w"], [maxsize=360000]) - + Opens a new file object. After writing bytes a SizeError will be raised. - + """ def __init__(self, name, mode="a", maxsize=360000, *args, **kwargs): super(LogFile, self).__init__(name, mode, maxsize, *args, **kwargs) @@ -48,29 +50,32 @@ class LogFile(io.FileIO): def write(self, data): self.written += len(data) - + + # TODO(gryf): revisit need for encode/decode madness data = data.encode('utf-8') if len(data) <= 0: return + if self.eol: - super(LogFile, self).write(self.get_time().encode("utf-8") + b' :: ') + super(LogFile, self).write(self.get_time().encode("utf-8") + + b' :: ') self.eol = False if data[-1] == '\n': self.eol = True data = data[:-1] - super(LogFile, self).write(data.replace( - b'\n', b'\n' + self.get_time().encode("utf-8") + b' :: ')) + super(LogFile, self).write(data.replace(b'\n', b'\n' + self.get_time() + .encode("utf-8") + b' :: ')) if self.eol: super(LogFile, self).write('\n') - + self.flush() if self.written > self.maxsize: raise SizeError - + def get_time(self): - """ Return a string with the current time nicely formatted. + """Return a string with the current time nicely formatted. The format of the returned string is yyyy/mm/dd HH:MM:SS @@ -82,21 +87,21 @@ class LogFile(io.FileIO): str(x[4]).rjust(2, '0'), ':', str(x[5]).rjust(2, '0')]) def rotate(self): - """ Rotate logfile. """ + """Rotate logfile.""" return rotate(self) def note(self, text): """Writes a specially formated note text to the file. - + The note starts with the string '\\n#*=' so you can easily filter them. - + """ self.write("\n#*===== %s =====\n" % (text,)) class ManagedLog(object): """ManagedLog(name, [maxsize=360000], [maxsave=9]) - + A ManagedLog instance is a persistent log object. Write data with the write() method. The log size and rotation is handled automatically. @@ -108,29 +113,29 @@ class ManagedLog(object): self.maxsave = maxsave def __repr__(self): - return "%s(%r, %r, %r)" % (self.__class__.__name__, self._lf.name, + return "%s(%r, %r, %r)" % (self.__class__.__name__, self._lf.name, self._lf.maxsize, self.maxsave) def write(self, data): - """ Write logfile. """ + """Write logfile.""" try: self._lf.write(data) except SizeError: self._lf = rotate(self._lf, self.maxsave) def note(self, data): - """ Write a note to the logfile. """ + """Write a note to the logfile.""" try: self._lf.note(data) except SizeError: self._lf = rotate(self._lf, self.maxsave) def written(self): - """ Return whether the logfile was written. """ + """Return whether the logfile was written.""" return self._lf.written def rotate(self): - """ Rotate logfile. """ + """Rotate logfile.""" self._lf = rotate(self._lf, self.maxsave) # auto-delegate remaining methods (but you should not read or seek an open @@ -141,9 +146,9 @@ class ManagedLog(object): # useful for logged stdout for daemon processes class ManagedStdio(ManagedLog): - """ Manage stdout/stderr. """ + """Manage stdout/stderr.""" def write(self, data): - """ Write logfile to disk. """ + """Write logfile to disk.""" try: self._lf.write(data) except SizeError: @@ -157,7 +162,7 @@ class ManagedStdio(ManagedLog): def rotate(fileobj, maxsave=9): - """ Rotate fileobj. """ + """Rotate fileobj.""" name = fileobj.name mode = fileobj.mode maxsize = fileobj.maxsize @@ -168,7 +173,7 @@ def rotate(fileobj, maxsave=9): # assumes basename logfile is closed. def shiftlogs(basename, maxsave): - """ Shift logfiles. """ + """Shift logfiles.""" topname = "%s.%d" % (basename, maxsave) if os.path.isfile(topname): os.unlink(topname) @@ -187,11 +192,12 @@ def shiftlogs(basename, maxsave): def open(name, maxsize=360000, maxsave=9): - """ Open logfile. """ + """Open logfile.""" return ManagedLog(name, maxsize, maxsave) + def writelog(logobj, data): - """ Write logfile. """ + """Write logfile.""" try: logobj.write(data) except SizeError: diff --git a/wicd/misc.py b/wicd/misc.py index cd72a2b..108ad18 100644 --- a/wicd/misc.py +++ b/wicd/misc.py @@ -1,4 +1,4 @@ -""" misc - miscellaneous functions for wicd +"""misc - miscellaneous functions for wicd This module contains a large variety of utility functions used throughout wicd. @@ -22,23 +22,24 @@ throughout wicd. # along with this program. If not, see . # -import os -import locale -import sys -import re -import string -from gi.repository import GLib as gobject -from threading import Thread -from subprocess import Popen, STDOUT, PIPE, call -from subprocess import getoutput from itertools import repeat, chain +import locale +import os +import re from pipes import quote import socket +import string +from subprocess import Popen, STDOUT, PIPE, call +from subprocess import getoutput +import sys +from threading import Thread + +from gi.repository import GLib as gobject from wicd.translations import _ # wicd imports -from . import wpath +from wicd import wpath # Connection state constants NOT_CONNECTED = 0 @@ -46,13 +47,11 @@ CONNECTING = 1 WIRELESS = 2 WIRED = 3 SUSPENDED = 4 -_const_status_dict = { - NOT_CONNECTED: _('Not connected'), - CONNECTING: _('Connection in progress'), - WIRELESS: _('Connected to a wireless network'), - WIRED: _('Connected to a wired network'), - SUSPENDED: _('Connection suspended'), -} +_const_status_dict = {NOT_CONNECTED: _('Not connected'), + CONNECTING: _('Connection in progress'), + WIRELESS: _('Connected to a wireless network'), + WIRED: _('Connected to a wired network'), + SUSPENDED: _('Connection suspended')} # Automatic app selection constant AUTO = 0 @@ -75,17 +74,15 @@ ROUTE = 2 GKSUDO = 1 KDESU = 2 KTSUSS = 3 -_sudo_dict = { - AUTO : "", - GKSUDO : "gksudo", - KDESU : "kdesu", - KTSUSS: "ktsuss", -} +_sudo_dict = {AUTO: "", + GKSUDO: "gksudo", + KDESU: "kdesu", + KTSUSS: "ktsuss"} _status_dict = { 'aborted': _('Connection Cancelled'), - 'association_failed': _('Connection failed: Could not contact the ' + \ - 'wireless access point.'), + 'association_failed': _('Connection failed: Could not contact the ' + 'wireless access point.'), 'bad_pass': _('Connection Failed: Bad password'), 'configuring_interface': _('Configuring wireless interface...'), 'dhcp_failed': _('Connection Failed: Unable to Get IP Address'), @@ -107,14 +104,15 @@ _status_dict = { 'verifying_association': _('Verifying access point association...'), } + class WicdError(Exception): - """ Custom Exception type. """ + """Custom Exception type.""" pass - + def Run(cmd, include_stderr=False, return_pipe=False, return_obj=False, return_retcode=True): - """ Run a command. + """Run a command. Runs the given command, returning either the output of the program, or a pipe to read output from. @@ -144,34 +142,35 @@ def Run(cmd, include_stderr=False, return_pipe=False, std_in = PIPE else: std_in = None - + # We need to make sure that the results of the command we run # are in English, so we set up a temporary environment. tmpenv = os.environ.copy() tmpenv["LC_ALL"] = "C" tmpenv["LANG"] = "C" - + try: f = Popen(cmd, shell=False, stdout=PIPE, stdin=std_in, stderr=err, close_fds=fds, cwd='/', env=tmpenv) except OSError as e: print(("Running command %s failed: %s" % (str(cmd), str(e)))) return "" - + if return_obj: return f if return_pipe: return f.stdout else: return f.communicate()[0].decode() - + + def LaunchAndWait(cmd): - """ Launches the given program with the given arguments, then blocks. + """Launches the given program with the given arguments, then blocks. cmd : A list contained the program name and its arguments. returns: The exit code of the process. - + """ if not isinstance(cmd, list): cmd = to_unicode(str(cmd)) @@ -179,8 +178,9 @@ def LaunchAndWait(cmd): p = Popen(cmd, shell=False, stdout=PIPE, stderr=STDOUT, stdin=None) return p.wait() + def IsValidIP(ip): - """ Make sure an entered IP is valid. """ + """Make sure an entered IP is valid.""" if not ip: return False @@ -189,6 +189,7 @@ def IsValidIP(ip): return False return True + def IsValidIPv4(ip): ''' Make sure an entered IP is a valid IPv4. ''' try: @@ -197,6 +198,7 @@ def IsValidIPv4(ip): return False return True + def IsValidIPv6(ip): ''' Make sure an entered IP is a valid IPv6. ''' try: @@ -205,8 +207,9 @@ def IsValidIPv6(ip): return False return True + def PromptToStartDaemon(): - """ Prompt the user to start the daemon """ + """Prompt the user to start the daemon""" daemonloc = wpath.sbin + 'wicd' sudo_prog = choose_sudo_prog() if not sudo_prog: @@ -215,26 +218,29 @@ def PromptToStartDaemon(): msg = '--message' else: msg = '--caption' - sudo_args = [sudo_prog, msg, + sudo_args = [sudo_prog, msg, _("Wicd needs to access your computer's network cards."), daemonloc] os.spawnvpe(os.P_WAIT, sudo_prog, sudo_args, os.environ) return True + def RunRegex(regex, s): - """ runs a regex search on a string """ + """runs a regex search on a string""" m = regex.search(s) if m: return m.groups()[0] else: return None + def WriteLine(my_file, text): - """ write a line to a file """ + """write a line to a file""" my_file.write(text + "\n") + def ExecuteScripts(scripts_dir, verbose=False, extra_parameters=()): - """ Execute every executable file in a given directory. """ + """Execute every executable file in a given directory.""" if not os.path.exists(scripts_dir): return for obj in sorted(os.listdir(scripts_dir)): @@ -245,9 +251,10 @@ def ExecuteScripts(scripts_dir, verbose=False, extra_parameters=()): ExecuteScript(os.path.abspath(obj), verbose=verbose, extra_parameters=extra_parameters) + def ExecuteScript(script, verbose=False, extra_parameters=()): - """ Execute a command and send its output to the bit bucket. """ - extra_parameters = [ quote(s) for s in extra_parameters ] + """Execute a command and send its output to the bit bucket.""" + extra_parameters = [quote(s) for s in extra_parameters] params = ' '.join(extra_parameters) # escape script name script = quote(script) @@ -257,26 +264,29 @@ def ExecuteScript(script, verbose=False, extra_parameters=()): if verbose: print(("%s returned %s" % (script, ret))) + def ReadFile(filename): - """ read in a file and return it's contents as a string """ + """read in a file and return it's contents as a string""" if not os.path.exists(filename): return None - my_file = open(filename,'r') + my_file = open(filename, 'r') data = my_file.read().strip() my_file.close() return str(data) + def to_bool(var): - """ Convert a string to type bool, but make "False"/"0" become False. """ + """Convert a string to type bool, but make "False"/"0" become False.""" if var in ("False", "0"): var = False else: var = bool(var) return var + def Noneify(variable, convert_to_bool=True): - """ Convert string types to either None or booleans""" - #set string Nones to real Nones + """Convert string types to either None or booleans""" + # set string Nones to real Nones if variable in ("None", "", None): return None if convert_to_bool: @@ -287,8 +297,9 @@ def Noneify(variable, convert_to_bool=True): return True return variable + def ParseEncryption(network): - """ Parse through an encryption template file + """Parse through an encryption template file Parses an encryption template, reading in a network's info and creating a config file for it @@ -309,8 +320,8 @@ def ParseEncryption(network): if line.strip().startswith("}"): # This is the last line, so we just write it. config_file = ''.join([config_file, line]) - elif "$_" in line: - for cur_val in re.findall('\$_([A-Z0-9_]+)', line): + elif "$_" in line: + for cur_val in re.findall(r'\$_([A-Z0-9_]+)', line): if cur_val: rep_val = network.get(cur_val.lower()) if not rep_val: @@ -329,7 +340,7 @@ def ParseEncryption(network): else: # Just a regular entry. config_file = ''.join([config_file, line]) - # Write the data to the files then chmod them so they can't be read + # Write the data to the files then chmod them so they can't be read # by normal users. if network.get('bssid'): file_name = network['bssid'].replace(":", "").lower() @@ -344,8 +355,9 @@ def ParseEncryption(network): f.write(config_file) f.close() -def LoadEncryptionMethods(wired = False): - """ Load encryption methods from configuration files + +def LoadEncryptionMethods(wired=False): + """Load encryption methods from configuration files Loads all the encryption methods from the template files in /encryption/templates into a data structure. To be @@ -357,11 +369,11 @@ def LoadEncryptionMethods(wired = False): else: active_fname = "active" try: - enctypes = open(wpath.encryption + active_fname,"r").readlines() + enctypes = open(wpath.encryption + active_fname, "r").readlines() except IOError as e: print("Fatal Error: template index file is missing.") raise IOError(e) - + # Parse each encryption method encryptionTypes = [] for enctype in enctypes: @@ -370,6 +382,7 @@ def LoadEncryptionMethods(wired = False): encryptionTypes.append(parsed_template) return encryptionTypes + def __parse_field_ent(fields, field_type='require'): fields = fields.split(" ") ret = [] @@ -383,8 +396,9 @@ def __parse_field_ent(fields, field_type='require'): ret.append([val, disp_val[1:]]) return ret + def _parse_enc_template(enctype): - """ Parse an encryption template. """ + """Parse an encryption template.""" def parse_ent(line, key): return line.replace(key, "").replace("=", "").strip() @@ -405,10 +419,12 @@ def _parse_enc_template(enctype): if line.startswith("name") and not cur_type["name"]: cur_type["name"] = parse_ent(line, "name") elif line.startswith("require"): - cur_type["required"] = __parse_field_ent(parse_ent(line, "require")) + cur_type["required"] = __parse_field_ent(parse_ent(line, + "require")) if not cur_type["required"]: # An error occured parsing the require line. - print(("Invalid 'required' line found in template %s" % enctype)) + print("Invalid 'required' line found in template %s" % + enctype) continue elif line.startswith("optional"): cur_type["optional"] = __parse_field_ent(parse_ent(line, @@ -416,32 +432,34 @@ def _parse_enc_template(enctype): field_type="optional") if not cur_type["optional"]: # An error occured parsing the optional line. - print(("Invalid 'optional' line found in template %s" % enctype)) + print("Invalid 'optional' line found in template %s" % + enctype) continue elif line.startswith("protected"): - cur_type["protected"] = __parse_field_ent( - parse_ent(line, "protected"), - field_type="protected" - ) + cur_type["protected"] = __parse_field_ent(parse_ent(line, + "protected"), + field_type="protected") if not cur_type["protected"]: # An error occured parsing the protected line. - print(("Invalid 'protected' line found in template %s" % enctype)) + print("Invalid 'protected' line found in template %s" % + enctype) continue elif line.startswith("----"): # We're done. break f.close() if not cur_type["required"]: - print(("Failed to find a 'require' line in template %s" % enctype)) + print("Failed to find a 'require' line in template %s" % enctype) return None if not cur_type["name"]: - print(("Failed to find a 'name' line in template %s" % enctype)) + print("Failed to find a 'name' line in template %s" % enctype) return None else: return cur_type + def noneToString(text): - """ Convert None, "None", or "" to string type "None" + """Convert None, "None", or "" to string type "None" Used for putting text in a text box. If the value to put in is 'None', the box will be blank. @@ -452,8 +470,9 @@ def noneToString(text): else: return to_unicode(text) + def sanitize_config(s): - """ Sanitize property names to be used in config-files. """ + """Sanitize property names to be used in config-files.""" allowed = string.ascii_letters + '_' + string.digits table = string.maketrans(allowed, ' ' * len(allowed)) @@ -461,20 +480,22 @@ def sanitize_config(s): # make it simple. return s.encode('ascii', 'replace').translate(None, table) + def sanitize_escaped(s): - """ Sanitize double-escaped unicode strings. """ + """Sanitize double-escaped unicode strings.""" lastpos = -1 while True: lastpos = s.find('\\x', lastpos + 1) - #print lastpos + # print lastpos if lastpos == -1: break c = s[lastpos+2:lastpos+4] # i.e. get the next two characters s = s.replace('\\x'+c, chr(int(c, 16))) return s + def to_unicode(x): - """ Attempts to convert a string to utf-8. """ + """Attempts to convert a string to utf-8.""" # If this is a unicode string, encode it and return if not isinstance(x, bytes): return x @@ -495,11 +516,12 @@ def to_unicode(x): ret = x.decode('latin-1').encode('utf-8') except UnicodeError: ret = x.decode('utf-8', 'replace').encode('utf-8') - + return ret - + + def RenameProcess(new_name): - """ Renames the process calling the function to the given name. """ + """Renames the process calling the function to the given name.""" if 'linux' not in sys.platform: print('Unsupported platform') return False @@ -509,16 +531,17 @@ def RenameProcess(new_name): libc = ctypes.CDLL(find_library('c')) libc.prctl(15, new_name, 0, 0, 0) return True - except: + except Exception: print("rename failed") return False - + + def detect_desktop_environment(): - """ Try to determine which desktop environment is in use. - + """Try to determine which desktop environment is in use. + Choose between kde, gnome, or xfce based on environment variables and a call to xprop. - + """ desktop_environment = 'generic' if os.environ.get('KDE_FULL_SESSION') == 'true': @@ -534,8 +557,9 @@ def detect_desktop_environment(): pass return desktop_environment + def get_sudo_cmd(msg, prog_num=0): - """ Returns a graphical sudo command for generic use. """ + """Returns a graphical sudo command for generic use.""" sudo_prog = choose_sudo_prog(prog_num) if not sudo_prog: return None @@ -545,34 +569,36 @@ def get_sudo_cmd(msg, prog_num=0): msg_flag = "--caption" return [sudo_prog, msg_flag, msg] + def choose_sudo_prog(prog_num=0): - """ Try to intelligently decide which graphical sudo program to use. """ + """Try to intelligently decide which graphical sudo program to use.""" if prog_num: return find_path(_sudo_dict[prog_num]) desktop_env = detect_desktop_environment() env_path = os.environ['PATH'].split(":") paths = [] - + if desktop_env == "kde": progs = ["kdesu", "kdesudo", "ktsuss"] else: progs = ["gksudo", "gksu", "ktsuss"] - + for prog in progs: paths.extend([os.path.join(p, prog) for p in env_path]) - + for path in paths: if os.path.exists(path): return path return "" + def find_path(cmd): - """ Try to find a full path for a given file name. - + """Try to find a full path for a given file name. + Search the all the paths in the environment variable PATH for the given file name, or return None if a full path for the file can not be found. - + """ paths = os.getenv("PATH").split(':') if not paths: @@ -583,28 +609,32 @@ def find_path(cmd): return os.path.join(path, cmd) return None + def noneToBlankString(text): - """ Converts NoneType or "None" to a blank string. """ + """Converts NoneType or "None" to a blank string.""" if text in (None, "None"): return "" else: return str(text) + def stringToNone(text): - """ Performs opposite function of noneToString. """ + """Performs opposite function of noneToString.""" if text in ("", None, "None"): return None else: return str(text) + def checkboxTextboxToggle(checkbox, textboxes): - """ Manage {de,}activation of textboxes depending on checkboxes. """ + """Manage {de,}activation of textboxes depending on checkboxes.""" # FIXME: should be moved to UI-specific files? for textbox in textboxes: textbox.set_sensitive(checkbox.get_active()) + def threaded(f): - """ A decorator that will make any function run in a new thread. """ + """A decorator that will make any function run in a new thread.""" def wrapper(*args, **kwargs): t = Thread(target=f, args=args, kwargs=kwargs) @@ -618,8 +648,9 @@ def threaded(f): return wrapper + def timeout_add(time, func, milli=False): - """ Convience function for running a function on a timer. """ + """Convience function for running a function on a timer.""" if hasattr(gobject, "timeout_add_seconds") and not milli: return gobject.timeout_add_seconds(time, func) else: @@ -627,16 +658,19 @@ def timeout_add(time, func, milli=False): time = time * 1000 return gobject.timeout_add(time, func) + def izip_longest(*args, **kwds): - """ Implement the itertools.izip_longest method. - + """Implement the itertools.izip_longest method. + We implement the method here because its new in Python 2.6. - + """ # izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D- fillvalue = kwds.get('fillvalue') - def sentinel(counter = ([fillvalue]*(len(args)-1)).pop): - yield counter() # yields the fillvalue, or raises IndexError + + def sentinel(counter=([fillvalue]*(len(args)-1)).pop): + yield counter() # yields the fillvalue, or raises IndexError + fillers = repeat(fillvalue) iters = [chain(it, sentinel(), fillers) for it in args] try: @@ -645,8 +679,9 @@ def izip_longest(*args, **kwds): except IndexError: pass + def grouper(n, iterable, fillvalue=None): - """ Iterate over several elements at once + """Iterate over several elements at once "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" diff --git a/wicd/monitor.py b/wicd/monitor.py index 4fed8fa..0a3f48b 100644 --- a/wicd/monitor.py +++ b/wicd/monitor.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 -""" monitor -- connection monitoring process +"""monitor -- connection monitoring process This process is spawned as a child of the daemon, and is responsible for monitoring connection status and initiating autoreconnection @@ -24,9 +24,9 @@ when appropriate. # along with this program. If not, see . # -from gi.repository import GLib as gobject import time +from gi.repository import GLib as gobject from dbus import DBusException from wicd import wpath @@ -46,6 +46,7 @@ wireless = dbus_dict["wireless"] mainloop = None + def diewithdbus(func): """ Decorator catching DBus exceptions, making wicd quit. @@ -67,12 +68,13 @@ def diewithdbus(func): wrapper.__name__ = func.__name__ wrapper.__dict__ = func.__dict__ wrapper.__doc__ = func.__doc__ - return wrapper + return wrapper + class ConnectionStatus(object): - """ Class for monitoring the computer's connection status. """ + """Class for monitoring the computer's connection status.""" def __init__(self): - """ Initialize variables needed for the connection status methods. """ + """Initialize variables needed for the connection status methods.""" self.last_strength = -2 self.last_state = misc.NOT_CONNECTED self.last_reconnect_time = time.time() @@ -90,22 +92,22 @@ class ConnectionStatus(object): self.__lost_dbus_count = 0 self._to_time = daemon.GetBackendUpdateInterval() self.update_callback = None - + self.add_poll_callback() bus = dbusmanager.get_bus() - bus.add_signal_receiver(self._force_update_connection_status, + bus.add_signal_receiver(self._force_update_connection_status, "UpdateState", "org.wicd.daemon") bus.add_signal_receiver(self._update_timeout_interval, "SignalBackendChanged", "org.wicd.daemon") def _update_timeout_interval(self, interval): - """ Update the callback interval when signaled by the daemon. """ + """Update the callback interval when signaled by the daemon.""" self._to_time = interval gobject.source_remove(self.update_callback) self.add_poll_callback() def _force_update_connection_status(self): - """ Run a connection status update on demand. + """Run a connection status update on demand. Removes the scheduled update_connection_status() call, explicitly calls the function, and reschedules @@ -115,18 +117,18 @@ class ConnectionStatus(object): gobject.source_remove(self.update_callback) self.update_connection_status() self.add_poll_callback() - + def add_poll_callback(self): - """ Registers a polling call at a predetermined interval. - + """Registers a polling call at a predetermined interval. + The polling interval is determined by the backend in use. - + """ self.update_callback = misc.timeout_add(self._to_time, self.update_connection_status) - + def check_for_wired_connection(self, wired_ip): - """ Checks for a wired connection. + """Checks for a wired connection. Checks for two states: 1) A wired connection is not in use, but a cable is plugged @@ -150,20 +152,20 @@ class ConnectionStatus(object): return True # Wired connection isn't active elif wired_ip and self.still_wired: - # If we still have an IP, but no cable is plugged in + # If we still have an IP, but no cable is plugged in # we should disconnect to clear it. wired.DisconnectWired() self.still_wired = False return False def check_for_wireless_connection(self, wireless_ip): - """ Checks for an active wireless connection. + """Checks for an active wireless connection. Checks for an active wireless connection. Also notes if the signal strength is 0, and if it remains there for too long, triggers a wireless disconnect. - Returns True if wireless connection is active, and + Returns True if wireless connection is active, and False otherwise. """ @@ -197,17 +199,17 @@ class ConnectionStatus(object): self.connection_lost_counter = 0 if (wifi_signal != self.last_strength or - self.network != self.last_network): + self.network != self.last_network): self.last_strength = wifi_signal self.last_network = self.network self.signal_changed = True - daemon.SetCurrentInterface(daemon.GetWirelessInterface()) + daemon.SetCurrentInterface(daemon.GetWirelessInterface()) return True @diewithdbus def update_connection_status(self): - """ Updates the tray icon and current connection status. + """Updates the tray icon and current connection status. Determines the current connection state and sends a dbus signal announcing when the status changes. Also starts the automatic @@ -253,8 +255,8 @@ class ConnectionStatus(object): if not daemon.GetGUIOpen(): print('Killing wireless connection to switch to wired...') wireless.DisconnectWireless() - daemon.AutoConnect(False, reply_handler=lambda *a:None, - error_handler=lambda *a:None) + daemon.AutoConnect(False, reply_handler=lambda *a: None, + error_handler=lambda *a: None) return self.update_state(misc.NOT_CONNECTED) return self.update_state(misc.WIRELESS, wifi_ip=wifi_ip) @@ -267,7 +269,7 @@ class ConnectionStatus(object): return self.update_state(state) def update_state(self, state, wired_ip=None, wifi_ip=None): - """ Set the current connection state. """ + """Set the current connection state.""" # Set our connection state/info. iwconfig = self.iwconfig if state == misc.NOT_CONNECTED: @@ -278,15 +280,18 @@ class ConnectionStatus(object): if wired.CheckIfWiredConnecting(): info = ["wired"] else: - info = ["wireless", - misc.noneToBlankString(wireless.GetCurrentNetwork(iwconfig))] + info = ["wireless", misc. + noneToBlankString(wireless. + GetCurrentNetwork(iwconfig))] elif state == misc.WIRELESS: self.reconnect_tries = 0 info = [str(wifi_ip), - misc.noneToBlankString(wireless.GetCurrentNetwork(iwconfig)), - str(self._get_printable_sig_strength()), - str(wireless.GetCurrentNetworkID(iwconfig)), - misc.noneToBlankString(wireless.GetCurrentBitrate(iwconfig))] + misc.noneToBlankString(wireless. + GetCurrentNetwork(iwconfig)), + str(self._get_printable_sig_strength()), + str(wireless.GetCurrentNetworkID(iwconfig)), + misc.noneToBlankString(wireless. + GetCurrentBitrate(iwconfig))] elif state == misc.WIRED: self.reconnect_tries = 0 info = [str(wired_ip)] @@ -297,12 +302,12 @@ class ConnectionStatus(object): daemon.SetConnectionStatus(state, info) # Send a D-Bus signal announcing status has changed if necessary. - if (state != self.last_state or (state == misc.WIRELESS and + if (state != self.last_state or (state == misc.WIRELESS and self.signal_changed)): daemon.EmitStatusChanged(state, info) - if (state != self.last_state) and (state == misc.NOT_CONNECTED) and \ - (not daemon.GetForcedDisconnect()): + if (state != self.last_state and state == misc.NOT_CONNECTED and + not daemon.GetForcedDisconnect()): daemon.Disconnect() # Disconnect() sets forced disconnect = True # so we'll revert that @@ -311,7 +316,7 @@ class ConnectionStatus(object): return True def _get_printable_sig_strength(self, always_positive=False): - """ Get the correct signal strength format. """ + """Get the correct signal strength format.""" try: if daemon.GetSignalDisplayType() == 0: signal = wireless.GetCurrentSignalStrength(self.iwconfig) @@ -327,12 +332,12 @@ class ConnectionStatus(object): else: wifi_signal = int(signal) except TypeError: - wifi_signal = 0 + wifi_signal = 0 return wifi_signal def auto_reconnect(self, from_wireless=None): - """ Automatically reconnects to a network if needed. + """Automatically reconnects to a network if needed. If automatic reconnection is turned on, this method will attempt to first reconnect to the last used wireless network, and @@ -344,7 +349,7 @@ class ConnectionStatus(object): # Some checks to keep reconnect retries from going crazy. if (self.reconnect_tries > 3 and - (time.time() - self.last_reconnect_time) < 200): + (time.time() - self.last_reconnect_time) < 200): print("Throttling autoreconnect") return @@ -364,24 +369,26 @@ class ConnectionStatus(object): # before we reconnect print('Disconnecting from network') wireless.DisconnectWireless() - print(('Trying to reconnect to last used wireless ' + \ - 'network')) + print('Trying to reconnect to last used wireless network') wireless.ConnectWireless(cur_net_id) else: daemon.AutoConnect(True, reply_handler=reply_handle, error_handler=err_handle) self.reconnecting = False + def reply_handle(): - """ Just a dummy function needed for asynchronous dbus calls. """ + """Just a dummy function needed for asynchronous dbus calls.""" pass + def err_handle(error): - """ Just a dummy function needed for asynchronous dbus calls. """ + """Just a dummy function needed for asynchronous dbus calls.""" pass + def main(): - """ Starts the connection monitor. + """Starts the connection monitor. Starts a ConnectionStatus instance, sets the status to update an amount of time determined by the active backend. diff --git a/wicd/networking.py b/wicd/networking.py index fda9df1..9ab461a 100644 --- a/wicd/networking.py +++ b/wicd/networking.py @@ -1,7 +1,4 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- - -""" networking - Provides wrappers for common network operations +"""networking - Provides wrappers for common network operations This module provides wrappers of the common network tasks as well as threads to perform the actual connecting to networks. @@ -50,11 +47,10 @@ import os from signal import SIGTERM from functools import cmp_to_key -# wicd imports -from . import misc -from . import wpath -from .backend import BackendManager -from .translations import _ +# wicd imports +from wicd import misc +from wicd import wpath +from wicd.backend import BackendManager if __name__ == '__main__': wpath.chdir(__file__) @@ -62,56 +58,63 @@ if __name__ == '__main__': BACKEND = None BACKEND_MGR = BackendManager() + def abortable(func): - """ Mark a method in a ConnectionThread as abortable. - + """Mark a method in a ConnectionThread as abortable. + This decorator runs a check that will abort the connection thread if necessary before running a given method. - + """ def wrapper(self, *__args, **__kargs): self.abort_if_needed() return func(self, *__args, **__kargs) - + wrapper.__name__ = func.__name__ wrapper.__dict__ = func.__dict__ wrapper.__doc__ = func.__doc__ wrapper.__module = func.__module__ return wrapper + def get_backend_list(): - """ Returns a list of available backends. """ + """Returns a list of available backends.""" if BACKEND_MGR: return BACKEND_MGR.get_available_backends() else: return [""] - + + def get_backend_update_interval(): - """ Returns the suggested connection status update interval. """ + """Returns the suggested connection status update interval.""" if BACKEND_MGR: return BACKEND_MGR.get_update_interval() else: return 5 # Seconds, this should never happen though. - + + def get_current_backend(): - """ Returns the current backend instance. """ + """Returns the current backend instance.""" if BACKEND_MGR: return BACKEND_MGR.get_current_backend() else: return None - + + def get_backend_description(backend_name): - """ Returns the description of the currently loaded backend. """ + """Returns the description of the currently loaded backend.""" return BACKEND_MGR.get_backend_description(backend_name) + def get_backend_description_dict(): - """ Returns a dict of all available backend descriptions. """ + """Returns a dict of all available backend descriptions.""" d = {} for be in get_backend_list(): if be: d[be] = get_backend_description(be) return d + def expand_script_macros(script, msg, bssid, essid): """Expands any supported macros in a script. @@ -120,7 +123,7 @@ def expand_script_macros(script, msg, bssid, essid): msg -- the name of the script, %{script} will be expanded to this. bssid -- the bssid of the network we connect to, defaults to 'wired'. essid -- the essid of the network we connect to, defaults to 'wired'. - + """ def repl(match): macro = match.group(1).lower() @@ -128,20 +131,20 @@ def expand_script_macros(script, msg, bssid, essid): return macro_dict[macro] print(('Warning: found illegal macro %s in %s script' % (macro, msg))) return match.group() - - macro_dict = { 'script' : msg, - 'bssid' : bssid, - 'essid' : essid } + + macro_dict = {'script': msg, + 'bssid': bssid, + 'essid': essid} regex = re.compile(r'%\{([a-zA-Z0-9]+)\}') expanded = regex.sub(repl, script) print(("Expanded '%s' to '%s'" % (script, expanded))) return expanded - + class Controller(object): - """ Parent class for the different interface types. """ + """Parent class for the different interface types.""" def __init__(self, debug=False): - """ Initialise the class. """ + """Initialise the class.""" self.global_dns_1 = None self.global_dns_2 = None self.global_dns_3 = None @@ -158,54 +161,57 @@ class Controller(object): self.post_disconnect_script = None self.driver = None self.iface = None - + def get_debug(self): - """ Getter for debug property. """ + """Getter for debug property.""" return self._debug + def set_debug(self, value): - """ Setter for debug property. """ + """Setter for debug property.""" self._debug = value if self.iface: self.iface.SetDebugMode(value) debug = property(get_debug, set_debug) - + def set_dhcp_client(self, value): - """ Setter for dhcp_client property. """ + """Setter for dhcp_client property.""" self._dhcp_client = value if self.iface: self.iface.DHCP_CLIENT = value + def get_dhcp_client(self): - """ Getter for dhcp_client property. """ + """Getter for dhcp_client property.""" return self._dhcp_client dhcp_client = property(get_dhcp_client, set_dhcp_client) - + def set_flush_tool(self, value): - """ Setter for flush_tool property. """ + """Setter for flush_tool property.""" self._flush_tool = value if self.iface: self.iface.flush_tool = value + def get_flush_tool(self): - """ Getter for flush_tool property. """ + """Getter for flush_tool property.""" return self._flush_tool flush_tool = property(get_flush_tool, set_flush_tool) - + def LoadBackend(self, backend_name): - """ Load the given networking backend. """ + """Load the given networking backend.""" global BACKEND if backend_name == self._backend: return self._backend = BACKEND_MGR.load_backend(backend_name) BACKEND = self._backend - + def NeedsExternalCalls(self): - """ Returns true if the loaded backend needs external calls. """ + """Returns true if the loaded backend needs external calls.""" if self._backend: return self._backend.NeedsExternalCalls() else: return True - + def GetIP(self, ifconfig=""): - """ Get the IP of the interface. + """Get the IP of the interface. Returns: The IP address of the interface in dotted notation. @@ -214,7 +220,7 @@ class Controller(object): return self.iface.GetIP(ifconfig) def Disconnect(self, nettype, name, mac): - """ Disconnect from the network. """ + """Disconnect from the network.""" iface = self.iface # mac and name need to be strings if mac in (None, ''): @@ -222,7 +228,7 @@ class Controller(object): if name in (None, ''): name = 'X' misc.ExecuteScripts(wpath.predisconnectscripts, self.debug, - extra_parameters=(nettype, name, mac)) + extra_parameters=(nettype, name, mac)) if self.pre_disconnect_script: print('Running pre-disconnect script') misc.ExecuteScript(expand_script_macros(self.pre_disconnect_script, @@ -239,73 +245,74 @@ class Controller(object): extra_parameters=(nettype, name, mac)) if self.post_disconnect_script: print('Running post-disconnect script') - misc.ExecuteScript(expand_script_macros(self.post_disconnect_script, + misc.ExecuteScript(expand_script_macros(self. + post_disconnect_script, 'post-disconnection', - mac, name), + mac, name), self.debug) - + def ReleaseDHCP(self): - """ Release the DHCP lease for this interface. """ + """Release the DHCP lease for this interface.""" return self.iface.ReleaseDHCP() - + def KillDHCP(self): - """ Kill the managed DHCP client if its in a connecting state. """ + """Kill the managed DHCP client if its in a connecting state.""" print('running kill dhcp.') - if (self.connecting_thread.is_connecting and - self.iface.dhcp_object): + if (self.connecting_thread.is_connecting and + self.iface.dhcp_object): if self.iface.dhcp_object.poll() is None: os.kill(self.iface.dhcp_object.pid, SIGTERM) self.iface.dhcp_object = None - + def IsUp(self): - """ Calls the IsUp method for the wired interface. - + """Calls the IsUp method for the wired interface. + Returns: True if the interface is up, False otherwise. - + """ return self.iface.IsUp() - + def EnableInterface(self): - """ Puts the interface up. - + """Puts the interface up. + Returns: True if the interface was put up succesfully, False otherwise. - + """ return self.iface.Up() - + def DisableInterface(self): - """ Puts the interface down. - + """Puts the interface down. + Returns: True if the interface was put down succesfully, False otherwise. - + """ return self.iface.Down() - + def AppAvailable(self, app): - """ Determine if the given application is installed. """ + """Determine if the given application is installed.""" return self.iface.AppAvailable(app) - + class ConnectThread(threading.Thread): - """ A class to perform network connections in a multi-threaded way. + """A class to perform network connections in a multi-threaded way. Useless on it's own, this class provides the generic functions necessary for connecting using a separate thread. - + """ is_connecting = None should_die = False lock = threading.Lock() - def __init__(self, network, interface_name, before_script, after_script, + def __init__(self, network, interface_name, before_script, after_script, pre_disconnect_script, post_disconnect_script, gdns1, gdns2, gdns3, gdns_dom, gsearch_dom, iface, debug): - """ Initialise the required object variables and the thread. + """Initialise the required object variables and the thread. Keyword arguments: network -- the network to connect to @@ -344,7 +351,7 @@ class ConnectThread(threading.Thread): self.connecting_status = None self.debug = debug - + self.SetStatus('interface_down') def _connect(self): @@ -356,21 +363,22 @@ class ConnectThread(threading.Thread): self._connect() finally: self.is_connecting = False - + def set_should_die(self, val): - """ Setter for should_die property. """ + """Setter for should_die property.""" self.lock.acquire() try: self._should_die = val finally: self.lock.release() + def get_should_die(self): - """ Getter for should_die property. """ + """Getter for should_die property.""" return self._should_die should_die = property(get_should_die, set_should_die) def SetStatus(self, status): - """ Set the threads current status message in a thread-safe way. + """Set the threads current status message in a thread-safe way. Keyword arguments: status -- the current connection status @@ -383,7 +391,7 @@ class ConnectThread(threading.Thread): self.lock.release() def GetStatus(self): - """ Get the threads current status message in a thread-safe way. + """Get the threads current status message in a thread-safe way. Returns: The current connection status. @@ -395,67 +403,68 @@ class ConnectThread(threading.Thread): finally: self.lock.release() return status - + @abortable def reset_ip_addresses(self, iface): - """ Resets the IP addresses for both wired/wireless interfaces. - + """Resets the IP addresses for both wired/wireless interfaces. + Sets a false ip so that when we set the real one, the correct routing entry is created. - + """ print('Setting false IP...') self.SetStatus('resetting_ip_address') iface.SetAddress('0.0.0.0') - + @abortable def put_iface_down(self, iface): - """ Puts the given interface down. """ + """Puts the given interface down.""" print('Putting interface down') self.SetStatus('interface_down') iface.Down() - + @abortable - def run_global_scripts_if_needed(self, script_dir, extra_parameters=()): - """ Run global scripts if needed. '""" + def run_scripts(self, script_dir, extra_parameters=()): + """Execute all script in provided script_dir.""" misc.ExecuteScripts(script_dir, verbose=self.debug, extra_parameters=extra_parameters) @abortable def run_script_if_needed(self, script, msg, bssid='wired', essid='wired'): - """ Execute a given script if needed. - + """Execute a given script if needed. + Keyword arguments: script -- the script to execute, or None/'' if there isn't one. msg -- the name of the script to display in the log. - + """ if script: print(('Executing %s script' % (msg))) misc.ExecuteScript(expand_script_macros(script, msg, bssid, essid), self.debug) - + @abortable def flush_routes(self, iface): - """ Flush the routes for both wired/wireless interfaces. """ + """Flush the routes for both wired/wireless interfaces.""" self.SetStatus('flushing_routing_table') print('Flushing the routing table...') iface.FlushRoutes() - + @abortable def set_broadcast_address(self, iface): - """ Set the broadcast address for the given interface. """ - if not self.network.get('broadcast') == None: + """Set the broadcast address for the given interface.""" + if self.network.get('broadcast') is not None: self.SetStatus('setting_broadcast_address') - print(('Setting the broadcast address...' + self.network['broadcast'])) + print('Setting the broadcast address...' + + self.network['broadcast']) iface.SetAddress(broadcast=self.network['broadcast']) - + @abortable def set_ip_address(self, iface): - """ Set the IP address for the given interface. - + """Set the IP address for the given interface. + Assigns a static IP if one is requested, otherwise calls DHCP. - + """ if self.network.get('ip'): self.SetStatus('setting_static_ip') @@ -467,9 +476,9 @@ class ConnectThread(threading.Thread): else: # Run dhcp... self.SetStatus('running_dhcp') - if self.network.get('usedhcphostname') == None: + if self.network.get('usedhcphostname') is None: self.network['usedhcphostname'] = False - if self.network.get('dhcphostname') == None: + if self.network.get('dhcphostname') is None: self.network['dhcphostname'] = os.uname()[1] if self.network['usedhcphostname']: hname = self.network['dhcphostname'] @@ -477,10 +486,15 @@ class ConnectThread(threading.Thread): else: hname = None print("Running DHCP with NO hostname") - - # Check if a global DNS is configured. If it is, then let the DHCP know *not* to update resolv.conf + + # Check if a global DNS is configured. If it is, then let the DHCP + # know *not* to update resolv.conf staticdns = False - if self.network.get('use_global_dns') or (self.network.get('use_static_dns') and (self.network.get('dns1') or self.network.get('dns2') or self.network.get('dns3'))): + if (self.network.get('use_global_dns') or + (self.network.get('use_static_dns') and + (self.network.get('dns1') or + self.network.get('dns2') or + self.network.get('dns3')))): staticdns = True dhcp_status = iface.StartDHCP(hname, staticdns) @@ -491,7 +505,7 @@ class ConnectThread(threading.Thread): @abortable def flush_dns_addresses(self, iface): - """ Flush the added DNS address(es). + """Flush the added DNS address(es). This is only useful when using resolvconf, since we effectively have no foolproof way of removing added DNS addresses from a non-resolvconf @@ -502,20 +516,21 @@ class ConnectThread(threading.Thread): @abortable def set_dns_addresses(self, iface): - """ Set the DNS address(es). + """Set the DNS address(es). If static DNS servers or global DNS servers are specified, set them. Otherwise do nothing. - + """ if self.network.get('use_global_dns'): iface.SetDNS(misc.Noneify(self.global_dns_1), - misc.Noneify(self.global_dns_2), + misc.Noneify(self.global_dns_2), misc.Noneify(self.global_dns_3), misc.Noneify(self.global_dns_dom), misc.Noneify(self.global_search_dom)) - elif self.network.get('use_static_dns') and (self.network.get('dns1') or - self.network.get('dns2') or self.network.get('dns3')): + elif (self.network.get('use_static_dns') and + (self.network.get('dns1') or self.network.get('dns2') + or self.network.get('dns3'))): self.SetStatus('setting_static_dns') iface.SetDNS(self.network.get('dns1'), self.network.get('dns2'), @@ -525,12 +540,12 @@ class ConnectThread(threading.Thread): @abortable def release_dhcp_clients(self, iface): - """ Release all running dhcp clients. """ + """Release all running dhcp clients.""" print("Releasing DHCP leases...") iface.ReleaseDHCP() - + def connect_aborted(self, reason): - """ Sets the thread status to aborted. """ + """Sets the thread status to aborted.""" if self.abort_reason: reason = self.abort_reason self.connecting_status = reason @@ -538,14 +553,14 @@ class ConnectThread(threading.Thread): self.connect_result = reason self.is_connecting = False print('exiting connection thread') - + def abort_connection(self, reason=""): - """ Schedule a connection abortion for the given reason. """ + """Schedule a connection abortion for the given reason.""" self.abort_reason = reason self.should_die = True - + def abort_if_needed(self): - """ Abort the thread is it has been requested. """ + """Abort the thread is it has been requested.""" self.lock.acquire() try: if self._should_die: @@ -553,16 +568,16 @@ class ConnectThread(threading.Thread): raise SystemExit finally: self.lock.release() - + @abortable def stop_wpa(self, iface): - """ Stops wpa_supplicant. """ + """Stops wpa_supplicant.""" print('Stopping wpa_supplicant') iface.StopWPA() - + @abortable def put_iface_up(self, iface): - """ Bring up given interface. """ + """Bring up given interface.""" print('Putting interface up...') self.SetStatus('interface_up') iface.Up() @@ -571,65 +586,69 @@ class ConnectThread(threading.Thread): if iface.IsUp(): return self.abort_if_needed() - + # If we get here, the interface never came up print("WARNING: Timed out waiting for interface to come up") class Wireless(Controller): - """ A wrapper for common wireless interface functions. """ + """A wrapper for common wireless interface functions.""" def __init__(self, debug=False): - """ Initialize the class. """ + """Initialize the class.""" Controller.__init__(self, debug=debug) self._wpa_driver = None self._wireless_interface = None - self.wiface = None + self.wiface = None self.should_verify_ap = True - + def set_wireless_iface(self, value): - """ Setter for wireless_interface property. """ + """Setter for wireless_interface property.""" self._wireless_interface = value if self.wiface: self.wiface.SetInterface(value) + def get_wireless_iface(self): - """ Getter for wireless_interface property. """ + """Getter for wireless_interface property.""" return self._wireless_interface - wireless_interface = property(get_wireless_iface, set_wireless_iface) - + wireless_interface = property(get_wireless_iface, set_wireless_iface) + def set_wpa_driver(self, value): - """ Setter for wpa_driver property. """ + """Setter for wpa_driver property.""" self._wpa_driver = value if self.wiface: self.SetWPADriver(value) + def get_wpa_driver(self): - """ Getter for wpa_driver property. """ + """Getter for wpa_driver property.""" return self._wpa_driver wpa_driver = property(get_wpa_driver, set_wpa_driver) - + def set_iface(self, value): - """ Setter for iface property. """ + """Setter for iface property.""" self.wiface = value + def get_iface(self): - """ Getter for iface property. """ + """Getter for iface property.""" return self.wiface iface = property(get_iface, set_iface) - + def LoadBackend(self, backend): - """ Load a given backend. + """Load a given backend. Load up a backend into the backend manager and associate with the networking interface. - + """ Controller.LoadBackend(self, backend) backend = self._backend if backend: self.wiface = backend.WirelessInterface(self.wireless_interface, - self.debug, self.wpa_driver) + self.debug, + self.wpa_driver) def Scan(self, essid=None): - """ Scan for available wireless networks. + """Scan for available wireless networks. Keyword arguments: essid -- The essid of a hidden network @@ -639,14 +658,15 @@ class Wireless(Controller): """ def comp(x, y): - """ Custom sorting function. """ + """Custom sorting function.""" if 'quality' in x: key = 'quality' else: key = 'strength' - return ((x[key] > y[key]) - (x[key] < y[key])) # cmp(x[key], y[key]) - + return ((x[key] > y[key]) - + (x[key] < y[key])) # cmp(x[key], y[key]) + if not self.wiface: return [] wiface = self.wiface @@ -656,7 +676,8 @@ class Wireless(Controller): # If there is a hidden essid then set it now, so that when it is # scanned it will be recognized. - # Note: this does not always work, sometimes we have to pass it with "iwlist wlan0 scan essid -- XXXXX" + # Note: this does not always work, sometimes we have to pass it with + # "iwlist wlan0 scan essid -- XXXXX" essid = misc.Noneify(essid) if essid is not None: print(('Setting hidden essid ' + essid)) @@ -666,11 +687,11 @@ class Wireless(Controller): aps = wiface.GetNetworks(essid) aps.sort(key=cmp_to_key(comp), reverse=True) - + return aps def Connect(self, network, debug=False): - """ Spawn a connection thread to connect to the network. + """Spawn a connection thread to connect to the network. Keyword arguments: network -- network to connect to @@ -678,20 +699,20 @@ class Wireless(Controller): """ if not self.wiface: return False - - self.connecting_thread = WirelessConnectThread(network, - self.wireless_interface, self.wpa_driver, self.before_script, - self.after_script, self.pre_disconnect_script, - self.post_disconnect_script, self.global_dns_1, - self.global_dns_2, self.global_dns_3, self.global_dns_dom, - self.global_search_dom, self.wiface, self.should_verify_ap, - self.bitrate, self.allow_lower_bitrates, debug) + + self.connecting_thread = WirelessConnectThread( + network, self.wireless_interface, self.wpa_driver, + self.before_script, self.after_script, self.pre_disconnect_script, + self.post_disconnect_script, self.global_dns_1, self.global_dns_2, + self.global_dns_3, self.global_dns_dom, self.global_search_dom, + self.wiface, self.should_verify_ap, self.bitrate, + self.allow_lower_bitrates, debug) self.connecting_thread.setDaemon(True) self.connecting_thread.start() return True def GetSignalStrength(self, iwconfig=""): - """ Get signal strength of the current network. + """Get signal strength of the current network. Returns: The current signal strength. @@ -700,7 +721,7 @@ class Wireless(Controller): return self.wiface.GetSignalStrength(iwconfig) def GetDBMStrength(self, iwconfig=""): - """ Get the dBm signal strength of the current network. + """Get the dBm signal strength of the current network. Returns: The current dBm signal strength. @@ -709,7 +730,7 @@ class Wireless(Controller): return self.wiface.GetDBMStrength(iwconfig) def GetCurrentNetwork(self, iwconfig=""): - """ Get current network name. + """Get current network name. Returns: The name of the currently connected network. @@ -718,49 +739,49 @@ class Wireless(Controller): if self.connecting_thread and self.connecting_thread.is_connecting: return self.connecting_thread.network['essid'] return self.wiface.GetCurrentNetwork(iwconfig) - + def GetBSSID(self): - """ Get the BSSID of the current access point. - + """Get the BSSID of the current access point. + Returns: The MAC Adress of the active access point as a string, or None the BSSID can't be found. - + """ return self.wiface.GetBSSID() def GetCurrentBitrate(self, iwconfig): - """ Get the current bitrate of the interface. - + """Get the current bitrate of the interface. + Returns: The bitrate of the active access point as a string, or None the bitrate can't be found. - + """ return self.wiface.GetCurrentBitrate(iwconfig) def GetOperationalMode(self, iwconfig): - """ Get the current operational mode of the interface. - + """Get the current operational mode of the interface. + Returns: The operational mode of the interface as a string, or None if the operational mode can't be found. - + """ return self.wiface.GetOperationalMode(iwconfig) def GetAvailableAuthMethods(self, iwlistauth): - """ Get the available authentication methods for the interface. - + """Get the available authentication methods for the interface. + Returns: The available authentication methods of the interface as a string, or None if the auth methods can't be found. - + """ return self.wiface.GetAvailableAuthMethods(iwlistauth) def GetAvailableBitrates(self): - """ Get the available bitrates for the interface. + """Get the available bitrates for the interface. Returns: The available bitrates of the interface as a string, or None if the @@ -769,20 +790,19 @@ class Wireless(Controller): return self.wiface.GetAvailableBitrates() def GetIwconfig(self): - """ Get the out of iwconfig. """ + """Get the out of iwconfig.""" return self.wiface.GetIwconfig() - + def GetWpaSupplicantDrivers(self): - """ Returns all valid wpa_supplicant drivers on the system. """ + """Returns all valid wpa_supplicant drivers on the system.""" return BACKEND.GetWpaSupplicantDrivers() - + def StopWPA(self): - """ Stop wpa_supplicant. """ + """Stop wpa_supplicant.""" return self.wiface.StopWPA() - def CreateAdHocNetwork(self, essid, channel, ip, enctype, key, - enc_used): - """ Create an ad-hoc wireless network. + def CreateAdHocNetwork(self, essid, channel, ip, enctype, key, enc_used): + """Create an ad-hoc wireless network. Keyword arguments: essid -- essid of the ad-hoc network @@ -814,7 +834,7 @@ class Wireless(Controller): wiface.SetAddress(ip, '255.255.255.0') def DetectWirelessInterface(self): - """ Detect available wireless interfaces. + """Detect available wireless interfaces. Returns: The first available wireless interface. @@ -827,16 +847,16 @@ class Wireless(Controller): return None def GetKillSwitchStatus(self): - """ Get the current status of the Killswitch. - + """Get the current status of the Killswitch. + Returns: True if the killswitch is on, False otherwise. - + """ return self.wiface.GetKillSwitchStatus() def SwitchRfKill(self): - """ Switches the rfkill on/off for wireless cards. """ + """Switches the rfkill on/off for wireless cards.""" types = ['wifi', 'wlan', 'wimax', 'wwan'] try: if self.GetRfKillStatus(): @@ -853,43 +873,44 @@ class Wireless(Controller): return False def GetRfKillStatus(self): - """ Determines if rfkill switch is active or not. + """Determines if rfkill switch is active or not. Returns: True if rfkill (soft-)switch is enabled. """ cmd = 'rfkill list' rfkill_out = misc.Run(cmd) - soft_blocks = [x for x in rfkill_out.split('\t') if x.startswith('Soft')] + soft_blocks = [x for x in rfkill_out.split('\t') + if x.startswith('Soft')] for line in [x.strip() for x in soft_blocks]: if line.endswith('yes'): return True return False def Disconnect(self): - """ Disconnect the given iface. - + """Disconnect the given iface. + Executes the disconnect script associated with a given interface, Resets it's IP address, and puts the interface down then up. - + """ if BACKEND.NeedsExternalCalls(): iwconfig = self.GetIwconfig() else: iwconfig = None bssid = self.wiface.GetBSSID(iwconfig) - essid = self.wiface.GetCurrentNetwork(iwconfig) + essid = self.wiface.GetCurrentNetwork(iwconfig) Controller.Disconnect(self, 'wireless', essid, bssid) self.StopWPA() - + def SetWPADriver(self, driver): - """ Sets the wpa_supplicant driver associated with the interface. """ + """Sets the wpa_supplicant driver associated with the interface.""" self.wiface.SetWpaDriver(driver) - + class WirelessConnectThread(ConnectThread): - """ A thread class to perform the connection to a wireless network. + """A thread class to perform the connection to a wireless network. This thread, when run, will perform the necessary steps to connect to the specified network. @@ -898,9 +919,9 @@ class WirelessConnectThread(ConnectThread): def __init__(self, network, wireless, wpa_driver, before_script, after_script, pre_disconnect_script, post_disconnect_script, - gdns1, gdns2, gdns3, gdns_dom, gsearch_dom, wiface, + gdns1, gdns2, gdns3, gdns_dom, gsearch_dom, wiface, should_verify_ap, bitrate, allow_lower_bitrates, debug=False): - """ Initialise the thread with network information. + """Initialise the thread with network information. Keyword arguments: network -- the network to connect to @@ -917,7 +938,7 @@ class WirelessConnectThread(ConnectThread): allow_lower_bitrates -- whether to allow lower bitrates or not """ - ConnectThread.__init__(self, network, wireless, before_script, + ConnectThread.__init__(self, network, wireless, before_script, after_script, pre_disconnect_script, post_disconnect_script, gdns1, gdns2, gdns3, gdns_dom, gsearch_dom, wiface, debug) @@ -927,7 +948,7 @@ class WirelessConnectThread(ConnectThread): self.allow_lower_bitrates = allow_lower_bitrates def _connect(self): - """ The main function of the connection thread. + """The main function of the connection thread. This function performs the necessary calls to connect to the specified network, using the information provided. The following @@ -942,17 +963,14 @@ class WirelessConnectThread(ConnectThread): """ wiface = self.iface self.is_connecting = True - + # Run pre-connection script. - self.run_global_scripts_if_needed(wpath.preconnectscripts, - extra_parameters=('wireless', - self.network['essid'], - self.network['bssid']) - ) - self.run_script_if_needed(self.before_script, 'pre-connection', + self.run_scripts(wpath.preconnectscripts, + extra_parameters=('wireless', self.network['essid'], + self.network['bssid'])) + self.run_script_if_needed(self.before_script, 'pre-connection', self.network['bssid'], self.network['essid']) - # Take down interface and clean up previous connections. self.put_iface_down(wiface) self.release_dhcp_clients(wiface) @@ -966,11 +984,11 @@ class WirelessConnectThread(ConnectThread): # Put interface up. self.SetStatus('configuring_interface') self.put_iface_up(wiface) - + # Generate PSK and authenticate if needed. if self.wpa_driver != 'ralink legacy': self.generate_psk_and_authenticate(wiface) - + # Associate. wiface.Associate(self.network['essid'], self.network['channel'], self.network['bssid']) @@ -979,7 +997,7 @@ class WirelessConnectThread(ConnectThread): if self.wpa_driver == 'ralink legacy': if self.network.get('key'): wiface.Authenticate(self.network) - + # Validate Authentication. if self.network.get('enctype'): self.SetStatus('validating_authentication') @@ -993,14 +1011,12 @@ class WirelessConnectThread(ConnectThread): self.set_ip_address(wiface) self.set_dns_addresses(wiface) self.verify_association(wiface) - + # Run post-connection script. - self.run_global_scripts_if_needed(wpath.postconnectscripts, - extra_parameters=('wireless', - self.network['essid'], - self.network['bssid']) - ) - self.run_script_if_needed(self.after_script, 'post-connection', + self.run_scripts(wpath.postconnectscripts, + extra_parameters=('wireless', self.network['essid'], + self.network['bssid'])) + self.run_script_if_needed(self.after_script, 'post-connection', self.network['bssid'], self.network['essid']) self.SetStatus('done') @@ -1009,27 +1025,28 @@ class WirelessConnectThread(ConnectThread): print(("IP Address is: " + str(wiface.GetIP()))) self.connect_result = "success" self.is_connecting = False - + @abortable def verify_association(self, iface): - """ Verify that our association the AP is valid. - + """Verify that our association the AP is valid. + Try to ping the gateway we have set to see if we're really associated with it. This is only done if we're using a static IP. - + """ if self.network.get('gateway') and self.should_verify_ap: self.SetStatus('verifying_association') print("Verifying AP association...") for tries in range(1, 11): print(("Attempt %d of 10..." % tries)) - retcode = self.iface.VerifyAPAssociation(self.network['gateway']) - if retcode == 0: + retcode = self.iface.VerifyAPAssociation(self. + network['gateway']) + if retcode == 0: print("Successfully associated.") break time.sleep(1) - #TODO this should be in wnettools.py + # TODO this should be in wnettools.py if retcode: print("Connection Failed: Failed to ping the access point!") # Clean up before aborting. @@ -1041,14 +1058,14 @@ class WirelessConnectThread(ConnectThread): self.abort_connection('association_failed') else: print('not verifying') - + @abortable def generate_psk_and_authenticate(self, wiface): - """ Generates a PSK and authenticates if necessary. - + """Generates a PSK and authenticates if necessary. + Generates a PSK, and starts the authentication process if encryption is on. - + """ # Check to see if we need to generate a PSK (only for non-ralink # cards). @@ -1059,12 +1076,12 @@ class WirelessConnectThread(ConnectThread): self.SetStatus('generating_psk') print('Generating psk...') self.network['psk'] = wiface.GeneratePSK(self.network) - + if not self.network.get('psk'): self.network['psk'] = self.network['key'] - print(('WARNING: PSK generation failed! Falling back to ' + \ - 'wireless key.\nPlease report this error to the wicd ' + \ - 'developers!')) + print('WARNING: PSK generation failed! Falling back to ' + 'wireless key.\nPlease report this error to the wicd ' + 'developers!') # Generate the wpa_supplicant file... if self.network.get('enctype'): self.SetStatus('generating_wpa_config') @@ -1073,54 +1090,59 @@ class WirelessConnectThread(ConnectThread): class Wired(Controller): - """ A wrapper for common wired interface functions. """ + """A wrapper for common wired interface functions.""" def __init__(self, debug=False): - """ Initialise the class. """ + """Initialise the class.""" Controller.__init__(self, debug=debug) self.wpa_driver = None self._link_detect = None self._wired_interface = None self.liface = None - - def set_link_detect(self, value): - """ Setter for link_detect property. """ + + @property + def link_detect(self): + """Getter for link_detect property.""" + return self._link_detect + + @link_detect.setter + def link_detect(self, value): + """Setter for link_detect property.""" self._link_detect = value if self.liface: self.liface.link_detect = value - def get_link_detect(self): - """ Getter for link_detect property. """ - return self._link_detect - link_detect = property(get_link_detect, set_link_detect) - - - def set_wired_iface(self, value): - """ Setter for wired_interface property. """ + + @property + def wired_iface(self): + """Getter for wired_interface property.""" + return self._wired_interface + + @wired_iface.setter + def wired_iface(self, value): + """Setter for wired_interface property.""" self._wired_interface = value if self.liface: - self.liface.SetInterface(value) - def get_wired_iface(self): - """ Getter for wired_interface property. """ - return self._wired_interface - wired_interface = property(get_wired_iface, set_wired_iface) - - def set_iface(self, value): - """ Setter for iface property. """ - self.liface = value - def get_iface(self): - """ Getter for iface property. """ + self.liface.SetInterface(value) + + @property + def iface(self): + """Getter for iface property.""" return self.liface - iface = property(get_iface, set_iface) - + + @iface.setter + def iface(self, value): + """Setter for iface property.""" + self.liface = value + def LoadBackend(self, backend): - """ Load the backend up. """ + """Load the backend up.""" Controller.LoadBackend(self, backend) if self._backend: self.liface = self._backend.WiredInterface(self.wired_interface, self.debug) def CheckPluggedIn(self): - """ Check whether the wired connection is plugged in. + """Check whether the wired connection is plugged in. Returns: The status of the physical connection link. @@ -1129,7 +1151,7 @@ class Wired(Controller): return self.liface.GetPluggedIn() def Connect(self, network, debug=False): - """ Spawn a connection thread to connect to the network. + """Spawn a connection thread to connect to the network. Keyword arguments: network -- network to connect to @@ -1137,26 +1159,26 @@ class Wired(Controller): """ if not self.liface: return False - self.connecting_thread = WiredConnectThread(network, - self.wired_interface, self.before_script, self.after_script, - self.pre_disconnect_script, self.post_disconnect_script, - self.global_dns_1, self.global_dns_2, self.global_dns_3, - self.global_dns_dom, self.global_search_dom, self.liface, - debug) + self.connecting_thread = WiredConnectThread( + network, self.wired_interface, self.before_script, + self.after_script, self.pre_disconnect_script, + self.post_disconnect_script, self.global_dns_1, self.global_dns_2, + self.global_dns_3, self.global_dns_dom, self.global_search_dom, + self.liface, debug) self.connecting_thread.setDaemon(True) self.connecting_thread.start() return self.connecting_thread - + def Disconnect(self): Controller.Disconnect(self, 'wired', 'wired', 'wired') self.StopWPA() - + def StopWPA(self): - """ Stop wpa_supplicant. """ + """Stop wpa_supplicant.""" self.liface.StopWPA() - + def DetectWiredInterface(self): - """ Attempts to automatically detect a wired interface. """ + """Attempts to automatically detect a wired interface.""" try: return BACKEND.GetWiredInterfaces()[0] except IndexError: @@ -1164,16 +1186,16 @@ class Wired(Controller): class WiredConnectThread(ConnectThread): - """ A thread class to perform the connection to a wired network. + """A thread class to perform the connection to a wired network. This thread, when run, will perform the necessary steps to connect to the specified network. """ - def __init__(self, network, wired, before_script, after_script, + def __init__(self, network, wired, before_script, after_script, pre_disconnect_script, post_disconnect_script, gdns1, gdns2, gdns3, gdns_dom, gsearch_dom, liface, debug=False): - """ Initialise the thread with network information. + """Initialise the thread with network information. Keyword arguments: network -- the network to connect to @@ -1188,14 +1210,14 @@ class WiredConnectThread(ConnectThread): gdns3 -- global DNS server 3 """ - ConnectThread.__init__(self, network, wired, before_script, + ConnectThread.__init__(self, network, wired, before_script, after_script, pre_disconnect_script, post_disconnect_script, gdns1, gdns2, gdns3, gdns_dom, gsearch_dom, liface, debug) def _connect(self): - """ The main function of the connection thread. + """The main function of the connection thread. This function performs the necessary calls to connect to the specified network, using the information provided. The following @@ -1213,12 +1235,11 @@ class WiredConnectThread(ConnectThread): self.is_connecting = True # Run pre-connection script. - self.run_global_scripts_if_needed(wpath.preconnectscripts, - extra_parameters=('wired', 'wired', - self.network['profilename']) - ) - self.run_script_if_needed(self.before_script, 'pre-connection', 'wired', - 'wired') + self.run_scripts(wpath.preconnectscripts, + extra_parameters=('wired', 'wired', + self.network['profilename'])) + self.run_script_if_needed(self.before_script, 'pre-connection', + 'wired', 'wired') # Take down interface and clean up previous connections. self.put_iface_down(liface) @@ -1227,31 +1248,30 @@ class WiredConnectThread(ConnectThread): self.stop_wpa(liface) self.flush_routes(liface) self.flush_dns_addresses(liface) - + # Bring up interface. self.put_iface_up(liface) - + # Manage encryption. if self.network.get('encryption_enabled'): liface.Authenticate(self.network) - + # Set gateway, IP adresses, and DNS servers. self.set_broadcast_address(liface) self.set_ip_address(liface) self.set_dns_addresses(liface) - + # Run post-connection script. - self.run_global_scripts_if_needed(wpath.postconnectscripts, - extra_parameters=('wired', 'wired', - self.network['profilename']) - ) - self.run_script_if_needed(self.after_script, 'post-connection', 'wired', - 'wired') + self.run_scripts(wpath.postconnectscripts, + extra_parameters=('wired', 'wired', + self.network['profilename'])) + self.run_script_if_needed(self.after_script, 'post-connection', + 'wired', 'wired') self.SetStatus('done') print('Connecting thread exiting.') if self.debug: print(("IP Address is: " + str(liface.GetIP()))) - + self.connect_result = "success" self.is_connecting = False diff --git a/wicd/suspend.py b/wicd/suspend.py index bcbcb0b..b27c173 100644 --- a/wicd/suspend.py +++ b/wicd/suspend.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 -""" Suspends the wicd daemon. +"""Suspends the wicd daemon. Sets a flag in the daemon that will stop it from monitoring network status. Used for when a laptop enters hibernation/suspension. @@ -23,10 +23,10 @@ Used for when a laptop enters hibernation/suspension. # You should have received a copy of the GNU General Public License # along with this program. If not, see . # +import sys import dbus import dbus.service -import sys try: bus = dbus.SystemBus() diff --git a/wicd/translations.py b/wicd/translations.py index 5678564..63262f7 100644 --- a/wicd/translations.py +++ b/wicd/translations.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 # -* coding: utf-8 -*- -""" translations -- module for handling the translation strings for wicd. """ +"""translations -- module for handling the translation strings for wicd.""" # # Copyright (C) 2007 - 2009 Adam Blackburn # Copyright (C) 2007 - 2009 Dan O'Reilly @@ -21,12 +21,12 @@ # import locale import os -from . import wpath +from wicd import wpath import gettext def get_gettext(): - """ Set up gettext for translations. """ + """Set up gettext for translations.""" # Borrowed from an excellent post on how to do this at # http://www.learningpython.com/2006/12/03/translating-your-pythonpygtk-application/ local_path = wpath.translations @@ -41,8 +41,8 @@ def get_gettext(): try: # This avoids a bug: locale.getdefaultlocale() prefers # LC_CTYPE over LANG/LANGUAGE - lc, encoding = locale.getdefaultlocale(envvars=('LC_MESSAGES', - 'LC_ALL', 'LANG', + lc, encoding = locale.getdefaultlocale(envvars=('LC_MESSAGES', + 'LC_ALL', 'LANG', 'LANGUAGE')) except ValueError as e: print((str(e))) @@ -50,11 +50,11 @@ def get_gettext(): if (lc): langs += [lc] langs += ["en_US"] - lang = gettext.translation('wicd', local_path, languages=langs, + lang = gettext.translation('wicd', local_path, languages=langs, fallback=True) return lang.gettext -_ = get_gettext() +_ = get_gettext() # noqa # language[] should contain only strings in encryption templates, which @@ -66,13 +66,15 @@ language = {} # FIXME: these were present in wicd 1.7.0, can't find where they are. # Leaving here for future reference, they should be removed whenever # possible. -#language['cannot_start_daemon'] = _('Unable to connect to wicd daemon ' + \ -# 'DBus interface. This typically means there was a problem starting ' + \ -# 'the daemon. Check the wicd log for more information.') -#language['backend_alert'] = _('Changes to your backend won't occur until ' + \ -# 'the daemon is restarted.') -#language['about_help'] = _('Stop a network connection in progress') -#language['connect'] = _('Connect') +# language['cannot_start_daemon'] = _('Unable to connect to wicd daemon ' +# 'DBus interface. This typically means ' +# 'there was a problem starting the ' +# 'daemon. Check the wicd log for more ' +# 'information.') +# language['backend_alert'] = _('Changes to your backend won't occur until ' +# 'the daemon is restarted.') +# language['about_help'] = _('Stop a network connection in progress') +# language['connect'] = _('Connect') # from templates, dict populated with: # grep -R "*" encryption/templates/ | tr " " "\n" | grep "^*" | \ diff --git a/wicd/wicd-daemon.py b/wicd/wicd-daemon.py index 3667d76..da53a2a 100644 --- a/wicd/wicd-daemon.py +++ b/wicd/wicd-daemon.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- -""" wicd - wireless connection daemon implementation. +"""wicd - wireless connection daemon implementation. This module implements the wicd daemon that provides network connection management, for both wireless and wired networks. The daemon @@ -71,8 +71,9 @@ wireless_conf = os.path.join(wpath.etc, "wireless-settings.conf") wired_conf = os.path.join(wpath.etc, "wired-settings.conf") dhclient_conf = os.path.join(wpath.etc, "dhclient.conf.template") + class WicdDaemon(dbus.service.Object, object): - """ The main wicd daemon class. + """The main wicd daemon class. This class mostly contains exported DBus methods that are not associated directly with either wired or wireless actions. There @@ -81,8 +82,8 @@ class WicdDaemon(dbus.service.Object, object): """ def __init__(self, bus_name, object_path="/org/wicd/daemon", auto_connect=True, keep_connection=False): - """ Initializes the daemon DBus object. """ - dbus.service.Object.__init__(self, bus_name=bus_name, + """Initializes the daemon DBus object.""" + dbus.service.Object.__init__(self, bus_name=bus_name, object_path=object_path) self.config = ConfigManager(os.path.join(wpath.etc, "manager-settings.conf")) @@ -94,7 +95,7 @@ class WicdDaemon(dbus.service.Object, object): self.forced_disconnect = False self.need_profile_chooser = False self.current_interface = None - self.vpn_session = None + self.vpn_session = None self.gui_open = False self.suspended = False self._debug_mode = False @@ -120,7 +121,7 @@ class WicdDaemon(dbus.service.Object, object): self.auto_reconnect = True self.keep_connection = keep_connection - # This will speed up the scanning process - if a client doesn't + # This will speed up the scanning process - if a client doesn't # need a fresh scan, just feed them the old one. A fresh scan # can be done by calling Scan(fresh=True). self.LastScan = [] @@ -138,17 +139,18 @@ class WicdDaemon(dbus.service.Object, object): self.wireless_bus.Scan() def get_debug_mode(self): - """ Getter for debug_mode property. """ + """Getter for debug_mode property.""" return self._debug_mode + def set_debug_mode(self, mode): - """ Setter for debug_mode property. """ + """Setter for debug_mode property.""" self._debug_mode = mode self.config.debug = mode debug_mode = property(get_debug_mode, set_debug_mode) @dbus.service.method('org.wicd.daemon') def Hello(self): - """ Returns the version number. + """Returns the version number. This number is major-minor-micro. Major is only incremented if minor reaches > 9. Minor is incremented if changes that break core stucture @@ -160,30 +162,33 @@ class WicdDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon') def SetWiredInterface(self, interface): - """ Sets the wired interface for the daemon to use. """ + """Sets the wired interface for the daemon to use.""" print("setting wired interface %s" % (str(interface))) - # Set it to a blank string, otherwise a network card named "None" will be searched + # Set it to a blank string, otherwise a network card named "None" will + # be searched self.wired.wired_interface = noneToBlankString(interface) self.config.set("Settings", "wired_interface", interface, write=True) @dbus.service.method('org.wicd.daemon') def SetWirelessInterface(self, interface): - """ Sets the wireless interface the daemon will use. """ + """Sets the wireless interface the daemon will use.""" print("setting wireless interface %s" % (str(interface))) - # Set it to a blank string, otherwise a network card named "None" will be searched + # Set it to a blank string, otherwise a network card named "None" will + # be searched self.wifi.wireless_interface = noneToBlankString(interface) - self.config.set("Settings", "wireless_interface", interface, write=True) + self.config.set("Settings", "wireless_interface", interface, + write=True) @dbus.service.method('org.wicd.daemon') def SetWPADriver(self, driver): - """ Sets the wpa driver the wpa_supplicant will use. """ + """Sets the wpa driver the wpa_supplicant will use.""" print("setting wpa driver", str(driver)) self.wifi.wpa_driver = driver self.config.set("Settings", "wpa_driver", driver, write=True) @dbus.service.method('org.wicd.daemon') def SetUseGlobalDNS(self, use): - """ Sets a boolean which determines if global DNS is enabled. """ + """Sets a boolean which determines if global DNS is enabled.""" print('setting use global dns to', use) use = misc.to_bool(use) self.config.set("Settings", "use_global_dns", use, write=True) @@ -192,9 +197,9 @@ class WicdDaemon(dbus.service.Object, object): self.wired.use_global_dns = use @dbus.service.method('org.wicd.daemon') - def SetGlobalDNS(self, dns1=None, dns2=None, dns3=None, - dns_dom =None, search_dom=None): - """ Sets the global dns addresses. """ + def SetGlobalDNS(self, dns1=None, dns2=None, dns3=None, dns_dom=None, + search_dom=None): + """Sets the global dns addresses.""" print("setting global dns") self.config.set("Settings", "global_dns_1", misc.noneToString(dns1)) self.dns1 = dns1 @@ -209,12 +214,12 @@ class WicdDaemon(dbus.service.Object, object): self.wifi.global_dns_3 = dns3 self.wired.global_dns_3 = dns3 self.config.set("Settings", "global_dns_dom", - misc.noneToString(dns_dom)) + misc.noneToString(dns_dom)) self.dns_dom = dns_dom self.wifi.dns_dom = dns_dom self.wired.dns_dom = dns_dom self.config.set("Settings", "global_search_dom", - misc.noneToString(search_dom)) + misc.noneToString(search_dom)) self.search_dom = search_dom self.wifi.global_search_dom = search_dom self.wired.global_search_dom = search_dom @@ -225,12 +230,12 @@ class WicdDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon') def SetBackend(self, backend): - """ Sets a new backend. """ + """Sets a new backend.""" print("setting backend to %s" % backend) backends = networking.BACKEND_MGR.get_available_backends() if backend not in backends: - print("backend %s not available, trying to fallback to another" \ - % backend) + print(f"backend {backend} not available, trying to fallback to " + f"another") try: backend = backends[0] except IndexError: @@ -248,57 +253,57 @@ class WicdDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon') def GetCurrentBackend(self): - """ Returns the currently loaded backend. """ + """Returns the currently loaded backend.""" return networking.get_current_backend() @dbus.service.method('org.wicd.daemon') def GetBackendUpdateInterval(self): - """ Returns status update interval for the loaded backend. """ + """Returns status update interval for the loaded backend.""" return networking.get_backend_update_interval() @dbus.service.method('org.wicd.daemon') def GetBackendDescription(self, backend_name): - """ Returns the description of the given backend. """ + """Returns the description of the given backend.""" return networking.get_backend_description(backend_name) @dbus.service.method('org.wicd.daemon') def GetBackendDescriptionDict(self): - """ Returns a dict of all backend names mapped to their description. """ + """Returns a dict of all backend names mapped to their description.""" return networking.get_backend_description_dict() @dbus.service.method('org.wicd.daemon') def GetSavedBackend(self): - """ Returns the backend saved to disk. """ + """Returns the backend saved to disk.""" return self.config.get("Settings", "backend") @dbus.service.method('org.wicd.daemon') def GetBackendList(self): - """ Returns a list of all backends available. """ + """Returns a list of all backends available.""" return networking.get_backend_list() @dbus.service.method('org.wicd.daemon') def GetUseGlobalDNS(self): - """ Returns a boolean that determines if global dns is enabled. """ + """Returns a boolean that determines if global dns is enabled.""" return bool(self.use_global_dns) @dbus.service.method('org.wicd.daemon') def GetWPADriver(self): - """ Returns the wpa driver the daemon is using. """ + """Returns the wpa driver the daemon is using.""" return str(self.wifi.wpa_driver) @dbus.service.method('org.wicd.daemon') def GetWiredInterface(self): - """ Returns the wired interface. """ + """Returns the wired interface.""" return str(self.wired.wired_interface) @dbus.service.method('org.wicd.daemon') def GetWirelessInterface(self): - """ Returns the wireless interface the daemon is using. """ + """Returns the wireless interface the daemon is using.""" return str(self.wifi.wireless_interface) @dbus.service.method('org.wicd.daemon') def NeedsExternalCalls(self): - """ Returns true if the loaded backend needs external calls. """ + """Returns true if the loaded backend needs external calls.""" if self.wifi: return self.wifi.NeedsExternalCalls() elif self.wired: @@ -308,7 +313,7 @@ class WicdDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon') def SetDebugMode(self, debug): - """ Sets if debugging mode is on or off. """ + """Sets if debugging mode is on or off.""" self.config.set("Settings", "debug_mode", debug, write=True) self.debug_mode = misc.to_bool(debug) self.wifi.debug = debug @@ -318,19 +323,19 @@ class WicdDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon') def GetDebugMode(self): - """ Returns whether debugging is enabled. """ + """Returns whether debugging is enabled.""" return bool(self.debug_mode) @dbus.service.method('org.wicd.daemon') def Disconnect(self): - """ Disconnects all networks. """ + """Disconnects all networks.""" self.SetForcedDisconnect(True) self.wifi.Disconnect() self.wired.Disconnect() @dbus.service.method('org.wicd.daemon') def FormatSignalForPrinting(self, sign): - """ Returns the suffix to display after the signal strength number. """ + """Returns the suffix to display after the signal strength number.""" if self.GetSignalDisplayType() == 1: return '%s dBm' % sign else: @@ -344,7 +349,7 @@ class WicdDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon') def SetSuspend(self, val): - """ Toggles whether or not monitoring connection status is suspended """ + """Toggles whether or not monitoring connection status is suspended""" self.suspended = val if self.suspended: self.Disconnect() @@ -353,14 +358,14 @@ class WicdDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon') def GetSuspend(self): - """ Returns True if the computer is in the suspend state. """ + """Returns True if the computer is in the suspend state.""" return self.suspended @dbus.service.method('org.wicd.daemon') def AutoConnect(self, fresh): - """ Attempts to autoconnect to a wired or wireless network. + """Attempts to autoconnect to a wired or wireless network. - Autoconnect will first try to connect to a wired network, if that + Autoconnect will first try to connect to a wired network, if that fails it tries a wireless connection. """ @@ -380,33 +385,33 @@ class WicdDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon') def GetAutoReconnect(self): - """ Returns the value of self.auto_reconnect. See SetAutoReconnect. """ + """Returns the value of self.auto_reconnect. See SetAutoReconnect.""" return bool(self.auto_reconnect) @dbus.service.method('org.wicd.daemon') def SetAutoReconnect(self, value): - """ Sets the value of self.auto_reconnect. + """Sets the value of self.auto_reconnect. If True, wicd will try to reconnect as soon as it detects that an internet connection is lost. If False, it will do nothing, and wait for the user to initiate reconnection. """ - print('setting automatically reconnect when connection drops %s' % value) - self.config.set("Settings", "auto_reconnect", misc.to_bool(value), + print(f'setting automatically reconnect when connection drops {value}') + self.config.set("Settings", "auto_reconnect", misc.to_bool(value), write=True) self.auto_reconnect = misc.to_bool(value) @dbus.service.method('org.wicd.daemon') def GetGlobalDNSAddresses(self): - """ Returns the global dns addresses. """ + """Returns the global dns addresses.""" return (misc.noneToString(self.dns1), misc.noneToString(self.dns2), misc.noneToString(self.dns3), misc.noneToString(self.dns_dom), misc.noneToString(self.search_dom)) @dbus.service.method('org.wicd.daemon') def CheckIfConnecting(self): - """ Returns if a network connection is being made. """ + """Returns if a network connection is being made.""" if self.wired_bus.CheckIfWiredConnecting() or \ self.wireless_bus.CheckIfWirelessConnecting(): return True @@ -415,7 +420,7 @@ class WicdDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon') def CancelConnect(self): - """ Cancels the wireless connection attempt """ + """Cancels the wireless connection attempt""" print('canceling connection attempt') if self.wifi.connecting_thread: self.wifi.connecting_thread.should_die = True @@ -433,17 +438,17 @@ class WicdDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon') def GetCurrentInterface(self): - """ Returns the active interface """ + """Returns the active interface""" return self.current_interface - @dbus.service.method('org.wicd.daemon') + @dbus.service.method('org.wicd.daemon') def SetCurrentInterface(self, iface): - """ Sets the current active interface """ + """Sets the current active interface""" self.current_interface = str(iface) @dbus.service.method('org.wicd.daemon') def SetNeedWiredProfileChooser(self, val): - """ Sets the need_wired_profile_chooser variable. + """Sets the need_wired_profile_chooser variable. If set to True, that alerts the wicd frontend to display the chooser, if False the frontend will do nothing. This function is only needed @@ -455,7 +460,7 @@ class WicdDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon') def ShouldAutoReconnect(self): - """ Returns True if it's the right time to try autoreconnecting. """ + """Returns True if it's the right time to try autoreconnecting.""" if self.GetAutoReconnect() and not self.CheckIfConnecting() and \ not self.GetForcedDisconnect() and not self.auto_connecting and \ not self.gui_open: @@ -465,12 +470,12 @@ class WicdDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon') def GetForcedDisconnect(self): - """ Returns the forced_disconnect status. See SetForcedDisconnect. """ + """Returns the forced_disconnect status. See SetForcedDisconnect.""" return bool(self.forced_disconnect) @dbus.service.method('org.wicd.daemon') def SetForcedDisconnect(self, value): - """ Sets the forced_disconnect status. + """Sets the forced_disconnect status. Set to True when a user manually disconnects or cancels a connection. It gets set to False as soon as the connection process is manually @@ -483,7 +488,7 @@ class WicdDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon') def GetSignalDisplayType(self): - """ Returns the signal display type. + """Returns the signal display type. Returns either 0 or 1. 0 for signal strength as a percentage @@ -494,13 +499,13 @@ class WicdDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon') def SetSignalDisplayType(self, value): - """ Sets the signal display type and writes it the wicd config file. """ + """Sets the signal display type and writes it the wicd config file.""" self.config.set("Settings", "signal_display_type", value, write=True) self.signal_display_type = int(value) @dbus.service.method('org.wicd.daemon') def GetGUIOpen(self): - """ Returns the value of gui_open. + """Returns the value of gui_open. Returns the vlaue of gui_open, which is a boolean that keeps track of the state of the wicd GUI. If the GUI is open, wicd will not @@ -518,24 +523,24 @@ class WicdDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon') def SetGUIOpen(self, val): - """ Sets the value of gui_open. """ + """Sets the value of gui_open.""" self.gui_open = bool(val) @dbus.service.method('org.wicd.daemon') def SetAlwaysShowWiredInterface(self, value): - """ Sets always_show_wired_interface to the given value. """ - self.config.set("Settings", "always_show_wired_interface", + """Sets always_show_wired_interface to the given value.""" + self.config.set("Settings", "always_show_wired_interface", misc.to_bool(value), write=True) self.always_show_wired_interface = misc.to_bool(value) @dbus.service.method('org.wicd.daemon') def GetAlwaysShowWiredInterface(self): - """ Returns always_show_wired_interface """ + """Returns always_show_wired_interface""" return bool(self.always_show_wired_interface) @dbus.service.method('org.wicd.daemon') def SetWiredAutoConnectMethod(self, method): - """ Sets which method to use to autoconnect to wired networks. """ + """Sets which method to use to autoconnect to wired networks.""" # 1 = default profile # 2 = show list # 3 = last used profile @@ -543,32 +548,32 @@ class WicdDaemon(dbus.service.Object, object): write=True) self.wired_connect_mode = int(method) self.wired_bus.connect_mode = int(method) - + @dbus.service.method('org.wicd.daemon') def SetShouldVerifyAp(self, value): - """ Enable/disable wireless AP verification. - + """Enable/disable wireless AP verification. + If this is True, wicd will try to verify that we are associated with the Wireless AP after a connection attempt appears to succeed. - + """ self.config.set("Settings", "should_verify_ap", int(value), write=True) self.wifi.should_verify_ap = misc.to_bool(value) - + @dbus.service.method('org.wicd.daemon') def GetShouldVerifyAp(self): - """ Returns current value for WAP connection verification. """ + """Returns current value for WAP connection verification.""" return bool(self.wifi.should_verify_ap) @dbus.service.method('org.wicd.daemon') def GetWiredAutoConnectMethod(self): - """ Returns the wired autoconnect method. """ + """Returns the wired autoconnect method.""" return int(self.wired_connect_mode) @dbus.service.method('org.wicd.daemon') def GetPreferWiredNetwork(self): - """ Returns True if wired network preference is set. + """Returns True if wired network preference is set. If this is True, wicd will switch from a wireless connection to a wired one if an ethernet connection is available. @@ -578,13 +583,13 @@ class WicdDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon') def SetPreferWiredNetwork(self, value): - """ Sets the prefer_wired state. """ + """Sets the prefer_wired state.""" self.config.set("Settings", "prefer_wired", bool(value), write=True) self.prefer_wired = bool(value) @dbus.service.method('org.wicd.daemon') def GetShowNeverConnect(self): - """ Returns True if show_never_connect is set + """Returns True if show_never_connect is set if True then the client will show networks marked as never connect """ @@ -592,20 +597,20 @@ class WicdDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon') def SetShowNeverConnect(self, value): - """ Sets the how_never_connect state. """ + """Sets the how_never_connect state.""" self.config.set("Settings", "show_never_connect", bool(value), - write=True) + write=True) self.show_never_connect = bool(value) @dbus.service.method('org.wicd.daemon') def SetConnectionStatus(self, state, info): - """ Sets the connection status. + """Sets the connection status. Keyword arguments: state - An int representing the state of the connection as defined in misc.py. - info - a list of strings containing data about the connection state. + info - a list of strings containing data about the connection state. The contents of this list are dependent on the connection state. state - info contents: @@ -627,7 +632,7 @@ class WicdDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon', out_signature='(uas)') def GetConnectionStatus(self): - """ Returns the current connection state in list form. + """Returns the current connection state in list form. See SetConnectionStatus for more information about the data structure being returned. @@ -637,7 +642,7 @@ class WicdDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon') def GetNeedWiredProfileChooser(self): - """ Returns need_profile_chooser. + """Returns need_profile_chooser. Returns a boolean specifying if the wired profile chooser needs to be launched. @@ -647,12 +652,13 @@ class WicdDaemon(dbus.service.Object, object): @dbus.service.method("org.wicd.daemon") def GetAppAvailable(self, app): - """ Determine if a given application is available.""" - return bool(self.wifi.AppAvailable(app) or self.wired.AppAvailable(app)) + """Determine if a given application is available.""" + return bool(self.wifi.AppAvailable(app) or + self.wired.AppAvailable(app)) @dbus.service.method('org.wicd.daemon') def GetDHCPClient(self): - """ Returns the current DHCP client constant. + """Returns the current DHCP client constant. See misc.py for a definition of the constants. @@ -661,7 +667,7 @@ class WicdDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon') def SetDHCPClient(self, client): - """ Sets the DHCP client constant. + """Sets the DHCP client constant. See misc.py for a definition of the constants. @@ -674,12 +680,12 @@ class WicdDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon') def GetLinkDetectionTool(self): - """ Returns the current link detection tool constant. """ + """Returns the current link detection tool constant.""" return self.link_detect_tool @dbus.service.method('org.wicd.daemon') def SetLinkDetectionTool(self, link_tool): - """ Sets the link detection tool. + """Sets the link detection tool. Sets the value of the tool wicd should use to detect if a cable is plugged in. If using a backend that doesn't use @@ -694,12 +700,12 @@ class WicdDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon') def GetFlushTool(self): - """ Returns the current flush tool constant. """ + """Returns the current flush tool constant.""" return self.flush_tool @dbus.service.method('org.wicd.daemon') def SetFlushTool(self, flush_tool): - """ Sets the flush tool. + """Sets the flush tool. Sets the value of the tool wicd should use to flush routing tables. The value is associated with a particular tool, as specified in @@ -713,17 +719,17 @@ class WicdDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon') def GetSudoApp(self): - """ Get the preferred sudo app. """ + """Get the preferred sudo app.""" return self.sudo_app @dbus.service.method('org.wicd.daemon') def SetSudoApp(self, sudo_app): - """ Set the preferred sudo app. """ + """Set the preferred sudo app.""" self.sudo_app = sudo_app self.config.set("Settings", "sudo_app", sudo_app, write=True) def _wired_autoconnect(self, fresh=True): - """ Attempts to autoconnect to a wired network. """ + """Attempts to autoconnect to a wired network.""" wiredb = self.wired_bus if self.GetWiredAutoConnectMethod() == 3 and \ not self.GetNeedWiredProfileChooser(): @@ -740,8 +746,8 @@ class WicdDaemon(dbus.service.Object, object): elif self.GetWiredAutoConnectMethod() == 1: network = wiredb.GetDefaultWiredNetwork() if not network: - print("Couldn't find a default wired connection," + \ - " wired autoconnect failed.") + print("Couldn't find a default wired connection, wired " + "autoconnect failed.") self.wireless_bus._wireless_autoconnect(fresh) return @@ -749,7 +755,7 @@ class WicdDaemon(dbus.service.Object, object): else: network = wiredb.GetLastUsedWiredNetwork() if not network: - print("no previous wired profile available, wired " + \ + print("no previous wired profile available, wired " "autoconnect failed.") self.wireless_bus._wireless_autoconnect(fresh) return @@ -760,14 +766,14 @@ class WicdDaemon(dbus.service.Object, object): self.auto_connecting = True time.sleep(1.5) try: - gobject.timeout_add_seconds(3, self._monitor_wired_autoconnect, + gobject.timeout_add_seconds(3, self._monitor_wired_autoconnect, fresh) except AttributeError: gobject.timeout_add(3000, self._monitor_wired_autoconnect, fresh) return True def _monitor_wired_autoconnect(self, fresh): - """ Monitor a wired auto-connection attempt. + """Monitor a wired auto-connection attempt. Helper method called on a timer that monitors a wired connection attempt and makes decisions about what to @@ -788,24 +794,24 @@ class WicdDaemon(dbus.service.Object, object): @dbus.service.method("org.wicd.daemon") def ConnectResultsAvailable(self): - """ Return whether connection results are available. """ + """Return whether connection results are available.""" wired_thread = self.wired.connecting_thread wifi_thread = self.wifi.connecting_thread - if ((wired_thread and wired_thread.connect_result) or - (wifi_thread and wifi_thread.connect_result)): + if (wired_thread and wired_thread.connect_result or + wifi_thread and wifi_thread.connect_result): return True else: return False @dbus.service.method("org.wicd.daemon") def SendConnectResultsIfAvail(self): - """ Send connection results if they're available. '""" + """Send connection results if they're available. '""" if self.ConnectResultsAvailable(): self.SendConnectResult() @dbus.service.method("org.wicd.daemon") def SendConnectResult(self): - """ Send connection result. """ + """Send connection result.""" wired_thread = self.wired.connecting_thread wifi_thread = self.wifi.connecting_thread if wired_thread and wired_thread.connect_result: @@ -815,9 +821,9 @@ class WicdDaemon(dbus.service.Object, object): self.ConnectResultsSent(wifi_thread.connect_result) wifi_thread.connect_result = "" - @dbus.service.signal(dbus_interface="org.wicd.daemon",signature='s') + @dbus.service.signal(dbus_interface="org.wicd.daemon", signature='s') def ConnectResultsSent(self, result): - """ Signal emit when connection results are sent. """ + """Signal emit when connection results are sent.""" print("Sending connection attempt result %s" % result) @dbus.service.method("org.wicd.daemon") @@ -827,44 +833,44 @@ class WicdDaemon(dbus.service.Object, object): @dbus.service.signal(dbus_interface='org.wicd.daemon', signature='') def LaunchChooser(self): - """ Emits the wired profile chooser dbus signal. """ + """Emits the wired profile chooser dbus signal.""" print('calling wired profile chooser') self.SetNeedWiredProfileChooser(True) @dbus.service.signal(dbus_interface="org.wicd.daemon", signature='') def DaemonStarting(self): - """ Emits a signa indicating the daemon is starting. """ + """Emits a signa indicating the daemon is starting.""" pass @dbus.service.signal(dbus_interface='org.wicd.daemon', signature='') def DaemonClosing(self): - """ Emits a signal indicating the daemon will be closing. """ + """Emits a signal indicating the daemon will be closing.""" # By default, disconnect network links on close. if not self.keep_connection: self.Disconnect() @dbus.service.method('org.wicd.daemon', in_signature='uav') def EmitStatusChanged(self, state, info): - """ Calls the StatusChanged signal method. """ + """Calls the StatusChanged signal method.""" self.StatusChanged(state, info) @dbus.service.signal(dbus_interface='org.wicd.daemon', signature='uav') def StatusChanged(self, state, info): - """ Emits a "status changed" dbus signal. + """Emits a "status changed" dbus signal. This D-Bus signal is emitted when the connection status changes. This signal can be hooked to monitor the network state. """ pass - + @dbus.service.signal(dbus_interface='org.wicd.daemon', signature='i') def SignalBackendChanged(self, interval): - """ Emits a signal when the current backend changes. """ + """Emits a signal when the current backend changes.""" pass def ReadConfig(self): - """ Reads the manager-settings.conf file. + """Reads the manager-settings.conf file. Reads the manager-settings.conf file and loads the stored values into memory. @@ -881,7 +887,8 @@ class WicdDaemon(dbus.service.Object, object): iface = self.wireless_bus.DetectWirelessInterface() if not iface: iface = 'wlan0' - self.SetWirelessInterface(app_conf.get("Settings", "wireless_interface", + self.SetWirelessInterface(app_conf.get("Settings", + "wireless_interface", default=iface)) iface = self.wired_bus.DetectWiredInterface() if not iface: @@ -890,10 +897,11 @@ class WicdDaemon(dbus.service.Object, object): default=iface)) self.SetWPADriver(app_conf.get("Settings", "wpa_driver", - default="wext")) - self.SetAlwaysShowWiredInterface(app_conf.get("Settings", - "always_show_wired_interface", - default=False)) + default="wext")) + self.SetAlwaysShowWiredInterface(app_conf. + get("Settings", + "always_show_wired_interface", + default=False)) self.SetUseGlobalDNS(app_conf.get("Settings", "use_global_dns", default=False)) dns1 = app_conf.get("Settings", "global_dns_1", default='None') @@ -901,15 +909,16 @@ class WicdDaemon(dbus.service.Object, object): dns3 = app_conf.get("Settings", "global_dns_3", default='None') dns_dom = app_conf.get("Settings", "global_dns_dom", default='None') search_dom = app_conf.get("Settings", "global_search_dom", - default='None') + default='None') self.SetGlobalDNS(dns1, dns2, dns3, dns_dom, search_dom) self.SetAutoReconnect(app_conf.get("Settings", "auto_reconnect", default=True)) - self.SetDebugMode(app_conf.get("Settings", "debug_mode", default=False)) + self.SetDebugMode(app_conf.get("Settings", "debug_mode", + default=False)) self.SetWiredAutoConnectMethod(app_conf.get("Settings", "wired_connect_mode", default=1)) - self.SetSignalDisplayType(app_conf.get("Settings", + self.SetSignalDisplayType(app_conf.get("Settings", "signal_display_type", default=0)) self.SetShouldVerifyAp(app_conf.get("Settings", "should_verify_ap", @@ -919,10 +928,10 @@ class WicdDaemon(dbus.service.Object, object): default=0)) self.SetFlushTool(app_conf.get("Settings", "flush_tool", default=0)) self.SetSudoApp(app_conf.get("Settings", "sudo_app", default=0)) - self.SetPreferWiredNetwork(app_conf.get("Settings", "prefer_wired", + self.SetPreferWiredNetwork(app_conf.get("Settings", "prefer_wired", default=False)) - self.SetShowNeverConnect(app_conf.get("Settings", "show_never_connect", - default=True)) + self.SetShowNeverConnect(app_conf.get("Settings", "show_never_connect", + default=True)) app_conf.write() if os.path.isfile(wireless_conf): @@ -941,7 +950,7 @@ class WicdDaemon(dbus.service.Object, object): if not os.path.isfile(dhclient_conf): print("dhclient.conf.template not found, copying...") - shutil.copy(dhclient_conf + ".default", dhclient_conf) + shutil.copy(dhclient_conf + ".default", dhclient_conf) # Hide the files, so the keys aren't exposed. print("chmoding configuration files 0600...") os.chmod(app_conf.get_config(), 0o600) @@ -959,14 +968,11 @@ class WicdDaemon(dbus.service.Object, object): print("Using wireless interface..." + self.GetWirelessInterface()) print("Using wired interface..." + self.GetWiredInterface()) -############################## -###### Wireless Daemon ####### -############################## class WirelessDaemon(dbus.service.Object, object): - """ DBus interface for wireless connection operations. """ + """DBus interface for wireless connection operations.""" def __init__(self, bus_name, daemon, wifi=None, debug=False): - """ Intitialize the wireless DBus interface. """ + """Intitialize the wireless DBus interface.""" dbus.service.Object.__init__(self, bus_name=bus_name, object_path='/org/wicd/daemon/wireless') self.hidden_essid = None @@ -978,22 +984,23 @@ class WirelessDaemon(dbus.service.Object, object): self.config = ConfigManager(wireless_conf, debug=debug) def get_debug_mode(self): - """ Getter for the debug_mode property. """ + """Getter for the debug_mode property.""" return self._debug_mode + def set_debug_mode(self, mode): - """ Setter for the debug_mode property. """ + """Setter for the debug_mode property.""" self._debug_mode = mode self.config.debug = mode debug_mode = property(get_debug_mode, set_debug_mode) @dbus.service.method('org.wicd.daemon.wireless') def SetHiddenNetworkESSID(self, essid): - """ Sets the ESSID of a hidden network for use with Scan(). """ + """Sets the ESSID of a hidden network for use with Scan().""" self.hidden_essid = str(misc.Noneify(essid)) @dbus.service.method('org.wicd.daemon.wireless') def Scan(self, sync=False): - """ Scan for wireless networks. + """Scan for wireless networks. Scans for wireless networks, optionally using a (hidden) essid set with SetHiddenNetworkESSID. @@ -1017,11 +1024,11 @@ class WirelessDaemon(dbus.service.Object, object): @misc.threaded def _async_scan(self): - """ Run a scan in its own thread. """ + """Run a scan in its own thread.""" self._sync_scan() def _sync_scan(self): - """ Run a scan and send a signal when its finished. """ + """Run a scan and send a signal when its finished.""" scan = self.wifi.Scan(str(self.hidden_essid)) self.LastScan = scan if self.debug_mode: @@ -1033,42 +1040,42 @@ class WirelessDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon.wireless') def GetIwconfig(self): - """ Calls and returns the output of iwconfig""" + """Calls and returns the output of iwconfig""" return misc.to_unicode(self.wifi.GetIwconfig()) @dbus.service.method('org.wicd.daemon.wireless') def GetNumberOfNetworks(self): - """ Returns number of networks. """ + """Returns number of networks.""" return len(self.LastScan) @dbus.service.method('org.wicd.daemon.wireless') def GetApBssid(self): - """ Gets the MAC address for the active network. """ + """Gets the MAC address for the active network.""" return self.wifi.GetBSSID() @dbus.service.method('org.wicd.daemon.wireless') def GetCurrentBitrate(self, iwconfig): - """ Returns the current bitrate for the active network. """ + """Returns the current bitrate for the active network.""" return self.wifi.GetCurrentBitrate(iwconfig) @dbus.service.method('org.wicd.daemon.wireless') def GetOperationalMode(self, iwconfig): - """ Returns the operational mode for the iwconfig parameter """ + """Returns the operational mode for the iwconfig parameter""" return misc.to_unicode(self.wifi.GetOperationalMode(iwconfig)) @dbus.service.method('org.wicd.daemon.wireless') def GetAvailableAuthMethods(self, iwlistauth): - """ Returns the operational mode for the iwlistauth parameter """ + """Returns the operational mode for the iwlistauth parameter""" return misc.to_unicode(self.wifi.GetAvailableAuthMethods(iwlistauth)) @dbus.service.method('org.wicd.daemon.wireless') def GetAvailableBitrates(self): - """ Returns the available bitrates the wifi card can use """ + """Returns the available bitrates the wifi card can use""" return self.wifi.GetAvailableBitrates() @dbus.service.method('org.wicd.daemon.wireless') def GetOperableBitrates(self, networkid): - """ Returns the real bitrates a connection to a network can use. + """Returns the real bitrates a connection to a network can use. This is the intersection between the bitrates the AP can transmit to, and the bitrates the wireless card can use. @@ -1080,28 +1087,28 @@ class WirelessDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon.wireless') def CreateAdHocNetwork(self, essid, channel, ip, enctype, key, encused, ics): - """ Creates an ad-hoc network using user inputted settings. """ + """Creates an ad-hoc network using user inputted settings.""" self.wifi.CreateAdHocNetwork(essid, channel, ip, enctype, key, encused) @dbus.service.method('org.wicd.daemon.wireless') def GetKillSwitchEnabled(self): - """ Returns true if kill switch is pressed. """ + """Returns true if kill switch is pressed.""" status = self.wifi.GetKillSwitchStatus() return status @dbus.service.method('org.wicd.daemon.wireless') def SwitchRfKill(self): - """ Switches the rfkill on/off for wireless cards. """ + """Switches the rfkill on/off for wireless cards.""" return self.wifi.SwitchRfKill() @dbus.service.method('org.wicd.daemon.wireless') def GetRfKillEnabled(self): - """ Returns true if rfkill switch is enabled. """ + """Returns true if rfkill switch is enabled.""" return self.wifi.GetRfKillStatus() @dbus.service.method('org.wicd.daemon.wireless') def GetWirelessProperty(self, networkid, prop): - """ Retrieves wireless property from the network specified """ + """Retrieves wireless property from the network specified""" try: value = self.LastScan[networkid].get(prop) except IndexError: @@ -1111,12 +1118,12 @@ class WirelessDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon.wireless') def SetWirelessProperty(self, netid, prop, value): - """ Sets property to value in network specified. """ + """Sets property to value in network specified.""" # We don't write script settings here. prop = misc.sanitize_config(prop) if prop.endswith('script'): - print('Setting script properties through the daemon' \ - + ' is not permitted.') + print('Setting script properties through the daemon is not ' + 'permitted.') return False # whitelist some props that need different handling if prop in ('key_index', ): @@ -1127,7 +1134,7 @@ class WirelessDaemon(dbus.service.Object, 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() if iface: print('Automatically detected wireless interface ' + iface) @@ -1137,18 +1144,18 @@ class WirelessDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon.wireless') def DisconnectWireless(self): - """ Disconnects the wireless network. """ + """Disconnects the wireless network.""" self.wifi.Disconnect() self.daemon.UpdateState() @dbus.service.method('org.wicd.daemon.wireless') def IsWirelessUp(self): - """ Returns a boolean specifying if wireless is up or down. """ + """Returns a boolean specifying if wireless is up or down.""" return self.wifi.IsUp() @dbus.service.method('org.wicd.daemon.wireless') def GetCurrentSignalStrength(self, iwconfig=None): - """ Returns the current signal strength. """ + """Returns the current signal strength.""" try: strength = int(self.wifi.GetSignalStrength(iwconfig)) except TypeError: @@ -1157,60 +1164,60 @@ class WirelessDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon.wireless') def GetCurrentDBMStrength(self, iwconfig=None): - """ Returns the current dbm signal strength. """ + """Returns the current dbm signal strength.""" try: dbm_strength = int(self.wifi.GetDBMStrength(iwconfig)) - except: + except Exception: dbm_strength = 0 return dbm_strength @dbus.service.method('org.wicd.daemon.wireless') def GetCurrentNetwork(self, iwconfig=None): - """ Returns the current network. """ + """Returns the current network.""" current_network = str(self.wifi.GetCurrentNetwork(iwconfig)) return current_network @dbus.service.method('org.wicd.daemon.wireless') def GetCurrentNetworkID(self, iwconfig=None): - """ Returns the id of the current network, or -1 if its not found. """ + """Returns the id of the current network, or -1 if its not found.""" currentESSID = self.GetCurrentNetwork(iwconfig) for x in range(0, len(self.LastScan)): if self.LastScan[x]['essid'] == currentESSID: return x if self.debug_mode: - print('GetCurrentNetworkID: Returning -1, current network not found') + print('GetCurrentNetworkID: Returning -1, current network not ' + 'found') return -1 @dbus.service.method('org.wicd.daemon.wireless') def EnableWirelessInterface(self): - """ Calls a method to enable the wireless interface. """ + """Calls a method to enable the wireless interface.""" result = self.wifi.EnableInterface() return result @dbus.service.method('org.wicd.daemon.wireless') def DisableWirelessInterface(self): - """ Calls a method to disable the wireless interface. """ + """Calls a method to disable the wireless interface.""" result = self.wifi.DisableInterface() return result @dbus.service.method('org.wicd.daemon.wireless') def ConnectWireless(self, nid): - """ Connects the the wireless network specified by i""" + """Connects the the wireless network specified by i""" self.SaveWirelessNetworkProfile(nid) # Will returned instantly, that way we don't hold up dbus. # CheckIfWirelessConnecting can be used to test if the connection # is done. self.wifi.before_script = self.GetWirelessProperty(nid, 'beforescript') self.wifi.after_script = self.GetWirelessProperty(nid, 'afterscript') - self.wifi.pre_disconnect_script = self.GetWirelessProperty(nid, - 'predisconnectscript') - self.wifi.post_disconnect_script = self.GetWirelessProperty(nid, - 'postdisconnectscript') + self.wifi.pre_disconnect_script = ( + self.GetWirelessProperty(nid, 'predisconnectscript')) + self.wifi.post_disconnect_script = ( + self.GetWirelessProperty(nid, 'postdisconnectscript')) self.wifi.bitrate = self.GetWirelessProperty(nid, 'bitrate') - self.wifi.allow_lower_bitrates = self.GetWirelessProperty(nid, - 'allow_lower_bitrates') - print('Connecting to wireless network ' + \ - str(self.LastScan[nid]['essid'])) + self.wifi.allow_lower_bitrates = ( + self.GetWirelessProperty(nid, 'allow_lower_bitrates')) + print(f"Connecting to wireless network {self.LastScan[nid]['essid']}") # disconnect to make sure that scripts are run self.wifi.Disconnect() self.daemon.wired_bus.wired.Disconnect() @@ -1220,7 +1227,9 @@ class WirelessDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon.wireless') def CheckIfWirelessConnecting(self): - """Returns True if wireless interface is connecting, otherwise False.""" + """ + Returns True if wireless interface is connecting, otherwise False. + """ if self.wifi.connecting_thread: return self.wifi.connecting_thread.is_connecting else: @@ -1228,13 +1237,13 @@ class WirelessDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon.wireless') def GetWirelessIP(self, ifconfig=""): - """ Returns the IP associated with the wireless interface. """ + """Returns the IP associated with the wireless interface.""" ip = self.wifi.GetIP(ifconfig) return ip @dbus.service.method('org.wicd.daemon.wireless') def CheckWirelessConnectingStatus(self): - """ Returns the wireless interface's status code. """ + """Returns the wireless interface's status code.""" if self.wifi.connecting_thread: stat = self.wifi.connecting_thread.GetStatus() return stat @@ -1243,7 +1252,7 @@ class WirelessDaemon(dbus.service.Object, object): @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 self.wifi.connecting_thread: stat = self.CheckWirelessConnectingStatus() return _status_dict[stat] @@ -1252,7 +1261,7 @@ class WirelessDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon.wireless') def ReadWirelessNetworkProfile(self, nid): - """ Reads in wireless profile as the active network """ + """Reads in wireless profile as the active network""" cur_network = self.LastScan[nid] essid_key = "essid:%s" % cur_network["essid"] bssid_key = cur_network["bssid"] @@ -1282,7 +1291,7 @@ class WirelessDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon.wireless') def SaveWirelessNetworkProfile(self, nid): - """ Writes a wireless profile to disk. """ + """Writes a wireless profile to disk.""" def write_script_ent(prof, script): if not self.config.has_option(prof, script): self.config.set(prof, script, None) @@ -1322,11 +1331,11 @@ class WirelessDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon.wireless') def SaveWirelessNetworkProperty(self, nid, option): - """ Writes a particular wireless property to disk. """ + """Writes a particular wireless property to disk.""" option = misc.sanitize_config(option) if option.endswith("script"): - print('You cannot save script information to disk through ' + \ - 'the daemon.') + print('You cannot save script information to disk through the ' + 'daemon.') return config = self.config cur_network = self.LastScan[nid] @@ -1341,18 +1350,18 @@ class WirelessDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon.wireless') def RemoveGlobalEssidEntry(self, networkid): - """ Removes the global entry for the networkid provided. """ + """Removes the global entry for the networkid provided.""" essid_key = "essid:" + str(self.LastScan[networkid]) self.config.remove_section(essid_key) @dbus.service.method('org.wicd.daemon.wireless') def GetWpaSupplicantDrivers(self): - """ Returns all valid wpa_supplicant drivers. """ + """Returns all valid wpa_supplicant drivers.""" return self.wifi.GetWpaSupplicantDrivers() @dbus.service.method('org.wicd.daemon.wireless') def ReloadConfig(self): - """ Reloads the active config file. """ + """Reloads the active config file.""" self.config.reload() @dbus.service.method('org.wicd.daemon.wireless', out_signature='as') @@ -1374,31 +1383,32 @@ class WirelessDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon.wireless') def DeleteWirelessNetwork(self, section): - """ Deletes a wireless network section. """ + """Deletes a wireless network section.""" section = misc.to_unicode(section) - print("Deleting wireless settings for %s (%s)" % \ - (self.config.get(section, 'essid'), str(section))) + print("Deleting wireless settings for %s (%s)" % + (self.config.get(section, 'essid'), str(section))) self.config.remove_section(section) self.config.write() - @dbus.service.signal(dbus_interface='org.wicd.daemon.wireless', \ - signature='') + @dbus.service.signal(dbus_interface='org.wicd.daemon.wireless', + signature='') def SendStartScanSignal(self): - """ Emits a signal announcing a scan has started. """ + """Emits a signal announcing a scan has started.""" self._scanning = True - @dbus.service.signal(dbus_interface='org.wicd.daemon.wireless', \ - signature='') + @dbus.service.signal(dbus_interface='org.wicd.daemon.wireless', + signature='') def SendEndScanSignal(self): - """ Emits a signal announcing a scan has finished. """ + """Emits a signal announcing a scan has finished.""" self._scanning = False def _wireless_autoconnect(self, fresh=True): - """ Attempts to autoconnect to a wireless network. """ - print("No wired connection present, attempting to autoconnect " + \ - "to wireless network") + """Attempts to autoconnect to a wireless network.""" + print("No wired connection present, attempting to autoconnect to " + "wireless network") if self.wifi.wireless_interface is None: - print('Autoconnect failed because wireless interface returned None') + print('Autoconnect failed because wireless interface returned ' + 'None') return if fresh: self.Scan(sync=True) @@ -1409,25 +1419,22 @@ class WirelessDaemon(dbus.service.Object, object): print(network["essid"] + ' has profile') if bool(network.get('automatic')): if network.get('never'): - print(network["essid"],'marked never connect') + print(f'{network["essid"]} marked never connect') continue else: - print(network["essid"],'has no never connect value') - print('trying to automatically connect to...' + \ - network["essid"]) + print(f'{network["essid"]} has no never connect value') + print(f'trying to automatically connect to... ' + f'{network["essid"]}') self.ConnectWireless(x) time.sleep(1) return print("Unable to autoconnect, you'll have to manually connect") -########################### -###### Wired Daemon ####### -########################### class WiredDaemon(dbus.service.Object, object): - """ DBus interface for wired connection operations. """ + """DBus interface for wired connection operations.""" def __init__(self, bus_name, daemon, wired=None, debug=False): - """ Intitialize the wireless DBus interface. """ + """Intitialize the wireless DBus interface.""" dbus.service.Object.__init__(self, bus_name=bus_name, object_path="/org/wicd/daemon/wired") self.daemon = daemon @@ -1438,23 +1445,24 @@ class WiredDaemon(dbus.service.Object, object): self.config = ConfigManager(wired_conf, debug=debug) def get_debug_mode(self): - """ Getter for debug_mode property. """ + """Getter for debug_mode property.""" return self._debug_mode + def set_debug_mode(self, mode): - """ Setter for debug_mode property. """ + """Setter for debug_mode property.""" self._debug_mode = mode self.config.debug = mode debug_mode = property(get_debug_mode, set_debug_mode) @dbus.service.method('org.wicd.daemon.wired') def GetWiredIP(self, ifconfig=""): - """ Returns the wired interface's ip address. """ + """Returns the wired interface's ip address.""" ip = self.wired.GetIP(ifconfig) return ip @dbus.service.method('org.wicd.daemon.wired') def CheckIfWiredConnecting(self): - """ Returns True if wired interface is connecting, otherwise False. """ + """Returns True if wired interface is connecting, otherwise False.""" if self.wired.connecting_thread: return self.wired.connecting_thread.is_connecting else: @@ -1470,7 +1478,7 @@ class WiredDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon.wired') def CheckWiredConnectingMessage(self): - """ Returns the wired interface's status message. """ + """Returns the wired interface's status message.""" if self.wired.connecting_thread: return _status_dict[self.CheckWiredConnectingStatus()] else: @@ -1478,7 +1486,7 @@ class WiredDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon.wired') def DetectWiredInterface(self): - """ Returns an automatically detected wireless interface. """ + """Returns an automatically detected wireless interface.""" iface = self.wired.DetectWiredInterface() if iface: print('automatically detected wired interface ' + str(iface)) @@ -1488,12 +1496,12 @@ class WiredDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon.wired') def SetWiredProperty(self, prop, value): - """ Sets the given property to the given value. """ + """Sets the given property to the given value.""" if self.WiredNetwork: prop = misc.sanitize_config(prop) if prop.endswith('script'): - print('Setting script properties through the daemon' \ - + ' is not permitted.') + print('Setting script properties through the daemon is not ' + 'permitted.') return False self.WiredNetwork[prop] = misc.to_unicode(misc.Noneify(value)) return True @@ -1503,7 +1511,7 @@ class WiredDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon.wired') def GetWiredProperty(self, prop): - """ Returns the requested wired property. """ + """Returns the requested wired property.""" if self.WiredNetwork: value = self.WiredNetwork.get(prop) return value @@ -1513,7 +1521,7 @@ class WiredDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon.wired') def HasWiredDriver(self): - """ Returns True if a driver is associated with this interface. """ + """Returns True if a driver is associated with this interface.""" if self.wired.driver: return True else: @@ -1521,13 +1529,13 @@ class WiredDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon.wired') def DisconnectWired(self): - """ Disconnects the wired network. """ + """Disconnects the wired network.""" self.wired.Disconnect() self.daemon.UpdateState() @dbus.service.method('org.wicd.daemon.wired') def CheckPluggedIn(self): - """ Returns True if a ethernet cable is present, False otherwise. """ + """Returns True if a ethernet cable is present, False otherwise.""" if self.wired.wired_interface and self.wired.wired_interface != "None": return self.wired.CheckPluggedIn() else: @@ -1535,22 +1543,22 @@ class WiredDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon.wired') def IsWiredUp(self): - """ Returns a boolean specifying if wired iface is up or down. """ + """Returns a boolean specifying if wired iface is up or down.""" return self.wired.IsUp() @dbus.service.method('org.wicd.daemon.wired') def EnableWiredInterface(self): - """ Calls a method to enable the wired interface. """ + """Calls a method to enable the wired interface.""" return self.wired.EnableInterface() @dbus.service.method('org.wicd.daemon.wired') def DisableWiredInterface(self): - """ Calls a method to disable the wired interface. """ + """Calls a method to disable the wired interface.""" return self.wired.DisableInterface() @dbus.service.method('org.wicd.daemon.wired') def ConnectWired(self): - """ Connects to a wired network. """ + """Connects to a wired network.""" self.wired.before_script = self.GetWiredProperty("beforescript") self.wired.after_script = self.GetWiredProperty("afterscript") self.wired.pre_disconnect_script = \ @@ -1562,13 +1570,14 @@ class WiredDaemon(dbus.service.Object, object): self.wired.Disconnect() self.daemon.SetForcedDisconnect(False) self.UnsetWiredLastUsed() - self.config.set(self._cur_wired_prof_name, "lastused", True, write=True) + self.config.set(self._cur_wired_prof_name, "lastused", True, + write=True) self.wired.Connect(self.WiredNetwork, debug=self.debug_mode) self.daemon.UpdateState() @dbus.service.method('org.wicd.daemon.wired') def CreateWiredNetworkProfile(self, profilename, default=False): - """ Creates a wired network profile. """ + """Creates a wired network profile.""" if not profilename: return False profilename = misc.to_unicode(profilename) @@ -1576,9 +1585,9 @@ class WiredDaemon(dbus.service.Object, object): if self.config.has_section(profilename): return False - for option in ["ip", "broadcast", "netmask", "gateway", "search_domain", - "dns_domain", "dns1", "dns2", "dns3", "beforescript", - "afterscript", "predisconnectscript", + for option in ["ip", "broadcast", "netmask", "gateway", + "search_domain", "dns_domain", "dns1", "dns2", "dns3", + "beforescript", "afterscript", "predisconnectscript", "postdisconnectscript", "encryption_enabled"]: self.config.set(profilename, option, None) self.config.set(profilename, "default", default) @@ -1588,7 +1597,7 @@ class WiredDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon.wired') def UnsetWiredLastUsed(self): - """ Finds the previous lastused network, and sets lastused to False. """ + """Finds the previous lastused network, and sets lastused to False.""" profileList = self.config.sections() for profile in profileList: if misc.to_bool(self.config.get(profile, "lastused")): @@ -1596,7 +1605,7 @@ class WiredDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon.wired') def UnsetWiredDefault(self): - """ Unsets the default option in the current default wired profile. """ + """Unsets the default option in the current default wired profile.""" profileList = self.config.sections() for profile in profileList: if misc.to_bool(self.config.get(profile, "default")): @@ -1604,7 +1613,7 @@ class WiredDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon.wired') def GetDefaultWiredNetwork(self): - """ Returns the current default wired network. """ + """Returns the current default wired network.""" profileList = self.config.sections() for profile in profileList: if misc.to_bool(self.config.get(profile, "default")): @@ -1613,7 +1622,7 @@ class WiredDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon.wired') def GetLastUsedWiredNetwork(self): - """ Returns the profile of the last used wired network. """ + """Returns the profile of the last used wired network.""" profileList = self.config.sections() for profile in profileList: if misc.to_bool(self.config.get(profile, "lastused")): @@ -1622,7 +1631,7 @@ class WiredDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon.wired') def DeleteWiredNetworkProfile(self, profilename): - """ Deletes a wired network profile. """ + """Deletes a wired network profile.""" profilename = misc.to_unicode(profilename) print("Deleting wired profile for " + str(profilename)) self.config.remove_section(profilename) @@ -1630,7 +1639,7 @@ class WiredDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon.wired') def SaveWiredNetworkProfile(self, profilename): - """ Writes a wired network profile to disk. """ + """Writes a wired network profile to disk.""" def write_script_ent(prof, script): if not self.config.has_option(prof, script): self.config.set(prof, script, None) @@ -1657,7 +1666,7 @@ class WiredDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon.wired') def ReadWiredNetworkProfile(self, profilename): - """ Reads a wired network profile in as the currently active profile """ + """Reads a wired network profile in as the currently active profile""" profile = {} profilename = misc.to_unicode(profilename) if self.config.has_section(profilename): @@ -1680,7 +1689,7 @@ class WiredDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon.wired') def GetWiredProfileList(self): - """ Returns a list of all wired profiles in wired-settings.conf. """ + """Returns a list of all wired profiles in wired-settings.conf.""" sections = self.config.sections() if not sections: sections = [""] @@ -1688,7 +1697,7 @@ class WiredDaemon(dbus.service.Object, object): @dbus.service.method('org.wicd.daemon.wired') def ReloadConfig(self): - """ Reloads the active config file. """ + """Reloads the active config file.""" self.config.reload() @dbus.service.method('org.wicd.daemon.wired', out_signature='as') @@ -1696,10 +1705,11 @@ class WiredDaemon(dbus.service.Object, object): ''' Returns a list of wireless interfaces on the system. ''' return wnettools.GetWiredInterfaces() + def usage(): - """ Print help screen. """ + """Print help screen.""" print(""" -wicd %s +wicd %s wireless (and wired) connection daemon. Arguments: @@ -1712,8 +1722,9 @@ Arguments: \t-h\t--help\t\tPrint this help. """ % (wpath.version + ' (bzr-r%s)' % wpath.revision)) + def daemonize(): - """ Disconnect from the controlling terminal. + """Disconnect from the controlling terminal. Fork twice, once to disconnect ourselves from the parent terminal and a second time to prevent any files we open from becoming our controlling @@ -1730,7 +1741,8 @@ def daemonize(): if pid > 0: sys.exit(0) except OSError as e: - print("Fork #1 failed: %d (%s)" % (e.errno, e.strerror), file=sys.stderr) + print("Fork #1 failed: %d (%s)" % (e.errno, e.strerror), + file=sys.stderr) sys.exit(1) # Decouple from parent environment to stop us from being a zombie. @@ -1752,7 +1764,8 @@ def daemonize(): os.umask(0) os.chdir('/') except OSError as e: - print("Fork #2 failed: %d (%s)" % (e.errno, e.strerror), file=sys.stderr) + print("Fork #2 failed: %d (%s)" % (e.errno, e.strerror), + file=sys.stderr) sys.exit(1) sys.stdin.close() @@ -1763,7 +1776,7 @@ def daemonize(): maxfd = os.sysconf("SC_OPEN_MAX") except (AttributeError, ValueError): maxfd = 1024 - + for fd in range(0, maxfd): try: os.close(fd) @@ -1778,7 +1791,7 @@ def daemonize(): def main(argv): - """ The main daemon program. + """The main daemon program. Keyword arguments: argv -- The arguments passed to the script. @@ -1787,9 +1800,12 @@ def main(argv): # back up resolv.conf before we do anything else try: backup_location = wpath.varlib + 'resolv.conf.orig' - # Don't back up if the backup already exists, either as a regular file or a symlink - # The backup file should have been cleaned up by wicd, so perhaps it didn't exit cleanly... - if not os.path.exists(backup_location) and not os.path.islink(backup_location): + # Don't back up if the backup already exists, either as a regular file + # or a symlink + # The backup file should have been cleaned up by wicd, so perhaps it + # didn't exit cleanly... + if (not os.path.exists(backup_location) and + not os.path.islink(backup_location)): if os.path.islink('/etc/resolv.conf'): dest = os.readlink('/etc/resolv.conf') os.symlink(dest, backup_location) @@ -1808,9 +1824,9 @@ def main(argv): try: opts, args = getopt.getopt(sys.argv[1:], 'fenoahkc', - ['help', 'no-daemon', 'no-poll', 'no-stderr', - 'no-stdout', 'no-autoconnect', 'kill', - 'keep-connection']) + ['help', 'no-daemon', 'no-poll', + 'no-stderr', 'no-stdout', 'no-autoconnect', + 'kill', 'keep-connection']) except getopt.GetoptError: # Print help information and exit usage() @@ -1840,7 +1856,7 @@ def main(argv): try: f = open(wpath.pidfile) except IOError: - #print >> sys.stderr, "No wicd instance active, aborting." + # print >> sys.stderr, "No wicd instance active, aborting." sys.exit(1) # restore resolv.conf on quit @@ -1875,7 +1891,7 @@ def main(argv): if not os.path.exists(wpath.networks): os.makedirs(wpath.networks) - + if do_daemonize: daemonize() @@ -1914,10 +1930,10 @@ def main(argv): bus = dbus.SystemBus() wicd_bus = dbus.service.BusName('org.wicd.daemon', bus=bus) daemon = WicdDaemon(wicd_bus, auto_connect=auto_connect, - keep_connection=keep_connection) + keep_connection=keep_connection) child_pid = None if not no_poll: - child_pid = Popen([wpath.python, "-O", + child_pid = Popen([wpath.python, "-O", os.path.join(wpath.daemon, "monitor.py")], shell=False, close_fds=True).pid atexit.register(on_exit, child_pid) @@ -1930,8 +1946,9 @@ def main(argv): pass daemon.DaemonClosing() + def on_exit(child_pid): - """ Called when a SIGTERM is caught, kills monitor.py before exiting. """ + """Called when a SIGTERM is caught, kills monitor.py before exiting.""" if child_pid: print('Daemon going down, killing wicd-monitor...') try: @@ -1947,10 +1964,10 @@ def on_exit(child_pid): if __name__ == '__main__': if os.getuid() != 0: - print(("Root privileges are required for the daemon to run properly." + - " Exiting.")) + print("Root privileges are required for the daemon to run properly. " + "Exiting.") sys.exit(1) # No more needed since PyGObject 3.11, c.f. # https://wiki.gnome.org/PyGObject/Threading - #gobject.threads_init() + # gobject.threads_init() main(sys.argv) diff --git a/wicd/wnettools.py b/wicd/wnettools.py index 80b4037..6bef898 100644 --- a/wicd/wnettools.py +++ b/wicd/wnettools.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- -""" Network interface control tools for wicd. +"""Network interface control tools for wicd. This module implements functions to control and obtain information from network interfaces. @@ -31,29 +31,30 @@ class BaseWirelessInterface() -- Control a wireless network interface. # along with this program. If not, see . # -import os -import re -import random -import time import dbus -import socket, fcntl +import fcntl +import functools +import os +import random +import re import shutil -from functools import cmp_to_key +import socket +import time -from . import wpath -from . import misc -from .misc import find_path +from wicd import wpath +from wicd import misc +from wicd.misc import find_path # Regular expressions. _re_mode = (re.I | re.M | re.S) essid_pattern = re.compile('.*ESSID:"?(.*?)".*\n', _re_mode) ap_mac_pattern = re.compile('.*Address: (.*?)\n', _re_mode) -channel_pattern = re.compile('.*Channel:?=? ?(\d+)', _re_mode) -strength_pattern = re.compile('.*Quality:?=? ?(\d+)\s*/?\s*(\d*)', _re_mode) -altstrength_pattern = re.compile('.*Signal level:?=? ?(\d+)\s*/?\s*(\d*)', - _re_mode) -signaldbm_pattern = re.compile('.*Signal level:?=? ?(-\d\d*)', _re_mode) -bitrates_pattern = re.compile('([\d\.]+)\s+\S+/s', _re_mode) +channel_pattern = re.compile(r'.*Channel:?=? ?(\d+)', _re_mode) +strength_pattern = re.compile(r'.*Quality:?=? ?(\d+)\s*/?\s*(\d*)', _re_mode) +altstrength_pattern = re.compile(r'.*Signal level:?=? ?(\d+)\s*/?\s*(\d*)', + _re_mode) +signaldbm_pattern = re.compile(r'.*Signal level:?=? ?(-\d\d*)', _re_mode) +bitrates_pattern = re.compile(r'([\d\.]+)\s+\S+/s', _re_mode) mode_pattern = re.compile('.*Mode:([A-Za-z-]*?)\n', _re_mode) freq_pattern = re.compile('.*Frequency:(.*?)\n', _re_mode) wep_pattern = re.compile('.*Encryption key:(.*?)\n', _re_mode) @@ -61,17 +62,17 @@ altwpa_pattern = re.compile('(wpa_ie)', _re_mode) wpa1_pattern = re.compile('(WPA Version 1)', _re_mode) wpa2_pattern = re.compile('(WPA2)', _re_mode) -#iwconfig-only regular expressions. +# iwconfig-only regular expressions. ip_up = re.compile(r'flags=[0.9]*<([^>]*)>', re.S) ip_pattern = re.compile(r'inet [Aa]d?dr[^.]*:([^.]*\.[^.]*\.[^.]*\.[0-9]*)', - re.S) + re.S) ip_pattern1 = re.compile(r'inet ([^.]*\.[^.]*\.[^.]*\.[0-9]*)', re.S) -bssid_pattern = re.compile('.*[(Access Point)|(Cell)]: ' + \ - '(([0-9A-Z]{2}:){5}[0-9A-Z]{2})', _re_mode) +bssid_pattern = re.compile('.*[(Access Point)|(Cell)]: ' + '(([0-9A-Z]{2}:){5}[0-9A-Z]{2})', _re_mode) bitrate_pattern = re.compile('.*Bit Rate[=:](.*?/s)', _re_mode) opmode_pattern = re.compile('.*Mode:(.*?) ', _re_mode) -authmethods_pattern = re.compile('.*Authentication capabilities ' + \ - ':\n(.*?)Current', _re_mode) +authmethods_pattern = re.compile('.*Authentication capabilities ' + ':\n(.*?)Current', _re_mode) # Regular expressions for wpa_cli output auth_pattern = re.compile('.*wpa_state=(.*?)\n', _re_mode) @@ -85,47 +86,52 @@ blacklist_norm = list(";`$!*|><&\\") blacklist_strict_t = str.maketrans(dict.fromkeys(blacklist_strict, None)) blacklist_norm_t = str.maketrans(dict.fromkeys(blacklist_norm, None)) +_cache = {} + + def _sanitize_string(string): - """ Sanitize string. """ + """Sanitize string.""" if string: return str(string).translate(blacklist_norm_t) else: return string + def _sanitize_string_strict(string): - """ Sanitize string in a stricter way. """ + """Sanitize string in a stricter way.""" if string: return str(string).translate(blacklist_strict_t) else: return string - -_cache = {} + + def timedcache(duration=5): - """ A caching decorator for use with wnettools methods. - + """A caching decorator for use with wnettools methods. + Caches the results of a function for a given number of seconds (defaults to 5). - + """ def _timedcache(f): def __timedcache(self, *args, **kwargs): key = str(args) + str(kwargs) + str(f) if hasattr(self, 'iface'): key += self.iface - if (key in _cache and - (time.time() - _cache[key]['time']) < duration): + if (key in _cache and + (time.time() - _cache[key]['time']) < duration): return _cache[key]['value'] else: value = f(self, *args, **kwargs) - _cache[key] = { 'time' : time.time(), 'value' : value } + _cache[key] = {'time': time.time(), 'value': value} return value - + return __timedcache - + return _timedcache + def GetDefaultGateway(): - """ Attempts to determine the default gateway by parsing route -n. """ + """Attempts to determine the default gateway by parsing route -n.""" route_info = misc.Run("route -n") lines = route_info.split('\n') gateway = None @@ -137,20 +143,21 @@ def GetDefaultGateway(): if words[0] == '0.0.0.0': gateway = words[1] break - + if not gateway: print('couldn\'t retrieve default gateway from route -n') return gateway + def isWireless(devname): """ - Classic-style wifi device classification using linux/wireless.h + Classic-style wifi device classification using linux/wireless.h This should be extended or replaced by nl80211.h style classification in the future, if wireless.h is fully replaced. """ we = None for t in [socket.AF_INET, socket.AF_INET6, socket.AF_IPX, socket.AF_AX25, - socket.AF_APPLETALK]: + socket.AF_APPLETALK]: try: sk = socket.socket(t, socket.SOCK_DGRAM) except socket.error: @@ -159,7 +166,7 @@ def isWireless(devname): continue skfd = sk.fileno() try: - #define SIOCGIWNAME 0x8b01 in linux/wireless.h + # define SIOCGIWNAME 0x8b01 in linux/wireless.h # "used to verify the presence of wireless extensions" we = fcntl.ioctl(skfd, 0x8b01, devname) except IOError: @@ -167,8 +174,9 @@ def isWireless(devname): sk.close() return we is not None + def GetWirelessInterfaces(): - """ Get available wireless interfaces. + """Get available wireless interfaces. Attempts to get an interface first by parsing /proc/net/wireless, and should that fail, by parsing iwconfig. @@ -177,48 +185,55 @@ def GetWirelessInterfaces(): """ dev_dir = '/sys/class/net/' - ifnames = [iface for iface in os.listdir(dev_dir) if isWireless(str(iface))] + ifnames = [iface for iface in os.listdir(dev_dir) + if isWireless(str(iface))] return ifnames + def GetWiredInterfaces(): - """ Returns a list of wired interfaces on the system. """ + """Returns a list of wired interfaces on the system.""" basedir = '/sys/class/net/' return [iface for iface in os.listdir(basedir) - if os.path.isdir(basedir + iface) and not 'wireless' - in os.listdir(basedir + iface) and + if os.path.isdir(basedir + iface) and + 'wireless' not in os.listdir(basedir + iface) and open(basedir + iface + "/type").readlines()[0].strip() == "1"] + def NeedsExternalCalls(): - """ Returns True if the backend needs to use an external program. """ + """Returns True if the backend needs to use an external program.""" raise NotImplementedError + def GetWpaSupplicantDrivers(): - """ Returns a list of all valid wpa_supplicant drivers. """ + """Returns a list of all valid wpa_supplicant drivers.""" output = misc.Run(["wpa_supplicant", "-h"]) try: output = output.split("drivers:")[1].split("options:")[0].strip() except KeyError: print("Warning: Couldn't get list of valid wpa_supplicant drivers") return [""] - patt = re.compile("(\S+)\s+=.*") + patt = re.compile(r"(\S+)\s+=.*") drivers = patt.findall(output) or [""] # We cannot use the "wired" driver for wireless interfaces. if 'wired' in drivers: drivers.remove('wired') return drivers + + def IsValidWpaSuppDriver(driver): - """ Returns True if given string is a valid wpa_supplicant driver. """ + """Returns True if given string is a valid wpa_supplicant driver.""" output = misc.Run(["wpa_supplicant", "-D%s" % driver, "-iolan19", "-c/etc/abcd%sdefzz.zconfz" % random.randint(1, 1000)]) - return not "Unsupported driver" in output - + return "Unsupported driver" not in output + + def neediface(default_response): - """ A decorator for only running a method if self.iface is defined. - + """A decorator for only running a method if self.iface is defined. + This decorator is wrapped around Interface methods, and will return a provided default_response value if self.iface is not defined. - + """ def wrapper(func): def newfunc(self, *args, **kwargs): @@ -234,9 +249,9 @@ def neediface(default_response): class BaseInterface(object): - """ Control a network interface. """ + """Control a network interface.""" def __init__(self, iface, verbose=False): - """ Initialise the object. + """Initialise the object. Keyword arguments: iface -- the name of the interface @@ -247,7 +262,7 @@ class BaseInterface(object): self.verbose = verbose self.DHCP_CLIENT = None self.flush_tool = None - self.link_detect = None + self.link_detect = None self.dhcp_object = None self.ethtool_cmd = None @@ -268,50 +283,49 @@ class BaseInterface(object): self.ktsuss_cmd = None def SetDebugMode(self, value): - """ If True, verbose output is enabled. """ + """If True, verbose output is enabled.""" self.verbose = value def SetInterface(self, iface): - """ Sets the interface. - + """Sets the interface. + Keyword arguments: iface -- the name of the interface. - + """ self.iface = _sanitize_string_strict(str(iface)) - + def _find_program_path(self, program): - """ Determines the full path for the given program. - + """Determines the full path for the given program. + Searches for a given program name on the PATH. - + Keyword arguments: program -- The name of the program to search for - + Returns: The full path of the program or None - + """ path = find_path(program) if not path and self.verbose: print("WARNING: No path found for %s" % program) return path - def _get_dhcp_command(self, flavor=None, hostname=None, staticdns=False): - """ Returns the correct DHCP client command. - + """Returns the correct DHCP client command. + Given a type of DHCP request (create or release a lease), this method will build a command to complete the request using the correct dhcp client, and cli options. - + """ def get_client_name(cl): - """ Converts the integer value for a dhcp client to a string. """ + """Converts the integer value for a dhcp client to a string.""" if self.dhcpcd_cmd and cl in [misc.DHCPCD, misc.AUTO]: client = "dhcpcd" cmd = self.dhcpcd_cmd - elif self.pump_cmd and cl in [misc.PUMP, misc.AUTO]: + elif self.pump_cmd and cl in [misc.PUMP, misc.AUTO]: client = "pump" cmd = self.pump_cmd elif self.dhclient_cmd and cl in [misc.DHCLIENT, misc.AUTO]: @@ -327,37 +341,35 @@ class BaseInterface(object): cmd = "" return (client, cmd) - # probably /var/lib/wicd/dhclient.conf with defaults - dhclient_conf_path = os.path.join( - wpath.varlib, - 'dhclient.conf' - ) - + # probably /var/lib/wicd/dhclient.conf with defaults + dhclient_conf_path = os.path.join(wpath.varlib, 'dhclient.conf') + client_dict = { - "dhclient" : - {'connect' : r"%(cmd)s -cf %(dhclientconf)s %(extra)s %(iface)s", - 'connect_with_hostname' : r"%(cmd)s -cf %(dhclientconf)s %(extra)s %(iface)s", - 'release' : r"%(cmd)s -r %(iface)s", - 'id' : misc.DHCLIENT, - }, - "pump" : - { 'connect' : r"%(cmd)s -i %(iface)s %(extra)s", - 'connect_with_hostname' : r"%(cmd)s -i %(iface)s -h %(hostname)s %(extra)s", - 'release' : r"%(cmd)s -r -i %(iface)s", - 'id' : misc.PUMP, - }, - "dhcpcd" : - {'connect' : r"%(cmd)s --noipv4ll %(extra)s %(iface)s", - 'connect_with_hostname' : r"%(cmd)s -h %(hostname)s --noipv4ll %(extra)s %(iface)s ", - 'release' : r"%(cmd)s -k %(iface)s", - 'id' : misc.DHCPCD, - }, + "dhclient": + {'connect': r"%(cmd)s -cf %(dhclientconf)s " + r"%(extra)s %(iface)s", + 'connect_with_hostname': r"%(cmd)s -cf %(dhclientconf)s " + r"%(extra)s %(iface)s", + 'release': r"%(cmd)s -r %(iface)s", + 'id': misc.DHCLIENT}, + "pump": + {'connect': r"%(cmd)s -i %(iface)s %(extra)s", + 'connect_with_hostname': r"%(cmd)s -i %(iface)s -h " + r"%(hostname)s %(extra)s", + 'release': r"%(cmd)s -r -i %(iface)s", + 'id': misc.PUMP}, + "dhcpcd": + {'connect': r"%(cmd)s --noipv4ll %(extra)s %(iface)s", + 'connect_with_hostname': r"%(cmd)s -h %(hostname)s " + r"--noipv4ll %(extra)s %(iface)s ", + 'release': r"%(cmd)s -k %(iface)s", + 'id': misc.DHCPCD}, "udhcpc": - {'connect' : r"%(cmd)s -n -i %(iface)s %(extra)s", - 'connect_with_hostname' : r"%(cmd)s -n -i %(iface)s -H %(hostname)s %(extra)s", - 'release' : r"killall -SIGUSR2 %(cmd)s", - 'id' : misc.UDHCPC, - }, + {'connect': r"%(cmd)s -n -i %(iface)s %(extra)s", + 'connect_with_hostname': r"%(cmd)s -n -i %(iface)s -H " + r"%(hostname)s %(extra)s", + 'release': r"killall -SIGUSR2 %(cmd)s", + 'id': misc.UDHCPC}, } (client_name, cmd) = get_client_name(self.DHCP_CLIENT) @@ -366,29 +378,32 @@ class BaseInterface(object): if client_name == "dhclient" and flavor: if hostname: print('attempting to set hostname with dhclient') - print('using dhcpcd or another supported client may work better') + print('using dhcpcd or another supported client may work ' + 'better') - dhclient_template = \ - open(os.path.join(wpath.etc, 'dhclient.conf.template'), 'r') + dhclient_template = open(os.path. + join(wpath.etc, + 'dhclient.conf.template'), 'r') output_conf = open(dhclient_conf_path, 'w') for line in dhclient_template.readlines(): - line = line.replace('# ', 'send host-name "%s";' \ - % hostname) + line = line.replace('# ', 'send host-name ' + '"%s";' % hostname) output_conf.write(line) output_conf.close() dhclient_template.close() else: - shutil.copy(os.path.join(wpath.etc, 'dhclient.conf.template'), \ - dhclient_conf_path) + shutil.copy(os.path.join(wpath.etc, + 'dhclient.conf.template'), + dhclient_conf_path) os.chmod(dhclient_conf_path, 0o644) if not client_name or not cmd: print("WARNING: Failed to find a valid dhcp client!") return "" - + if flavor == "connect": # set up (optional) extra arguments to the dhcp client, @@ -398,36 +413,36 @@ class BaseInterface(object): extra_args = "--nohook resolv.conf" if hostname: - return client_dict[client_name]['connect_with_hostname'] % \ - { "cmd" : cmd, - "iface" : self.iface, - "hostname" : hostname, - 'extra': extra_args, - 'dhclientconf' : dhclient_conf_path } + return (client_dict[client_name]['connect_with_hostname'] % + {"cmd": cmd, + "iface": self.iface, + "hostname": hostname, + 'extra': extra_args, + 'dhclientconf': dhclient_conf_path}) else: - return client_dict[client_name]['connect'] % \ - { "cmd" : cmd, - "iface" : self.iface, - 'extra': extra_args, - 'dhclientconf' : dhclient_conf_path } + return (client_dict[client_name]['connect'] % + {"cmd": cmd, + "iface": self.iface, + 'extra': extra_args, + 'dhclientconf': dhclient_conf_path}) elif flavor == "release": - return client_dict[client_name]['release'] % \ - {"cmd": cmd, "iface": self.iface} + return client_dict[client_name]['release'] % {"cmd": cmd, + "iface": self.iface} else: return client_dict[client_name]['id'] - + def AppAvailable(self, app): - """ Return whether a given app is available. - + """Return whether a given app is available. + Given the name of an executable, determines if it is available for use by checking for a defined 'app'_cmd instance variable. - + """ return bool(self.__dict__.get("%s_cmd" % app.replace("-", ""))) - + def Check(self): - """ Check that all required tools are available. """ + """Check that all required tools are available.""" # THINGS TO CHECK FOR: ethtool, pptp-linux, dhclient, host self.CheckDHCP() self.CheckWiredTools() @@ -437,22 +452,22 @@ class BaseInterface(object): self.CheckResolvConf() def CheckResolvConf(self): - """ Checks for the existence of resolvconf.""" + """Checks for the existence of resolvconf.""" self.resolvconf_cmd = self._find_program_path("resolvconf") - + def CheckDHCP(self): - """ Check for the existence of valid DHCP clients. - + """Check for the existence of valid DHCP clients. + Checks for the existence of a supported DHCP client. If one is found, the appropriate values for DHCP_CMD, DHCP_RELEASE, and DHCP_CLIENT are set. If a supported client is not found, a warning is printed. - + """ self.dhclient_cmd = self._find_program_path("dhclient") - if self.dhclient_cmd != None: + if self.dhclient_cmd is not None: output = misc.Run(self.dhclient_cmd + " --version", - include_stderr=True) + include_stderr=True) if '4.' in output: self.dhclient_needs_verbose = True else: @@ -460,36 +475,36 @@ class BaseInterface(object): self.dhcpcd_cmd = self._find_program_path("dhcpcd") self.pump_cmd = self._find_program_path("pump") self.udhcpc_cmd = self._find_program_path("udhcpc") - + def CheckWiredTools(self): - """ Check for the existence of ethtool and mii-tool. """ + """Check for the existence of ethtool and mii-tool.""" self.miitool_cmd = self._find_program_path("mii-tool") self.ethtool_cmd = self._find_program_path("ethtool") - + def CheckWirelessTools(self): - """ Check for the existence of wpa_cli """ + """Check for the existence of wpa_cli""" self.wpa_cli_cmd = self._find_program_path("wpa_cli") if not self.wpa_cli_cmd: print("wpa_cli not found. Authentication will not be validated.") - + def CheckRouteFlushTool(self): - """ Check for a route flush tool. """ + """Check for a route flush tool.""" self.ip_cmd = self._find_program_path("ip") self.route_cmd = self._find_program_path("route") - + def CheckSudoApplications(self): - """ Check for available root-gaining 'sudo' applications. """ + """Check for available root-gaining 'sudo' applications.""" self.gksudo_cmd = self._find_program_path("gksudo") self.kdesu_cmd = self._find_program_path("kdesu") self.ktsuss_cmd = self._find_program_path("ktsuss") @neediface(False) def Up(self): - """ Bring the network interface up. - + """Bring the network interface up. + Returns: True - + """ cmd = 'ifconfig ' + self.iface + ' up' if self.verbose: @@ -499,22 +514,22 @@ class BaseInterface(object): @neediface(False) def Down(self): - """ Take down the network interface. - + """Take down the network interface. + Returns: True - + """ cmd = 'ifconfig ' + self.iface + ' down' if self.verbose: print(cmd) misc.Run(cmd) return True - + @timedcache(2) @neediface("") def GetIfconfig(self): - """ Runs ifconfig and returns the output. """ + """Runs ifconfig and returns the output.""" cmd = "ifconfig %s" % self.iface if self.verbose: print(cmd) @@ -522,7 +537,7 @@ class BaseInterface(object): @neediface("") def SetAddress(self, ip=None, netmask=None, broadcast=None): - """ Set the IP addresses of an interface. + """Set the IP addresses of an interface. Keyword arguments: ip -- interface IP address in dotted quad form @@ -536,7 +551,7 @@ class BaseInterface(object): if not misc.IsValidIP(val): print('WARNING: Invalid IP address found, aborting!') return False - + cmd = ''.join(['ifconfig ', self.iface, ' ']) if ip: cmd = ''.join([cmd, ip, ' ']) @@ -549,21 +564,21 @@ class BaseInterface(object): misc.Run(cmd) def _parse_dhclient(self, pipe): - """ Parse the output of dhclient. - + """Parse the output of dhclient. + Parses the output of dhclient and returns the status of the connection attempt. Keyword arguments: pipe -- stdout pipe to the dhclient process. - + Returns: 'success' if succesful', an error code string otherwise. - + """ dhclient_complete = False dhclient_success = False - + while not dhclient_complete: line = pipe.readline() if line == '': # Empty string means dhclient is done. @@ -573,22 +588,22 @@ class BaseInterface(object): if line.startswith('bound'): dhclient_success = True dhclient_complete = True - + return self._check_dhcp_result(dhclient_success) - + def _parse_pump(self, pipe): - """ Determines if obtaining an IP using pump succeeded. + """Determines if obtaining an IP using pump succeeded. Keyword arguments: pipe -- stdout pipe to the pump process. - + Returns: 'success' if succesful, an error code string otherwise. - + """ pump_complete = False pump_success = True - + while not pump_complete: line = pipe.readline() if line == '': @@ -597,22 +612,22 @@ class BaseInterface(object): pump_success = False pump_complete = True print(misc.to_unicode(line)) - + return self._check_dhcp_result(pump_success) def _parse_dhcpcd(self, pipe): - """ Determines if obtaining an IP using dhcpcd succeeded. - + """Determines if obtaining an IP using dhcpcd succeeded. + Keyword arguments: pipe -- stdout pipe to the dhcpcd process. - + Returns: 'success' if succesful, an error code string otherwise. - + """ dhcpcd_complete = False dhcpcd_success = True - + while not dhcpcd_complete: line = pipe.readline() if "Error" in line or "timed out" in line: @@ -621,11 +636,11 @@ class BaseInterface(object): elif line == '': dhcpcd_complete = True print(misc.to_unicode(line)) - + return self._check_dhcp_result(dhcpcd_success) def _parse_udhcpc(self, pipe): - """ Determines if obtaining an IP using udhcpc succeeded. + """Determines if obtaining an IP using udhcpc succeeded. Keyword arguments: pipe -- stdout pipe to the dhcpcd process. @@ -649,14 +664,14 @@ class BaseInterface(object): return self._check_dhcp_result(udhcpc_success) def _check_dhcp_result(self, success): - """ Print and return the correct DHCP connection result. - + """Print and return the correct DHCP connection result. + Keyword Arguments: success -- boolean specifying if DHCP was succesful. - + Returns: 'success' if success == True, 'dhcp_failed' otherwise. - + """ if success: print('DHCP connection successful') @@ -664,30 +679,29 @@ class BaseInterface(object): else: print('DHCP connection failed') return 'dhcp_failed' - + @neediface(False) def StartDHCP(self, hostname, staticdns): - """ Start the DHCP client to obtain an IP address. + """Start the DHCP client to obtain an IP address. Keyword Arguments: hostname -- the hostname to send to the DHCP server - + Returns: A string representing the result of the DHCP command. See _check_dhcp_result for the possible values. - + """ cmd = self._get_dhcp_command('connect', hostname, staticdns) if self.verbose: print(cmd) self.dhcp_object = misc.Run(cmd, include_stderr=True, return_obj=True) pipe = self.dhcp_object.stdout - client_dict = { misc.DHCLIENT : self._parse_dhclient, - misc.DHCPCD : self._parse_dhcpcd, - misc.PUMP : self._parse_pump, - misc.UDHCPC : self._parse_udhcpc, - } - + client_dict = {misc.DHCLIENT: self._parse_dhclient, + misc.DHCPCD: self._parse_dhcpcd, + misc.PUMP: self._parse_pump, + misc.UDHCPC: self._parse_udhcpc} + DHCP_CLIENT = self._get_dhcp_command() if DHCP_CLIENT in client_dict: ret = client_dict[DHCP_CLIENT](pipe) @@ -696,10 +710,10 @@ class BaseInterface(object): ret = None self.dhcp_object.wait() return ret - + @neediface(False) def ReleaseDHCP(self): - """ Release the DHCP lease for this interface. """ + """Release the DHCP lease for this interface.""" cmd = self._get_dhcp_command("release") if self.verbose: print(cmd) @@ -707,21 +721,21 @@ class BaseInterface(object): @neediface(False) def DelDefaultRoute(self): - """ Delete only the default route for a device. """ + """Delete only the default route for a device.""" if self.ip_cmd and self.flush_tool in [misc.AUTO, misc.IP]: cmd = '%s route del default dev %s' % (self.ip_cmd, self.iface) elif self.route_cmd and self.flush_tool in [misc.AUTO, misc.ROUTE]: cmd = '%s del default dev %s' % (self.route_cmd, self.iface) else: print("No route manipulation command available!") - return + return if self.verbose: print(cmd) misc.Run(cmd) @neediface(False) def FlushDNS(self): - """ Remove added DNS servers from system resolv.conf. + """Remove added DNS servers from system resolv.conf. Only useful for resolvconf-based setups. @@ -734,9 +748,9 @@ class BaseInterface(object): p.communicate() @neediface(False) - def SetDNS(self, dns1=None, dns2=None, dns3=None, + def SetDNS(self, dns1=None, dns2=None, dns3=None, dns_dom=None, search_dom=None): - """ Set the DNS of the system to the specified DNS servers. + """Set the DNS of the system to the specified DNS servers. Opens up resolv.conf and writes in the nameservers. @@ -762,7 +776,8 @@ class BaseInterface(object): print('Setting DNS : ' + dns) valid_dns_list.append("nameserver %s\n" % dns) else: - print('DNS IP %s is not a valid IP address, skipping' % dns) + print('DNS IP %s is not a valid IP address, skipping' % + dns) if valid_dns_list: resolv_params += ''.join(valid_dns_list) @@ -777,10 +792,10 @@ class BaseInterface(object): resolv = open("/etc/resolv.conf", "w") resolv.write(resolv_params + "\n") resolv.close() - + @neediface(False) def FlushRoutes(self): - """ Flush network routes for this device. """ + """Flush network routes for this device.""" if self.ip_cmd and self.flush_tool in [misc.AUTO, misc.IP]: cmds = ['%s route flush dev %s' % (self.ip_cmd, self.iface)] elif self.route_cmd and self.flush_tool in [misc.AUTO, misc.ROUTE]: @@ -795,7 +810,7 @@ class BaseInterface(object): @neediface(False) def SetDefaultRoute(self, gw): - """ Add a default route with the specified gateway. + """Add a default route with the specified gateway. Keyword arguments: gw -- gateway of the default route in dotted quad form @@ -811,7 +826,7 @@ class BaseInterface(object): @neediface("") def GetIP(self, ifconfig=""): - """ Get the IP address of the interface. + """Get the IP address of the interface. Returns: The IP address of the interface in dotted quad form. @@ -830,11 +845,11 @@ class BaseInterface(object): @neediface(False) def VerifyAPAssociation(self, gateway): - """ Verify assocation with an access point. - + """Verify assocation with an access point. + Verifies that an access point can be contacted by trying to ping it. - + """ if "iputils" in misc.Run(["ping", "-V"]): cmd = "ping -q -w 3 -c 1 %s" % gateway @@ -852,7 +867,7 @@ class BaseInterface(object): @neediface(False) def IsUp(self, ifconfig=None): - """ Determines if the interface is up. + """Determines if the interface is up. Returns: True if the interface is up, False otherwise. @@ -862,22 +877,21 @@ class BaseInterface(object): try: flags = open(flags_file, "r").read().strip() except IOError: - print("Could not open %s, using ifconfig to determine status" \ - % flags_file) + print("Could not open %s, using ifconfig to determine status" % + flags_file) return self._slow_is_up(ifconfig) return bool(int(flags, 16) & 1) - + @neediface(False) def StopWPA(self): - """ Terminates wpa using wpa_cli""" + """Terminates wpa using wpa_cli""" cmd = 'wpa_cli -i %s terminate' % self.iface if self.verbose: print(cmd) misc.Run(cmd) - - + def _slow_is_up(self, ifconfig=None): - """ Determine if an interface is up using ifconfig. """ + """Determine if an interface is up using ifconfig.""" if not ifconfig: output = self.GetIfconfig() else: @@ -892,14 +906,14 @@ class BaseInterface(object): # check classic ifconfig output style for line in lines[1:4]: if line.strip().startswith('UP'): - return True + return True return False class BaseWiredInterface(BaseInterface): - """ Control a wired network interface. """ + """Control a wired network interface.""" def __init__(self, iface, verbose=False): - """ Initialise the wired network interface class. + """Initialise the wired network interface class. Keyword arguments: iface -- name of the interface @@ -910,7 +924,7 @@ class BaseWiredInterface(BaseInterface): @neediface(False) def GetPluggedIn(self): - """ Get the current physical connection state. + """Get the current physical connection state. The method will first attempt to use ethtool do determine physical connection state. Should ethtool fail to run properly, @@ -933,7 +947,7 @@ class BaseWiredInterface(BaseInterface): time.sleep(2) if self.IsUp() or tries > MAX_TRIES: break - + if os.path.exists(carrier_path): carrier = open(carrier_path, 'r') try: @@ -944,12 +958,13 @@ class BaseWiredInterface(BaseInterface): elif link == 0: return False except (IOError, ValueError, TypeError): - print('Error checking link using /sys/class/net/%s/carrier' \ - % self.iface) - + print('Error checking link using /sys/class/net/%s/carrier' % + self.iface) + if self.ethtool_cmd and self.link_detect in [misc.ETHTOOL, misc.AUTO]: return self._eth_get_plugged_in() - elif self.miitool_cmd and self.link_detect in [misc.MIITOOL, misc.AUTO]: + elif self.miitool_cmd and self.link_detect in [misc.MIITOOL, + misc.AUTO]: return self._mii_get_plugged_in() else: print(('Error: No way of checking for a wired connection. Make ' + @@ -957,11 +972,11 @@ class BaseWiredInterface(BaseInterface): return False def _eth_get_plugged_in(self): - """ Use ethtool to determine the physical connection state. - + """Use ethtool to determine the physical connection state. + Returns: True if a link is detected, False otherwise. - + """ cmd = "%s %s" % (self.ethtool_cmd, self.iface) if not self.IsUp(): @@ -971,26 +986,24 @@ class BaseWiredInterface(BaseInterface): if self.verbose: print(cmd) tool_data = misc.Run(cmd, include_stderr=True) - if misc.RunRegex( - re.compile('(Link detected: yes)', re.I | re.M | re.S), - tool_data - ): + if misc.RunRegex(re.compile('(Link detected: yes)', + re.I | re.M | re.S), tool_data): return True else: return False - + def _mii_get_plugged_in(self): - """ Use mii-tool to determine the physical connection state. - + """Use mii-tool to determine the physical connection state. + Returns: True if a link is detected, False otherwise. - + """ cmd = "%s %s" % (self.miitool_cmd, self.iface) if self.verbose: print(cmd) tool_data = misc.Run(cmd, include_stderr=True) - if misc.RunRegex(re.compile('(Invalid argument)', re.I | re.M | re.S), + if misc.RunRegex(re.compile('(Invalid argument)', re.I | re.M | re.S), tool_data) is not None: print('Wired Interface is down, putting it up') self.Up() @@ -998,15 +1011,15 @@ class BaseWiredInterface(BaseInterface): if self.verbose: print(cmd) tool_data = misc.Run(cmd, include_stderr=True) - + if misc.RunRegex(re.compile('(link ok)', re.I | re.M | re.S), tool_data) is not None: return True else: return False - + def Authenticate(self, network): - """ Authenticate with wpa_supplicant. """ + """Authenticate with wpa_supplicant.""" misc.ParseEncryption(network) cmd = ['wpa_supplicant', '-B', '-i', self.iface, '-c', os.path.join(wpath.networks, 'wired'), @@ -1015,10 +1028,11 @@ class BaseWiredInterface(BaseInterface): print(cmd) misc.Run(cmd) + class BaseWirelessInterface(BaseInterface): - """ Control a wireless network interface. """ + """Control a wireless network interface.""" def __init__(self, iface, verbose=False, wpa_driver='wext'): - """ Initialise the wireless network interface class. + """Initialise the wireless network interface class. Keyword arguments: iface -- name of the interface @@ -1028,14 +1042,14 @@ class BaseWirelessInterface(BaseInterface): BaseInterface.__init__(self, iface, verbose) self.wpa_driver = wpa_driver self.scan_iface = None - + def SetWpaDriver(self, driver): - """ Sets the wpa_driver. """ + """Sets the wpa_driver.""" self.wpa_driver = _sanitize_string(driver) @neediface(False) def SetEssid(self, essid): - """ Set the essid of the wireless interface. + """Set the essid of the wireless interface. Keyword arguments: essid -- essid to set the interface to @@ -1048,11 +1062,11 @@ class BaseWirelessInterface(BaseInterface): @neediface(False) def GetKillSwitchStatus(self): - """ Determines if the wireless killswitch is enabled. - + """Determines if the wireless killswitch is enabled. + Returns: True if the killswitch is enabled, False otherwise. - + """ output = self.GetIwconfig() @@ -1063,18 +1077,18 @@ class BaseWirelessInterface(BaseInterface): radiostatus = False return radiostatus - + @timedcache(2) @neediface(False) def GetIwconfig(self): - """ Returns the output of iwconfig for this interface. """ + """Returns the output of iwconfig for this interface.""" cmd = "iwconfig " + self.iface if self.verbose: print(cmd) return misc.Run(cmd) def _FreqToChannel(self, freq): - """ Translate the specified frequency to a channel. + """Translate the specified frequency to a channel. Note: This function is simply a lookup dict and therefore the freq argument must be in the dict to provide a valid channel. @@ -1088,24 +1102,25 @@ class BaseWirelessInterface(BaseInterface): """ ret = None freq_dict = {'2.412 GHz': 1, '2.417 GHz': 2, '2.422 GHz': 3, - '2.427 GHz': 4, '2.432 GHz': 5, '2.437 GHz': 6, - '2.442 GHz': 7, '2.447 GHz': 8, '2.452 GHz': 9, - '2.457 GHz': 10, '2.462 GHz': 11, '2.467 GHz': 12, - '2.472 GHz': 13, '2.484 GHz': 14 } + '2.427 GHz': 4, '2.432 GHz': 5, '2.437 GHz': 6, + '2.442 GHz': 7, '2.447 GHz': 8, '2.452 GHz': 9, + '2.457 GHz': 10, '2.462 GHz': 11, '2.467 GHz': 12, + '2.472 GHz': 13, '2.484 GHz': 14} try: ret = freq_dict[freq] except KeyError: - print("Couldn't determine channel number for frequency:", str(freq)) - + print("Couldn't determine channel number for frequency:", + str(freq)) + return ret def _GetRalinkInfo(self): - """ Get a network info list used for ralink drivers - + """Get a network info list used for ralink drivers + Calls iwpriv get_site_survey, which on some ralink cards will return encryption and signal strength info for wireless networks in the area. - + """ iwpriv = misc.Run('iwpriv ' + self.iface + ' get_site_survey') if self.verbose: @@ -1156,7 +1171,7 @@ class BaseWirelessInterface(BaseInterface): return aps def _ParseRalinkAccessPoint(self, ap, ralink_info, cell): - """ Parse encryption and signal strength info for ralink cards + """Parse encryption and signal strength info for ralink cards Keyword arguments: ap -- array containing info about the current access point @@ -1179,7 +1194,7 @@ class BaseWirelessInterface(BaseInterface): @neediface(False) def SetMode(self, mode): - """ Set the mode of the wireless interface. + """Set the mode of the wireless interface. Keyword arguments: mode -- mode to set the interface to @@ -1197,7 +1212,7 @@ class BaseWirelessInterface(BaseInterface): @neediface(False) def SetChannel(self, channel): - """ Set the channel of the wireless interface. + """Set the channel of the wireless interface. Keyword arguments: channel -- channel to set the interface to @@ -1206,7 +1221,7 @@ class BaseWirelessInterface(BaseInterface): if not channel.isdigit(): print('WARNING: Invalid channel found. Aborting!') return False - + cmd = 'iwconfig %s channel %s' % (self.iface, str(channel)) if self.verbose: print(cmd) @@ -1214,7 +1229,7 @@ class BaseWirelessInterface(BaseInterface): @neediface(False) def SetKey(self, key): - """ Set the encryption key of the wireless interface. + """Set the encryption key of the wireless interface. Keyword arguments: key -- encryption key to set @@ -1234,7 +1249,7 @@ class BaseWirelessInterface(BaseInterface): allow_lower -- whether to allow lower bitrates, or keep it fixed (bool) ''' # FIXME: what if, in future, bitrates won't be "M(egabit per second)" - #+anymore? + # +anymore? if bitrate == 'auto': cmd = 'iwconfig %s rate auto' else: @@ -1246,7 +1261,7 @@ class BaseWirelessInterface(BaseInterface): @neediface(False) def Associate(self, essid, channel=None, bssid=None): - """ Associate with the specified wireless network. + """Associate with the specified wireless network. Keyword arguments: essid -- essid of the network @@ -1266,19 +1281,19 @@ class BaseWirelessInterface(BaseInterface): if self.verbose: print(cmd) misc.Run(cmd) - + def GeneratePSK(self, network): - """ Generate a PSK using wpa_passphrase. + """Generate a PSK using wpa_passphrase. Keyword arguments: network -- dictionary containing network info - + """ wpa_pass_path = misc.find_path('wpa_passphrase') if not wpa_pass_path: return None - key_pattern = re.compile('network={.*?\spsk=(.*?)\n}.*', - re.I | re.M | re.S) + key_pattern = re.compile(r'network={.*?\spsk=(.*?)\n}.*', + re.I | re.M | re.S) cmd = [wpa_pass_path, str(network['essid']), str(network['key'])] if self.verbose: print(cmd) @@ -1286,7 +1301,7 @@ class BaseWirelessInterface(BaseInterface): @neediface(False) def Authenticate(self, network): - """ Authenticate with the specified wireless network. + """Authenticate with the specified wireless network. Keyword arguments: network -- dictionary containing network info @@ -1301,7 +1316,7 @@ class BaseWirelessInterface(BaseInterface): else: driver = '-D' + self.wpa_driver cmd = ['wpa_supplicant', '-B', '-i', self.iface, '-c', - os.path.join(wpath.networks, + os.path.join(wpath.networks, network['bssid'].replace(':', '').lower()), driver] if self.verbose: @@ -1309,7 +1324,7 @@ class BaseWirelessInterface(BaseInterface): misc.Run(cmd) def _AuthenticateRalinkLegacy(self, network): - """ Authenticate with the specified wireless network. + """Authenticate with the specified wireless network. This function handles Ralink legacy cards that cannot use wpa_supplicant. @@ -1318,14 +1333,14 @@ class BaseWirelessInterface(BaseInterface): network -- dictionary containing network info """ - if network.get('key') != None: + if network.get('key') is not None: try: info = self._GetRalinkInfo()[network.get('bssid')] except KeyError: - print("Could not find current network in iwpriv " + \ + print("Could not find current network in iwpriv " "get_site_survey results. Cannot authenticate.") return - + if info['enctype'] == "WEP" and info['authtype'] == 'OPEN': print('Setting up WEP') cmd = ''.join(['iwconfig ', self.iface, ' key ', @@ -1342,7 +1357,7 @@ class BaseWirelessInterface(BaseInterface): cmd_list.append('%(keyname)s="%(key)s"' % network) if info['nettype'] == 'SHARED' and info['enctype'] == 'WEP': cmd_list.append('DefaultKeyID=1') - + for cmd in cmd_list: cmd = ['iwpriv', self.iface, 'set', cmd] if self.verbose: @@ -1351,7 +1366,7 @@ class BaseWirelessInterface(BaseInterface): @neediface([]) def GetNetworks(self, essid=None): - """ Get a list of available wireless networks. + """Get a list of available wireless networks. Returns: A list containing available wireless networks. @@ -1360,8 +1375,10 @@ class BaseWirelessInterface(BaseInterface): cmd = 'iwlist ' + self.iface + ' scan' - # If there is a hidden essid then it was set earlier, with iwconfig wlan0 essid, - # but on some drivers (iwlwifi, in my case) we have to pass it to iwlist scan. + # If there is a hidden essid then it was set earlier, with + # iwconfig wlan0 essid, + # but on some drivers (iwlwifi, in my case) we have to pass it to + # iwlist scan. essid = misc.Noneify(essid) if essid is not None: print('Passing hidden essid to iwlist scan: ' + essid) @@ -1374,7 +1391,7 @@ class BaseWirelessInterface(BaseInterface): # this way we can look at only one network at a time. # The spaces around ' Cell ' are to minimize the chance that someone # has an essid named Cell... - networks = results.split( ' Cell ' ) + networks = results.split(' Cell ') # Get available network info from iwpriv get_site_survey # if we're using a ralink card (needed to get encryption info) @@ -1395,14 +1412,14 @@ class BaseWirelessInterface(BaseInterface): # Normally we only get duplicate bssids with hidden # networks. If we hit this, we only want the entry # with the real essid to be in the network list. - if (entry['bssid'] not in access_points - or not entry['hidden']): + if (entry['bssid'] not in access_points + or not entry['hidden']): access_points[entry['bssid']] = entry return list(access_points.values()) - + def _ParseAccessPoint(self, cell, ralink_info): - """ Parse a single cell from the output of iwlist. + """Parse a single cell from the output of iwlist. Keyword arguments: cell -- string containing the cell information @@ -1436,7 +1453,7 @@ class BaseWirelessInterface(BaseInterface): # Channel - For cards that don't have a channel number, # convert the frequency. ap['channel'] = misc.RunRegex(channel_pattern, cell) - if ap['channel'] == None: + if ap['channel'] is None: freq = misc.RunRegex(freq_pattern, cell) ap['channel'] = self._FreqToChannel(freq) @@ -1445,7 +1462,10 @@ class BaseWirelessInterface(BaseInterface): m = re.findall(bitrates_pattern, bitrates) if m: # numeric sort - ap['bitrates'] = sorted(m, key=cmp_to_key(lambda x, y: int(float(x) - float(y)))) + ap['bitrates'] = sorted(m, + key=functools. + cmp_to_key(lambda x, y: + int(float(x) - float(y)))) else: ap['bitrates'] = None @@ -1487,13 +1507,14 @@ class BaseWirelessInterface(BaseInterface): # quality displayed or it isn't found) if misc.RunRegex(signaldbm_pattern, cell): ap['strength'] = misc.RunRegex(signaldbm_pattern, cell) - elif self.wpa_driver != RALINK_DRIVER: # This is already set for ralink + # This is already set for ralink + elif self.wpa_driver != RALINK_DRIVER: ap['strength'] = -1 return ap def ValidateAuthentication(self, auth_time): - """ Validate WPA authentication. + """Validate WPA authentication. Validate that the wpa_supplicant authentication process was successful. @@ -1501,10 +1522,10 @@ class BaseWirelessInterface(BaseInterface): NOTE: It's possible this could return False, though in reality wpa_supplicant just isn't finished yet. - + Keyword arguments: auth_time -- The time at which authentication began. - + Returns: True if wpa_supplicant authenticated succesfully, False otherwise. @@ -1543,18 +1564,17 @@ class BaseWirelessInterface(BaseInterface): print('wpa_supplicant authentication may have failed.') return False - def _ForceSupplicantScan(self): - """ Force wpa_supplicant to rescan available networks. - + """Force wpa_supplicant to rescan available networks. + This function forces wpa_supplicant to rescan. This works around authentication validation sometimes failing for - wpa_supplicant because it remains in a DISCONNECTED state for + wpa_supplicant because it remains in a DISCONNECTED state for quite a while, after which a rescan is required, and then attempting to authenticate. This whole process takes a long time, so we manually speed it up if we see it happening. - + """ print('wpa_supplicant rescan forced...') cmd = 'wpa_cli -i' + self.iface + ' scan' @@ -1562,34 +1582,34 @@ class BaseWirelessInterface(BaseInterface): @neediface("") def GetBSSID(self, iwconfig=None): - """ Get the MAC address for the interface. """ + """Get the MAC address for the interface.""" if not iwconfig: output = self.GetIwconfig() else: output = iwconfig - + bssid = misc.RunRegex(bssid_pattern, output) return bssid @neediface("") def GetCurrentBitrate(self, iwconfig=None): - """ Get the current bitrate for the interface. """ + """Get the current bitrate for the interface.""" if not iwconfig: output = self.GetIwconfig() else: output = iwconfig - + bitrate = misc.RunRegex(bitrate_pattern, output) return bitrate @neediface("") def GetOperationalMode(self, iwconfig=None): - """ Get the operational mode for the interface. """ + """Get the operational mode for the interface.""" if not iwconfig: output = self.GetIwconfig() else: output = iwconfig - + opmode = misc.RunRegex(opmode_pattern, output) if opmode: opmode = opmode.strip() @@ -1597,7 +1617,7 @@ class BaseWirelessInterface(BaseInterface): @neediface("") def GetAvailableAuthMethods(self, iwlistauth=None): - """ Get the available authentication methods for the interface. """ + """Get the available authentication methods for the interface.""" if not iwlistauth: cmd = 'iwlist ' + self.iface + ' auth' if self.verbose: @@ -1605,14 +1625,14 @@ class BaseWirelessInterface(BaseInterface): output = misc.Run(cmd) else: output = iwlistauth - + authm = misc.RunRegex(authmethods_pattern, output) authm_list = [m.strip() for m in authm.split('\n') if m.strip()] return ';'.join(authm_list) @neediface('') def GetAvailableBitrates(self): - """ Get the available bitrates the wifi card can use. """ + """Get the available bitrates the wifi card can use.""" cmd = 'iwlist ' + self.iface + ' rate' if self.verbose: @@ -1626,7 +1646,7 @@ class BaseWirelessInterface(BaseInterface): return dbus.Array(rates, signature='v') def _get_link_quality(self, output): - """ Parse out the link quality from iwlist scan or iwconfig output. """ + """Parse out the link quality from iwlist scan or iwconfig output.""" try: [(strength, max_strength)] = strength_pattern.findall(output) except ValueError: @@ -1634,12 +1654,13 @@ class BaseWirelessInterface(BaseInterface): if strength in ['', None]: try: - [(strength, max_strength)] = altstrength_pattern.findall(output) + [(strength, + max_strength)] = altstrength_pattern.findall(output) except ValueError: # if the pattern was unable to match anything # we'll return 101, which will allow us to stay # connected even though we don't know the strength - # it also allows us to tell if + # it also allows us to tell if return 101 if strength not in ['', None] and max_strength: return (100 * int(strength) // int(max_strength)) @@ -1650,7 +1671,7 @@ class BaseWirelessInterface(BaseInterface): @neediface(-1) def GetSignalStrength(self, iwconfig=None): - """ Get the signal strength of the current network. + """Get the signal strength of the current network. Returns: The signal strength. @@ -1661,10 +1682,10 @@ class BaseWirelessInterface(BaseInterface): else: output = iwconfig return self._get_link_quality(output) - + @neediface(-100) def GetDBMStrength(self, iwconfig=None): - """ Get the dBm signal strength of the current network. + """Get the dBm signal strength of the current network. Returns: The dBm signal strength. @@ -1679,7 +1700,7 @@ class BaseWirelessInterface(BaseInterface): @neediface("") def GetCurrentNetwork(self, iwconfig=None): - """ Get the essid of the current network. + """Get the essid of the current network. Returns: The current network essid.