1
0
mirror of https://github.com/gryf/wicd.git synced 2025-12-19 04:20:22 +01:00

Style changes for python files

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

View File

@@ -1,6 +1,6 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
""" Scriptable command-line interface. """ """Scriptable command-line interface."""
# This program is free software; you can redistribute it and/or modify # 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 # it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or # the Free Software Foundation; either version 2 of the License, or
@@ -17,9 +17,11 @@
# MA 02110-1301, USA. # MA 02110-1301, USA.
import optparse import optparse
import sys
import dbus import dbus
import dbus.service import dbus.service
import sys
from wicd import misc from wicd import misc
from wicd.translations import _ from wicd.translations import _
@@ -52,13 +54,13 @@ try:
'org.wicd.daemon.config' 'org.wicd.daemon.config'
) )
except dbus.DBusException: except dbus.DBusException:
print(('Error: Could not connect to the daemon. ' + \ print('Error: Could not connect to the daemon. Please make sure it is '
'Please make sure it is running.')) 'running.')
sys.exit(3) sys.exit(3)
if not daemon: if not daemon:
print(('Error connecting to wicd via D-Bus. ' + \ print('Error connecting to wicd via D-Bus. Please make sure the wicd '
'Please make sure the wicd service is running.')) 'service is running.')
sys.exit(3) sys.exit(3)
parser = optparse.OptionParser() parser = optparse.OptionParser()
@@ -71,7 +73,8 @@ parser.add_option('--name', '-m')
parser.add_option('--scan', '-S', default=False, action='store_true') parser.add_option('--scan', '-S', default=False, action='store_true')
parser.add_option('--save', '-w', 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('--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('--disconnect', '-x', default=False, action='store_true')
parser.add_option('--connect', '-c', default=False, action='store_true') parser.add_option('--connect', '-c', default=False, action='store_true')
parser.add_option('--list-encryption-types', '-e', default=False, parser.add_option('--list-encryption-types', '-e', default=False,
@@ -88,8 +91,8 @@ options, arguments = parser.parse_args()
op_performed = False op_performed = False
if not (options.wireless or options.wired) and not options.status: if not (options.wireless or options.wired) and not options.status:
print(("Please use --wireless or --wired to specify " + \ print("Please use --wireless or --wired to specify the type of "
"the type of connection to operate on.")) "connection to operate on.")
if options.status: if options.status:
status, info = daemon.GetConnectionStatus() status, info = daemon.GetConnectionStatus()
@@ -109,46 +112,47 @@ if options.status:
print((_('Connection type') + ': ' + conn_type)) print((_('Connection type') + ': ' + conn_type))
if status == misc.WIRELESS: if status == misc.WIRELESS:
strength = daemon.FormatSignalForPrinting(info[2]) strength = daemon.FormatSignalForPrinting(info[2])
print((_('Connected to $A at $B (IP: $C)') \ print(_('Connected to $A at $B (IP: $C)')
.replace('$A', info[1]) \ .replace('$A', info[1])
.replace('$B', strength) \ .replace('$B', strength)
.replace('$C', info[0]))) .replace('$C', info[0]))
print((_('Network ID: $A') \ print(_('Network ID: $A').replace('$A', info[3]))
.replace('$A', info[3])))
else: else:
print((_('Connected to wired network (IP: $A)') \ print(_('Connected to wired network (IP: $A)')
.replace('$A', info[0]))) .replace('$A', info[0]))
else: else:
if status == misc.CONNECTING: if status == misc.CONNECTING:
if info[0] == 'wired': if info[0] == 'wired':
print((_('Connecting to wired network.'))) print(_('Connecting to wired network.'))
elif info[0] == 'wireless': elif info[0] == 'wireless':
print((_('Connecting to wireless network "$A".') \ print(_('Connecting to wireless network "$A".')
.replace('$A', info[1]))) .replace('$A', info[1]))
op_performed = True op_performed = True
# functions
def is_valid_wireless_network_id(network_id): def is_valid_wireless_network_id(network_id):
""" Check if it's a valid wireless network. '""" """Check if it's a valid wireless network."""
if not (network_id >= 0 \ if not (network_id >= 0 and
and network_id < wireless.GetNumberOfNetworks()): network_id < wireless.GetNumberOfNetworks()):
print('Invalid wireless network identifier.') print('Invalid wireless network identifier.')
sys.exit(1) sys.exit(1)
def is_valid_wired_network_id(network_id): 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()) num = len(wired.GetWiredProfileList())
if not (network_id < num and \ if not (network_id < num and network_id >= 0):
network_id >= 0):
print('Invalid wired network identifier.') print('Invalid wired network identifier.')
sys.exit(4) sys.exit(4)
def is_valid_wired_network_profile(profile_name): def is_valid_wired_network_profile(profile_name):
""" Check if it's a valid wired network profile. '""" """Check if it's a valid wired network profile. """
if not profile_name in wired.GetWiredProfileList(): if profile_name not in wired.GetWiredProfileList():
print('Profile of that name does not exist.') print('Profile of that name does not exist.')
sys.exit(5) sys.exit(5)
if options.scan and options.wireless: if options.scan and options.wireless:
# synchronized scan # synchronized scan
wireless.Scan(True) wireless.Scan(True)
@@ -163,10 +167,11 @@ if options.list_networks:
if options.wireless: if options.wireless:
print('#\tBSSID\t\t\tChannel\tESSID') print('#\tBSSID\t\t\tChannel\tESSID')
for network_id in range(0, wireless.GetNumberOfNetworks()): for network_id in range(0, wireless.GetNumberOfNetworks()):
print(('%s\t%s\t%s\t%s' % (network_id, print('%s\t%s\t%s\t%s' %
(network_id,
wireless.GetWirelessProperty(network_id, 'bssid'), wireless.GetWirelessProperty(network_id, 'bssid'),
wireless.GetWirelessProperty(network_id, 'channel'), wireless.GetWirelessProperty(network_id, 'channel'),
wireless.GetWirelessProperty(network_id, 'essid')))) wireless.GetWirelessProperty(network_id, 'essid')))
elif options.wired: elif options.wired:
print('#\tProfile name') print('#\tProfile name')
i = 0 i = 0
@@ -186,22 +191,22 @@ if options.network_details:
# we're connected to a network, print IP # we're connected to a network, print IP
print(("IP: %s" % wireless.GetWirelessIP(0))) print(("IP: %s" % wireless.GetWirelessIP(0)))
print(("Essid: %s" % wireless.GetWirelessProperty(network_id, "essid"))) print("Essid: %s" % wireless.GetWirelessProperty(network_id, "essid"))
print(("Bssid: %s" % wireless.GetWirelessProperty(network_id, "bssid"))) print("Bssid: %s" % wireless.GetWirelessProperty(network_id, "bssid"))
if wireless.GetWirelessProperty(network_id, "encryption"): if wireless.GetWirelessProperty(network_id, "encryption"):
print("Encryption: On") print("Encryption: On")
print(("Encryption Method: %s" % \ print("Encryption Method: %s" %
wireless.GetWirelessProperty(network_id, "encryption_method"))) wireless.GetWirelessProperty(network_id,
"encryption_method"))
else: else:
print("Encryption: Off") print("Encryption: Off")
print(("Quality: %s" % \ print("Quality: %s" %
wireless.GetWirelessProperty(network_id, "quality"))) wireless.GetWirelessProperty(network_id, "quality"))
print(("Mode: %s" % \ print("Mode: %s" % wireless.GetWirelessProperty(network_id, "mode"))
wireless.GetWirelessProperty(network_id, "mode"))) print("Channel: %s" %
print(("Channel: %s" % \ wireless.GetWirelessProperty(network_id, "channel"))
wireless.GetWirelessProperty(network_id, "channel"))) print("Bit Rates: %s" %
print(("Bit Rates: %s" % \ wireless.GetWirelessProperty(network_id, "bitrates"))
wireless.GetWirelessProperty(network_id, "bitrates")))
op_performed = True op_performed = True
# network properties # network properties
@@ -216,11 +221,11 @@ if options.network_property:
network_id = wireless.GetCurrentNetworkID(0) network_id = wireless.GetCurrentNetworkID(0)
is_valid_wireless_network_id(network_id) is_valid_wireless_network_id(network_id)
if not options.set_to: if not options.set_to:
print((wireless.GetWirelessProperty(network_id, print(wireless.GetWirelessProperty(network_id,
options.network_property))) options.network_property))
else: else:
wireless.SetWirelessProperty(network_id, \ wireless.SetWirelessProperty(network_id, options.network_property,
options.network_property, options.set_to) options.set_to)
elif options.wired: elif options.wired:
if not options.set_to: if not options.set_to:
print((wired.GetWiredProperty(options.network_property))) print((wired.GetWiredProperty(options.network_property)))
@@ -232,13 +237,13 @@ if options.disconnect:
daemon.Disconnect() daemon.Disconnect()
if options.wireless: if options.wireless:
if wireless.GetCurrentNetworkID(0) > -1: if wireless.GetCurrentNetworkID(0) > -1:
print(("Disconnecting from %s on %s" % \ print("Disconnecting from %s on %s" %
(wireless.GetCurrentNetwork(0), (wireless.GetCurrentNetwork(0),
wireless.DetectWirelessInterface()))) wireless.DetectWirelessInterface()))
elif options.wired: elif options.wired:
if wired.CheckPluggedIn(): if wired.CheckPluggedIn():
print(("Disconnecting from wired connection on %s" % \ print("Disconnecting from wired connection on %s" %
wired.DetectWiredInterface())) wired.DetectWiredInterface())
op_performed = True op_performed = True
if options.connect: if options.connect:
@@ -247,16 +252,16 @@ if options.connect:
is_valid_wireless_network_id(options.network) is_valid_wireless_network_id(options.network)
name = wireless.GetWirelessProperty(options.network, 'essid') name = wireless.GetWirelessProperty(options.network, 'essid')
encryption = wireless.GetWirelessProperty(options.network, 'enctype') encryption = wireless.GetWirelessProperty(options.network, 'enctype')
print(("Connecting to %s with %s on %s" % (name, encryption, print("Connecting to %s with %s on %s" %
wireless.DetectWirelessInterface()))) (name, encryption, wireless.DetectWirelessInterface()))
wireless.ConnectWireless(options.network) wireless.ConnectWireless(options.network)
check = wireless.CheckIfWirelessConnecting check = wireless.CheckIfWirelessConnecting
status = wireless.CheckWirelessConnectingStatus status = wireless.CheckWirelessConnectingStatus
message = wireless.CheckWirelessConnectingMessage message = wireless.CheckWirelessConnectingMessage
elif options.wired: elif options.wired:
print(("Connecting to wired connection on %s" % \ print("Connecting to wired connection on %s" %
wired.DetectWiredInterface())) wired.DetectWiredInterface())
wired.ConnectWired() wired.ConnectWired()
check = wired.CheckIfWiredConnecting check = wired.CheckIfWiredConnecting
@@ -273,8 +278,8 @@ if options.connect:
while check(): while check():
next_ = status() next_ = status()
if next_ != last: if next_ != last:
# avoid a race condition where status is updated to "done" after # avoid a race condition where status is updated to "done"
# the loop check # after the loop check
if next_ == "done": if next_ == "done":
break break
print((message())) print((message()))
@@ -284,14 +289,16 @@ if options.connect:
exit_status = 6 exit_status = 6
op_performed = True op_performed = True
def str_properties(prop): def str_properties(prop):
""" Pretty print optional and required properties. """ """Pretty print optional and required properties."""
if len(prop) == 0: if len(prop) == 0:
return "None" return "None"
else: else:
tmp = [(x[0], x[1].replace('_', ' ')) for x in type['required']] tmp = [(x[0], x[1].replace('_', ' ')) for x in type['required']]
return ', '.join("%s (%s)" % (x, y) for x, y in tmp) return ', '.join("%s (%s)" % (x, y) for x, y in tmp)
if options.wireless and options.list_encryption_types: if options.wireless and options.list_encryption_types:
et = misc.LoadEncryptionMethods() et = misc.LoadEncryptionMethods()
# print 'Installed encryption templates:' # print 'Installed encryption templates:'
@@ -302,7 +309,7 @@ if options.wireless and options.list_encryption_types:
print((' Req: %s' % str_properties(t['required']))) print((' Req: %s' % str_properties(t['required'])))
print('---') print('---')
# don't print optionals (yet) # don't print optionals (yet)
#print ' Opt: %s' % str_properties(type['optional']) # print ' Opt: %s' % str_properties(type['optional'])
i += 1 i += 1
op_performed = True op_performed = True
@@ -318,4 +325,3 @@ if not op_performed:
print("No operations performed.") print("No operations performed.")
sys.exit(exit_status) sys.exit(exit_status)

View File

@@ -23,16 +23,17 @@ Also recycles a lot of configscript.py, too. :-)
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA. # MA 02110-1301, USA.
import sys
import os
import urwid
import urwid.curses_display
from wicd.translations import _ from wicd.translations import _
from configscript import write_scripts, get_script_info from configscript import write_scripts, get_script_info
from configscript import none_to_blank, blank_to_none from configscript import none_to_blank, blank_to_none
import urwid
import urwid.curses_display
import sys
import os
ui = None ui = None
frame = None frame = None
pre_entry = None pre_entry = None
@@ -42,20 +43,18 @@ post_disconnect_entry = None
def main(argv): def main(argv):
""" Main function. """ """Main function."""
global ui, frame global ui, frame
if len(argv) < 2: if len(argv) < 2:
print('Network id to configure is missing, aborting.') print('Network id to configure is missing, aborting.')
sys.exit(1) sys.exit(1)
ui = urwid.curses_display.Screen() ui = urwid.curses_display.Screen()
ui.register_palette([ ui.register_palette([('body', 'default', 'default'),
('body', 'default', 'default'),
('focus', 'dark magenta', 'light gray'), ('focus', 'dark magenta', 'light gray'),
('editcp', 'default', 'default', 'standout'), ('editcp', 'default', 'default', 'standout'),
('editbx', 'light gray', 'dark blue'), ('editbx', 'light gray', 'dark blue'),
('editfc', 'white', 'dark blue', 'bold'), ('editfc', 'white', 'dark blue', 'bold')])
])
network = argv[1] network = argv[1]
network_type = argv[2] network_type = argv[2]
@@ -70,69 +69,69 @@ def main(argv):
global pre_entry, post_entry, pre_disconnect_entry, post_disconnect_entry global pre_entry, post_entry, pre_disconnect_entry, post_disconnect_entry
pre_entry = urwid.AttrWrap(urwid.Edit(pre_entry_t, pre_entry = urwid.AttrWrap(urwid.Edit(pre_entry_t,
none_to_blank(script_info.get('pre_entry'))), none_to_blank(script_info.
get('pre_entry'))),
'editbx', 'editfc') 'editbx', 'editfc')
post_entry = urwid.AttrWrap(urwid.Edit(post_entry_t, post_entry = urwid.AttrWrap(urwid.Edit(post_entry_t,
none_to_blank(script_info.get('post_entry'))), none_to_blank(script_info.
get('post_entry'))),
'editbx', 'editfc') 'editbx', 'editfc')
pre_disconnect_entry = urwid.AttrWrap(urwid.Edit(pre_disconnect_entry_t, pre_disconnect_entry = urwid.AttrWrap(
urwid.Edit(pre_disconnect_entry_t,
none_to_blank(script_info.get('pre_disconnect_entry'))), none_to_blank(script_info.get('pre_disconnect_entry'))),
'editbx', 'editfc') 'editbx', 'editfc')
post_disconnect_entry = urwid.AttrWrap(urwid.Edit(post_disconnect_entry_t, post_disconnect_entry = urwid.AttrWrap(
urwid.Edit(post_disconnect_entry_t,
none_to_blank(script_info.get('post_disconnect_entry'))), none_to_blank(script_info.get('post_disconnect_entry'))),
'editbx', 'editfc') 'editbx', 'editfc')
# The buttons # The buttons
ok_button = urwid.AttrWrap( ok_button = urwid.AttrWrap(urwid.Button(_('OK'), ok_callback), 'body',
urwid.Button(_('OK'), ok_callback), 'focus')
'body', 'focus' cancel_button = urwid.AttrWrap(urwid.Button(_('Cancel'), cancel_callback),
) 'body', 'focus')
cancel_button = urwid.AttrWrap(
urwid.Button(_('Cancel'), cancel_callback),
'body', 'focus'
)
button_cols = urwid.Columns([ok_button, cancel_button], dividechars=1) button_cols = urwid.Columns([ok_button, cancel_button], dividechars=1)
lbox = urwid.Pile([('fixed', 2, urwid.Filler(pre_entry)), 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(post_entry)),
('fixed', 2, urwid.Filler(pre_disconnect_entry)), ('fixed', 2, urwid.Filler(pre_disconnect_entry)),
('fixed', 2, urwid.Filler(post_disconnect_entry)), ('fixed', 2, urwid.Filler(post_disconnect_entry)),
#blank, blank, blank, blank, blank, # blank, blank, blank, blank, blank,
urwid.Filler(button_cols, 'bottom') urwid.Filler(button_cols, 'bottom')])
])
frame = urwid.Frame(lbox) frame = urwid.Frame(lbox)
result = ui.run_wrapper(run) result = ui.run_wrapper(run)
if result: if result:
script_info["pre_entry"] = blank_to_none(pre_entry.get_edit_text()) 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["post_entry"] = blank_to_none(post_entry.get_edit_text())
script_info["pre_disconnect_entry"] = \ script_info["pre_disconnect_entry"] = blank_to_none(
blank_to_none(pre_disconnect_entry.get_edit_text()) pre_disconnect_entry.get_edit_text())
script_info["post_disconnect_entry"] = \ script_info["post_disconnect_entry"] = blank_to_none(
blank_to_none(post_disconnect_entry.get_edit_text()) post_disconnect_entry.get_edit_text())
write_scripts(network, network_type, script_info) write_scripts(network, network_type, script_info)
OK_PRESSED = False OK_PRESSED = False
CANCEL_PRESSED = False CANCEL_PRESSED = False
def ok_callback(button_object, user_data=None): def ok_callback(button_object, user_data=None):
""" Callback. """ """Callback."""
global OK_PRESSED global OK_PRESSED
OK_PRESSED = True OK_PRESSED = True
def cancel_callback(button_object, user_data=None): def cancel_callback(button_object, user_data=None):
""" Callback. """ """Callback."""
global CANCEL_PRESSED global CANCEL_PRESSED
CANCEL_PRESSED = True CANCEL_PRESSED = True
def run(): def run():
""" Run the UI. """ """Run the UI."""
dim = ui.get_cols_rows() dim = ui.get_cols_rows()
ui.set_mouse_tracking() ui.set_mouse_tracking()
@@ -147,7 +146,7 @@ def run():
if "esc" in keys or 'Q' in keys: if "esc" in keys or 'Q' in keys:
return False return False
for k in keys: for k in keys:
#Send key to underlying widget: # Send key to underlying widget:
if urwid.is_mouse_event(k): if urwid.is_mouse_event(k):
event, button, col, row = k event, button, col, row = k
frame.mouse_event(dim, event, button, col, row, focus=True) frame.mouse_event(dim, event, button, col, row, focus=True)
@@ -159,6 +158,7 @@ def run():
if OK_PRESSED or 'meta enter' in keys: if OK_PRESSED or 'meta enter' in keys:
return True return True
if __name__ == '__main__': if __name__ == '__main__':
if os.getuid() != 0: if os.getuid() != 0:
print("Root privileges are required to configure scripts. Exiting.") print("Root privileges are required to configure scripts. Exiting.")

View File

@@ -1,7 +1,7 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# -* coding: utf-8 -*- # -* 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. wicd-curses.
""" """
@@ -51,7 +51,7 @@ class SelText(urwid.Text):
class NSelListBox(urwid.ListBox): class NSelListBox(urwid.ListBox):
""" Non-selectable ListBox. """ """Non-selectable ListBox."""
def selectable(self): def selectable(self):
return False return False
@@ -82,11 +82,11 @@ class DynWrap(urwid.AttrWrap):
self.__super.__init__(w, cur_attr, focus_attr) self.__super.__init__(w, cur_attr, focus_attr)
def get_sensitive(self): def get_sensitive(self):
""" Getter for sensitive property. """ """Getter for sensitive property."""
return self._sensitive return self._sensitive
def set_sensitive(self, state): def set_sensitive(self, state):
""" Setter for sensitive property. """ """Setter for sensitive property."""
if state: if state:
self.set_attr(self._attrs[0]) self.set_attr(self._attrs[0])
else: else:
@@ -95,11 +95,11 @@ class DynWrap(urwid.AttrWrap):
property(get_sensitive, set_sensitive) property(get_sensitive, set_sensitive)
def get_attrs(self): def get_attrs(self):
""" Getter for attrs property. """ """Getter for attrs property."""
return self._attrs return self._attrs
def set_attrs(self, attrs): def set_attrs(self, attrs):
""" Setter for attrs property. """ """Setter for attrs property."""
self._attrs = attrs self._attrs = attrs
property(get_attrs, set_attrs) property(get_attrs, set_attrs)
@@ -108,7 +108,7 @@ class DynWrap(urwid.AttrWrap):
class DynEdit(DynWrap): class DynEdit(DynWrap):
""" Edit DynWrap'ed to the most common specifications. """ """Edit DynWrap'ed to the most common specifications."""
# pylint: disable-msg=W0231 # pylint: disable-msg=W0231
def __init__(self, caption='', edit_text='', sensitive=True, def __init__(self, caption='', edit_text='', sensitive=True,
attrs=('editbx', 'editnfc'), focus_attr='editfc'): attrs=('editbx', 'editnfc'), focus_attr='editfc'):
@@ -119,7 +119,7 @@ class DynEdit(DynWrap):
class DynIntEdit(DynWrap): class DynIntEdit(DynWrap):
""" IntEdit DynWrap'ed to the most common specifications. """ """IntEdit DynWrap'ed to the most common specifications."""
# pylint: disable-msg=W0231 # pylint: disable-msg=W0231
def __init__(self, caption='', edit_text='', sensitive=True, def __init__(self, caption='', edit_text='', sensitive=True,
attrs=('editbx', 'editnfc'), focus_attr='editfc'): attrs=('editbx', 'editnfc'), focus_attr='editfc'):
@@ -130,12 +130,12 @@ class DynIntEdit(DynWrap):
class DynRadioButton(DynWrap): class DynRadioButton(DynWrap):
""" RadioButton DynWrap'ed to the most common specifications. """ """RadioButton DynWrap'ed to the most common specifications."""
# pylint: disable-msg=W0231 # pylint: disable-msg=W0231
def __init__(self, group, label, state='first True', on_state_change=None, def __init__(self, group, label, state='first True', on_state_change=None,
user_data=None, sensitive=True, attrs=('body', 'editnfc'), user_data=None, sensitive=True, attrs=('body', 'editnfc'),
focus_attr='body'): focus_attr='body'):
#caption = ('editcp', caption + ':') # caption = ('editcp', caption + ':')
button = urwid.RadioButton(group, label, state, on_state_change, button = urwid.RadioButton(group, label, state, on_state_change,
user_data) user_data)
# pylint: disable-msg=E1101 # pylint: disable-msg=E1101
@@ -143,7 +143,7 @@ class DynRadioButton(DynWrap):
class MaskingEditException(Exception): class MaskingEditException(Exception):
""" Custom exception. """ """Custom exception."""
pass pass
@@ -163,27 +163,27 @@ class MaskingEdit(urwid.Edit):
mask_mode="always", mask_char='*'): mask_mode="always", mask_char='*'):
self.mask_mode = mask_mode self.mask_mode = mask_mode
if len(mask_char) > 1: if len(mask_char) > 1:
raise MaskingEditException('Masks of more than one character are' + raise MaskingEditException('Masks of more than one character are '
' not supported!') 'not supported!')
self.mask_char = mask_char self.mask_char = mask_char
# pylint: disable-msg=E1101 # pylint: disable-msg=E1101
self.__super.__init__(caption, edit_text, multiline, align, wrap, self.__super.__init__(caption, edit_text, multiline, align, wrap,
allow_tab, edit_pos, layout) allow_tab, edit_pos, layout)
def get_caption(self): def get_caption(self):
""" Return caption. """ """Return caption."""
return self.caption return self.caption
def get_mask_mode(self): def get_mask_mode(self):
""" Getter for mask_mode property. """ """Getter for mask_mode property."""
return self.mask_mode return self.mask_mode
def set_mask_mode(self, mode): def set_mask_mode(self, mode):
""" Setter for mask_mode property.""" """Setter for mask_mode property."""
self.mask_mode = mode self.mask_mode = mode
def get_masked_text(self): def get_masked_text(self):
""" Get masked out text. """ """Get masked out text."""
return self.mask_char * len(self.get_edit_text()) return self.mask_char * len(self.get_edit_text())
def render(self, xxx_todo_changeme, focus=False): 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): if self.mask_mode == "off" or (self.mask_mode == 'no_focus' and focus):
# pylint: disable-msg=E1101 # pylint: disable-msg=E1101
canv = self.__super.render((maxcol, ), focus) canv = self.__super.render((maxcol, ), focus)
# The cache messes this thing up, because I am totally changing what # The cache messes this thing up, because I am totally changing
# is displayed. # what is displayed.
self._invalidate() self._invalidate()
return canv return canv
@@ -226,9 +226,10 @@ class TabColumns(urwid.WidgetWrap):
# FIXME Make the bottom_part optional # FIXME Make the bottom_part optional
# pylint: disable-msg=W0231 # pylint: disable-msg=W0231
def __init__(self, tab_str, tab_wid, title, bottom_part=None, def __init__(self, tab_str, tab_wid, title, bottom_part=None,
attr=('body', 'focus'), attrsel='tab active', attrtitle='header'): attr=('body', 'focus'), attrsel='tab active',
#self.bottom_part = bottom_part attrtitle='header'):
#title_wid = urwid.Text((attrtitle, title), align='right') # self.bottom_part = bottom_part
# title_wid = urwid.Text((attrtitle, title), align='right')
column_list = [] column_list = []
for w in tab_str: for w in tab_str:
text, trash = w.get_text() text, trash = w.get_text()
@@ -238,31 +239,31 @@ class TabColumns(urwid.WidgetWrap):
self.tab_map = dict(list(zip(tab_str, tab_wid))) self.tab_map = dict(list(zip(tab_str, tab_wid)))
self.active_tab = tab_str[0] self.active_tab = tab_str[0]
self.columns = urwid.Columns(column_list, dividechars=1) self.columns = urwid.Columns(column_list, dividechars=1)
#walker = urwid.SimpleListWalker([self.columns, tab_wid[0]]) # walker = urwid.SimpleListWalker([self.columns, tab_wid[0]])
#self.listbox = urwid.ListBox(walker) # self.listbox = urwid.ListBox(walker)
self.gen_pile(tab_wid[0], True) self.gen_pile(tab_wid[0], True)
self.frame = urwid.Frame(self.pile) self.frame = urwid.Frame(self.pile)
# pylint: disable-msg=E1101 # pylint: disable-msg=E1101
self.__super.__init__(self.frame) self.__super.__init__(self.frame)
def gen_pile(self, lbox, firstrun=False): def gen_pile(self, lbox, firstrun=False):
""" Make the pile in the middle. """ """Make the pile in the middle."""
self.pile = urwid.Pile([ self.pile = urwid.Pile([('fixed', 1,
('fixed', 1, urwid.Filler(self.columns, 'top')), urwid.Filler(self.columns, 'top')),
urwid.Filler(lbox, 'top', height=('relative', 99)), urwid.Filler(lbox, 'top',
#('fixed', 1, urwid.Filler(self.bottom_part, 'bottom')) height=('relative', 99))])
]) # ('fixed', 1, urwid.Filler(self.bottom_part, 'bottom'))])
if not firstrun: if not firstrun:
self.frame.set_body(self.pile) self.frame.set_body(self.pile)
self._w = self.frame self._w = self.frame
self._invalidate() self._invalidate()
def selectable(self): def selectable(self):
""" Return whether the widget is selectable. """ """Return whether the widget is selectable."""
return True return True
def keypress(self, size, key): 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 # If the key is page up or page down, move focus to the tabs and call
# left or right on the tabs. # left or right on the tabs.
if key == "page up" or key == "page down": if key == "page up" or key == "page down":
@@ -285,7 +286,7 @@ class TabColumns(urwid.WidgetWrap):
return key return key
def mouse_event(self, size, event, button, x, y, focus): def mouse_event(self, size, event, button, x, y, focus):
""" Handle mouse events. """ """Handle mouse events."""
wid = self.pile.get_focus().get_body() wid = self.pile.get_focus().get_body()
if wid == self.columns: if wid == self.columns:
self.active_tab.set_attr('body') self.active_tab.set_attr('body')
@@ -299,7 +300,7 @@ class TabColumns(urwid.WidgetWrap):
class ComboBoxException(Exception): class ComboBoxException(Exception):
""" Custom exception. """ """Custom exception."""
pass pass
@@ -314,39 +315,40 @@ class ComboBox(urwid.WidgetWrap):
class ComboSpace(urwid.WidgetWrap): class ComboSpace(urwid.WidgetWrap):
"""The actual menu-like space that comes down from the ComboBox""" """The actual menu-like space that comes down from the ComboBox"""
# pylint: disable-msg=W0231 # pylint: disable-msg=W0231
def __init__(self, l, body, ui, show_first, pos=(0, 0), def __init__(self, data, body, ui, show_first, pos=(0, 0),
attr=('body', 'focus')): attr=('body', 'focus')):
""" """
body : parent widget body : parent widget
l : stuff to include in the combobox data : stuff to include in the combobox
ui : the screen ui : the screen
show_first: index of the element in the list to pick first show_first: index of the element in the list to pick first
pos : a tuple of (row,col) where to put the list pos : a tuple of (row,col) where to put the list
attr : a tuple of (attr_no_focus,attr_focus) attr : a tuple of (attr_no_focus,attr_focus)
""" """
#Calculate width and height of the menu widget: # Calculate width and height of the menu widget:
height = len(l) height = len(data)
width = 0 width = 0
for entry in l: for entry in data:
if len(entry) > width: if len(entry) > width:
width = len(entry) width = len(entry)
content = [urwid.AttrWrap(SelText(w), attr[0], attr[1]) content = [urwid.AttrWrap(SelText(w), attr[0], attr[1])
for w in l] for w in data]
self._listbox = urwid.ListBox(content) self._listbox = urwid.ListBox(content)
self._listbox.set_focus(show_first) self._listbox.set_focus(show_first)
overlay = urwid.Overlay(self._listbox, body, ('fixed left', pos[0]), overlay = urwid.Overlay(self._listbox, body,
width + 2, ('fixed top', pos[1]), height) ('fixed left', pos[0]), width + 2,
('fixed top', pos[1]), height)
# pylint: disable-msg=E1101 # pylint: disable-msg=E1101
self.__super.__init__(overlay) self.__super.__init__(overlay)
def show(self, ui, display): def show(self, ui, display):
""" Show widget. """ """Show widget."""
dim = ui.get_cols_rows() dim = ui.get_cols_rows()
keys = True keys = True
#Event loop: # Event loop:
while True: while True:
if keys: if keys:
ui.draw_screen(dim, self.render(dim, True)) ui.draw_screen(dim, self.render(dim, True))
@@ -363,19 +365,19 @@ class ComboBox(urwid.WidgetWrap):
return text return text
for k in keys: for k in keys:
#Send key to underlying widget: # Send key to underlying widget:
self._w.keypress(dim, k) self._w.keypress(dim, k)
#def get_size(self): # def get_size(self):
# pylint: disable-msg=W0231 # pylint: disable-msg=W0231
def __init__(self, label='', l=None, attrs=('body', 'editnfc'), def __init__(self, label='', data=None, attrs=('body', 'editnfc'),
focus_attr='focus', use_enter=True, focus=0, callback=None, focus_attr='focus', use_enter=True, focus=0, callback=None,
user_args=None): user_args=None):
""" """
label : bit of text that preceeds the combobox. If it is "", then label : bit of text that preceeds the combobox. If it is "", then
ignore it ignore it
l : stuff to include in the combobox data : stuff to include in the combobox
body : parent widget body : parent widget
ui : the screen ui : the screen
row : where this object is to be found onscreen row : where this object is to be found onscreen
@@ -388,9 +390,9 @@ class ComboBox(urwid.WidgetWrap):
self.label = urwid.Text(label) self.label = urwid.Text(label)
self.attrs = attrs self.attrs = attrs
self.focus_attr = focus_attr self.focus_attr = focus_attr
if l is None: if data is None:
l = [] data = []
self.list = l self.list = data
s, trash = self.label.get_text() s, trash = self.label.get_text()
@@ -424,12 +426,12 @@ class ComboBox(urwid.WidgetWrap):
self.ui = None self.ui = None
self.row = None self.row = None
def set_list(self, l): def set_list(self, data):
""" Populate widget list. """ """Populate widget list."""
self.list = l self.list = data
def set_focus(self, index): def set_focus(self, index):
""" Set widget focus. """ """Set widget focus."""
if urwid.VERSION < (1, 1, 0): if urwid.VERSION < (1, 1, 0):
self.focus = index self.focus = index
else: else:
@@ -447,11 +449,11 @@ class ComboBox(urwid.WidgetWrap):
self.overlay._listbox.set_focus(index) self.overlay._listbox.set_focus(index)
def rebuild_combobox(self): def rebuild_combobox(self):
""" Rebuild combobox. """ """Rebuild combobox."""
self.build_combobox(self.parent, self.ui, self.row) self.build_combobox(self.parent, self.ui, self.row)
def build_combobox(self, parent, ui, row): def build_combobox(self, parent, ui, row):
""" Build combobox. """ """Build combobox."""
s, trash = self.label.get_text() s, trash = self.label.get_text()
if urwid.VERSION < (1, 1, 0): if urwid.VERSION < (1, 1, 0):
@@ -479,7 +481,7 @@ class ComboBox(urwid.WidgetWrap):
# If we press space or enter, be a combo box! # If we press space or enter, be a combo box!
def keypress(self, size, key): def keypress(self, size, key):
""" Handle keypresses. """ """Handle keypresses."""
activate = key == ' ' activate = key == ' '
if self.use_enter: if self.use_enter:
activate = activate or key == 'enter' activate = activate or key == 'enter'
@@ -490,43 +492,43 @@ class ComboBox(urwid.WidgetWrap):
retval = self.overlay.show(self.ui, self.parent) retval = self.overlay.show(self.ui, self.parent)
if retval is not None: if retval is not None:
self.set_focus(self.list.index(retval)) 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: if self.callback is not None:
self.callback(self, self.overlay._listbox.get_focus()[1], self.callback(self, self.overlay._listbox.get_focus()[1],
self.user_args) self.user_args)
return self._w.keypress(size, key) return self._w.keypress(size, key)
def selectable(self): def selectable(self):
""" Return whether the widget is selectable. """ """Return whether the widget is selectable."""
return self.cbox.selectable() return self.cbox.selectable()
def get_focus(self): def get_focus(self):
""" Return widget focus. """ """Return widget focus."""
if self.overlay: if self.overlay:
return self.overlay._listbox.get_focus() return self.overlay._listbox.get_focus()
else: else:
if urwid.VERSION < (1, 1, 0): if urwid.VERSION < (1, 1, 0):
return None, self.focus return None, self.focus
else: else:
return None, self._w.focus_position # pylint: disable-msg=E1103 return None, self._w.focus_position
def get_sensitive(self): def get_sensitive(self):
""" Return widget sensitivity. """ """Return widget sensitivity."""
return self.cbox.get_sensitive() return self.cbox.get_sensitive()
def set_sensitive(self, state): def set_sensitive(self, state):
""" Set widget sensitivity. """ """Set widget sensitivity."""
self.cbox.set_sensitive(state) self.cbox.set_sensitive(state)
# This is a h4x3d copy of some of the code in Ian Ward's dialog.py example. # This is a h4x3d copy of some of the code in Ian Ward's dialog.py example.
class DialogExit(Exception): class DialogExit(Exception):
""" Custom exception. """ """Custom exception."""
pass pass
class Dialog2(urwid.WidgetWrap): class Dialog2(urwid.WidgetWrap):
""" Base class for other dialogs. """ """Base class for other dialogs."""
def __init__(self, text, height, width, body=None): def __init__(self, text, height, width, body=None):
self.buttons = None self.buttons = None
@@ -553,28 +555,28 @@ class Dialog2(urwid.WidgetWrap):
# buttons: tuple of name,exitcode # buttons: tuple of name,exitcode
def add_buttons(self, buttons): def add_buttons(self, buttons):
""" Add buttons. """ """Add buttons."""
l = [] data = []
maxlen = 0 maxlen = 0
for name, exitcode in buttons: for name, exitcode in buttons:
b = urwid.Button(name, self.button_press) b = urwid.Button(name, self.button_press)
b.exitcode = exitcode b.exitcode = exitcode
b = urwid.AttrWrap(b, 'body', 'focus') b = urwid.AttrWrap(b, 'body', 'focus')
l.append(b) data.append(b)
maxlen = max(len(name), maxlen) maxlen = max(len(name), maxlen)
maxlen += 4 # because of '< ... >' 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([ self.frame.footer = urwid.Pile([
urwid.Divider(), urwid.Divider(),
self.buttons self.buttons
], focus_item=1) ], focus_item=1)
def button_press(self, button): def button_press(self, button):
""" Handle button press. """ """Handle button press."""
raise DialogExit(button.exitcode) raise DialogExit(button.exitcode)
def run(self, ui, parent): def run(self, ui, parent):
""" Run the UI. """ """Run the UI."""
ui.set_mouse_tracking() ui.set_mouse_tracking()
size = ui.get_cols_rows() size = ui.get_cols_rows()
overlay = urwid.Overlay( overlay = urwid.Overlay(
@@ -610,20 +612,20 @@ class Dialog2(urwid.WidgetWrap):
return self.on_exit(e.args[0]) return self.on_exit(e.args[0])
def on_exit(self, exitcode): def on_exit(self, exitcode):
""" Handle dialog exit. """ """Handle dialog exit."""
return exitcode, "" return exitcode, ""
def unhandled_key(self, size, key): def unhandled_key(self, size, key):
""" Handle keypresses. """ """Handle keypresses."""
pass pass
class TextDialog(Dialog2): 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', def __init__(self, text, height, width, header=None, align='left',
buttons=(_('OK'), 1)): buttons=(_('OK'), 1)):
l = [urwid.Text(text)] data = [urwid.Text(text)]
body = urwid.ListBox(l) body = urwid.ListBox(data)
body = urwid.AttrWrap(body, 'body') body = urwid.AttrWrap(body, 'body')
Dialog2.__init__(self, header, height + 2, width + 2, body) Dialog2.__init__(self, header, height + 2, width + 2, body)
@@ -633,7 +635,7 @@ class TextDialog(Dialog2):
self.add_buttons([buttons]) self.add_buttons([buttons])
def unhandled_key(self, size, k): def unhandled_key(self, size, k):
""" Handle keys. """ """Handle keys."""
if k in ('up', 'page up', 'down', 'page down'): if k in ('up', 'page up', 'down', 'page down'):
self.frame.set_focus('body') self.frame.set_focus('body')
self.view.keypress(size, k) self.view.keypress(size, k)
@@ -641,7 +643,7 @@ class TextDialog(Dialog2):
class InputDialog(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=''): def __init__(self, text, height, width, ok_name=_('OK'), edit_text=''):
self.edit = urwid.Edit(wrap='clip', edit_text=edit_text) self.edit = urwid.Edit(wrap='clip', edit_text=edit_text)
body = urwid.ListBox([self.edit]) body = urwid.ListBox([self.edit])
@@ -653,7 +655,7 @@ class InputDialog(Dialog2):
self.add_buttons([(ok_name, 0), (_('Cancel'), -1)]) self.add_buttons([(ok_name, 0), (_('Cancel'), -1)])
def unhandled_key(self, size, k): def unhandled_key(self, size, k):
""" Handle keys. """ """Handle keys."""
if k in ('up', 'page up'): if k in ('up', 'page up'):
self.frame.set_focus('body') self.frame.set_focus('body')
if k in ('down', 'page down'): if k in ('down', 'page down'):
@@ -664,12 +666,12 @@ class InputDialog(Dialog2):
self.view.keypress(size, k) self.view.keypress(size, k)
def on_exit(self, exitcode): def on_exit(self, exitcode):
""" Handle dialog exit. """ """Handle dialog exit."""
return exitcode, self.edit.get_edit_text() return exitcode, self.edit.get_edit_text()
class ClickCols(urwid.WidgetWrap): class ClickCols(urwid.WidgetWrap):
""" Clickable menubar. """ """Clickable menubar."""
# pylint: disable-msg=W0231 # pylint: disable-msg=W0231
def __init__(self, items, callback=None, args=None): def __init__(self, items, callback=None, args=None):
cols = urwid.Columns(items) cols = urwid.Columns(items)
@@ -679,24 +681,26 @@ class ClickCols(urwid.WidgetWrap):
self.args = args self.args = args
def mouse_event(self, size, event, button, x, y, focus): def mouse_event(self, size, event, button, x, y, focus):
""" Handle mouse events. """ """Handle mouse events."""
if event == "mouse press": 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]) self.callback([self.args])
class OptCols(urwid.WidgetWrap): 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 # tuples = [(key,desc)], on_event gets passed a key
# attrs = (attr_key,attr_desc) # attrs = (attr_key,attr_desc)
# handler = function passed the key of the "button" pressed # handler = function passed the key of the "button" pressed
# mentions of 'left' and right will be converted to <- and -> respectively # mentions of 'left' and right will be converted to <- and -> respectively
# pylint: disable-msg=W0231 # 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 # Find the longest string. Keys for this bar should be no greater than
# 2 characters long (e.g., -> for left) # 2 characters long (e.g., -> for left)
#maxlen = 6 # maxlen = 6
#for i in tuples: # for i in tuples:
# newmax = len(i[0])+len(i[1]) # newmax = len(i[0])+len(i[1])
# if newmax > maxlen: # if newmax > maxlen:
# maxlen = newmax # maxlen = newmax
@@ -719,7 +723,7 @@ class OptCols(urwid.WidgetWrap):
else: else:
callback = handler callback = handler
args = cmd[0] args = cmd[0]
#self.callbacks.append(cmd[2]) # self.callbacks.append(cmd[2])
col = ClickCols([ col = ClickCols([
('fixed', len(key) + 1, urwid.Text((attrs[0], key + ':'))), ('fixed', len(key) + 1, urwid.Text((attrs[0], key + ':'))),
urwid.AttrWrap(urwid.Text(cmd[1]), attrs[1])], urwid.AttrWrap(urwid.Text(cmd[1]), attrs[1])],
@@ -736,10 +740,10 @@ class OptCols(urwid.WidgetWrap):
self.__super.__init__(cols) self.__super.__init__(cols)
def debugClick(self, args): def debugClick(self, args):
""" Debug clicks. """ """Debug clicks."""
self.debug.set_text(args) self.debug.set_text(args)
def mouse_event(self, size, event, button, x, y, focus): def mouse_event(self, size, event, button, x, y, focus):
""" Handle mouse events. """ """Handle mouse events."""
# Widgets are evenly long (as of current), so... # Widgets are evenly long (as of current), so...
return self._w.mouse_event(size, event, button, x, y, focus) return self._w.mouse_event(size, event, button, x, y, focus)

View File

@@ -1,7 +1,7 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
""" """
netentry_curses -- everyone's favorite networks settings dialogs... in text netentry_curses -- everyone's favorite networks settings dialogs... in text
form! form!
""" """
# Copyright (C) 2009 Andrew Psaltis # Copyright (C) 2009 Andrew Psaltis
@@ -20,6 +20,7 @@
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA. # MA 02110-1301, USA.
import os
import urwid import urwid
from curses_misc import DynWrap, MaskingEdit, ComboBox, error 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.misc import noneToString, stringToNone, noneToBlankString, to_bool
from wicd.translations import language, _ from wicd.translations import language, _
import os
daemon = None daemon = None
wired = None wired = None
@@ -36,7 +36,7 @@ wireless = None
# Call this first! # Call this first!
def dbus_init(dbus_ifaces): def dbus_init(dbus_ifaces):
""" Initialize DBus interfaces. """ """Initialize DBus interfaces."""
global daemon, wired, wireless global daemon, wired, wireless
daemon = dbus_ifaces['daemon'] daemon = dbus_ifaces['daemon']
wired = dbus_ifaces['wired'] wired = dbus_ifaces['wired']
@@ -47,10 +47,10 @@ class AdvancedSettingsDialog(urwid.WidgetWrap):
""" """
Settings dialog. Settings dialog.
Both the wired and the wireless settings preferences dialogs use some of the Both the wired and the wireless settings preferences dialogs use some of
same fields. the same fields.
This will be used to produce the individual network settings dialogs way far This will be used to produce the individual network settings dialogs way
below. far below.
""" """
# pylint: disable-msg=W0231 # pylint: disable-msg=W0231
def __init__(self): def __init__(self):
@@ -84,28 +84,20 @@ class AdvancedSettingsDialog(urwid.WidgetWrap):
cancel_t = _('Cancel') cancel_t = _('Cancel')
ok_t = _('OK') ok_t = _('OK')
self.static_ip_cb = urwid.CheckBox(static_ip_t, self.static_ip_cb = urwid.CheckBox(
on_state_change=self.static_ip_toggle) static_ip_t, on_state_change=self.static_ip_toggle)
self.ip_edit = DynWrap(urwid.Edit(ip_t), False) self.ip_edit = DynWrap(urwid.Edit(ip_t), False)
self.netmask_edit = DynWrap(urwid.Edit(netmask_t), False) self.netmask_edit = DynWrap(urwid.Edit(netmask_t), False)
self.gateway_edit = DynWrap(urwid.Edit(gateway_t), False) self.gateway_edit = DynWrap(urwid.Edit(gateway_t), False)
self.static_dns_cb = DynWrap( self.static_dns_cb = DynWrap(
urwid.CheckBox(use_static_dns_t, on_state_change=self.dns_toggle), urwid.CheckBox(use_static_dns_t, on_state_change=self.dns_toggle),
True, True, ('body', 'editnfc'), None)
('body', 'editnfc'),
None
)
self.global_dns_cb = DynWrap( self.global_dns_cb = DynWrap(
urwid.CheckBox(use_global_dns_t, on_state_change=self.dns_toggle), urwid.CheckBox(use_global_dns_t, on_state_change=self.dns_toggle),
False, False, ('body', 'editnfc'), None)
('body', 'editnfc'), self.checkb_cols = urwid.Columns([self.static_dns_cb,
None self.global_dns_cb])
)
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.dns_dom_edit = DynWrap(urwid.Edit(dns_dom_t), False)
self.search_dom_edit = DynWrap(urwid.Edit(search_dom_t), False) self.search_dom_edit = DynWrap(urwid.Edit(search_dom_t), False)
self.dns1 = DynWrap(urwid.Edit(dns1_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.dns3 = DynWrap(urwid.Edit(dns3_t), False)
self.use_dhcp_h = urwid.CheckBox( self.use_dhcp_h = urwid.CheckBox(
use_dhcp_h_t, use_dhcp_h_t, False,
False, on_state_change=self.use_dhcp_h_toggle)
on_state_change=self.use_dhcp_h_toggle
)
self.dhcp_h = DynWrap(urwid.Edit(dhcp_h_t), False) self.dhcp_h = DynWrap(urwid.Edit(dhcp_h_t), False)
_blank = urwid.Text('') _blank = urwid.Text('')
@@ -144,11 +134,11 @@ class AdvancedSettingsDialog(urwid.WidgetWrap):
self.__super.__init__(self._frame) self.__super.__init__(self._frame)
def use_dhcp_h_toggle(self, checkb, new_state, user_data=None): 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) self.dhcp_h.set_sensitive(new_state)
def static_ip_toggle(self, checkb, new_state, user_data=None): 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]: for w in [self.ip_edit, self.netmask_edit, self.gateway_edit]:
w.set_sensitive(new_state) w.set_sensitive(new_state)
self.static_dns_cb.set_state(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) self.checkb_cols.set_focus(self.static_dns_cb)
def dns_toggle(self, checkb, new_state, user_data=None): 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(): if checkb == self.static_dns_cb.get_w():
for w in [ for w in [
self.dns_dom_edit, self.dns_dom_edit,
@@ -174,17 +164,17 @@ class AdvancedSettingsDialog(urwid.WidgetWrap):
self.global_dns_cb.set_sensitive(new_state) self.global_dns_cb.set_sensitive(new_state)
# use_global_dns_cb is DynWrapped # use_global_dns_cb is DynWrapped
if checkb == self.global_dns_cb.get_w(): if checkb == self.global_dns_cb.get_w():
for w in [self.dns_dom_edit, self.search_dom_edit, for w in [self.dns_dom_edit, self.search_dom_edit, self.dns1,
self.dns1, self.dns2, self.dns3 ]: self.dns2, self.dns3]:
w.set_sensitive(not new_state) w.set_sensitive(not new_state)
def set_net_prop(self, option, value): def set_net_prop(self, option, value):
""" Set network property. MUST BE OVERRIDEN. """ """Set network property. MUST BE OVERRIDEN."""
raise NotImplementedError raise NotImplementedError
# Code totally yanked from netentry.py # Code totally yanked from netentry.py
def save_settings(self): 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(): if self.static_ip_cb.get_state():
for i in [ for i in [
self.ip_edit, self.ip_edit,
@@ -219,12 +209,13 @@ class AdvancedSettingsDialog(urwid.WidgetWrap):
self.set_net_prop('dns_domain', 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", 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("dns1", noneToString(self.dns1.get_edit_text()))
self.set_net_prop("dns2", noneToString(self.dns2.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())) self.set_net_prop("dns3", noneToString(self.dns3.get_edit_text()))
elif self.static_dns_cb.get_state() and \ elif (self.static_dns_cb.get_state() and
self.global_dns_cb.get_state(): self.global_dns_cb.get_state()):
self.set_net_prop('use_static_dns', True) self.set_net_prop('use_static_dns', True)
self.set_net_prop('use_global_dns', True) self.set_net_prop('use_global_dns', True)
else: else:
@@ -240,20 +231,20 @@ class AdvancedSettingsDialog(urwid.WidgetWrap):
# Prevent comboboxes from dying. # Prevent comboboxes from dying.
def ready_widgets(self, ui, body): def ready_widgets(self, ui, body):
""" Build comboboxes. """ """Build comboboxes."""
self.ui = ui self.ui = ui
self.body = body self.body = body
self.encryption_combo.build_combobox(body, ui, 14) self.encryption_combo.build_combobox(body, ui, 14)
self.change_encrypt_method() self.change_encrypt_method()
def combo_on_change(self, combobox, new_index, user_data=None): 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() self.change_encrypt_method()
# More or less ripped from netentry.py # More or less ripped from netentry.py
def change_encrypt_method(self): def change_encrypt_method(self):
""" Change encrypt method based on combobox. """ """Change encrypt method based on combobox."""
#self.lbox_encrypt = urwid.ListBox() # self.lbox_encrypt = urwid.ListBox()
self.encryption_info = {} self.encryption_info = {}
wid, ID = self.encryption_combo.get_focus() wid, ID = self.encryption_combo.get_focus()
methods = self.encrypt_types methods = self.encrypt_types
@@ -288,36 +279,35 @@ class AdvancedSettingsDialog(urwid.WidgetWrap):
wired.GetWiredProperty(field[0]))) wired.GetWiredProperty(field[0])))
else: else:
edit.set_edit_text(noneToBlankString( 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? # Make this into a listbox?
self.pile_encrypt = DynWrap( self.pile_encrypt = DynWrap(urwid.Pile(theList),
urwid.Pile(theList), attrs=('editbx', 'editnfc'))
attrs=('editbx', 'editnfc')
)
self.pile_encrypt.set_sensitive(self.encryption_chkbox.get_state()) 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.insert(self._w.body.body.__len__(),
#self._w.body.body.append(self.pile_encrypt) self.pile_encrypt)
# self._w.body.body.append(self.pile_encrypt)
def encryption_toggle(self, chkbox, new_state, user_data=None): 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.encryption_combo.set_sensitive(new_state)
self.pile_encrypt.set_sensitive(new_state) self.pile_encrypt.set_sensitive(new_state)
class WiredSettingsDialog(AdvancedSettingsDialog): class WiredSettingsDialog(AdvancedSettingsDialog):
""" Settings dialog for wired interface. """ """Settings dialog for wired interface."""
def __init__(self, name, parent): def __init__(self, name, parent):
AdvancedSettingsDialog.__init__(self) AdvancedSettingsDialog.__init__(self)
self.wired = True self.wired = True
self.set_default = urwid.CheckBox( self.set_default = urwid.CheckBox(
_('Use as default profile (overwrites any previous default)') _('Use as default profile (overwrites any previous default)'))
) # self.cur_default =
#self.cur_default =
# Add widgets to listbox # Add widgets to listbox
self._w.body.body.append(self.set_default) self._w.body.body.append(self.set_default)
@@ -347,11 +337,11 @@ class WiredSettingsDialog(AdvancedSettingsDialog):
self.set_values() self.set_values()
def set_net_prop(self, option, value): def set_net_prop(self, option, value):
""" Set network property. """ """Set network property."""
wired.SetWiredProperty(option, value) wired.SetWiredProperty(option, value)
def set_values(self): def set_values(self):
""" Load saved values. """ """Load saved values."""
self.ip_edit.set_edit_text(self.format_entry("ip")) self.ip_edit.set_edit_text(self.format_entry("ip"))
self.netmask_edit.set_edit_text(self.format_entry("netmask")) self.netmask_edit.set_edit_text(self.format_entry("netmask"))
self.gateway_edit.set_edit_text(self.format_entry("gateway")) 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"))) self.set_default.set_state(to_bool(wired.GetWiredProperty("default")))
# Throw the encryption stuff into a list # Throw the encryption stuff into a list
l = [] combo_items = []
activeID = -1 # Set the menu to this item when we are done activeID = -1 # Set the menu to this item when we are done
for x, enc_type in enumerate(self.encrypt_types): 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"): if enc_type['type'] == wired.GetWiredProperty("enctype"):
activeID = x activeID = x
self.encryption_combo.set_list(l) self.encryption_combo.set_list(combo_items)
self.encryption_combo.set_focus(activeID) self.encryption_combo.set_focus(activeID)
if wired.GetWiredProperty("encryption_enabled"): if wired.GetWiredProperty("encryption_enabled"):
self.encryption_chkbox.set_state(True, do_callback=False) self.encryption_chkbox.set_state(True, do_callback=False)
self.encryption_combo.set_sensitive(True) self.encryption_combo.set_sensitive(True)
#self.lbox_encrypt_info.set_sensitive(True) # self.lbox_encrypt_info.set_sensitive(True)
else: else:
self.encryption_combo.set_focus(0) self.encryption_combo.set_focus(0)
self.encryption_combo.set_sensitive(False) self.encryption_combo.set_sensitive(False)
@@ -405,7 +395,7 @@ class WiredSettingsDialog(AdvancedSettingsDialog):
self.dhcp_h.set_edit_text(str(dhcphname)) self.dhcp_h.set_edit_text(str(dhcphname))
def save_settings(self): def save_settings(self):
""" Save settings to disk. """ """Save settings to disk."""
# Check encryption info # Check encryption info
if self.encryption_chkbox.get_state(): if self.encryption_chkbox.get_state():
encrypt_info = self.encryption_info encrypt_info = self.encryption_info
@@ -447,7 +437,7 @@ class WiredSettingsDialog(AdvancedSettingsDialog):
return True return True
def format_entry(self, label): 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)) return noneToBlankString(wired.GetWiredProperty(label))
def prerun(self, ui, dim, display): def prerun(self, ui, dim, display):
@@ -455,7 +445,7 @@ class WiredSettingsDialog(AdvancedSettingsDialog):
class WirelessSettingsDialog(AdvancedSettingsDialog): class WirelessSettingsDialog(AdvancedSettingsDialog):
""" Settings dialog for wireless interfaces. """ """Settings dialog for wireless interfaces."""
def __init__(self, networkID, parent): def __init__(self, networkID, parent):
AdvancedSettingsDialog.__init__(self) AdvancedSettingsDialog.__init__(self)
self.wired = False self.wired = False
@@ -502,17 +492,21 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
self.encrypt_types = misc.LoadEncryptionMethods() self.encrypt_types = misc.LoadEncryptionMethods()
self.set_values() self.set_values()
title = _('Configuring preferences for wireless network "$A" ($B)'). \ title = (_('Configuring preferences for wireless network "$A" ($B)')
replace('$A', wireless.GetWirelessProperty(networkID, 'essid')). \ .replace('$A', wireless.GetWirelessProperty(networkID,
replace('$B', wireless.GetWirelessProperty(networkID, 'bssid')) 'essid'))
.replace('$B', wireless.GetWirelessProperty(networkID,
'bssid')))
self._w.header = urwid.Text(('header', title), align='right') self._w.header = urwid.Text(('header', title), align='right')
def set_values(self): 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 networkID = self.networkid
self.ip_edit.set_edit_text(self.format_entry(networkID, "ip")) self.ip_edit.set_edit_text(self.format_entry(networkID, "ip"))
self.netmask_edit.set_edit_text(self.format_entry(networkID, "netmask")) self.netmask_edit.set_edit_text(self.format_entry(networkID,
self.gateway_edit.set_edit_text(self.format_entry(networkID, "gateway")) "netmask"))
self.gateway_edit.set_edit_text(self.format_entry(networkID,
"gateway"))
self.global_dns_cb.set_state( self.global_dns_cb.set_state(
bool(wireless.GetWirelessProperty(networkID, 'use_global_dns'))) bool(wireless.GetWirelessProperty(networkID, 'use_global_dns')))
@@ -547,32 +541,29 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
to_bool(self.format_entry(networkID, 'allow_lower_bitrates')) to_bool(self.format_entry(networkID, 'allow_lower_bitrates'))
) )
#self.reset_static_checkboxes() # self.reset_static_checkboxes()
self.encryption_chkbox.set_state( self.encryption_chkbox.set_state(
bool(wireless.GetWirelessProperty(networkID, 'encryption')), bool(wireless.GetWirelessProperty(networkID, 'encryption')),
do_callback=False) do_callback=False)
self.global_settings_chkbox.set_state( self.global_settings_chkbox.set_state(
bool(wireless.GetWirelessProperty( bool(wireless.GetWirelessProperty(networkID,
networkID, 'use_settings_globally')))
'use_settings_globally')
)
)
# Throw the encryption stuff into a list # Throw the encryption stuff into a list
l = [] combo_items = []
activeID = -1 # Set the menu to this item when we are done activeID = -1 # Set the menu to this item when we are done
for x, enc_type in enumerate(self.encrypt_types): for x, enc_type in enumerate(self.encrypt_types):
l.append(enc_type['name']) combo_items.append(enc_type['name'])
if enc_type['type'] == \ if enc_type['type'] == wireless.GetWirelessProperty(networkID,
wireless.GetWirelessProperty(networkID, "enctype"): "enctype"):
activeID = x activeID = x
self.encryption_combo.set_list(l) self.encryption_combo.set_list(combo_items)
self.encryption_combo.set_focus(activeID) self.encryption_combo.set_focus(activeID)
if activeID != -1: if activeID != -1:
self.encryption_chkbox.set_state(True, do_callback=False) self.encryption_chkbox.set_state(True, do_callback=False)
self.encryption_combo.set_sensitive(True) self.encryption_combo.set_sensitive(True)
#self.lbox_encrypt_info.set_sensitive(True) # self.lbox_encrypt_info.set_sensitive(True)
else: else:
self.encryption_combo.set_focus(0) self.encryption_combo.set_focus(0)
@@ -587,16 +578,17 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
self.dhcp_h.set_edit_text(str(dhcphname)) self.dhcp_h.set_edit_text(str(dhcphname))
def set_net_prop(self, option, value): 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) wireless.SetWirelessProperty(self.networkid, option, value)
def format_entry(self, networkid, label): def format_entry(self, networkid, label):
""" Helper method for fetching/formatting wireless properties. """ """Helper method for fetching/formatting wireless properties."""
return noneToBlankString(wireless.GetWirelessProperty(networkid, label)) return noneToBlankString(wireless.GetWirelessProperty(networkid,
label))
# Ripped from netentry.py # Ripped from netentry.py
def save_settings(self): def save_settings(self):
""" Save settings to disk. """ """Save settings to disk."""
# Check encryption info # Check encryption info
if self.encryption_chkbox.get_state(): if self.encryption_chkbox.get_state():
encrypt_info = self.encryption_info encrypt_info = self.encryption_info
@@ -607,29 +599,21 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
) )
# Make sure all required fields are filled in. # Make sure all required fields are filled in.
for entry_info in list(encrypt_info.values()): for entry_info in list(encrypt_info.values()):
if entry_info[0].get_edit_text() == "" \ if (entry_info[0].get_edit_text() == "" and
and entry_info[1] == 'required': entry_info[1] == 'required'):
error( error(self.ui, self.parent, "%s (%s)" %
self.ui, (_('Required encryption information is missing.'),
self.parent, entry_info[0].get_caption()[0:-2]))
"%s (%s)" % (
_('Required encryption information is missing.'),
entry_info[0].get_caption()[0:-2]
)
)
return False return False
for entry_key, entry_info in list(encrypt_info.items()): for entry_key, entry_info in list(encrypt_info.items()):
self.set_net_prop(entry_key, noneToString(entry_info[0]. self.set_net_prop(entry_key, noneToString(entry_info[0].
get_edit_text())) get_edit_text()))
elif not self.encryption_chkbox.get_state() and \ elif (not self.encryption_chkbox.get_state() and
wireless.GetWirelessProperty(self.networkid, "encryption"): wireless.GetWirelessProperty(self.networkid, "encryption")):
# Encrypt checkbox is off, but the network needs it. # Encrypt checkbox is off, but the network needs it.
error( error(self.ui, self.parent,
self.ui, _('This network requires encryption to be enabled.'))
self.parent,
_('This network requires encryption to be enabled.')
)
return False return False
else: else:
self.set_net_prop("enctype", "None") self.set_net_prop("enctype", "None")
@@ -657,7 +641,7 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
return True return True
def ready_widgets(self, ui, body): def ready_widgets(self, ui, body):
""" Build comboboxes. """ """Build comboboxes."""
AdvancedSettingsDialog.ready_widgets(self, ui, body) AdvancedSettingsDialog.ready_widgets(self, ui, body)
self.ui = ui self.ui = ui
self.body = body self.body = body

View File

@@ -32,7 +32,7 @@ wired = None
class PrefsDialog(urwid.WidgetWrap): class PrefsDialog(urwid.WidgetWrap):
""" Preferences dialog. """ """Preferences dialog."""
# pylint: disable-msg=W0231 # pylint: disable-msg=W0231
def __init__(self, body, pos, ui, dbus=None): def __init__(self, body, pos, ui, dbus=None):
global daemon, wireless, wired global daemon, wireless, wired
@@ -48,14 +48,15 @@ class PrefsDialog(urwid.WidgetWrap):
width, height = ui.get_cols_rows() width, height = ui.get_cols_rows()
height -= 3 height -= 3
#width = 80 # width = 80
#height = 20 # height = 20
# Stuff that goes at the top # Stuff that goes at the top
header0_t = _('General Settings') header0_t = _('General Settings')
header1_t = _('External Programs') header1_t = _('External Programs')
header2_t = _('Advanced Settings') 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.header1 = urwid.AttrWrap(SelText(header1_t), 'body', 'focus')
self.header2 = urwid.AttrWrap(SelText(header2_t), 'body', 'focus') self.header2 = urwid.AttrWrap(SelText(header2_t), 'body', 'focus')
title = ('Preferences') title = ('Preferences')
@@ -63,9 +64,7 @@ class PrefsDialog(urwid.WidgetWrap):
# Blank line # Blank line
_blank = urwid.Text('') _blank = urwid.Text('')
#### # Text in the widgets
#### Text in the widgets
####
# General Settings # General Settings
net_cat_t = ('header', ('Network Interfaces')) net_cat_t = ('header', ('Network Interfaces'))
@@ -90,7 +89,7 @@ class PrefsDialog(urwid.WidgetWrap):
auto_reconn_cat_t = ('header', _('Automatic Reconnection')) auto_reconn_cat_t = ('header', _('Automatic Reconnection'))
auto_reconn_t = _('Automatically reconnect on connection loss') auto_reconn_t = _('Automatically reconnect on connection loss')
#### External Programs # External Programs
automatic_t = _('Automatic (recommended)') automatic_t = _('Automatic (recommended)')
dhcp_header_t = ('header', _('DHCP Client')) dhcp_header_t = ('header', _('DHCP Client'))
@@ -108,12 +107,12 @@ class PrefsDialog(urwid.WidgetWrap):
flush1_t = 'ip' flush1_t = 'ip'
flush2_t = 'route' flush2_t = 'route'
#### Advanced Settings # Advanced Settings
wpa_cat_t = ('header', _('WPA Supplicant')) wpa_cat_t = ('header', _('WPA Supplicant'))
wpa_t = ('editcp', 'Driver:') wpa_t = ('editcp', 'Driver:')
wpa_list = [] wpa_list = []
wpa_warn_t = ('important', wpa_warn_t = ('important', _('You should almost always use wext as '
_('You should almost always use wext as the WPA supplicant driver')) 'the WPA supplicant driver'))
backend_cat_t = ('header', _('Backend')) backend_cat_t = ('header', _('Backend'))
backend_t = _('Backend') + ':' backend_t = _('Backend') + ':'
@@ -124,12 +123,10 @@ class PrefsDialog(urwid.WidgetWrap):
wless_cat_t = ('header', _('Wireless Interface')) wless_cat_t = ('header', _('Wireless Interface'))
use_dbm_t = _('Use dBm to measure signal strength') use_dbm_t = _('Use dBm to measure signal strength')
verify_ap_t = \ verify_ap_t = _('Ping static gateways after connecting to verify '
_('Ping static gateways after connecting to verify association') 'association')
#### # UI Widgets
#### UI Widgets
####
# General Settings # General Settings
self.net_cat = urwid.Text(net_cat_t) 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 # Default the global DNS settings to off. They will be reenabled later
# if so required. # if so required.
global_dns_state = False global_dns_state = False
self.global_dns_checkb = urwid.CheckBox(global_dns_t, self.global_dns_checkb = urwid.CheckBox(global_dns_t, global_dns_state,
global_dns_state, on_state_change=self.
on_state_change=self.global_dns_trigger global_dns_trigger)
)
self.search_dom = DynWrap(urwid.Edit(search_dom_t), global_dns_state) 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.dns_dom = DynWrap(urwid.Edit(dns_dom_t), global_dns_state)
self.dns1 = DynWrap(urwid.Edit(dns1_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_l = []
self.wired_auto_cat = urwid.Text(wired_auto_cat_t) 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_1 = urwid.RadioButton(self.wired_auto_l,
self.wired_auto_2 = urwid.RadioButton(self.wired_auto_l, wired_auto_2_t) wired_auto_1_t)
self.wired_auto_3 = urwid.RadioButton(self.wired_auto_l, wired_auto_3_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_cat = urwid.Text(auto_reconn_cat_t)
self.auto_reconn_checkb = urwid.CheckBox(auto_reconn_t) self.auto_reconn_checkb = urwid.CheckBox(auto_reconn_t)
@@ -180,7 +179,8 @@ class PrefsDialog(urwid.WidgetWrap):
self.auto_reconn_checkb self.auto_reconn_checkb
]) ])
#### External Programs tab # External Programs tab
automatic_t = _('Automatic (recommended)') automatic_t = _('Automatic (recommended)')
self.dhcp_header = urwid.Text(dhcp_header_t) self.dhcp_header = urwid.Text(dhcp_header_t)
@@ -223,7 +223,8 @@ class PrefsDialog(urwid.WidgetWrap):
self.flush0, self.flush1, self.flush2 self.flush0, self.flush1, self.flush2
]) ])
#### Advanced settings # Advanced settings
self.wpa_cat = urwid.Text(wpa_cat_t) self.wpa_cat = urwid.Text(wpa_cat_t)
self.wpa_cbox = ComboBox(wpa_t) self.wpa_cbox = ComboBox(wpa_t)
self.wpa_warn = urwid.Text(wpa_warn_t) self.wpa_warn = urwid.Text(wpa_warn_t)
@@ -257,15 +258,16 @@ class PrefsDialog(urwid.WidgetWrap):
self.header1: externalLB, self.header1: externalLB,
self.header2: advancedLB self.header2: advancedLB
} }
#self.load_settings()
# self.load_settings()
self.tabs = TabColumns(headerList, lbList, _('Preferences')) self.tabs = TabColumns(headerList, lbList, _('Preferences'))
# pylint: disable-msg=E1101 # pylint: disable-msg=E1101
self.__super.__init__(self.tabs) self.__super.__init__(self.tabs)
def load_settings(self): def load_settings(self):
""" Load settings to be used in the dialog. """ """Load settings to be used in the dialog."""
### General Settings # General Settings
# ComboBox does not like dbus.Strings as text markups. My fault. :/ # ComboBox does not like dbus.Strings as text markups. My fault. :/
wless_iface = str(daemon.GetWirelessInterface()) wless_iface = str(daemon.GetWirelessInterface())
wired_iface = str(daemon.GetWiredInterface()) wired_iface = str(daemon.GetWiredInterface())
@@ -280,7 +282,8 @@ class PrefsDialog(urwid.WidgetWrap):
theDNS = daemon.GetGlobalDNSAddresses() theDNS = daemon.GetGlobalDNSAddresses()
i = 0 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])) w.set_edit_text(misc.noneToBlankString(theDNS[i]))
i += 1 i += 1
@@ -289,11 +292,11 @@ class PrefsDialog(urwid.WidgetWrap):
self.auto_reconn_checkb.set_state(daemon.GetAutoReconnect()) self.auto_reconn_checkb.set_state(daemon.GetAutoReconnect())
def find_avail(apps): def find_avail(apps):
""" Find available apps. """ """Find available apps."""
for app in apps[1:]: for app in apps[1:]:
app.set_sensitive(daemon.GetAppAvailable(app.get_label())) app.set_sensitive(daemon.GetAppAvailable(app.get_label()))
### External Programs # External Programs
find_avail(self.dhcp_l) find_avail(self.dhcp_l)
dhcp_method = daemon.GetDHCPClient() dhcp_method = daemon.GetDHCPClient()
self.dhcp_l[dhcp_method].set_state(True) self.dhcp_l[dhcp_method].set_state(True)
@@ -306,7 +309,7 @@ class PrefsDialog(urwid.WidgetWrap):
flush_method = daemon.GetFlushTool() flush_method = daemon.GetFlushTool()
self.flush_l[flush_method].set_state(True) self.flush_l[flush_method].set_state(True)
### Advanced settings # Advanced settings
# wpa_supplicant janx # wpa_supplicant janx
self.wpadrivers = wireless.GetWpaSupplicantDrivers() self.wpadrivers = wireless.GetWpaSupplicantDrivers()
self.wpadrivers.append("ralink_legacy") self.wpadrivers.append("ralink_legacy")
@@ -337,7 +340,7 @@ class PrefsDialog(urwid.WidgetWrap):
self.verify_ap_checkb.set_state(daemon.GetShouldVerifyAp()) self.verify_ap_checkb.set_state(daemon.GetShouldVerifyAp())
def save_settings(self): 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""" This exact order is found in prefs.py"""
daemon.SetUseGlobalDNS(self.global_dns_checkb.get_state()) daemon.SetUseGlobalDNS(self.global_dns_checkb.get_state())
@@ -404,11 +407,12 @@ class PrefsDialog(urwid.WidgetWrap):
daemon.SetFlushTool(flush_tool) daemon.SetFlushTool(flush_tool)
def global_dns_trigger(self, check_box, new_state, user_data=None): def global_dns_trigger(self, check_box, new_state, user_data=None):
""" DNS CheckBox callback. """ """DNS CheckBox callback."""
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_sensitive(new_state) w.set_sensitive(new_state)
def ready_widgets(self, ui, body): def ready_widgets(self, ui, body):
""" Build comboboxes. """ """Build comboboxes."""
self.wpa_cbox.build_combobox(body, ui, 4) self.wpa_cbox.build_combobox(body, ui, 4)
self.backend_cbox.build_combobox(body, ui, 8) self.backend_cbox.build_combobox(body, ui, 8)

View File

@@ -1,7 +1,7 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# -* coding: utf-8 -*- # -* 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 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. 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. # Filter out a confusing urwid warning in python 2.6.
# This is valid as of urwid version 0.9.8.4 # This is valid as of urwid version 0.9.8.4
from optparse import OptionParser
import signal
import sys
import warnings 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 from dbus import DBusException
# It took me a while to figure out that I have to use this. # It took me a while to figure out that I have to use this.
from gi.repository import GLib as gobject from gi.repository import GLib as gobject
# Other important wicd-related stuff
from wicd import wpath from wicd import wpath
from wicd import misc from wicd import misc
from wicd import dbusmanager from wicd import dbusmanager
from wicd.translations import _
# Internal Python stuff
import sys
# SIGQUIT signal handling
import signal
# Curses UIs for other stuff # Curses UIs for other stuff
from curses_misc import ComboBox, Dialog2, NSelListBox, SelText, OptCols from curses_misc import ComboBox, Dialog2, NSelListBox, SelText, OptCols
@@ -67,51 +58,50 @@ from prefs_curses import PrefsDialog
import netentry_curses import netentry_curses
from netentry_curses import WirelessSettingsDialog, WiredSettingsDialog from netentry_curses import WirelessSettingsDialog, WiredSettingsDialog
from optparse import OptionParser
# Stuff about getting the script configurer running # Stuff about getting the script configurer running
#from grp import getgrgid # from grp import getgrgid
#from os import getgroups, system # from os import getgroups, system
#import logging # import logging
#import logging.handler # import logging.handler
CURSES_REV = wpath.curses_revision CURSES_REV = wpath.curses_revision
# Fix strings in wicd-curses # Fix strings in wicd-curses
#from wicd.translations import language # from wicd.translations import language
from wicd.translations import _
warnings.filterwarnings(
"ignore",
"The popen2 module is deprecated. Use the subprocess module."
)
ui = None ui = None
loop = None loop = None
bus = daemon = wireless = wired = None bus = daemon = wireless = wired = None
########################################
##### SUPPORT CLASSES
########################################
# Yay for decorators! # Yay for decorators!
def wrap_exceptions(func): def wrap_exceptions(func):
""" Decorator to wrap exceptions. """ """Decorator to wrap exceptions."""
def wrapper(*args, **kargs): def wrapper(*args, **kargs):
try: try:
return func(*args, **kargs) return func(*args, **kargs)
except KeyboardInterrupt: except KeyboardInterrupt:
#gobject.source_remove(redraw_tag) # gobject.source_remove(redraw_tag)
loop.quit() loop.quit()
ui.stop() ui.stop()
print("\n" + _('Terminated by user'), file=sys.stderr) print("\n" + _('Terminated by user'), file=sys.stderr)
#raise # raise
except DBusException: except DBusException:
loop.quit() loop.quit()
ui.stop() ui.stop()
print("\n" + _('DBus failure! ' print("\n" + _('DBus failure! This is most likely caused by the '
'This is most likely caused by the wicd daemon ' 'wicd daemon stopping while wicd-curses is '
'stopping while wicd-curses is running. ' 'running. Please restart the daemon, and then '
'Please restart the daemon, and then restart wicd-curses.'), file=sys.stderr) 'restart wicd-curses.'), file=sys.stderr)
raise raise
except: except Exception:
# Quit the loop # Quit the loop
#if 'loop' in locals(): # if 'loop' in locals():
loop.quit() loop.quit()
# Zap the screen # Zap the screen
ui.stop() ui.stop()
@@ -133,19 +123,14 @@ def wrap_exceptions(func):
return wrapper return wrapper
########################################
##### SUPPORT FUNCTIONS
########################################
# Look familiar? These two functions are clones of functions found in wicd's # 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. # gui.py file, except that now set_status is a function passed to them.
@wrap_exceptions @wrap_exceptions
def check_for_wired(wired_ip, set_status): 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(): if wired_ip and wired.CheckPluggedIn():
set_status( set_status(_('Connected to wired network (IP: $A)')
_('Connected to wired network (IP: $A)').replace('$A',wired_ip) .replace('$A', wired_ip))
)
return True return True
else: else:
return False return False
@@ -153,7 +138,7 @@ def check_for_wired(wired_ip, set_status):
@wrap_exceptions @wrap_exceptions
def check_for_wireless(iwconfig, wireless_ip, set_status): 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: if not wireless_ip:
return False return False
@@ -171,10 +156,10 @@ def check_for_wireless(iwconfig, wireless_ip, set_status):
return False return False
strength = misc.to_unicode(daemon.FormatSignalForPrinting(strength)) strength = misc.to_unicode(daemon.FormatSignalForPrinting(strength))
ip = misc.to_unicode(wireless_ip) ip = misc.to_unicode(wireless_ip)
set_status(_('Connected to $A at $B (IP: $C)').replace set_status(_('Connected to $A at $B (IP: $C)')
('$A', network).replace .replace('$A', network)
('$B', strength).replace .replace('$B', strength)
('$C', ip)) .replace('$C', ip))
return True return True
@@ -183,15 +168,15 @@ def check_for_wireless(iwconfig, wireless_ip, set_status):
# DBUS interfaces do. :P # DBUS interfaces do. :P
# Whatever calls this must be exception-wrapped if it is run if the UI is up # Whatever calls this must be exception-wrapped if it is run if the UI is up
def gen_network_list(): def gen_network_list():
""" Generate the list of networks. """ """Generate the list of networks."""
wiredL = wired.GetWiredProfileList() wiredL = wired.GetWiredProfileList()
wlessL = [] wlessL = []
# This one makes a list of NetLabels # This one makes a list of NetLabels
for network_id in range(0, wireless.GetNumberOfNetworks()): for network_id in range(0, wireless.GetNumberOfNetworks()):
is_active = \ is_active = (wireless.GetCurrentSignalStrength("") != 0 and
wireless.GetCurrentSignalStrength("") != 0 and \ wireless.GetCurrentNetworkID(wireless.GetIwconfig()) ==
wireless.GetCurrentNetworkID(wireless.GetIwconfig()) == network_id \ network_id and
and wireless.GetWirelessIP('') is not None wireless.GetWirelessIP('') is not None)
label = NetLabel(network_id, is_active) label = NetLabel(network_id, is_active)
wlessL.append(label) wlessL.append(label)
@@ -199,67 +184,80 @@ def gen_network_list():
def about_dialog(body): def about_dialog(body):
""" About dialog. """ """About dialog."""
# This looks A LOT better when it is actually displayed. I promise :-). # 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 # The ASCII Art "Wicd" was made from the "smslant" font on one of those
# online ASCII big text generators. # online ASCII big text generators.
theText = [ theText = [('green', " /// \\\\\\"),
('green', " /// \\\\\\"), " _ ___ __\n", " _ ___ __\n",
('green', " /// \\\\\\"), " | | /| / (_)______/ /\n", ('green', " /// \\\\\\"),
('green', " /// \\\\\\"), " | |/ |/ / / __/ _ / \n", " | | /| / (_)______/ /\n",
('green', "/|| // \\\\ ||\\"), " |__/|__/_/\__/\_,_/ \n", ('green', " /// \\\\\\"),
('green', "||| ||"), "(|^|)", ('green', "|| |||"), " | |/ |/ / / __/ _ / \n",
" ($VERSION) \n".replace("$VERSION", daemon.Hello()), ('green', "/|| // \\\\ ||\\"),
" |__/|__/_/\__/\_,_/ \n",
('green', "\\|| \\\\"), " |+| ", ('green', "// ||/ \n"), ('green', "||| ||"), "(|^|)", ('green', "|| |||"),
('green', " \\\\\\"), " |+| ", ('green', "///"), " ($VERSION) \n".replace("$VERSION",
daemon.Hello()),
('green', "\\|| \\\\"), " |+| ", ('green', "// ||/ \n"),
('green', " \\\\\\"), " |+| ", ('green', "///"),
" http://launchpad.net/wicd\n", " http://launchpad.net/wicd\n",
('green', " \\\\\\"), " |+| ", ('green', "///"), " ", ('green', " \\\\\\"), " |+| ", ('green', "///"), " ",
_('Brought to you by:'), "\n", _('Brought to you by:'), "\n",
('green', " \\\\\\"), " |+| ", ('green', "///"), " * Tom Van Braeckel\n", ('green', " \\\\\\"), " |+| ",
" __|+|__ * Adam Blackburn\n", ('green', "///"), " * Tom Van Braeckel\n",
" ___|+|___ * Dan O'Reilly\n", " __|+|__ * Adam Blackburn\n",
" ____|+|____ * Andrew Psaltis\n", " ___|+|___ * Dan O'Reilly\n",
" |-----------| * David Paleino\n"] " ____|+|____ * Andrew Psaltis\n",
" |-----------| * David Paleino\n"]
about = TextDialog(theText, 18, 55, header=('header', _('About Wicd'))) about = TextDialog(theText, 18, 55, header=('header', _('About Wicd')))
about.run(ui, body) about.run(ui, body)
# Modeled after htop's help # Modeled after htop's help
def help_dialog(body): def help_dialog(body):
""" Help dialog. """ """Help dialog."""
textT = urwid.Text(('header', _('wicd-curses help')), 'right') textT = urwid.Text(('header', _('wicd-curses help')), 'right')
textSH = urwid.Text([ textSH = urwid.Text([
'This is ', ('blue', 'wicd-curses-' + CURSES_REV), 'This is ', ('blue', 'wicd-curses-' + CURSES_REV),
' using wicd ', str(daemon.Hello()), '\n' ' using wicd ', str(daemon.Hello()), '\n'
]) ])
textH = urwid.Text([ textH = urwid.Text([_('For more detailed help, consult the wicd-curses(8) '
_('For more detailed help, consult the wicd-curses(8) man page.') + "\n", 'man page.') + "\n", ('bold', '->'), ' and ',
('bold', '->'), ' and ', ('bold', '<-'), ('bold', '<-'), " are the right and left arrows "
" are the right and left arrows respectively.\n" "respectively.\n"])
])
text1 = urwid.Text([ text1 = urwid.Text([('bold', ' H h ?'),
('bold', ' H h ?'), ": " + _('Display this help dialog') + "\n", ": " + _('Display this help dialog') + "\n",
('bold', 'enter C'), ": " + _('Connect to selected network') + "\n", ('bold', 'enter C'),
('bold', ' D'), ": " + _('Disconnect from all networks') + "\n", ": " + _('Connect to selected network') + "\n",
('bold', ' ESC'), ": " + _('Stop a connection in progress') + "\n", ('bold', ' D'),
('bold', ' F5 R'), ": " + _('Refresh network list') + "\n", ": " + _('Disconnect from all networks') + "\n",
('bold', ' P'), ": " + _('Preferences dialog') + "\n", ('bold', ' ESC'),
]) ": " + _('Stop a connection in progress') + "\n",
text2 = urwid.Text([ ('bold', ' F5 R'),
('bold', ' I'), ": " + _('Scan for hidden networks') + "\n", ": " + _('Refresh network list') + "\n",
('bold', ' S'), ": " + _('Select scripts') + "\n", ('bold', ' P'),
('bold', ' O'), ": " + _('Set up Ad-hoc network') + "\n", ": " + _('Preferences dialog') + "\n"])
('bold', ' X'), ": " + _('Remove settings for saved networks') + "\n", text2 = urwid.Text([('bold', ' I'),
('bold', ' ->'), ": " + _('Configure selected network') + "\n", ": " + _('Scan for hidden networks') + "\n",
('bold', ' A'), ": " + _("Display 'about' dialog") + "\n", ('bold', ' S'),
('bold', ' F8 q Q'), ": " + _('Quit wicd-curses') + "\n", ": " + _('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.')) 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('') 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): def run_configscript(parent, netname, nettype):
""" Run configuration script. """ """Run configuration script."""
configfile = wpath.etc + netname + '-settings.conf' configfile = wpath.etc + netname + '-settings.conf'
if nettype != 'wired': if nettype != 'wired':
header = 'profile' header = 'profile'
@@ -301,59 +299,62 @@ def run_configscript(parent, netname, nettype):
profname = nettype profname = nettype
else: else:
profname = wireless.GetWirelessProperty(int(netname), 'bssid') profname = wireless.GetWirelessProperty(int(netname), 'bssid')
theText = [ theText = [_('To avoid various complications, wicd-curses does not '
_('To avoid various complications, wicd-curses does not support directly ' 'support directly editing the scripts. However, you can '
'editing the scripts. However, you can edit them manually. First, (as root), ' 'edit them manually. First, (as root), open the "$A" config '
'open the "$A" config file, and look for the section labeled by the $B in ' 'file, and look for the section labeled by the $B in '
'question. In this case, this is:'). 'question. In this case, this is:')
replace('$A', configfile).replace('$B', header), .replace('$A', configfile)
"\n\n[" + profname + "]\n\n", .replace('$B', header),
_('You can also configure the wireless networks by looking for the "[<ESSID>]" ' "\n\n[" + profname + "]\n\n",
'field in the config file.'), _('You can also configure the wireless networks by looking '
_('Once there, you can adjust (or add) the "beforescript", "afterscript", ' 'for the "[<ESSID>]" field in the config file.'),
'"predisconnectscript" and "postdisconnectscript" variables as needed, to ' _('Once there, you can adjust (or add) the "beforescript", '
'change the preconnect, postconnect, predisconnect and postdisconnect scripts ' '"afterscript", "predisconnectscript" and '
'respectively. Note that you will be specifying the full path to the scripts ' '"postdisconnectscript" variables as needed, to change the '
'- not the actual script contents. You will need to add/edit the script ' 'preconnect, postconnect, predisconnect and postdisconnect '
'contents separately. Refer to the wicd manual page for more information.') '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 = TextDialog(theText, 20, 80)
dialog.run(ui, parent) dialog.run(ui, parent)
# This code works with many distributions, but not all of them. So, to # 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, # limit complications, it has been deactivated. If you want to run it,
# be my guest. Be sure to deactivate the above stuff first. # be my guest. Be sure to deactivate the above stuff first.
#loop.quit() # loop.quit()
#ui.stop() # ui.stop()
#argv = netname + ' ' +nettype # argv = netname + ' ' +nettype
##cmd = '/usr/lib/configscript_curses.py '+argv # #cmd = '/usr/lib/configscript_curses.py '+argv
#cmd = wpath.lib+'configscript_curses.py '+argv # cmd = wpath.lib+'configscript_curses.py '+argv
## Check whether we can sudo. Hopefully this is complete # # Check whether we can sudo. Hopefully this is complete
#glist = [] # glist = []
#for i in getgroups(): # for i in getgroups():
#glist.append(getgrgid(i)[0]) # glist.append(getgrgid(i)[0])
#if 'root' in glist: # if 'root' in glist:
#precmd = '' # precmd = ''
#precmdargv = '' # precmdargv = ''
#postcmd = '' # postcmd = ''
#elif 'admin' in glist or 'wheel' in glist or 'sudo' in glist: # elif 'admin' in glist or 'wheel' in glist or 'sudo' in glist:
#precmd = 'sudo' # precmd = 'sudo'
#precmdargv = '' # precmdargv = ''
#postcmd = '' # postcmd = ''
#else: # else:
#precmd = 'su' # precmd = 'su'
#precmdargv = ' -c "' # precmdargv = ' -c "'
#postcmd = '"' # postcmd = '"'
#print "Calling command: " + precmd + precmdargv + cmd + postcmd # print "Calling command: " + precmd + precmdargv + cmd + postcmd
#sys.stdout.flush() # sys.stdout.flush()
#system(precmd+precmdargv+cmd+postcmd) # system(precmd+precmdargv+cmd+postcmd)
#raw_input("Press enter!") # raw_input("Press enter!")
#main() # main()
def gen_list_header(): def gen_list_header():
""" Generate header. """ """Generate header."""
if daemon.GetSignalDisplayType() == 0: if daemon.GetSignalDisplayType() == 0:
# Allocate 25 cols for the ESSID name # Allocate 25 cols for the ESSID name
essidgap = 25 essidgap = 25
@@ -363,17 +364,15 @@ def gen_list_header():
return 'C %s %*s %9s %17s %6s %s' % \ return 'C %s %*s %9s %17s %6s %s' % \
('STR ', essidgap, 'ESSID', 'ENCRYPT', 'BSSID', 'MODE', 'CHNL') ('STR ', essidgap, 'ESSID', 'ENCRYPT', 'BSSID', 'MODE', 'CHNL')
""" Some people use CTRL-\ to quit the application (SIGQUIT) """
def handle_sigquit(signal_number, stack_frame): def handle_sigquit(signal_number, stack_frame):
"""Some people use CTRL-\ to quit the application (SIGQUIT)"""
loop.quit() loop.quit()
ui.stop() ui.stop()
########################################
##### URWID SUPPORT CLASSES
########################################
class NetLabel(urwid.WidgetWrap): class NetLabel(urwid.WidgetWrap):
""" Wireless network label. """ """Wireless network label."""
# pylint: disable-msg=W0231 # pylint: disable-msg=W0231
def __init__(self, i, is_active): def __init__(self, i, is_active):
# Pick which strength measure to use based on what the daemon says # Pick which strength measure to use based on what the daemon says
@@ -417,15 +416,15 @@ class NetLabel(urwid.WidgetWrap):
self.__super.__init__(w) self.__super.__init__(w)
def selectable(self): def selectable(self):
""" Return whether the widget is selectable. """ """Return whether the widget is selectable."""
return True return True
def keypress(self, size, key): def keypress(self, size, key):
""" Handle keypresses. """ """Handle keypresses."""
return self._w.keypress(size, key) return self._w.keypress(size, key)
def connect(self): def connect(self):
""" Execute connection. """ """Execute connection."""
wireless.ConnectWireless(self.id) wireless.ConnectWireless(self.id)
@@ -434,22 +433,22 @@ class WiredComboBox(ComboBox):
list : the list of wired network profiles. The rest is self-explanitory. list : the list of wired network profiles. The rest is self-explanitory.
""" """
# pylint: disable-msg=W0231 # pylint: disable-msg=W0231
def __init__(self, l): def __init__(self, wired_list):
self.ADD_PROFILE = '---' + _('Add a new profile') + '---' self.ADD_PROFILE = '---' + _('Add a new profile') + '---'
# pylint: disable-msg=E1101 # pylint: disable-msg=E1101
self.__super.__init__(use_enter=False) self.__super.__init__(use_enter=False)
self.theList = [] self.theList = []
self.set_list(l) self.set_list(wired_list)
def set_list(self, l): def set_list(self, wired_list):
""" Set contents of the combobox. """ """Set contents of the combobox."""
self.theList = l self.theList = wired_list
i = 0 i = 0
wiredL = [] wiredL = []
is_active = \ is_active = \
wireless.GetWirelessIP('') is None and \ wireless.GetWirelessIP('') is None and \
wired.GetWiredIP('') is not None wired.GetWiredIP('') is not None
for profile in l: for profile in wired_list:
theString = '%4s %25s' % (i, profile) theString = '%4s %25s' % (i, profile)
# Tag if no wireless IP present, and wired one is # Tag if no wireless IP present, and wired one is
if is_active: if is_active:
@@ -469,15 +468,13 @@ class WiredComboBox(ComboBox):
wired.ReadWiredNetworkProfile(self.get_selected_profile()) wired.ReadWiredNetworkProfile(self.get_selected_profile())
def keypress(self, size, key): def keypress(self, size, key):
""" Handle keypresses. """ """Handle keypresses."""
prev_focus = self.get_focus()[1] prev_focus = self.get_focus()[1]
key = ComboBox.keypress(self, size, key) key = ComboBox.keypress(self, size, key)
if key == ' ': if key == ' ':
if self.get_focus()[1] == len(self.list) - 1: if self.get_focus()[1] == len(self.list) - 1:
dialog = InputDialog( dialog = InputDialog(('header', _('Add a new wired profile')),
('header', _('Add a new wired profile')), 7, 30)
7, 30
)
exitcode, name = dialog.run(ui, self.parent) exitcode, name = dialog.run(ui, self.parent)
if exitcode == 0: if exitcode == 0:
name = name.strip() name = name.strip()
@@ -494,12 +491,9 @@ class WiredComboBox(ComboBox):
wired.ReadWiredNetworkProfile(self.get_selected_profile()) wired.ReadWiredNetworkProfile(self.get_selected_profile())
if key == 'delete': if key == 'delete':
if len(self.theList) == 1: if len(self.theList) == 1:
error( error(self.ui, self.parent,
self.ui, _('wicd-curses does not support deleting the last '
self.parent, 'wired profile. Try renaming it ("F2")'))
_('wicd-curses does not support deleting the last wired '
'profile. Try renaming it ("F2")')
)
return key return key
wired.DeleteWiredNetworkProfile(self.get_selected_profile()) wired.DeleteWiredNetworkProfile(self.get_selected_profile())
# Return to the top of the list if something is deleted. # Return to the top of the list if something is deleted.
@@ -536,7 +530,7 @@ class WiredComboBox(ComboBox):
class AdHocDialog(Dialog2): class AdHocDialog(Dialog2):
""" Dialog2 that initiates an Ad-Hoc network connection. """ """Dialog2 that initiates an Ad-Hoc network connection."""
def __init__(self): def __init__(self):
essid_t = _('ESSID') essid_t = _('ESSID')
ip_t = _('IP') ip_t = _('IP')
@@ -551,8 +545,8 @@ class AdHocDialog(Dialog2):
self.key_edit = DynEdit(key_t, sensitive=False) self.key_edit = DynEdit(key_t, sensitive=False)
self.use_ics_chkb = urwid.CheckBox(use_ics_t) self.use_ics_chkb = urwid.CheckBox(use_ics_t)
self.use_encrypt_chkb = urwid.CheckBox(use_encrypt_t, self.use_encrypt_chkb = urwid.CheckBox(
on_state_change=self.encrypt_callback) use_encrypt_t, on_state_change=self.encrypt_callback)
blank = urwid.Text('') blank = urwid.Text('')
@@ -561,9 +555,9 @@ class AdHocDialog(Dialog2):
self.ip_edit.set_edit_text("169.254.12.10") self.ip_edit.set_edit_text("169.254.12.10")
self.channel_edit.set_edit_text("3") self.channel_edit.set_edit_text("3")
l = [self.essid_edit, self.ip_edit, self.channel_edit, blank, lb = [self.essid_edit, self.ip_edit, self.channel_edit, blank,
self.use_ics_chkb, self.use_encrypt_chkb, self.key_edit] self.use_ics_chkb, self.use_encrypt_chkb, self.key_edit]
body = urwid.ListBox(l) body = urwid.ListBox(lb)
header = ('header', _('Create an Ad-Hoc Network')) header = ('header', _('Create an Ad-Hoc Network'))
Dialog2.__init__(self, header, 15, 50, body) Dialog2.__init__(self, header, 15, 50, body)
@@ -571,11 +565,11 @@ class AdHocDialog(Dialog2):
self.frame.set_focus('body') self.frame.set_focus('body')
def encrypt_callback(self, chkbox, new_state, user_info=None): def encrypt_callback(self, chkbox, new_state, user_info=None):
""" Set widget sensitivity. """ """Set widget sensitivity."""
self.key_edit.set_sensitive(new_state) self.key_edit.set_sensitive(new_state)
def unhandled_key(self, size, k): def unhandled_key(self, size, k):
""" Handle keypresses. """ """Handle keypresses."""
if k in ('up', 'page up'): if k in ('up', 'page up'):
self.frame.set_focus('body') self.frame.set_focus('body')
if k in ('down', 'page down'): if k in ('down', 'page down'):
@@ -587,7 +581,7 @@ class AdHocDialog(Dialog2):
self.view.keypress(size, k) self.view.keypress(size, k)
def on_exit(self, exitcode): def on_exit(self, exitcode):
""" Handle dialog exit. """ """Handle dialog exit."""
data = (self.essid_edit.get_edit_text(), data = (self.essid_edit.get_edit_text(),
self.ip_edit.get_edit_text().strip(), self.ip_edit.get_edit_text().strip(),
self.channel_edit.get_edit_text(), self.channel_edit.get_edit_text(),
@@ -599,7 +593,7 @@ class AdHocDialog(Dialog2):
# TODO # TODO
class ForgetDialog(Dialog2): class ForgetDialog(Dialog2):
""" Dialog2 that removes/forgets a network. """ """Dialog2 that removes/forgets a network."""
def __init__(self): def __init__(self):
self.to_remove = dict(essid=[], bssid=[]) self.to_remove = dict(essid=[], bssid=[])
@@ -608,7 +602,7 @@ class ForgetDialog(Dialog2):
'listbar' 'listbar'
) )
title = urwid.Text(_('Please select the networks to forget')) title = urwid.Text(_('Please select the networks to forget'))
l = [title, header] lb = [title, header]
for entry in wireless.GetSavedWirelessNetworks(): for entry in wireless.GetSavedWirelessNetworks():
label = '%20s %20s' label = '%20s %20s'
if entry[1] != 'None': if entry[1] != 'None':
@@ -623,8 +617,8 @@ class ForgetDialog(Dialog2):
on_state_change=self.update_to_remove, on_state_change=self.update_to_remove,
user_data=data user_data=data
) )
l.append(cb) lb.append(cb)
body = urwid.ListBox(l) body = urwid.ListBox(lb)
header = ('header', _('List of saved networks')) header = ('header', _('List of saved networks'))
Dialog2.__init__(self, header, 15, 50, body) Dialog2.__init__(self, header, 15, 50, body)
@@ -632,7 +626,7 @@ class ForgetDialog(Dialog2):
self.frame.set_focus('body') self.frame.set_focus('body')
def update_to_remove(self, widget, checked, data): def update_to_remove(self, widget, checked, data):
""" Update list of removable networks. """ """Update list of removable networks."""
if checked: if checked:
self.to_remove['essid'].append(data[0]) self.to_remove['essid'].append(data[0])
self.to_remove['bssid'].append(data[1]) self.to_remove['bssid'].append(data[1])
@@ -641,7 +635,7 @@ class ForgetDialog(Dialog2):
self.to_remove['bssid'].remove(data[1]) self.to_remove['bssid'].remove(data[1])
def unhandled_key(self, size, k): def unhandled_key(self, size, k):
""" Handle unhandled keys. """ """Handle unhandled keys."""
if k in ('up', 'page up'): if k in ('up', 'page up'):
self.frame.set_focus('body') self.frame.set_focus('body')
if k in ('down', 'page down'): if k in ('down', 'page down'):
@@ -653,13 +647,10 @@ class ForgetDialog(Dialog2):
self.view.keypress(size, k) self.view.keypress(size, k)
def on_exit(self, exitcode): def on_exit(self, exitcode):
""" Handle dialog exit. """ """Handle dialog exit."""
return exitcode, self.to_remove return exitcode, self.to_remove
########################################
##### APPLICATION INTERFACE CLASS
########################################
# The Whole Shebang # The Whole Shebang
class appGUI(): class appGUI():
"""The UI itself, all glory belongs to it!""" """The UI itself, all glory belongs to it!"""
@@ -686,7 +677,8 @@ class appGUI():
self.WIRED_IDX = 1 self.WIRED_IDX = 1
self.WLESS_IDX = 3 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.wiredH = urwid.Filler(urwid.Text(_('Wired Networks')))
self.list_header = urwid.AttrWrap( self.list_header = urwid.AttrWrap(
urwid.Text(gen_list_header()), 'listbar' urwid.Text(gen_list_header()), 'listbar'
@@ -713,10 +705,9 @@ class appGUI():
self.update_netlist(force_check=True, firstrun=True) self.update_netlist(force_check=True, firstrun=True)
# Keymappings proposed by nanotube in #wicd # Keymappings proposed by nanotube in #wicd
keys = [ keys = [('H', _('Help'), None),
('H', _('Help'), None),
('right', _('Config'), None), ('right', _('Config'), None),
#(' ', ' ', None), # (' ', ' ', None),
('K', _('RfKill'), None), ('K', _('RfKill'), None),
('C', _('Connect'), None), ('C', _('Connect'), None),
('D', _('Disconn'), None), ('D', _('Disconn'), None),
@@ -724,8 +715,7 @@ class appGUI():
('P', _('Prefs'), None), ('P', _('Prefs'), None),
('I', _('Hidden'), None), ('I', _('Hidden'), None),
('A', _('About'), None), ('A', _('About'), None),
('Q', _('Quit'), loop.quit) ('Q', _('Quit'), loop.quit)]
]
self.primaryCols = OptCols(keys, self.handle_keys) self.primaryCols = OptCols(keys, self.handle_keys)
self.status_label = urwid.AttrWrap(urwid.Text(''), 'important') self.status_label = urwid.AttrWrap(urwid.Text(''), 'important')
@@ -745,7 +735,8 @@ class appGUI():
self.prev_state = False self.prev_state = False
self.connecting = False self.connecting = False
self.screen_locked = 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.diag_type = 'none' # The type of dialog that is up
self.scanning = False self.scanning = False
@@ -753,28 +744,24 @@ class appGUI():
self.update_status() self.update_status()
#self.max_wait = ui.max_wait # self.max_wait = ui.max_wait
def doScan(self, sync=False): def doScan(self, sync=False):
""" Start wireless scan. """ """Start wireless scan."""
self.scanning = True self.scanning = True
wireless.Scan(False) wireless.Scan(False)
def init_other_optcols(self): def init_other_optcols(self):
""" Init "tabbed" preferences dialog. """ """Init "tabbed" preferences dialog."""
self.prefCols = OptCols([ self.prefCols = OptCols([('S', _('Save')),
('S', _('Save')),
('page up', _('Tab Left'), ), ('page up', _('Tab Left'), ),
('page down', _('Tab Right')), ('page down', _('Tab Right')),
('esc', _('Cancel')) ('esc', _('Cancel'))], self.handle_keys)
], self.handle_keys) self.confCols = OptCols([('S', _('Save')),
self.confCols = OptCols([ ('esc', _('Cancel'))], self.handle_keys)
('S', _('Save')),
('esc', _('Cancel'))
], self.handle_keys)
def lock_screen(self): def lock_screen(self):
""" Lock the screen. """ """Lock the screen."""
if self.diag_type == 'pref': if self.diag_type == 'pref':
self.do_diag_lock = True self.do_diag_lock = True
return True return True
@@ -783,7 +770,7 @@ class appGUI():
self.update_ui() self.update_ui()
def unlock_screen(self): def unlock_screen(self):
""" Unlock the screen. """ """Unlock the screen."""
if self.do_diag_lock: if self.do_diag_lock:
self.do_diag_lock = False self.do_diag_lock = False
return True return True
@@ -794,7 +781,7 @@ class appGUI():
self.update_ui() self.update_ui()
def raise_hidden_network_dialog(self): def raise_hidden_network_dialog(self):
""" Show hidden network dialog. """ """Show hidden network dialog."""
dialog = InputDialog( dialog = InputDialog(
('header', _('Select Hidden Network ESSID')), ('header', _('Select Hidden Network ESSID')),
7, 30, _('Scan') 7, 30, _('Scan')
@@ -824,7 +811,7 @@ class appGUI():
where = None where = None
else: else:
where = self.thePile.get_focus().get_focus()[1] where = self.thePile.get_focus().get_focus()[1]
#where = self.wlessLB.get_focus()[1] # where = self.wlessLB.get_focus()[1]
self.focusloc = [wlessorwired, where] self.focusloc = [wlessorwired, where]
# Be clunky until I get to a later stage of development. # Be clunky until I get to a later stage of development.
@@ -832,7 +819,7 @@ class appGUI():
@wrap_exceptions @wrap_exceptions
def update_netlist(self, state=None, x=None, force_check=False, def update_netlist(self, state=None, x=None, force_check=False,
firstrun=False): firstrun=False):
""" Update the list of networks. """ """Update the list of networks."""
# Don't even try to do this if we are running a dialog # Don't even try to do this if we are running a dialog
if self.diag: if self.diag:
return return
@@ -872,8 +859,10 @@ class appGUI():
get_body().set_focus(self.focusloc[1]) get_body().set_focus(self.focusloc[1])
else: else:
if self.wlessLB != self.no_wlan: if self.wlessLB != self.no_wlan:
# Set the focus to the last selected item, but never past the length of the list # Set the focus to the last selected item, but never
self.thePile.get_focus().set_focus(min(self.focusloc[1], len(wlessL) - 1)) # past the length of the list
self.thePile.get_focus().set_focus(
min(self .focusloc[1], len(wlessL) - 1))
else: else:
self.thePile.set_focus(self.wiredCB) self.thePile.set_focus(self.wiredCB)
else: else:
@@ -886,8 +875,10 @@ class appGUI():
if self.focusloc[1] is None: if self.focusloc[1] is None:
self.focusloc[1] = 0 self.focusloc[1] = 0
if self.wlessLB != self.no_wlan: if self.wlessLB != self.no_wlan:
# Set the focus to the last selected item, but never past the length of the list # Set the focus to the last selected item, but never past
self.wlessLB.set_focus(min(self.focusloc[1], len(wlessL) - 1)) # the length of the list
self.wlessLB.set_focus(min(self.focusloc[1],
len(wlessL) - 1))
self.prev_state = state self.prev_state = state
if not firstrun: if not firstrun:
@@ -896,13 +887,11 @@ class appGUI():
if wired.GetDefaultWiredNetwork() is not None: if wired.GetDefaultWiredNetwork() is not None:
self.wiredCB.get_body().set_focus( self.wiredCB.get_body().set_focus(
wired.GetWiredProfileList().index( wired.GetWiredProfileList().index(
wired.GetDefaultWiredNetwork() wired.GetDefaultWiredNetwork()))
)
)
@wrap_exceptions @wrap_exceptions
def update_status(self): def update_status(self):
""" Update the footer / statusbar. """ """Update the footer / statusbar."""
wired_connecting = wired.CheckIfWiredConnecting() wired_connecting = wired.CheckIfWiredConnecting()
wireless_connecting = wireless.CheckIfWirelessConnecting() wireless_connecting = wireless.CheckIfWirelessConnecting()
self.connecting = wired_connecting or wireless_connecting self.connecting = wired_connecting or wireless_connecting
@@ -929,7 +918,7 @@ class appGUI():
return True return True
def set_connecting_status(self, fast): def set_connecting_status(self, fast):
""" Set connecting status. """ """Set connecting status."""
wired_connecting = wired.CheckIfWiredConnecting() wired_connecting = wired.CheckIfWiredConnecting()
wireless_connecting = wireless.CheckIfWirelessConnecting() wireless_connecting = wireless.CheckIfWirelessConnecting()
if wireless_connecting: if wireless_connecting:
@@ -941,14 +930,14 @@ class appGUI():
stat = wireless.CheckWirelessConnectingMessage() stat = wireless.CheckWirelessConnectingMessage()
return self.set_status("%s: %s" % (essid, stat), True) return self.set_status("%s: %s" % (essid, stat), True)
if wired_connecting: if wired_connecting:
return self.set_status(_('Wired Network') + return self.set_status(_('Wired Network') + ': ' +
': ' + wired.CheckWiredConnectingMessage(), True) wired.CheckWiredConnectingMessage(), True)
else: else:
self.conn_status = False self.conn_status = False
return False return False
def set_status(self, text, from_idle=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 # 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 # from_idle : a check to see if we are being called directly from the
# mainloop # mainloop
@@ -975,22 +964,22 @@ class appGUI():
return True return True
def dbus_scan_finished(self): def dbus_scan_finished(self):
""" Handle DBus scan finish. """ """Handle DBus scan finish."""
# I'm pretty sure that I'll need this later. # I'm pretty sure that I'll need this later.
#if not self.connecting: # if not self.connecting:
# gobject.idle_add(self.refresh_networks, None, False, None) # gobject.idle_add(self.refresh_networks, None, False, None)
self.unlock_screen() self.unlock_screen()
self.scanning = False self.scanning = False
def dbus_scan_started(self): def dbus_scan_started(self):
""" Handle DBus scan start. """ """Handle DBus scan start."""
self.scanning = True self.scanning = True
if self.diag_type == 'conf': if self.diag_type == 'conf':
self.restore_primary() self.restore_primary()
self.lock_screen() self.lock_screen()
def restore_primary(self): def restore_primary(self):
""" Restore screen. """ """Restore screen."""
self.diag_type = 'none' self.diag_type = 'none'
if self.do_diag_lock or self.scanning: if self.do_diag_lock or self.scanning:
self.frame.set_body(self.screen_locker) self.frame.set_body(self.screen_locker)
@@ -1002,12 +991,12 @@ class appGUI():
self.update_ui() self.update_ui()
def handle_keys(self, keys): def handle_keys(self, keys):
""" Handle keys. """ """Handle keys."""
if not self.diag: if not self.diag:
# Handle keystrokes # Handle keystrokes
if "f8" in keys or 'Q' in keys or 'q' in keys: if "f8" in keys or 'Q' in keys or 'q' in keys:
loop.quit() loop.quit()
#return False # return False
if "f5" in keys or 'R' in keys: if "f5" in keys or 'R' in keys:
self.lock_screen() self.lock_screen()
self.doScan() self.doScan()
@@ -1065,7 +1054,8 @@ class appGUI():
) )
self.pref.load_settings() self.pref.load_settings()
self.pref.ready_widgets(ui, self.frame) 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 = self.pref
self.diag_type = 'pref' self.diag_type = 'pref'
self.frame.set_body(self.diag) self.frame.set_body(self.diag)
@@ -1091,7 +1081,7 @@ class appGUI():
run_configscript(self.frame, netname, nettype) run_configscript(self.frame, netname, nettype)
if "O" in keys: if "O" in keys:
exitcode, data = AdHocDialog().run(ui, self.frame) 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: if exitcode == 1:
wireless.CreateAdHocNetwork( wireless.CreateAdHocNetwork(
data[0], data[0],
@@ -1108,9 +1098,10 @@ class appGUI():
text = _('Are you sure you want to discard settings for ' text = _('Are you sure you want to discard settings for '
'the selected networks?') 'the selected networks?')
text += '\n\n' + '\n'.join(data['essid']) text += '\n\n' + '\n'.join(data['essid'])
confirm, trash = TextDialog(text, 20, 50, confirm, trash = TextDialog(
buttons=[(_('OK'), 1), (_('Cancel'), -1)], text, 20, 50,
).run(ui, self.frame) buttons=[(_('OK'), 1),
(_('Cancel'), -1)],).run(ui, self.frame)
if confirm == 1: if confirm == 1:
for x in data['bssid']: for x in data['bssid']:
wireless.DeleteWirelessNetwork(x) wireless.DeleteWirelessNetwork(x)
@@ -1132,7 +1123,8 @@ class appGUI():
break break
# F10 has been changed to S to avoid using function keys, # F10 has been changed to S to avoid using function keys,
# which are often caught by the terminal emulator. # 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': if k == 'f10' or k == 'S' or k == 's':
self.diag.save_settings() self.diag.save_settings()
self.restore_primary() self.restore_primary()
@@ -1142,14 +1134,14 @@ class appGUI():
continue continue
def call_update_ui(self, source, cb_condition): def call_update_ui(self, source, cb_condition):
""" Update UI. """ """Update UI."""
self.update_ui(True) self.update_ui(True)
return True return True
# Redraw the screen # Redraw the screen
@wrap_exceptions @wrap_exceptions
def update_ui(self, from_key=False): def update_ui(self, from_key=False):
""" Redraw the screen. """ """Redraw the screen."""
if not ui._started: if not ui._started:
return False return False
@@ -1163,11 +1155,11 @@ class appGUI():
# Get the input data # Get the input data
if self.update_tag is not None: if self.update_tag is not None:
gobject.source_remove(self.update_tag) gobject.source_remove(self.update_tag)
#if from_key: # if from_key:
return False return False
def connect(self, nettype, networkid, networkentry=None): def connect(self, nettype, networkid, networkentry=None):
""" Initiates the connection process in the daemon. """ """Initiates the connection process in the daemon."""
if nettype == "wireless": if nettype == "wireless":
wireless.ConnectWireless(networkid) wireless.ConnectWireless(networkid)
elif nettype == "wired": elif nettype == "wired":
@@ -1175,18 +1167,15 @@ class appGUI():
self.update_status() self.update_status()
########################################
##### INITIALIZATION FUNCTIONS
########################################
def main(): def main():
""" Main function. """ """Main function."""
global ui, dlogger global ui, dlogger
# We are not python. # We are not python.
misc.RenameProcess('wicd-curses') misc.RenameProcess('wicd-curses')
ui = urwid.raw_display.Screen() ui = urwid.raw_display.Screen()
#if options.debug: # if options.debug:
# dlogger = logging.getLogger("Debug") # dlogger = logging.getLogger("Debug")
# dlogger.setLevel(logging.DEBUG) # dlogger.setLevel(logging.DEBUG)
# dlogger.debug("wicd-curses debug logging started") # dlogger.debug("wicd-curses debug logging started")
@@ -1216,7 +1205,8 @@ def main():
('red', 'dark red', 'default'), ('red', 'dark red', 'default'),
('bold', 'white', 'black', 'bold') ('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) signal.signal(signal.SIGQUIT, handle_sigquit)
# This is a wrapper around a function that calls another a function that # This is a wrapper around a function that calls another a function that
# is a wrapper around a infinite loop. Fun. # is a wrapper around a infinite loop. Fun.
@@ -1226,7 +1216,7 @@ def main():
@wrap_exceptions @wrap_exceptions
def run(): def run():
""" Run the UI. """ """Run the UI."""
global loop global loop
loop = gobject.MainLoop() loop = gobject.MainLoop()
@@ -1254,12 +1244,13 @@ def run():
# Mostly borrowed from gui.py # Mostly borrowed from gui.py
def setup_dbus(force=True): def setup_dbus(force=True):
""" Initialize DBus. """ """Initialize DBus."""
global bus, daemon, wireless, wired global bus, daemon, wireless, wired
try: try:
dbusmanager.connect_to_dbus() dbusmanager.connect_to_dbus()
except DBusException: 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: try:
bus = dbusmanager.get_bus() bus = dbusmanager.get_bus()
@@ -1268,37 +1259,35 @@ def setup_dbus(force=True):
wireless = dbus_ifaces['wireless'] wireless = dbus_ifaces['wireless']
wired = dbus_ifaces['wired'] wired = dbus_ifaces['wired']
except DBusException: 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: if not daemon:
print('Error connecting to wicd via D-Bus. ' \ print('Error connecting to wicd via D-Bus.\nPlease make sure the '
'Please make sure the wicd service is running.') 'wicd service is running.')
sys.exit(3) sys.exit(3)
netentry_curses.dbus_init(dbus_ifaces) netentry_curses.dbus_init(dbus_ifaces)
return True return True
setup_dbus() setup_dbus()
########################################
##### MAIN ENTRY POINT
########################################
if __name__ == '__main__': if __name__ == '__main__':
try: try:
parser = OptionParser( parser = OptionParser(version="wicd-curses-%s (using wicd %s)" %
version="wicd-curses-%s (using wicd %s)" %
(CURSES_REV, daemon.Hello()), (CURSES_REV, daemon.Hello()),
prog="wicd-curses" prog="wicd-curses")
)
except Exception as e: except Exception as e:
if "DBus.Error.AccessDenied" in e.get_dbus_name(): if "DBus.Error.AccessDenied" in e.get_dbus_name():
print(_('ERROR: wicd-curses was denied access to the wicd daemon: ' print(_('ERROR: wicd-curses was denied access to the wicd daemon: '
'please check that your user is in the "$A" group.'). \ 'please check that your user is in the "$A" group.')
replace('$A', '\033[1;34m' + wpath.wicd_group + '\033[0m')) .replace('$A', '\033[1;34m' + wpath.wicd_group + '\033[0m'))
sys.exit(1) sys.exit(1)
else: else:
raise raise
#parser.add_option("-d", "--debug", action="store_true", dest='debug', # parser.add_option("-d", "--debug", action="store_true", dest='debug',
# help="enable logging of wicd-curses (currently does nothing)") # help="enable logging of wicd-curses (currently does nothing)")
(options, args) = parser.parse_args() (options, args) = parser.parse_args()

View File

@@ -1,6 +1,5 @@
#!/usr/bin/env python3 #!/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 Script for configuring the scripts for a network passed in as a
command line argument. This needs to run a separate process because 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. run as the current user.
""" """
# #
# Copyright (C) 2007-2009 Adam Blackburn # Copyright (C) 2007-2009 Adam Blackburn
# Copyright (C) 2007-2009 Dan O'Reilly # Copyright (C) 2007-2009 Dan O'Reilly
@@ -46,7 +44,7 @@ wired_conf = wpath.etc + 'wired-settings.conf'
def none_to_blank(text): 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 If text is None, 'None', or '' then this method will
return '', otherwise it will just return str(text). return '', otherwise it will just return str(text).
@@ -57,39 +55,40 @@ def none_to_blank(text):
else: else:
return str(text) return str(text)
def blank_to_none(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): if text in ("", None):
return "None" return "None"
else: else:
return str(text) return str(text)
def get_script_info(network, network_type): 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 = {} info = {}
if network_type == "wired": if network_type == "wired":
con = ConfigManager(wired_conf) con = ConfigManager(wired_conf)
if con.has_section(network): 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)
else: else:
bssid = wireless.GetWirelessProperty(int(network), "bssid") bssid = wireless.GetWirelessProperty(int(network), "bssid")
con = ConfigManager(wireless_conf) con = ConfigManager(wireless_conf)
if con.has_section(bssid): section = bssid
info["pre_entry"] = con.get(bssid, "beforescript", None)
info["post_entry"] = con.get(bssid, "afterscript", None) if con.has_section(section):
info["pre_disconnect_entry"] = con.get(bssid, 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) "predisconnectscript", None)
info["post_disconnect_entry"] = con.get(bssid, info["post_disconnect_entry"] = con.get(section,
"postdisconnectscript", None) "postdisconnectscript", None)
return info return info
def write_scripts(network, network_type, script_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": if network_type == "wired":
con = ConfigManager(wired_conf) con = ConfigManager(wired_conf)
con.set(network, "beforescript", script_info["pre_entry"]) con.set(network, "beforescript", script_info["pre_entry"])
@@ -117,8 +116,8 @@ def write_scripts(network, network_type, script_info):
wireless.SaveWirelessNetworkProfile(int(network)) wireless.SaveWirelessNetworkProfile(int(network))
def main (argv): def main(argv):
""" Runs the script configuration dialog. """ """Runs the script configuration dialog."""
if len(argv) < 2: if len(argv) < 2:
print('Network id to configure is missing, aborting.') print('Network id to configure is missing, aborting.')
sys.exit(1) sys.exit(1)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -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. chdir() -- Change directory to the location of the current file.
""" """
import os import os
# The path containing the wpath.py file. # 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_install_gnome_shell_extensions = %NO_INSTALL_GNOME_SHELL_EXTENSIONS%
no_use_notifications = %NO_USE_NOTIFICATIONS% no_use_notifications = %NO_USE_NOTIFICATIONS%
def chdir(f): def chdir(f):
"""Change directory to the location of the specified file. """Change directory to the location of the specified file.

319
setup.py
View File

@@ -16,16 +16,15 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from glob import glob
import os
import re
import shutil
import subprocess
from distutils.core import setup, Command from distutils.core import setup, Command
from distutils.command.build import build as _build from distutils.command.build import build as _build
from distutils.command.install import install as _install 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! # Be sure to keep this updated!
# VERSIONNUMBER # VERSIONNUMBER
@@ -46,8 +45,9 @@ os.chdir(os.path.abspath(os.path.split(__file__)[0]))
try: try:
if os.path.exists('.bzr') and os.system('bzr > /dev/null 2>&1') == 0: if os.path.exists('.bzr') and os.system('bzr > /dev/null 2>&1') == 0:
try: try:
os.system('bzr version-info --python > vcsinfo.py && 2to3-2.7 -w vcsinfo.py') os.system('bzr version-info --python > vcsinfo.py && 2to3-2.7 '
except: '-w vcsinfo.py')
except Exception:
pass pass
import vcsinfo import vcsinfo
REVISION_NUM = vcsinfo.version_info['revno'] REVISION_NUM = vcsinfo.version_info['revno']
@@ -55,6 +55,7 @@ except Exception as e:
print('failed to find revision number:') print('failed to find revision number:')
print(e) print(e)
class build(_build): class build(_build):
sub_commands = _build.sub_commands + [('compile_translations', None)] sub_commands = _build.sub_commands + [('compile_translations', None)]
@@ -64,9 +65,10 @@ class build(_build):
except ImportError: except ImportError:
self.run_command('configure') self.run_command('configure')
import wpath import wpath
#raise Exception, 'Please run "./setup.py configure" first.' # raise Exception, 'Please run "./setup.py configure" first.'
_build.run(self) _build.run(self)
class configure(Command): class configure(Command):
description = "configure the paths that Wicd will be installed to" description = "configure the paths that Wicd will be installed to"
@@ -87,21 +89,31 @@ class configure(Command):
('curses=', None, 'set the curses UI directory'), ('curses=', None, 'set the curses UI directory'),
('gtk=', None, 'set the GTK UI directory'), ('gtk=', None, 'set the GTK UI directory'),
('cli=', None, 'set the CLI 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'), ('networks=', None, 'set the encryption configuration directory'),
('log=', None, 'set the log directory'), ('log=', None, 'set the log directory'),
('resume=', None, 'set the directory the resume from suspend script is stored in'), ('resume=', None, 'set the directory the resume from suspend script '
('suspend=', None, 'set the directory the suspend script is stored in'), 'is stored in'),
('pmutils=', None, 'set the directory the pm-utils hooks are 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=', 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'), ('dbus-service=', None, 'set the directory where the dbus services '
('systemd=', None, 'set the directory where the systemd system services config files are stored in'), 'config files are stored in'),
('logrotate=', None, 'set the directory where the logrotate configuration 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'), ('desktop=', None, 'set the directory the .desktop file is stored in'),
('icons=', None, "set the base directory for the .desktop file's icons"), ('icons=', None, "set the base directory for the .desktop file's "
('translations=', None, 'set the directory translations are stored in'), "icons"),
('autostart=', None, 'set the directory that will be autostarted on desktop login'), ('translations=', None, 'set the directory translations are stored '
('varlib=',None , 'set the path for wicd\'s variable state data'), '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'), ('init=', None, 'set the directory for the init file'),
('docdir=', None, 'set the directory for the documentation'), ('docdir=', None, 'set the directory for the documentation'),
('mandir=', None, 'set the directory for the man pages'), ('mandir=', None, 'set the directory for the man pages'),
@@ -116,7 +128,8 @@ class configure(Command):
('initfile=', None, 'set the init file to use'), ('initfile=', None, 'set the init file to use'),
('initfilename=', None, "set the name of the init file (don't use)"), ('initfilename=', None, "set the name of the init file (don't use)"),
('wicdgroup=', None, "set the name of the group used for wicd"), ('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'), ('loggroup=', None, 'the group the log file belongs to'),
('logperms=', None, 'the log file permissions'), ('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-init', None, "do not install the init file"),
('no-install-man', None, 'do not install the man files'), ('no-install-man', None, 'do not install the man files'),
('no-install-i18n', None, 'do not install translation 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-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-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-ncurses', None, 'do not install the ncurses client'),
('no-install-cli', None, 'do not install the command line executable'), ('no-install-cli', None, 'do not install the command line executable'),
('no-install-gtk', None, 'do not install the gtk client'), ('no-install-gtk', None, 'do not install the gtk client'),
('no-install-gnome-shell-extensions', None, 'do not install the Gnome Shell extension'), ('no-install-gnome-shell-extensions', None, 'do not install the Gnome '
('no-use-notifications', None, 'do not ever allow the use of libnotify notifications') 'Shell extension'),
] ('no-use-notifications', None, 'do not ever allow the use of '
'libnotify notifications')]
def initialize_options(self): def initialize_options(self):
self.lib = '/usr/lib/wicd/' self.lib = '/usr/lib/wicd/'
@@ -202,9 +219,9 @@ class configure(Command):
self.ddistro = 'debian' self.ddistro = 'debian'
elif os.path.exists('/etc/arch-release'): elif os.path.exists('/etc/arch-release'):
self.ddistro = 'arch' self.ddistro = 'arch'
elif os.path.exists('/etc/slackware-version') or \ elif (os.path.exists('/etc/slackware-version') or
os.path.exists('/etc/slamd64-version') or \ os.path.exists('/etc/slamd64-version') or
os.path.exists('/etc/bluewhite64-version'): os.path.exists('/etc/bluewhite64-version')):
self.ddistro = 'slackware' self.ddistro = 'slackware'
elif os.path.exists('/etc/pld-release'): elif os.path.exists('/etc/pld-release'):
self.ddistro = 'pld' self.ddistro = 'pld'
@@ -214,12 +231,13 @@ class configure(Command):
self.distro = 'lunar' self.distro = 'lunar'
else: else:
self.ddistro = 'FAIL' self.ddistro = 'FAIL'
#self.no_install_init = True # self.no_install_init = True
#self.distro_detect_failed = True # self.distro_detect_failed = True
print('WARNING: Unable to detect the distribution in use. ' + \ print('WARNING: Unable to detect the distribution in use.\n'
'If you have specified --distro or --init and --initfile, configure will continue. ' + \ 'If you have specified --distro or --init and --initfile, '
'Please report this warning, along with the name of your ' + \ 'configure will continue.\nPlease report this warning, '
'distribution, to the wicd developers.') 'along with the name of your distribution, to the wicd '
'developers.')
# Try to get the pm-utils sleep hooks directory from pkg-config and # Try to get the pm-utils sleep hooks directory from pkg-config and
# the kde prefix from kde-config # the kde prefix from kde-config
@@ -228,10 +246,12 @@ class configure(Command):
# If we don't get anything from *-config, or it didn't run properly, # 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 # or the path is not a proper absolute path, raise an error
try: try:
pmtemp = subprocess.Popen(["pkg-config", "--variable=pm_sleephooks", pmtemp = subprocess.Popen(["pkg-config",
"--variable=pm_sleephooks",
"pm-utils"], stdout=subprocess.PIPE) "pm-utils"], stdout=subprocess.PIPE)
returncode = pmtemp.wait() # let it finish, and get the exit code returncode = pmtemp.wait() # let it finish, and get the exit code
pmutils_candidate = str(pmtemp.stdout.readline().strip()) # read stdout # read stdout
pmutils_candidate = str(pmtemp.stdout.readline().strip())
if len(pmutils_candidate) == 0 or returncode != 0 or \ if len(pmutils_candidate) == 0 or returncode != 0 or \
not os.path.isabs(pmutils_candidate): not os.path.isabs(pmutils_candidate):
raise ValueError raise ValueError
@@ -241,20 +261,27 @@ class configure(Command):
pass # use our default pass # use our default
try: try:
kdetemp = subprocess.Popen(["kde-config","--prefix"], stdout=subprocess.PIPE) kdetemp = subprocess.Popen(["kde-config", "--prefix"],
returncode = kdetemp.wait() # let it finish, and get the exit code stdout=subprocess.PIPE)
kdedir_candidate = str(kdetemp.stdout.readline().strip()) # read stdout # let it finish, and get the exit code
if len(kdedir_candidate) == 0 or returncode != 0 or \ returncode = kdetemp.wait()
not os.path.isabs(kdedir_candidate): # 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 raise ValueError
else: else:
self.kdedir = kdedir_candidate + '/share/autostart' self.kdedir = kdedir_candidate + '/share/autostart'
except (OSError, ValueError, FileNotFoundError): except (OSError, ValueError, FileNotFoundError):
# If kde-config isn't present, we'll check for kde-4.x # If kde-config isn't present, we'll check for kde-4.x
try: try:
kde4temp = subprocess.Popen(["kde4-config","--prefix"], stdout=subprocess.PIPE) kde4temp = subprocess.Popen(["kde4-config", "--prefix"],
returncode = kde4temp.wait() # let it finish, and get the exit code stdout=subprocess.PIPE)
kde4dir_candidate = str(kde4temp.stdout.readline().strip()) # read stdout # 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 \ if len(kde4dir_candidate) == 0 or returncode != 0 or \
not os.path.isabs(kde4dir_candidate): not os.path.isabs(kde4dir_candidate):
raise ValueError raise ValueError
@@ -266,7 +293,7 @@ class configure(Command):
# on the user's system # on the user's system
self.no_install_kde = True self.no_install_kde = True
# If the assumption above turns out to be wrong, do this: # 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.python = '/usr/bin/python3'
self.pidfile = '/var/run/wicd/wicd.pid' self.pidfile = '/var/run/wicd/wicd.pid'
@@ -309,11 +336,12 @@ class configure(Command):
elif self.distro in ['crux']: elif self.distro in ['crux']:
self.init = '/etc/rc.d/' self.init = '/etc/rc.d/'
elif self.distro in ['lunar']: elif self.distro in ['lunar']:
self.init='/etc/init.d/' self.init = '/etc/init.d/'
self.initfile = 'init/lunar/wicd' self.initfile = 'init/lunar/wicd'
else : else:
if self.distro == 'auto': 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 = self.ddistro
self.distro_check() self.distro_check()
else: else:
@@ -321,13 +349,13 @@ class configure(Command):
self.no_install_init = True self.no_install_init = True
self.distro_detect_failed = True self.distro_detect_failed = True
def finalize_options(self): def finalize_options(self):
self.distro_check() self.distro_check()
if self.distro_detect_failed and not self.no_install_init and \ if self.distro_detect_failed and not self.no_install_init and \
'FAIL' in [self.init, self.initfile]: 'FAIL' in [self.init, self.initfile]:
print('ERROR: Failed to detect distro. Configure cannot continue. ' + \ print('ERROR: Failed to detect distro. Configure cannot '
'Please specify --init and --initfile to continue with configuration.') 'continue.\nPlease specify --init and --initfile to '
'continue with configuration.')
# loop through the argument definitions in user_options # loop through the argument definitions in user_options
for argument in self.user_options: for argument in self.user_options:
@@ -354,7 +382,8 @@ class configure(Command):
cur_arg = argument[0][:-1] cur_arg = argument[0][:-1]
cur_arg_value = getattr(self, cur_arg.replace('-', '_')) cur_arg_value = getattr(self, cur_arg.replace('-', '_'))
print("%s is %s" % (cur_arg, cur_arg_value)) 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: else:
cur_arg = argument[0] cur_arg = argument[0]
cur_arg_value = getattr(self, cur_arg.replace('-', '_')) cur_arg_value = getattr(self, cur_arg.replace('-', '_'))
@@ -364,20 +393,21 @@ class configure(Command):
print('Replacing values in template files...') print('Replacing values in template files...')
for item in os.listdir('in'): for item in os.listdir('in'):
if item.endswith('.in'): if item.endswith('.in'):
print('Replacing values in',item, end=' ') print('Replacing values in', item, end=' ')
original_name = os.path.join('in',item) original_name = os.path.join('in', item)
item_in = open(original_name, 'r') item_in = open(original_name, 'r')
final_name = item[:-3].replace('=','/') final_name = item[:-3].replace('=', '/')
parent_dir = os.path.dirname(final_name) parent_dir = os.path.dirname(final_name)
if parent_dir and not os.path.exists(parent_dir): 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) os.makedirs(parent_dir)
print(final_name) print(final_name)
item_out = open(final_name, 'w') item_out = open(final_name, 'w')
for line in item_in.readlines(): for line in item_in.readlines():
for item, value in values: for item, value in values:
line = line.replace('%' + str(item.upper().replace('-','_')) + \ line = line.replace('%' + str(item.upper())
'%', str(value)) .replace('-', '_') + '%',
str(value))
# other things to replace that aren't arguments # other things to replace that aren't arguments
line = line.replace('%VERSION%', str(VERSION_NUM)) line = line.replace('%VERSION%', str(VERSION_NUM))
@@ -406,9 +436,9 @@ class clear_generated(Command):
print('Removing completed template files...') print('Removing completed template files...')
for item in os.listdir('in'): for item in os.listdir('in'):
if item.endswith('.in'): if item.endswith('.in'):
print('Removing completed',item, end=' ') print('Removing completed', item, end=' ')
original_name = os.path.join('in',item) original_name = os.path.join('in', item)
final_name = item[:-3].replace('=','/') final_name = item[:-3].replace('=', '/')
print(final_name, '...', end=' ') print(final_name, '...', end=' ')
if os.path.exists(final_name): if os.path.exists(final_name):
os.remove(final_name) os.remove(final_name)
@@ -420,6 +450,7 @@ class clear_generated(Command):
shutil.rmtree('translations/') shutil.rmtree('translations/')
os.makedirs('translations/') os.makedirs('translations/')
class install(_install): class install(_install):
def run(self): def run(self):
try: try:
@@ -428,7 +459,7 @@ class install(_install):
self.run_command('build') self.run_command('build')
import wpath import wpath
print("Using init file",(wpath.init, wpath.initfile)) print("Using init file", wpath.init, wpath.initfile)
data.extend([ data.extend([
(wpath.dbus, ['other/wicd.conf']), (wpath.dbus, ['other/wicd.conf']),
(wpath.dbus_service, ['other/org.wicd.daemon.service']), (wpath.dbus_service, ['other/org.wicd.daemon.service']),
@@ -437,12 +468,14 @@ class install(_install):
(wpath.log, [empty_file]), (wpath.log, [empty_file]),
(wpath.etc, ['other/dhclient.conf.template.default']), (wpath.etc, ['other/dhclient.conf.template.default']),
(wpath.encryption, [('encryption/templates/' + b) for b in (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.networks, [empty_file]),
(wpath.sbin, ['scripts/wicd']), (wpath.sbin, ['scripts/wicd']),
(wpath.daemon, ['wicd/monitor.py', 'wicd/wicd-daemon.py', (wpath.daemon, ['wicd/monitor.py', 'wicd/wicd-daemon.py',
'wicd/suspend.py', 'wicd/autoconnect.py']), 'wicd/suspend.py', 'wicd/autoconnect.py']),
(wpath.backends, ['wicd/backends/be-external.py', 'wicd/backends/be-ioctl.py']), (wpath.backends, ['wicd/backends/be-external.py',
'wicd/backends/be-ioctl.py']),
(wpath.scripts, [empty_file]), (wpath.scripts, [empty_file]),
(wpath.predisconnectscripts, [empty_file]), (wpath.predisconnectscripts, [empty_file]),
(wpath.postdisconnectscripts, [empty_file]), (wpath.postdisconnectscripts, [empty_file]),
@@ -465,21 +498,22 @@ class install(_install):
])) ]))
data.append((wpath.autostart, ['other/wicd-tray.desktop'])) data.append((wpath.autostart, ['other/wicd-tray.desktop']))
if not wpath.no_install_man: 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 size in os.listdir('icons'):
for category in os.listdir(os.path.join('icons', size)): for category in os.listdir(os.path.join('icons', size)):
imgdir = os.path.join('icons', size, category) imgdir = os.path.join('icons', size, category)
data.append( data.append((os.path.join(wpath.icons, size, category),
(os.path.join(wpath.icons, size, category), [(os.path.join(imgdir, f))
[(os.path.join(imgdir, f)) for f in os.listdir(imgdir) if not f.startswith('.')]) for f in os.listdir(imgdir)
) if not f.startswith('.')]))
for size in os.listdir('images'): for size in os.listdir('images'):
for category in os.listdir(os.path.join('images', size)): for category in os.listdir(os.path.join('images', size)):
imgdir = os.path.join('images', size, category) imgdir = os.path.join('images', size, category)
data.append( data.append((os.path.join(wpath.images, 'hicolor', size,
(os.path.join(wpath.images, 'hicolor', size, category), category),
[(os.path.join(imgdir, f)) for f in os.listdir(imgdir) if not f.startswith('.')]) [(os.path.join(imgdir, f))
) for f in os.listdir(imgdir)
if not f.startswith('.')]))
data.append((wpath.pixmaps, ['other/wicd-gtk.xpm'])) data.append((wpath.pixmaps, ['other/wicd-gtk.xpm']))
if not wpath.no_install_gnome_shell_extensions: if not wpath.no_install_gnome_shell_extensions:
data.append( data.append(
@@ -494,18 +528,19 @@ class install(_install):
data.append((wpath.curses, ['curses/configscript_curses.py'])) data.append((wpath.curses, ['curses/configscript_curses.py']))
data.append((wpath.bin, ['scripts/wicd-curses'])) data.append((wpath.bin, ['scripts/wicd-curses']))
if not wpath.no_install_man: 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: 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: 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: if not wpath.no_install_cli:
data.append((wpath.cli, ['cli/wicd-cli.py'])) data.append((wpath.cli, ['cli/wicd-cli.py']))
data.append((wpath.bin, ['scripts/wicd-cli'])) data.append((wpath.bin, ['scripts/wicd-cli']))
if not wpath.no_install_man: 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: 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) piddir = os.path.dirname(wpath.pidfile)
if not piddir.endswith('/'): if not piddir.endswith('/'):
piddir += '/' piddir += '/'
@@ -517,20 +552,27 @@ class install(_install):
if not wpath.no_install_gtk: if not wpath.no_install_gtk:
data.append((wpath.kdedir, ['other/wicd-tray.desktop'])) data.append((wpath.kdedir, ['other/wicd-tray.desktop']))
if not wpath.no_install_init: if not wpath.no_install_init:
data.append((wpath.init, [ wpath.initfile ])) data.append((wpath.init, [wpath.initfile]))
if not wpath.no_install_man: if not wpath.no_install_man:
data.append((wpath.mandir + 'man8/', ['man/wicd.8'])) data.append((wpath.mandir + 'man8/', ['man/wicd.8']))
data.append((wpath.mandir + 'man5/', ['man/wicd-manager-settings.conf.5'])) data.append((wpath.mandir + 'man5/',
data.append((wpath.mandir + 'man5/', ['man/wicd-wired-settings.conf.5'])) ['man/wicd-manager-settings.conf.5']))
data.append((wpath.mandir + 'man5/', ['man/wicd-wireless-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'])) data.append((wpath.mandir + 'man1/', ['man/wicd-client.1']))
if not wpath.no_install_man and not wpath.no_install_i18n_man: if not wpath.no_install_man and not wpath.no_install_i18n_man:
# Dutch translations of the man # Dutch translations of the man
data.append((wpath.mandir + 'nl/man8/', ['man/nl/wicd.8' ])) 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/',
data.append((wpath.mandir + 'nl/man5/', ['man/nl/wicd-wired-settings.conf.5'])) ['man/nl/wicd-manager-settings.conf.5']))
data.append((wpath.mandir + 'nl/man5/', ['man/nl/wicd-wireless-settings.conf.5'])) data.append((wpath.mandir + 'nl/man5/',
data.append((wpath.mandir + 'nl/man1/', ['man/nl/wicd-client.1'])) ['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: if not wpath.no_install_acpi:
data.append((wpath.resume, ['other/80-wicd-connect.sh'])) data.append((wpath.resume, ['other/80-wicd-connect.sh']))
data.append((wpath.suspend, ['other/50-wicd-suspend.sh'])) data.append((wpath.suspend, ['other/50-wicd-suspend.sh']))
@@ -543,11 +585,13 @@ class install(_install):
language = language.replace('translations/', '') language = language.replace('translations/', '')
print(language, end=' ') print(language, end=' ')
data.append((wpath.translations + language + '/LC_MESSAGES/', data.append((wpath.translations + language + '/LC_MESSAGES/',
['translations/' + language + '/LC_MESSAGES/wicd.mo'])) ['translations/' + language +
'/LC_MESSAGES/wicd.mo']))
print() print()
_install.run(self) _install.run(self)
class test(Command): class test(Command):
description = "run Wicd's unit tests" description = "run Wicd's unit tests"
@@ -565,6 +609,7 @@ class test(Command):
print('running tests') print('running tests')
tests.run_tests() tests.run_tests()
class update_message_catalog(Command): class update_message_catalog(Command):
description = "update wicd.pot with new strings" 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('pybabel extract . -o po/wicd.pot --sort-output')
os.system('xgettext -L glade data/wicd.ui -j -o po/wicd.pot') os.system('xgettext -L glade data/wicd.ui -j -o po/wicd.pot')
class update_translations(Command): class update_translations(Command):
description = "update po-files with new strings from wicd.pot" description = "update po-files with new strings from wicd.pot"
@@ -594,7 +640,9 @@ class update_translations(Command):
def run(self): def run(self):
for pofile in glob('po/*.po'): for pofile in glob('po/*.po'):
lang = pofile.replace('po/', '').replace('.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): class compile_translations(Command):
description = 'compile po-files to binary mo' description = 'compile po-files to binary mo'
@@ -628,36 +676,44 @@ class compile_translations(Command):
lang = pofile.replace('po/', '').replace('.po', '') lang = pofile.replace('po/', '').replace('.po', '')
compile_po = False compile_po = False
try: try:
msgfmt = subprocess.Popen(['msgfmt', '--statistics', pofile, msgfmt = subprocess.Popen(['msgfmt', '--statistics',
'-o', '/dev/null'], stderr=subprocess.PIPE) pofile, '-o', '/dev/null'],
returncode = msgfmt.wait() # let it finish, and get the exit code stderr=subprocess.PIPE)
# let it finish, and get the exit code
returncode = msgfmt.wait()
output = msgfmt.stderr.readline().strip().decode('utf-8') output = msgfmt.stderr.readline().strip().decode('utf-8')
if len(output) == 0 or returncode != 0: if len(output) == 0 or returncode != 0:
print(len(output), returncode) print(len(output), returncode)
raise ValueError raise ValueError
else: 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: if m:
done, fuzzy, missing = m.groups() done, fuzzy, missing = m.groups()
fuzzy = int(fuzzy) if fuzzy else 0 fuzzy = int(fuzzy) if fuzzy else 0
missing = int(missing) if missing 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: if completeness >= self.threshold:
compile_po = True compile_po = True
else: else:
print('Disabled %s (%s%% < %s%%).' % \ print('Disabled %s (%s%% < %s%%).' %
(lang, completeness*100, self.threshold*100)) (lang, completeness*100,
self.threshold*100))
continue continue
except (OSError, ValueError): except (OSError, ValueError):
print('ARGH') print('ARGH')
if compile_po: if compile_po:
os.makedirs('translations/' + lang + '/LC_MESSAGES/') 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 os.environ['LANG'] = oldlang
class uninstall(Command): class uninstall(Command):
description = "remove Wicd using uninstall.sh and install.log" description = "remove Wicd using uninstall.sh and install.log"
@@ -672,38 +728,35 @@ class uninstall(Command):
def run(self): def run(self):
os.system("./uninstall.sh") 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( py_modules = ['wicd.networking', 'wicd.misc', 'wicd.wnettools', 'wicd.wpath',
cmdclass = { 'wicd.dbusmanager', 'wicd.logfile', 'wicd.backend',
'build' : build, 'wicd.configmanager', 'wicd.translations']
'configure' : configure,
'install' : install, setup(cmdclass={'build': build,
'uninstall' : uninstall, 'configure': configure,
'test' : test, 'install': install,
'clear_generated' : clear_generated, 'uninstall': uninstall,
'update_message_catalog' : update_message_catalog, 'test': test,
'update_translations' : update_translations, 'clear_generated': clear_generated,
'compile_translations' : compile_translations, 'update_message_catalog': update_message_catalog,
}, 'update_translations': update_translations,
name = "wicd", 'compile_translations': compile_translations},
version = VERSION_NUM, name="wicd",
description = "A wireless and wired network manager", version=VERSION_NUM,
long_description = """A complete network connection manager description="A wireless and wired network manager",
Wicd supports wired and wireless networks, and capable of long_description="A complete network connection manager Wicd supports "
creating and tracking profiles for both. It has a "wired and wireless networks, and capable of creating and tracking "
template-based wireless encryption system, which allows the user "profiles for both. It has a template-based wireless encryption system, "
to easily add encryption methods used. It ships with some common "which allows the user to easily add encryption methods used. It ships "
encryption types, such as WPA and WEP. Wicd will automatically "with some common encryption types, such as WPA and WEP. Wicd will "
connect at startup to any preferred network within range. "automatically connect at startup to any preferred network within "
""", "range.",
author = "Tom Van Braeckel, Adam Blackburn, Dan O'Reilly, Andrew Psaltis, David Paleino", author="Tom Van Braeckel, Adam Blackburn, Dan O'Reilly, Andrew Psaltis, "
author_email = "tomvanbraeckel@gmail.com, compwiz18@gmail.com, oreilldf@gmail.com, ampsaltis@gmail.com, d.paleino@gmail.com", "David Paleino",
url = "https://launchpad.net/wicd", author_email="tomvanbraeckel@gmail.com, compwiz18@gmail.com, "
license = "http://www.gnu.org/licenses/old-licenses/gpl-2.0.html", "oreilldf@gmail.com, ampsaltis@gmail.com, d.paleino@gmail.com",
py_modules = py_modules, url="https://launchpad.net/wicd",
data_files = data, license="http://www.gnu.org/licenses/old-licenses/gpl-2.0.html",
) py_modules=py_modules,
data_files=data)

View File

@@ -4,6 +4,7 @@
import unittest import unittest
from wicd import misc from wicd import misc
class TestMisc(unittest.TestCase): class TestMisc(unittest.TestCase):
def test_misc_run(self): def test_misc_run(self):
output = misc.Run(['echo', 'hi']).strip() output = misc.Run(['echo', 'hi']).strip()
@@ -25,10 +26,12 @@ class TestMisc(unittest.TestCase):
self.assertTrue(misc.IsValidIP('::1')) self.assertTrue(misc.IsValidIP('::1'))
def test_valid_ip_6(self): 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): 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): def test_invalid_ip_1(self):
self.assertFalse(misc.IsValidIP('-10.0.-1.-1')) self.assertFalse(misc.IsValidIP('-10.0.-1.-1'))
@@ -46,10 +49,12 @@ class TestMisc(unittest.TestCase):
self.assertFalse(misc.IsValidIP('1:')) self.assertFalse(misc.IsValidIP('1:'))
def test_invalid_ip_6(self): 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): 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): def test_run_valid_regex(self):
import re import re
@@ -72,7 +77,7 @@ class TestMisc(unittest.TestCase):
def test_to_boolean_true(self): def test_to_boolean_true(self):
self.assertTrue(misc.to_bool('True')) 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')) self.assertTrue(misc.to_bool('1'))
def test_noneify_1(self): def test_noneify_1(self):
@@ -137,7 +142,8 @@ class TestMisc(unittest.TestCase):
self.assertEqual(misc.to_unicode('abcdef'), 'abcdef') self.assertEqual(misc.to_unicode('abcdef'), 'abcdef')
def test_to_unicode_4(self): 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): def test_to_unicode_5(self):
self.assertEqual(misc.to_unicode("berkåk"), "berkåk") self.assertEqual(misc.to_unicode("berkåk"), "berkåk")
@@ -163,13 +169,15 @@ class TestMisc(unittest.TestCase):
def test_string_to_none_4(self): def test_string_to_none_4(self):
self.assertEqual(misc.stringToNone('abcdef'), 'abcdef') self.assertEqual(misc.stringToNone('abcdef'), 'abcdef')
def suite(): def suite():
suite = unittest.TestSuite() suite = unittest.TestSuite()
tests = [] tests = []
[ tests.append(test) for test in dir(TestMisc) if test.startswith('test') ] [tests.append(test) for test in dir(TestMisc) if test.startswith('test')]
for test in tests: for test in tests:
suite.addTest(TestMisc(test)) suite.addTest(TestMisc(test))
return suite return suite
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()

View File

@@ -2,6 +2,7 @@ import unittest
from unittest import mock from unittest import mock
from wicd import wnettools from wicd import wnettools
class TestWnettools(unittest.TestCase): class TestWnettools(unittest.TestCase):
def setUp(self): def setUp(self):
self.interface = wnettools.BaseInterface('eth0') self.interface = wnettools.BaseInterface('eth0')
@@ -9,7 +10,7 @@ class TestWnettools(unittest.TestCase):
def test_find_wireless_interface(self): def test_find_wireless_interface(self):
interfaces = wnettools.GetWirelessInterfaces() interfaces = wnettools.GetWirelessInterfaces()
# wlan0 may change depending on your system # wlan0 may change depending on your system
#self.assertTrue('wlan0' in interfaces) # self.assertTrue('wlan0' in interfaces)
self.assertTrue(type(interfaces) == list) self.assertTrue(type(interfaces) == list)
@mock.patch('wicd.wnettools.os') @mock.patch('wicd.wnettools.os')
@@ -41,7 +42,8 @@ class TestWnettools(unittest.TestCase):
self.assertFalse(self.interface.verbose) self.assertFalse(self.interface.verbose)
def test_interface_name_sanitation(self): def test_interface_name_sanitation(self):
interface = wnettools.BaseInterface('blahblah; uptime > /tmp/blah | cat') interface = wnettools.BaseInterface('blahblah; uptime > /tmp/blah | '
'cat')
self.assertEqual(interface.iface, 'blahblahuptimetmpblahcat') self.assertEqual(interface.iface, 'blahblahuptimetmpblahcat')
def test_freq_translation_low(self): def test_freq_translation_low(self):
@@ -57,16 +59,21 @@ class TestWnettools(unittest.TestCase):
def test_generate_psk(self): def test_generate_psk(self):
interface = wnettools.BaseWirelessInterface('wlan0') interface = wnettools.BaseWirelessInterface('wlan0')
if 'wlan0' in wnettools.GetWirelessInterfaces(): if 'wlan0' in wnettools.GetWirelessInterfaces():
psk = interface.GeneratePSK({'essid' : 'Network 1', 'key' : 'arandompassphrase'}) psk = interface.GeneratePSK({'essid': 'Network 1',
self.assertEqual(psk, 'd70463014514f4b4ebb8e3aebbdec13f4437ac3a9af084b3433f3710e658a7be') 'key': 'arandompassphrase'})
self.assertEqual(psk, 'd70463014514f4b4ebb8e3aebbdec13f4437ac3a9a'
'f084b3433f3710e658a7be')
def suite(): def suite():
suite = unittest.TestSuite() suite = unittest.TestSuite()
tests = [] tests = []
[ tests.append(test) for test in dir(TestWnettools) if test.startswith('test') ] [tests.append(test) for test in dir(TestWnettools)
if test.startswith('test')]
for test in tests: for test in tests:
suite.addTest(TestWnettools(test)) suite.addTest(TestWnettools(test))
return suite return suite
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()

View File

@@ -1 +1 @@
""" WICD core module. """ """WICD core module."""

View File

@@ -1,6 +1,6 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
""" autoconnect -- Triggers an automatic connection attempt. """ """autoconnect -- Triggers an automatic connection attempt."""
# #
# Copyright (C) 2007 - 2009 Adam Blackburn # Copyright (C) 2007 - 2009 Adam Blackburn
@@ -18,19 +18,18 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
import sys
from wicd import dbusmanager import time
import dbus import dbus
import time
import sys
if getattr(dbus, 'version', (0, 0, 0)) < (0, 80, 0): if getattr(dbus, 'version', (0, 0, 0)) < (0, 80, 0):
import dbus.glib import dbus.glib
else: else:
from dbus.mainloop.glib import DBusGMainLoop from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True) DBusGMainLoop(set_as_default=True)
from wicd import dbusmanager
try: try:
dbusmanager.connect_to_dbus() dbusmanager.connect_to_dbus()
daemon = dbusmanager.get_interface('daemon') daemon = dbusmanager.get_interface('daemon')
@@ -40,14 +39,18 @@ except Exception as e:
print('Could not connect to daemon.', file=sys.stderr) print('Could not connect to daemon.', file=sys.stderr)
sys.exit(1) sys.exit(1)
def handler(*args): def handler(*args):
""" No-op handler. """ """No-op handler."""
pass pass
def error_handler(*args): def error_handler(*args):
""" Error handler. """ """Error handler."""
print('Async error autoconnecting.', file=sys.stderr) print('Async error autoconnecting.', file=sys.stderr)
sys.exit(3) sys.exit(3)
if __name__ == '__main__': if __name__ == '__main__':
try: try:
time.sleep(2) time.sleep(2)

View File

@@ -1,6 +1,6 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
""" Backend manager for wicd. """Backend manager for wicd.
Manages and loads the pluggable backends for wicd. Manages and loads the pluggable backends for wicd.
@@ -29,34 +29,35 @@ import os
import wicd.wpath as wpath import wicd.wpath as wpath
def fail(backend_name, reason): 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))) print(("Failed to load backend %s: %s" % (backend_name, reason)))
return True return True
class BackendManager(object): class BackendManager(object):
""" Manages, validates, and loads wicd backends. """ """Manages, validates, and loads wicd backends."""
def __init__(self): def __init__(self):
""" Initialize the backend manager. """ """Initialize the backend manager."""
self.backend_dir = wpath.backends self.backend_dir = wpath.backends
self.__loaded_backend = None self.__loaded_backend = None
def _valid_backend_file(self, be_file): def _valid_backend_file(self, be_file):
""" Make sure the backend file is valid. """ """Make sure the backend file is valid."""
return (os.path.exists(be_file) and return (os.path.exists(be_file) and
os.path.basename(be_file).startswith("be-") and os.path.basename(be_file).startswith("be-") and
be_file.endswith(".py")) be_file.endswith(".py"))
def get_current_backend(self): def get_current_backend(self):
""" Returns the name of the loaded backend. """ """Returns the name of the loaded backend."""
if self.__loaded_backend: if self.__loaded_backend:
return self.__loaded_backend.NAME return self.__loaded_backend.NAME
else: else:
return None return None
def get_available_backends(self): 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 = [] be_list = []
for f in os.listdir(self.backend_dir): for f in os.listdir(self.backend_dir):
if self._valid_backend_file(os.path.join(self.backend_dir, f)): if self._valid_backend_file(os.path.join(self.backend_dir, f)):
@@ -64,14 +65,14 @@ class BackendManager(object):
return be_list or [""] return be_list or [""]
def get_update_interval(self): 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: if self.__loaded_backend:
return self.__loaded_backend.UPDATE_INTERVAL return self.__loaded_backend.UPDATE_INTERVAL
else: else:
return None return None
def get_backend_description(self, backend_name): 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) backend = self._load_backend(backend_name)
if backend and backend.DESCRIPTION: if backend and backend.DESCRIPTION:
return backend.DESCRIPTION return backend.DESCRIPTION
@@ -79,7 +80,7 @@ class BackendManager(object):
return "No backend data available" return "No backend data available"
def _load_backend(self, backend_name): 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)) print(('trying to load backend %s' % backend_name))
backend_path = os.path.join(self.backend_dir, backend_path = os.path.join(self.backend_dir,
'be-' + backend_name + '.py') 'be-' + backend_name + '.py')
@@ -92,7 +93,7 @@ class BackendManager(object):
return None return None
def _validate_backend(self, backend, backend_name): def _validate_backend(self, backend, backend_name):
""" Ensures that a backend module is valid. """ """Ensures that a backend module is valid."""
failed = False failed = False
if not backend.NAME: if not backend.NAME:
failed = fail(backend_name, 'Missing NAME attribute.') failed = fail(backend_name, 'Missing NAME attribute.')
@@ -107,7 +108,7 @@ class BackendManager(object):
return failed return failed
def load_backend(self, backend_name): 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 Given a backend name be-foo, attempt to load a python module
in the backends directory called be-foo.py. The module must in the backends directory called be-foo.py. The module must

View File

@@ -1 +1 @@
""" Backends module. """ """Backends module."""

View File

@@ -29,9 +29,15 @@ class WirelessInterface() -- Control a wireless network interface.
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from wicd.wnettools import GetDefaultGateway, GetWiredInterfaces, \ from wicd.wnettools import BaseInterface
GetWirelessInterfaces, IsValidWpaSuppDriver, BaseWirelessInterface, \ from wicd.wnettools import BaseWiredInterface
BaseWiredInterface, BaseInterface, GetWpaSupplicantDrivers 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" NAME = "external"
UPDATE_INTERVAL = 5 UPDATE_INTERVAL = 5
@@ -46,14 +52,14 @@ more stable for some set ups.
def NeedsExternalCalls(*args, **kargs): def NeedsExternalCalls(*args, **kargs):
""" Return True, since this backend uses iwconfig/ifconfig. """ """Return True, since this backend uses iwconfig/ifconfig."""
return True return True
class Interface(BaseInterface): class Interface(BaseInterface):
""" Control a network interface. """ """Control a network interface."""
def __init__(self, iface, verbose=False): def __init__(self, iface, verbose=False):
""" Initialize the object. """Initialize the object.
Keyword arguments: Keyword arguments:
iface -- the name of the interface iface -- the name of the interface
@@ -65,9 +71,9 @@ class Interface(BaseInterface):
class WiredInterface(Interface, BaseWiredInterface): class WiredInterface(Interface, BaseWiredInterface):
""" Control a wired network interface. """ """Control a wired network interface."""
def __init__(self, iface, verbose=False): def __init__(self, iface, verbose=False):
""" Initialise the wired network interface class. """Initialise the wired network interface class.
Keyword arguments: Keyword arguments:
iface -- name of the interface iface -- name of the interface
@@ -79,9 +85,9 @@ class WiredInterface(Interface, BaseWiredInterface):
class WirelessInterface(Interface, BaseWirelessInterface): class WirelessInterface(Interface, BaseWirelessInterface):
""" Control a wireless network interface. """ """Control a wireless network interface."""
def __init__(self, iface, verbose=False, wpa_driver='wext'): def __init__(self, iface, verbose=False, wpa_driver='wext'):
""" Initialise the wireless network interface class. """Initialise the wireless network interface class.
Keyword arguments: Keyword arguments:
iface -- name of the interface iface -- name of the interface

View File

@@ -1,7 +1,7 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# -*- coding: utf-8 -*- # -*- 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 This module implements functions to control and obtain information from
network interfaces. It utilizes ioctl calls and python modules to 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 <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
import array
import fcntl
import os
import socket
import struct
import time
from wicd import misc from wicd import misc
from wicd import wpath from wicd import wpath
from wicd.wnettools import GetDefaultGateway, GetWiredInterfaces, \ from wicd.wnettools import BaseInterface
GetWirelessInterfaces, IsValidWpaSuppDriver, BaseWirelessInterface, \ from wicd.wnettools import BaseWiredInterface
BaseWiredInterface, BaseInterface, GetWpaSupplicantDrivers, wep_pattern, \ from wicd.wnettools import BaseWirelessInterface
signaldbm_pattern, neediface 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: try:
import iwscan import iwscan
IWSCAN_AVAIL = True IWSCAN_AVAIL = True
except ImportError: 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 IWSCAN_AVAIL = False
try: try:
import wpactrl import wpactrl
@@ -50,14 +65,6 @@ except ImportError:
print("WARNING: python-wpactrl not found, falling back to using wpa_cli.") print("WARNING: python-wpactrl not found, falling back to using wpa_cli.")
WPACTRL_AVAIL = False WPACTRL_AVAIL = False
import re
import os
import time
import socket
import fcntl
import struct
import array
NAME = "ioctl" NAME = "ioctl"
UPDATE_INTERVAL = 4 UPDATE_INTERVAL = 4
@@ -90,7 +97,7 @@ SIOCGIFFLAGS = 0x8913
def get_iw_ioctl_result(iface, call): 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: Keyword arguments:
call -- The ioctl call to make call -- The ioctl call to make
@@ -112,15 +119,16 @@ def get_iw_ioctl_result(iface, call):
return None return None
return buff.tostring() return buff.tostring()
def NeedsExternalCalls(*args, **kargs): 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 return False
class Interface(BaseInterface): class Interface(BaseInterface):
""" Control a network interface. """ """Control a network interface."""
def __init__(self, iface, verbose=False): def __init__(self, iface, verbose=False):
""" Initialise the object. """Initialise the object.
Keyword arguments: Keyword arguments:
iface -- the name of the interface iface -- the name of the interface
@@ -132,13 +140,13 @@ class Interface(BaseInterface):
self.Check() self.Check()
def CheckWirelessTools(self): def CheckWirelessTools(self):
""" Check for the existence needed wireless tools """ """Check for the existence needed wireless tools"""
if not WPACTRL_AVAIL: if not WPACTRL_AVAIL:
BaseInterface.CheckWirelessTools(self) BaseInterface.CheckWirelessTools(self)
@neediface("") @neediface("")
def GetIP(self, ifconfig=""): def GetIP(self, ifconfig=""):
""" Get the IP address of the interface. """Get the IP address of the interface.
Returns: Returns:
The IP address of the interface in dotted quad form. The IP address of the interface in dotted quad form.
@@ -156,7 +164,7 @@ class Interface(BaseInterface):
@neediface(False) @neediface(False)
def IsUp(self, ifconfig=None): def IsUp(self, ifconfig=None):
""" Determines if the interface is up. """Determines if the interface is up.
Returns: Returns:
True if the interface is up, False otherwise. True if the interface is up, False otherwise.
@@ -175,9 +183,9 @@ class Interface(BaseInterface):
class WiredInterface(Interface, BaseWiredInterface): class WiredInterface(Interface, BaseWiredInterface):
""" Control a wired network interface. """ """Control a wired network interface."""
def __init__(self, iface, verbose=False): def __init__(self, iface, verbose=False):
""" Initialise the wired network interface class. """Initialise the wired network interface class.
Keyword arguments: Keyword arguments:
iface -- name of the interface iface -- name of the interface
@@ -189,7 +197,7 @@ class WiredInterface(Interface, BaseWiredInterface):
@neediface(False) @neediface(False)
def GetPluggedIn(self): 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 The method will first attempt to use ethtool do determine
physical connection state. Should ethtool fail to run properly, 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]: if self.ethtool_cmd and self.link_detect in [misc.ETHTOOL, misc.AUTO]:
return self._eth_get_plugged_in() 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() return self._mii_get_plugged_in()
else: else:
print(('Error: No way of checking for a wired connection. Make' + print(('Error: No way of checking for a wired connection. Make' +
@@ -209,7 +218,7 @@ class WiredInterface(Interface, BaseWiredInterface):
return False return False
def _eth_get_plugged_in(self): def _eth_get_plugged_in(self):
""" Use ethtool to determine the physical connection state. """Use ethtool to determine the physical connection state.
Returns: Returns:
True if a link is detected, False otherwise. True if a link is detected, False otherwise.
@@ -231,7 +240,7 @@ class WiredInterface(Interface, BaseWiredInterface):
return bool(buff.tolist()[1]) return bool(buff.tolist()[1])
def _mii_get_plugged_in(self): 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: Returns:
True if a link is detected, False otherwise. True if a link is detected, False otherwise.
@@ -253,24 +262,23 @@ class WiredInterface(Interface, BaseWiredInterface):
class WirelessInterface(Interface, BaseWirelessInterface): class WirelessInterface(Interface, BaseWirelessInterface):
""" Control a wireless network interface. """ """Control a wireless network interface."""
def __init__(self, iface, verbose=False, wpa_driver='wext'): def __init__(self, iface, verbose=False, wpa_driver='wext'):
""" Initialise the wireless network interface class. """Initialise the wireless network interface class.
Keyword arguments: Keyword arguments:
iface -- name of the interface iface -- name of the interface
verbose -- print all commands verbose -- print all commands
""" """
BaseWirelessInterface.__init__(self, iface, verbose, BaseWirelessInterface.__init__(self, iface, verbose, wpa_driver)
wpa_driver)
Interface.__init__(self, iface, verbose) Interface.__init__(self, iface, verbose)
self.scan_iface = None self.scan_iface = None
self.CheckWirelessTools() self.CheckWirelessTools()
@neediface([]) @neediface([])
def GetNetworks(self, essid=None): 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, NOTE: the essid parameter is not used here,
it was added for the iwlist scan for hidden networks. it was added for the iwlist scan for hidden networks.
@@ -298,7 +306,7 @@ class WirelessInterface(Interface, BaseWirelessInterface):
return [_f for _f in [self._parse_ap(cell) for cell in results] if _f] return [_f for _f in [self._parse_ap(cell) for cell in results] if _f]
def _parse_ap(self, cell): def _parse_ap(self, cell):
""" Parse a single cell from the python-iwscan list. """ """Parse a single cell from the python-iwscan list."""
ap = {} ap = {}
try: try:
ap['essid'] = misc.to_unicode(cell['essid']) ap['essid'] = misc.to_unicode(cell['essid'])
@@ -306,7 +314,7 @@ class WirelessInterface(Interface, BaseWirelessInterface):
print('Unicode problem with the current network essid, ignoring!!') print('Unicode problem with the current network essid, ignoring!!')
return None return None
if ap['essid'] in [ "", '<hidden>']: if ap['essid'] in ["", '<hidden>']:
ap['essid'] = '<hidden>' ap['essid'] = '<hidden>'
ap['hidden'] = True ap['hidden'] = True
else: else:
@@ -344,13 +352,14 @@ class WirelessInterface(Interface, BaseWirelessInterface):
# quality displayed or it isn't found) # quality displayed or it isn't found)
if misc.RunRegex(signaldbm_pattern, cell["stats"]): if misc.RunRegex(signaldbm_pattern, cell["stats"]):
ap['strength'] = 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 # This is already set for ralink
elif self.wpa_driver != RALINK_DRIVER:
ap['strength'] = -1 ap['strength'] = -1
return ap return ap
def _connect_to_wpa_ctrl_iface(self): 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' ctrl_iface = '/var/run/wpa_supplicant'
socket_loc = os.path.join(ctrl_iface, self.iface) socket_loc = os.path.join(ctrl_iface, self.iface)
if os.path.exists(socket_loc): if os.path.exists(socket_loc):
@@ -360,12 +369,12 @@ class WirelessInterface(Interface, BaseWirelessInterface):
print(("Couldn't open ctrl_interface: %s" % e)) print(("Couldn't open ctrl_interface: %s" % e))
return None return None
else: else:
print(("Couldn't find a wpa_supplicant ctrl_interface for iface %s" \ print(f"Couldn't find a wpa_supplicant ctrl_interface for iface "
% self.iface)) f"{self.iface}")
return None return None
def ValidateAuthentication(self, auth_time): def ValidateAuthentication(self, auth_time):
""" Validate WPA authentication. """Validate WPA authentication.
Validate that the wpa_supplicant authentication Validate that the wpa_supplicant authentication
process was successful. process was successful.
@@ -384,7 +393,8 @@ class WirelessInterface(Interface, BaseWirelessInterface):
""" """
if not WPACTRL_AVAIL: if not WPACTRL_AVAIL:
# If we don't have python-wpactrl, use the slow version. # 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 # Right now there's no way to do this for ralink drivers
if self.wpa_driver == RALINK_DRIVER: if self.wpa_driver == RALINK_DRIVER:
@@ -401,16 +411,16 @@ class WirelessInterface(Interface, BaseWirelessInterface):
while (time.time() - auth_time) < MAX_TIME: while (time.time() - auth_time) < MAX_TIME:
try: try:
status = wpa.request("STATUS").split("\n") status = wpa.request("STATUS").split("\n")
except: except Exception:
print("wpa_supplicant status query failed.") print("wpa_supplicant status query failed.")
return False return False
if self.verbose: if self.verbose:
print(('wpa_supplicant ctrl_interface status query is %s' \ print(f'wpa_supplicant ctrl_interface status query is '
% str(status))) f'{status}')
try: 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: except ValueError:
return False return False
@@ -431,7 +441,7 @@ class WirelessInterface(Interface, BaseWirelessInterface):
@neediface(False) @neediface(False)
def StopWPA(self): def StopWPA(self):
""" Terminates wpa_supplicant using its ctrl interface. """ """Terminates wpa_supplicant using its ctrl interface."""
if not WPACTRL_AVAIL: if not WPACTRL_AVAIL:
return BaseWirelessInterface.StopWPA(self) return BaseWirelessInterface.StopWPA(self)
wpa = self._connect_to_wpa_ctrl_iface() wpa = self._connect_to_wpa_ctrl_iface()
@@ -440,7 +450,7 @@ class WirelessInterface(Interface, BaseWirelessInterface):
wpa.request("TERMINATE") wpa.request("TERMINATE")
def _AuthenticateRalinkLegacy(self, network): 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 This function handles Ralink legacy cards that cannot use
wpa_supplicant. wpa_supplicant.
@@ -449,14 +459,16 @@ class WirelessInterface(Interface, BaseWirelessInterface):
network -- dictionary containing network info network -- dictionary containing network info
""" """
if network.get('key') != None: if network.get('key') is None:
return
lines = self._GetRalinkInfo() lines = self._GetRalinkInfo()
for x in lines: for x in lines:
info = x.split() info = x.split()
if len(info) < 5: if len(info) < 5:
break break
if info[2] == network.get('essid'): if info[2] == network.get('essid'):
if info[5] == 'WEP' or (info[5] == 'OPEN' and \ if info[5] == 'WEP' or (info[5] == 'OPEN' and
info[4] == 'WEP'): info[4] == 'WEP'):
print('Setting up WEP') print('Setting up WEP')
cmd = ''.join(['iwconfig ', self.iface, ' key ', cmd = ''.join(['iwconfig ', self.iface, ' key ',
@@ -478,8 +490,8 @@ class WirelessInterface(Interface, BaseWirelessInterface):
auth_mode = 'WPA2PSK' auth_mode = 'WPA2PSK'
key_name = 'WPAPSK' key_name = 'WPAPSK'
else: else:
print(('Unknown AuthMode, can\'t complete ' + \ print("Unknown AuthMode, can\'t complete connection "
'connection process!')) "process!")
return return
cmd_list = [] cmd_list = []
@@ -500,7 +512,7 @@ class WirelessInterface(Interface, BaseWirelessInterface):
@neediface("") @neediface("")
def GetBSSID(self, iwconfig=None): 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] data = (self.iface + '\0' * 32)[:32]
try: try:
result = fcntl.ioctl(self.sock.fileno(), SIOCGIWAP, data)[16:] result = fcntl.ioctl(self.sock.fileno(), SIOCGIWAP, data)[16:]
@@ -513,7 +525,7 @@ class WirelessInterface(Interface, BaseWirelessInterface):
@neediface("") @neediface("")
def GetCurrentBitrate(self, iwconfig=None): 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] data = (self.iface + '\0' * 32)[:32]
fmt = "ihbb" fmt = "ihbb"
size = struct.calcsize(fmt) size = struct.calcsize(fmt)
@@ -526,19 +538,19 @@ class WirelessInterface(Interface, BaseWirelessInterface):
f, e, x, x = struct.unpack(fmt, result[:size]) f, e, x, x = struct.unpack(fmt, result[:size])
return "%s %s" % ((f / 1000000), 'Mb/s') return "%s %s" % ((f / 1000000), 'Mb/s')
#def GetOperationalMode(self, iwconfig=None): # def GetOperationalMode(self, iwconfig=None):
# """ Get the operational mode for the interface. """ # """ Get the operational mode for the interface."""
# TODO: implement me # TODO: implement me
# return '' # return ''
#def GetAvailableAuthMethods(self, iwlistauth=None): # def GetAvailableAuthMethods(self, iwlistauth=None):
# """ Get the authentication methods for the interface. """ # """ Get the authentication methods for the interface."""
# TODO: Implement me # TODO: Implement me
# return '' # return ''
@neediface(-1) @neediface(-1)
def GetSignalStrength(self, iwconfig=None): def GetSignalStrength(self, iwconfig=None):
""" Get the signal strength of the current network. """Get the signal strength of the current network.
Returns: Returns:
The signal strength. The signal strength.
@@ -555,7 +567,7 @@ class WirelessInterface(Interface, BaseWirelessInterface):
return None return None
def _get_max_strength(self): 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) buff = array.array('c', '\0' * 700)
addr, length = buff.buffer_info() addr, length = buff.buffer_info()
arg = struct.pack('Pi', addr, length) arg = struct.pack('Pi', addr, length)
@@ -576,7 +588,7 @@ class WirelessInterface(Interface, BaseWirelessInterface):
@neediface(-100) @neediface(-100)
def GetDBMStrength(self, iwconfig=None): def GetDBMStrength(self, iwconfig=None):
""" Get the dBm signal strength of the current network. """Get the dBm signal strength of the current network.
Returns: Returns:
The dBm signal strength. The dBm signal strength.
@@ -590,7 +602,7 @@ class WirelessInterface(Interface, BaseWirelessInterface):
@neediface("") @neediface("")
def GetCurrentNetwork(self, iwconfig=None): def GetCurrentNetwork(self, iwconfig=None):
""" Get the essid of the current network. """Get the essid of the current network.
Returns: Returns:
The current network essid. The current network essid.

View File

@@ -1,6 +1,6 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
""" configmanager -- Wicd configuration file manager """configmanager -- Wicd configuration file manager
Wrapper around ConfigParser for wicd, though it should be Wrapper around ConfigParser for wicd, though it should be
reusable for other purposes as well. reusable for other purposes as well.
@@ -25,17 +25,18 @@ reusable for other purposes as well.
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
import sys, os
from configparser import RawConfigParser, ParsingError
import codecs import codecs
import configparser
from wicd.misc import Noneify, to_unicode import os
import sys
from dbus import Int32 from dbus import Int32
from wicd.misc import Noneify, to_unicode
def sanitize_config_file(path): def sanitize_config_file(path):
""" Remove invalid lines from config file. """ """Remove invalid lines from config file."""
conf = open(path) conf = open(path)
newconf = '' newconf = ''
for line in conf: for line in conf:
@@ -46,10 +47,11 @@ def sanitize_config_file(path):
conf.write(newconf) conf.write(newconf)
conf.close() 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="`'`"): def __init__(self, path, debug=False, mark_whitespace="`'`"):
RawConfigParser.__init__(self) configparser.RawConfigParser.__init__(self)
self.config_file = path self.config_file = path
self.debug = debug self.debug = debug
self.mrk_ws = mark_whitespace self.mrk_ws = mark_whitespace
@@ -57,11 +59,11 @@ class ConfigManager(RawConfigParser):
sanitize_config_file(path) sanitize_config_file(path)
try: try:
self.read(path) self.read(path)
except ParsingError: except configparser.ParsingError:
self.write() self.write()
try: try:
self.read(path) self.read(path)
except ParsingError as p: except configparser.ParsingError as p:
print(("Could not start wicd: %s" % p.message)) print(("Could not start wicd: %s" % p.message))
sys.exit(1) sys.exit(1)
@@ -72,11 +74,11 @@ class ConfigManager(RawConfigParser):
return self.config_file return self.config_file
def get_config(self): def get_config(self):
""" Returns the path to the loaded config file. """ """Returns the path to the loaded config file."""
return self.config_file return self.config_file
def set_option(self, section, option, value, write=False): 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. Adds the option to write the config file change right away.
Also forces all the values being written to type str, and Also forces all the values being written to type str, and
@@ -89,18 +91,18 @@ class ConfigManager(RawConfigParser):
if isinstance(value, str): if isinstance(value, str):
value = to_unicode(value) value = to_unicode(value)
if value.startswith(' ') or value.endswith(' '): if value.startswith(' ') or value.endswith(' '):
value = "%(ws)s%(value)s%(ws)s" % {"value" : value, value = "%(ws)s%(value)s%(ws)s" % {"value": value,
"ws" : self.mrk_ws} "ws": self.mrk_ws}
RawConfigParser.set(self, section, str(option), value) configparser.RawConfigParser.set(self, section, str(option), value)
if write: if write:
self.write() self.write()
def set(self, *args, **kargs): def set(self, *args, **kargs):
""" Calls the set_option method. """ """Calls the set_option method."""
self.set_option(*args, **kargs) self.set_option(*args, **kargs)
def get_option(self, section, option, default="__None__"): def get_option(self, section, option, default="__None__"):
""" Wrapper around ConfigParser.get. """Wrapper around ConfigParser.get.
Automatically adds any missing sections, adds the ability Automatically adds any missing sections, adds the ability
to write a default value, and if one is provided prints if to write a default value, and if one is provided prints if
@@ -114,7 +116,7 @@ class ConfigManager(RawConfigParser):
return None return None
if self.has_option(section, option): if self.has_option(section, option):
ret = RawConfigParser.get(self, section, option) ret = configparser.RawConfigParser.get(self, section, option)
if (isinstance(ret, str) and ret.startswith(self.mrk_ws) if (isinstance(ret, str) and ret.startswith(self.mrk_ws)
and ret.endswith(self.mrk_ws)): and ret.endswith(self.mrk_ws)):
ret = ret[3:-3] ret = ret[3:-3]
@@ -122,18 +124,16 @@ class ConfigManager(RawConfigParser):
if default: if default:
if self.debug: if self.debug:
# mask out sensitive information # mask out sensitive information
if option in ['apsk', 'password', 'identity', \ if option in ['apsk', 'password', 'identity',
'private_key', 'private_key_passwd', \ 'private_key', 'private_key_passwd',
'key', 'passphrase']: 'key', 'passphrase']:
print((''.join(['found ', option, \ print(f'found {option} in configuration *****')
' in configuration *****'])))
else: else:
print((''.join(['found ', option, ' in configuration ', print(f'found {option} in configuration {ret}')
str(ret)])))
else: # Use the default, unless no default was provided else: # Use the default, unless no default was provided
if default != "__None__": if default != "__None__":
print(('did not find %s in configuration, setting default %s' \ print(f'did not find {option} in configuration, setting '
% (option, str(default)))) f'default {default}')
self.set(section, option, str(default), write=True) self.set(section, option, str(default), write=True)
ret = default ret = default
else: else:
@@ -154,50 +154,51 @@ class ConfigManager(RawConfigParser):
return to_unicode(ret) return to_unicode(ret)
def get(self, *args, **kargs): def get(self, *args, **kargs):
""" Calls the get_option method """ """Calls the get_option method"""
return self.get_option(*args, **kargs) return self.get_option(*args, **kargs)
def _write_one(self): def _write_one(self):
""" Writes the loaded config file to disk. """ """Writes the loaded config file to disk."""
for section in self.sections(): for section in self.sections():
if not section: if not section:
self.remove_section(section) self.remove_section(section)
configfile = open(self.config_file, 'w') configfile = open(self.config_file, 'w')
RawConfigParser.write(self, configfile) configparser.RawConfigParser.write(self, configfile)
configfile.close() configfile.close()
def remove_section(self, section): 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 This method only calls the ConfigParser.remove_section() method
if the section actually exists. if the section actually exists.
""" """
if self.has_section(section): if self.has_section(section):
RawConfigParser.remove_section(self, section) configparser.RawConfigParser.remove_section(self, section)
def reload(self): 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) self.read(self.config_file)
def read(self, path): 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 files in the directory obtained by adding '.d' to 'path'. The files
in the '.d' directory are read in normal sorted order and section in the '.d' directory are read in normal sorted order and section
entries in these files override entries in the main file. entries in these files override entries in the main file.
""" """
if os.path.exists(path): 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" path_d = path + ".d"
files = [] files = []
if os.path.exists(path_d): 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() files.sort()
for fname in files: for fname in files:
p = RawConfigParser() p = configparser.RawConfigParser()
p.readfp(codecs.open(fname, 'r', 'utf-8')) p.readfp(codecs.open(fname, 'r', 'utf-8'))
for section_name in p.sections(): for section_name in p.sections():
# New files override old, so remove first to avoid # New files override old, so remove first to avoid
@@ -209,9 +210,8 @@ class ConfigManager(RawConfigParser):
# Store the filename this section was read from. # Store the filename this section was read from.
self.set(section_name, '_filename_', fname) self.set(section_name, '_filename_', fname)
def _copy_section(self, name): 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 = ConfigManager("", self.debug, self.mrk_ws)
p.add_section(name) p.add_section(name)
for (iname, value) in self.items(name): for (iname, value) in self.items(name):
@@ -222,7 +222,7 @@ class ConfigManager(RawConfigParser):
return p return p
def write(self, fp=None): def write(self, fp=None):
""" Writes the loaded config file to disk. """ """Writes the loaded config file to disk."""
in_this_file = [] in_this_file = []
for sname in sorted(self.sections()): for sname in sorted(self.sections()):
fname = self.get_option(sname, '_filename_') fname = self.get_option(sname, '_filename_')
@@ -243,4 +243,3 @@ class ConfigManager(RawConfigParser):
p.set(sname, iname, value) p.set(sname, iname, value)
p.remove_option(sname, '_filename_') p.remove_option(sname, '_filename_')
p._write_one() p._write_one()

View File

@@ -1,6 +1,4 @@
#!/usr/bin/env python3 """The wicd DBus Manager.
""" The wicd DBus Manager.
A module for managing wicd's dbus interfaces. A module for managing wicd's dbus interfaces.
@@ -32,59 +30,65 @@ else:
DBUS_MANAGER = None DBUS_MANAGER = None
def get_dbus_ifaces(): def get_dbus_ifaces():
""" Return available DBus interfaces. """ """Return available DBus interfaces."""
return DBUS_MANAGER.get_dbus_ifaces() return DBUS_MANAGER.get_dbus_ifaces()
def get_interface(iface): def get_interface(iface):
""" Return specified interface. """ """Return specified interface."""
return DBUS_MANAGER.get_interface(iface) return DBUS_MANAGER.get_interface(iface)
def get_bus(): def get_bus():
""" Return the loaded System Bus. """ """Return the loaded System Bus."""
return DBUS_MANAGER.get_bus() return DBUS_MANAGER.get_bus()
def set_mainloop(loop): def set_mainloop(loop):
""" Set DBus main loop. """ """Set DBus main loop."""
return DBUS_MANAGER.set_mainloop(loop) return DBUS_MANAGER.set_mainloop(loop)
def connect_to_dbus(): def connect_to_dbus():
""" Connect to DBus. """ """Connect to DBus."""
return DBUS_MANAGER.connect_to_dbus() return DBUS_MANAGER.connect_to_dbus()
def threads_init(): def threads_init():
""" Init GLib threads. """ """Init GLib threads."""
dbus.mainloop.glib.threads_init() dbus.mainloop.glib.threads_init()
class DBusManager(object): class DBusManager(object):
""" Manages the DBus objects used by wicd. """ """Manages the DBus objects used by wicd."""
def __init__(self): def __init__(self):
self._bus = dbus.SystemBus() self._bus = dbus.SystemBus()
self._dbus_ifaces = {} self._dbus_ifaces = {}
def get_dbus_ifaces(self): def get_dbus_ifaces(self):
""" Returns a dict of dbus interfaces. """ """Returns a dict of dbus interfaces."""
if not self._dbus_ifaces: if not self._dbus_ifaces:
connect_to_dbus() connect_to_dbus()
return self._dbus_ifaces return self._dbus_ifaces
def get_interface(self, iface): def get_interface(self, iface):
""" Returns a DBus Interface. """ """Returns a DBus Interface."""
if not self._dbus_ifaces: if not self._dbus_ifaces:
connect_to_dbus() connect_to_dbus()
return self._dbus_ifaces[iface] return self._dbus_ifaces[iface]
def get_bus(self): def get_bus(self):
""" Returns the loaded SystemBus. """ """Returns the loaded SystemBus."""
return self._bus return self._bus
def set_mainloop(self, loop): def set_mainloop(self, loop):
""" Set DBus main loop. """ """Set DBus main loop."""
dbus.set_default_main_loop(loop) dbus.set_default_main_loop(loop)
def connect_to_dbus(self): 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') proxy_obj = self._bus.get_object("org.wicd.daemon", '/org/wicd/daemon')
daemon = dbus.Interface(proxy_obj, 'org.wicd.daemon') daemon = dbus.Interface(proxy_obj, 'org.wicd.daemon')
@@ -96,7 +100,8 @@ class DBusManager(object):
'/org/wicd/daemon/wired') '/org/wicd/daemon/wired')
wired = dbus.Interface(proxy_obj, 'org.wicd.daemon.wired') wired = dbus.Interface(proxy_obj, 'org.wicd.daemon.wired')
self._dbus_ifaces = {"daemon" : daemon, "wireless" : wireless, self._dbus_ifaces = {"daemon": daemon, "wireless": wireless,
"wired" : wired} "wired": wired}
DBUS_MANAGER = DBusManager() DBUS_MANAGER = DBusManager()

View File

@@ -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 <keith@kdart.com> # Copyright (C) 1999-2006 Keith Dart <keith@kdart.com>
# Copyright (C) 2008-2009 Dan O'Reilly <oreilldf@gmail.com> # Copyright (C) 2008-2009 Dan O'Reilly <oreilldf@gmail.com>
@@ -14,22 +21,17 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details. # 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 io
import os
import sys
import time
class SizeError(IOError): class SizeError(IOError):
""" Custom error class. """ """Custom error class."""
pass pass
class LogFile(io.FileIO): class LogFile(io.FileIO):
"""LogFile(name, [mode="w"], [maxsize=360000]) """LogFile(name, [mode="w"], [maxsize=360000])
@@ -49,19 +51,22 @@ class LogFile(io.FileIO):
def write(self, data): def write(self, data):
self.written += len(data) self.written += len(data)
# TODO(gryf): revisit need for encode/decode madness
data = data.encode('utf-8') data = data.encode('utf-8')
if len(data) <= 0: if len(data) <= 0:
return return
if self.eol: 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 self.eol = False
if data[-1] == '\n': if data[-1] == '\n':
self.eol = True self.eol = True
data = data[:-1] data = data[:-1]
super(LogFile, self).write(data.replace( super(LogFile, self).write(data.replace(b'\n', b'\n' + self.get_time()
b'\n', b'\n' + self.get_time().encode("utf-8") + b' :: ')) .encode("utf-8") + b' :: '))
if self.eol: if self.eol:
super(LogFile, self).write('\n') super(LogFile, self).write('\n')
@@ -70,7 +75,7 @@ class LogFile(io.FileIO):
raise SizeError raise SizeError
def get_time(self): 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 The format of the returned string is yyyy/mm/dd HH:MM:SS
@@ -82,7 +87,7 @@ class LogFile(io.FileIO):
str(x[4]).rjust(2, '0'), ':', str(x[5]).rjust(2, '0')]) str(x[4]).rjust(2, '0'), ':', str(x[5]).rjust(2, '0')])
def rotate(self): def rotate(self):
""" Rotate logfile. """ """Rotate logfile."""
return rotate(self) return rotate(self)
def note(self, text): def note(self, text):
@@ -112,25 +117,25 @@ class ManagedLog(object):
self._lf.maxsize, self.maxsave) self._lf.maxsize, self.maxsave)
def write(self, data): def write(self, data):
""" Write logfile. """ """Write logfile."""
try: try:
self._lf.write(data) self._lf.write(data)
except SizeError: except SizeError:
self._lf = rotate(self._lf, self.maxsave) self._lf = rotate(self._lf, self.maxsave)
def note(self, data): def note(self, data):
""" Write a note to the logfile. """ """Write a note to the logfile."""
try: try:
self._lf.note(data) self._lf.note(data)
except SizeError: except SizeError:
self._lf = rotate(self._lf, self.maxsave) self._lf = rotate(self._lf, self.maxsave)
def written(self): def written(self):
""" Return whether the logfile was written. """ """Return whether the logfile was written."""
return self._lf.written return self._lf.written
def rotate(self): def rotate(self):
""" Rotate logfile. """ """Rotate logfile."""
self._lf = rotate(self._lf, self.maxsave) self._lf = rotate(self._lf, self.maxsave)
# auto-delegate remaining methods (but you should not read or seek an open # 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 # useful for logged stdout for daemon processes
class ManagedStdio(ManagedLog): class ManagedStdio(ManagedLog):
""" Manage stdout/stderr. """ """Manage stdout/stderr."""
def write(self, data): def write(self, data):
""" Write logfile to disk. """ """Write logfile to disk."""
try: try:
self._lf.write(data) self._lf.write(data)
except SizeError: except SizeError:
@@ -157,7 +162,7 @@ class ManagedStdio(ManagedLog):
def rotate(fileobj, maxsave=9): def rotate(fileobj, maxsave=9):
""" Rotate fileobj. """ """Rotate fileobj."""
name = fileobj.name name = fileobj.name
mode = fileobj.mode mode = fileobj.mode
maxsize = fileobj.maxsize maxsize = fileobj.maxsize
@@ -168,7 +173,7 @@ def rotate(fileobj, maxsave=9):
# assumes basename logfile is closed. # assumes basename logfile is closed.
def shiftlogs(basename, maxsave): def shiftlogs(basename, maxsave):
""" Shift logfiles. """ """Shift logfiles."""
topname = "%s.%d" % (basename, maxsave) topname = "%s.%d" % (basename, maxsave)
if os.path.isfile(topname): if os.path.isfile(topname):
os.unlink(topname) os.unlink(topname)
@@ -187,11 +192,12 @@ def shiftlogs(basename, maxsave):
def open(name, maxsize=360000, maxsave=9): def open(name, maxsize=360000, maxsave=9):
""" Open logfile. """ """Open logfile."""
return ManagedLog(name, maxsize, maxsave) return ManagedLog(name, maxsize, maxsave)
def writelog(logobj, data): def writelog(logobj, data):
""" Write logfile. """ """Write logfile."""
try: try:
logobj.write(data) logobj.write(data)
except SizeError: except SizeError:

View File

@@ -1,4 +1,4 @@
""" misc - miscellaneous functions for wicd """misc - miscellaneous functions for wicd
This module contains a large variety of utility functions used This module contains a large variety of utility functions used
throughout wicd. throughout wicd.
@@ -22,23 +22,24 @@ throughout wicd.
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
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 from itertools import repeat, chain
import locale
import os
import re
from pipes import quote from pipes import quote
import socket 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 _ from wicd.translations import _
# wicd imports # wicd imports
from . import wpath from wicd import wpath
# Connection state constants # Connection state constants
NOT_CONNECTED = 0 NOT_CONNECTED = 0
@@ -46,13 +47,11 @@ CONNECTING = 1
WIRELESS = 2 WIRELESS = 2
WIRED = 3 WIRED = 3
SUSPENDED = 4 SUSPENDED = 4
_const_status_dict = { _const_status_dict = {NOT_CONNECTED: _('Not connected'),
NOT_CONNECTED: _('Not connected'),
CONNECTING: _('Connection in progress'), CONNECTING: _('Connection in progress'),
WIRELESS: _('Connected to a wireless network'), WIRELESS: _('Connected to a wireless network'),
WIRED: _('Connected to a wired network'), WIRED: _('Connected to a wired network'),
SUSPENDED: _('Connection suspended'), SUSPENDED: _('Connection suspended')}
}
# Automatic app selection constant # Automatic app selection constant
AUTO = 0 AUTO = 0
@@ -75,16 +74,14 @@ ROUTE = 2
GKSUDO = 1 GKSUDO = 1
KDESU = 2 KDESU = 2
KTSUSS = 3 KTSUSS = 3
_sudo_dict = { _sudo_dict = {AUTO: "",
AUTO : "", GKSUDO: "gksudo",
GKSUDO : "gksudo", KDESU: "kdesu",
KDESU : "kdesu", KTSUSS: "ktsuss"}
KTSUSS: "ktsuss",
}
_status_dict = { _status_dict = {
'aborted': _('Connection Cancelled'), 'aborted': _('Connection Cancelled'),
'association_failed': _('Connection failed: Could not contact the ' + \ 'association_failed': _('Connection failed: Could not contact the '
'wireless access point.'), 'wireless access point.'),
'bad_pass': _('Connection Failed: Bad password'), 'bad_pass': _('Connection Failed: Bad password'),
'configuring_interface': _('Configuring wireless interface...'), 'configuring_interface': _('Configuring wireless interface...'),
@@ -107,14 +104,15 @@ _status_dict = {
'verifying_association': _('Verifying access point association...'), 'verifying_association': _('Verifying access point association...'),
} }
class WicdError(Exception): class WicdError(Exception):
""" Custom Exception type. """ """Custom Exception type."""
pass pass
def Run(cmd, include_stderr=False, return_pipe=False, def Run(cmd, include_stderr=False, return_pipe=False,
return_obj=False, return_retcode=True): return_obj=False, return_retcode=True):
""" Run a command. """Run a command.
Runs the given command, returning either the output Runs the given command, returning either the output
of the program, or a pipe to read output from. of the program, or a pipe to read output from.
@@ -165,8 +163,9 @@ def Run(cmd, include_stderr=False, return_pipe=False,
else: else:
return f.communicate()[0].decode() return f.communicate()[0].decode()
def LaunchAndWait(cmd): 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. cmd : A list contained the program name and its arguments.
@@ -179,8 +178,9 @@ def LaunchAndWait(cmd):
p = Popen(cmd, shell=False, stdout=PIPE, stderr=STDOUT, stdin=None) p = Popen(cmd, shell=False, stdout=PIPE, stderr=STDOUT, stdin=None)
return p.wait() return p.wait()
def IsValidIP(ip): def IsValidIP(ip):
""" Make sure an entered IP is valid. """ """Make sure an entered IP is valid."""
if not ip: if not ip:
return False return False
@@ -189,6 +189,7 @@ def IsValidIP(ip):
return False return False
return True return True
def IsValidIPv4(ip): def IsValidIPv4(ip):
''' Make sure an entered IP is a valid IPv4. ''' ''' Make sure an entered IP is a valid IPv4. '''
try: try:
@@ -197,6 +198,7 @@ def IsValidIPv4(ip):
return False return False
return True return True
def IsValidIPv6(ip): def IsValidIPv6(ip):
''' Make sure an entered IP is a valid IPv6. ''' ''' Make sure an entered IP is a valid IPv6. '''
try: try:
@@ -205,8 +207,9 @@ def IsValidIPv6(ip):
return False return False
return True return True
def PromptToStartDaemon(): def PromptToStartDaemon():
""" Prompt the user to start the daemon """ """Prompt the user to start the daemon"""
daemonloc = wpath.sbin + 'wicd' daemonloc = wpath.sbin + 'wicd'
sudo_prog = choose_sudo_prog() sudo_prog = choose_sudo_prog()
if not sudo_prog: if not sudo_prog:
@@ -221,20 +224,23 @@ def PromptToStartDaemon():
os.spawnvpe(os.P_WAIT, sudo_prog, sudo_args, os.environ) os.spawnvpe(os.P_WAIT, sudo_prog, sudo_args, os.environ)
return True return True
def RunRegex(regex, s): def RunRegex(regex, s):
""" runs a regex search on a string """ """runs a regex search on a string"""
m = regex.search(s) m = regex.search(s)
if m: if m:
return m.groups()[0] return m.groups()[0]
else: else:
return None return None
def WriteLine(my_file, text): def WriteLine(my_file, text):
""" write a line to a file """ """write a line to a file"""
my_file.write(text + "\n") my_file.write(text + "\n")
def ExecuteScripts(scripts_dir, verbose=False, extra_parameters=()): 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): if not os.path.exists(scripts_dir):
return return
for obj in sorted(os.listdir(scripts_dir)): 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, ExecuteScript(os.path.abspath(obj), verbose=verbose,
extra_parameters=extra_parameters) extra_parameters=extra_parameters)
def ExecuteScript(script, verbose=False, extra_parameters=()): def ExecuteScript(script, verbose=False, extra_parameters=()):
""" Execute a command and send its output to the bit bucket. """ """Execute a command and send its output to the bit bucket."""
extra_parameters = [ quote(s) for s in extra_parameters ] extra_parameters = [quote(s) for s in extra_parameters]
params = ' '.join(extra_parameters) params = ' '.join(extra_parameters)
# escape script name # escape script name
script = quote(script) script = quote(script)
@@ -257,26 +264,29 @@ def ExecuteScript(script, verbose=False, extra_parameters=()):
if verbose: if verbose:
print(("%s returned %s" % (script, ret))) print(("%s returned %s" % (script, ret)))
def ReadFile(filename): 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): if not os.path.exists(filename):
return None return None
my_file = open(filename,'r') my_file = open(filename, 'r')
data = my_file.read().strip() data = my_file.read().strip()
my_file.close() my_file.close()
return str(data) return str(data)
def to_bool(var): 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"): if var in ("False", "0"):
var = False var = False
else: else:
var = bool(var) var = bool(var)
return var return var
def Noneify(variable, convert_to_bool=True): def Noneify(variable, convert_to_bool=True):
""" Convert string types to either None or booleans""" """Convert string types to either None or booleans"""
#set string Nones to real Nones # set string Nones to real Nones
if variable in ("None", "", None): if variable in ("None", "", None):
return None return None
if convert_to_bool: if convert_to_bool:
@@ -287,8 +297,9 @@ def Noneify(variable, convert_to_bool=True):
return True return True
return variable return variable
def ParseEncryption(network): 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 Parses an encryption template, reading in a network's info
and creating a config file for it and creating a config file for it
@@ -310,7 +321,7 @@ def ParseEncryption(network):
# This is the last line, so we just write it. # This is the last line, so we just write it.
config_file = ''.join([config_file, line]) config_file = ''.join([config_file, line])
elif "$_" in line: elif "$_" in line:
for cur_val in re.findall('\$_([A-Z0-9_]+)', line): for cur_val in re.findall(r'\$_([A-Z0-9_]+)', line):
if cur_val: if cur_val:
rep_val = network.get(cur_val.lower()) rep_val = network.get(cur_val.lower())
if not rep_val: if not rep_val:
@@ -344,8 +355,9 @@ def ParseEncryption(network):
f.write(config_file) f.write(config_file)
f.close() 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 Loads all the encryption methods from the template files
in /encryption/templates into a data structure. To be in /encryption/templates into a data structure. To be
@@ -357,7 +369,7 @@ def LoadEncryptionMethods(wired = False):
else: else:
active_fname = "active" active_fname = "active"
try: try:
enctypes = open(wpath.encryption + active_fname,"r").readlines() enctypes = open(wpath.encryption + active_fname, "r").readlines()
except IOError as e: except IOError as e:
print("Fatal Error: template index file is missing.") print("Fatal Error: template index file is missing.")
raise IOError(e) raise IOError(e)
@@ -370,6 +382,7 @@ def LoadEncryptionMethods(wired = False):
encryptionTypes.append(parsed_template) encryptionTypes.append(parsed_template)
return encryptionTypes return encryptionTypes
def __parse_field_ent(fields, field_type='require'): def __parse_field_ent(fields, field_type='require'):
fields = fields.split(" ") fields = fields.split(" ")
ret = [] ret = []
@@ -383,8 +396,9 @@ def __parse_field_ent(fields, field_type='require'):
ret.append([val, disp_val[1:]]) ret.append([val, disp_val[1:]])
return ret return ret
def _parse_enc_template(enctype): def _parse_enc_template(enctype):
""" Parse an encryption template. """ """Parse an encryption template."""
def parse_ent(line, key): def parse_ent(line, key):
return line.replace(key, "").replace("=", "").strip() return line.replace(key, "").replace("=", "").strip()
@@ -405,10 +419,12 @@ def _parse_enc_template(enctype):
if line.startswith("name") and not cur_type["name"]: if line.startswith("name") and not cur_type["name"]:
cur_type["name"] = parse_ent(line, "name") cur_type["name"] = parse_ent(line, "name")
elif line.startswith("require"): 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"]: if not cur_type["required"]:
# An error occured parsing the require line. # 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 continue
elif line.startswith("optional"): elif line.startswith("optional"):
cur_type["optional"] = __parse_field_ent(parse_ent(line, cur_type["optional"] = __parse_field_ent(parse_ent(line,
@@ -416,32 +432,34 @@ def _parse_enc_template(enctype):
field_type="optional") field_type="optional")
if not cur_type["optional"]: if not cur_type["optional"]:
# An error occured parsing the optional line. # 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 continue
elif line.startswith("protected"): elif line.startswith("protected"):
cur_type["protected"] = __parse_field_ent( cur_type["protected"] = __parse_field_ent(parse_ent(line,
parse_ent(line, "protected"), "protected"),
field_type="protected" field_type="protected")
)
if not cur_type["protected"]: if not cur_type["protected"]:
# An error occured parsing the protected line. # 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 continue
elif line.startswith("----"): elif line.startswith("----"):
# We're done. # We're done.
break break
f.close() f.close()
if not cur_type["required"]: 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 return None
if not cur_type["name"]: 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 return None
else: else:
return cur_type return cur_type
def noneToString(text): 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', Used for putting text in a text box. If the value to put in is 'None',
the box will be blank. the box will be blank.
@@ -452,8 +470,9 @@ def noneToString(text):
else: else:
return to_unicode(text) return to_unicode(text)
def sanitize_config(s): 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 allowed = string.ascii_letters + '_' + string.digits
table = string.maketrans(allowed, ' ' * len(allowed)) table = string.maketrans(allowed, ' ' * len(allowed))
@@ -461,20 +480,22 @@ def sanitize_config(s):
# make it simple. # make it simple.
return s.encode('ascii', 'replace').translate(None, table) return s.encode('ascii', 'replace').translate(None, table)
def sanitize_escaped(s): def sanitize_escaped(s):
""" Sanitize double-escaped unicode strings. """ """Sanitize double-escaped unicode strings."""
lastpos = -1 lastpos = -1
while True: while True:
lastpos = s.find('\\x', lastpos + 1) lastpos = s.find('\\x', lastpos + 1)
#print lastpos # print lastpos
if lastpos == -1: if lastpos == -1:
break break
c = s[lastpos+2:lastpos+4] # i.e. get the next two characters c = s[lastpos+2:lastpos+4] # i.e. get the next two characters
s = s.replace('\\x'+c, chr(int(c, 16))) s = s.replace('\\x'+c, chr(int(c, 16)))
return s return s
def to_unicode(x): 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 this is a unicode string, encode it and return
if not isinstance(x, bytes): if not isinstance(x, bytes):
return x return x
@@ -498,8 +519,9 @@ def to_unicode(x):
return ret return ret
def RenameProcess(new_name): 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: if 'linux' not in sys.platform:
print('Unsupported platform') print('Unsupported platform')
return False return False
@@ -509,12 +531,13 @@ def RenameProcess(new_name):
libc = ctypes.CDLL(find_library('c')) libc = ctypes.CDLL(find_library('c'))
libc.prctl(15, new_name, 0, 0, 0) libc.prctl(15, new_name, 0, 0, 0)
return True return True
except: except Exception:
print("rename failed") print("rename failed")
return False return False
def detect_desktop_environment(): 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 Choose between kde, gnome, or xfce based on environment
variables and a call to xprop. variables and a call to xprop.
@@ -534,8 +557,9 @@ def detect_desktop_environment():
pass pass
return desktop_environment return desktop_environment
def get_sudo_cmd(msg, prog_num=0): 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) sudo_prog = choose_sudo_prog(prog_num)
if not sudo_prog: if not sudo_prog:
return None return None
@@ -545,8 +569,9 @@ def get_sudo_cmd(msg, prog_num=0):
msg_flag = "--caption" msg_flag = "--caption"
return [sudo_prog, msg_flag, msg] return [sudo_prog, msg_flag, msg]
def choose_sudo_prog(prog_num=0): 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: if prog_num:
return find_path(_sudo_dict[prog_num]) return find_path(_sudo_dict[prog_num])
desktop_env = detect_desktop_environment() desktop_env = detect_desktop_environment()
@@ -566,8 +591,9 @@ def choose_sudo_prog(prog_num=0):
return path return path
return "" return ""
def find_path(cmd): 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 Search the all the paths in the environment variable PATH for
the given file name, or return None if a full path for the given file name, or return None if a full path for
@@ -583,28 +609,32 @@ def find_path(cmd):
return os.path.join(path, cmd) return os.path.join(path, cmd)
return None return None
def noneToBlankString(text): def noneToBlankString(text):
""" Converts NoneType or "None" to a blank string. """ """Converts NoneType or "None" to a blank string."""
if text in (None, "None"): if text in (None, "None"):
return "" return ""
else: else:
return str(text) return str(text)
def stringToNone(text): def stringToNone(text):
""" Performs opposite function of noneToString. """ """Performs opposite function of noneToString."""
if text in ("", None, "None"): if text in ("", None, "None"):
return None return None
else: else:
return str(text) return str(text)
def checkboxTextboxToggle(checkbox, textboxes): 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? # FIXME: should be moved to UI-specific files?
for textbox in textboxes: for textbox in textboxes:
textbox.set_sensitive(checkbox.get_active()) textbox.set_sensitive(checkbox.get_active())
def threaded(f): 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): def wrapper(*args, **kwargs):
t = Thread(target=f, args=args, kwargs=kwargs) t = Thread(target=f, args=args, kwargs=kwargs)
@@ -618,8 +648,9 @@ def threaded(f):
return wrapper return wrapper
def timeout_add(time, func, milli=False): 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: if hasattr(gobject, "timeout_add_seconds") and not milli:
return gobject.timeout_add_seconds(time, func) return gobject.timeout_add_seconds(time, func)
else: else:
@@ -627,16 +658,19 @@ def timeout_add(time, func, milli=False):
time = time * 1000 time = time * 1000
return gobject.timeout_add(time, func) return gobject.timeout_add(time, func)
def izip_longest(*args, **kwds): 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. We implement the method here because its new in Python 2.6.
""" """
# izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D- # izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
fillvalue = kwds.get('fillvalue') fillvalue = kwds.get('fillvalue')
def sentinel(counter = ([fillvalue]*(len(args)-1)).pop):
def sentinel(counter=([fillvalue]*(len(args)-1)).pop):
yield counter() # yields the fillvalue, or raises IndexError yield counter() # yields the fillvalue, or raises IndexError
fillers = repeat(fillvalue) fillers = repeat(fillvalue)
iters = [chain(it, sentinel(), fillers) for it in args] iters = [chain(it, sentinel(), fillers) for it in args]
try: try:
@@ -645,8 +679,9 @@ def izip_longest(*args, **kwds):
except IndexError: except IndexError:
pass pass
def grouper(n, iterable, fillvalue=None): 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" "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"

View File

@@ -1,6 +1,6 @@
#!/usr/bin/env python3 #!/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 This process is spawned as a child of the daemon, and is responsible
for monitoring connection status and initiating autoreconnection for monitoring connection status and initiating autoreconnection
@@ -24,9 +24,9 @@ when appropriate.
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
from gi.repository import GLib as gobject
import time import time
from gi.repository import GLib as gobject
from dbus import DBusException from dbus import DBusException
from wicd import wpath from wicd import wpath
@@ -46,6 +46,7 @@ wireless = dbus_dict["wireless"]
mainloop = None mainloop = None
def diewithdbus(func): def diewithdbus(func):
""" """
Decorator catching DBus exceptions, making wicd quit. Decorator catching DBus exceptions, making wicd quit.
@@ -69,10 +70,11 @@ def diewithdbus(func):
wrapper.__doc__ = func.__doc__ wrapper.__doc__ = func.__doc__
return wrapper return wrapper
class ConnectionStatus(object): class ConnectionStatus(object):
""" Class for monitoring the computer's connection status. """ """Class for monitoring the computer's connection status."""
def __init__(self): 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_strength = -2
self.last_state = misc.NOT_CONNECTED self.last_state = misc.NOT_CONNECTED
self.last_reconnect_time = time.time() self.last_reconnect_time = time.time()
@@ -99,13 +101,13 @@ class ConnectionStatus(object):
"SignalBackendChanged", "org.wicd.daemon") "SignalBackendChanged", "org.wicd.daemon")
def _update_timeout_interval(self, interval): 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 self._to_time = interval
gobject.source_remove(self.update_callback) gobject.source_remove(self.update_callback)
self.add_poll_callback() self.add_poll_callback()
def _force_update_connection_status(self): 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() Removes the scheduled update_connection_status()
call, explicitly calls the function, and reschedules call, explicitly calls the function, and reschedules
@@ -117,7 +119,7 @@ class ConnectionStatus(object):
self.add_poll_callback() self.add_poll_callback()
def add_poll_callback(self): 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. The polling interval is determined by the backend in use.
@@ -126,7 +128,7 @@ class ConnectionStatus(object):
self.update_connection_status) self.update_connection_status)
def check_for_wired_connection(self, wired_ip): def check_for_wired_connection(self, wired_ip):
""" Checks for a wired connection. """Checks for a wired connection.
Checks for two states: Checks for two states:
1) A wired connection is not in use, but a cable is plugged 1) A wired connection is not in use, but a cable is plugged
@@ -157,7 +159,7 @@ class ConnectionStatus(object):
return False return False
def check_for_wireless_connection(self, wireless_ip): 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 Checks for an active wireless connection. Also notes
if the signal strength is 0, and if it remains there if the signal strength is 0, and if it remains there
@@ -207,7 +209,7 @@ class ConnectionStatus(object):
@diewithdbus @diewithdbus
def update_connection_status(self): 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 Determines the current connection state and sends a dbus signal
announcing when the status changes. Also starts the automatic announcing when the status changes. Also starts the automatic
@@ -253,8 +255,8 @@ class ConnectionStatus(object):
if not daemon.GetGUIOpen(): if not daemon.GetGUIOpen():
print('Killing wireless connection to switch to wired...') print('Killing wireless connection to switch to wired...')
wireless.DisconnectWireless() wireless.DisconnectWireless()
daemon.AutoConnect(False, reply_handler=lambda *a:None, daemon.AutoConnect(False, reply_handler=lambda *a: None,
error_handler=lambda *a:None) error_handler=lambda *a: None)
return self.update_state(misc.NOT_CONNECTED) return self.update_state(misc.NOT_CONNECTED)
return self.update_state(misc.WIRELESS, wifi_ip=wifi_ip) return self.update_state(misc.WIRELESS, wifi_ip=wifi_ip)
@@ -267,7 +269,7 @@ class ConnectionStatus(object):
return self.update_state(state) return self.update_state(state)
def update_state(self, state, wired_ip=None, wifi_ip=None): 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. # Set our connection state/info.
iwconfig = self.iwconfig iwconfig = self.iwconfig
if state == misc.NOT_CONNECTED: if state == misc.NOT_CONNECTED:
@@ -278,15 +280,18 @@ class ConnectionStatus(object):
if wired.CheckIfWiredConnecting(): if wired.CheckIfWiredConnecting():
info = ["wired"] info = ["wired"]
else: else:
info = ["wireless", info = ["wireless", misc.
misc.noneToBlankString(wireless.GetCurrentNetwork(iwconfig))] noneToBlankString(wireless.
GetCurrentNetwork(iwconfig))]
elif state == misc.WIRELESS: elif state == misc.WIRELESS:
self.reconnect_tries = 0 self.reconnect_tries = 0
info = [str(wifi_ip), info = [str(wifi_ip),
misc.noneToBlankString(wireless.GetCurrentNetwork(iwconfig)), misc.noneToBlankString(wireless.
GetCurrentNetwork(iwconfig)),
str(self._get_printable_sig_strength()), str(self._get_printable_sig_strength()),
str(wireless.GetCurrentNetworkID(iwconfig)), str(wireless.GetCurrentNetworkID(iwconfig)),
misc.noneToBlankString(wireless.GetCurrentBitrate(iwconfig))] misc.noneToBlankString(wireless.
GetCurrentBitrate(iwconfig))]
elif state == misc.WIRED: elif state == misc.WIRED:
self.reconnect_tries = 0 self.reconnect_tries = 0
info = [str(wired_ip)] info = [str(wired_ip)]
@@ -301,8 +306,8 @@ class ConnectionStatus(object):
self.signal_changed)): self.signal_changed)):
daemon.EmitStatusChanged(state, info) daemon.EmitStatusChanged(state, info)
if (state != self.last_state) and (state == misc.NOT_CONNECTED) and \ if (state != self.last_state and state == misc.NOT_CONNECTED and
(not daemon.GetForcedDisconnect()): not daemon.GetForcedDisconnect()):
daemon.Disconnect() daemon.Disconnect()
# Disconnect() sets forced disconnect = True # Disconnect() sets forced disconnect = True
# so we'll revert that # so we'll revert that
@@ -311,7 +316,7 @@ class ConnectionStatus(object):
return True return True
def _get_printable_sig_strength(self, always_positive=False): def _get_printable_sig_strength(self, always_positive=False):
""" Get the correct signal strength format. """ """Get the correct signal strength format."""
try: try:
if daemon.GetSignalDisplayType() == 0: if daemon.GetSignalDisplayType() == 0:
signal = wireless.GetCurrentSignalStrength(self.iwconfig) signal = wireless.GetCurrentSignalStrength(self.iwconfig)
@@ -332,7 +337,7 @@ class ConnectionStatus(object):
return wifi_signal return wifi_signal
def auto_reconnect(self, from_wireless=None): 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 If automatic reconnection is turned on, this method will
attempt to first reconnect to the last used wireless network, and attempt to first reconnect to the last used wireless network, and
@@ -364,24 +369,26 @@ class ConnectionStatus(object):
# before we reconnect # before we reconnect
print('Disconnecting from network') print('Disconnecting from network')
wireless.DisconnectWireless() wireless.DisconnectWireless()
print(('Trying to reconnect to last used wireless ' + \ print('Trying to reconnect to last used wireless network')
'network'))
wireless.ConnectWireless(cur_net_id) wireless.ConnectWireless(cur_net_id)
else: else:
daemon.AutoConnect(True, reply_handler=reply_handle, daemon.AutoConnect(True, reply_handler=reply_handle,
error_handler=err_handle) error_handler=err_handle)
self.reconnecting = False self.reconnecting = False
def reply_handle(): def reply_handle():
""" Just a dummy function needed for asynchronous dbus calls. """ """Just a dummy function needed for asynchronous dbus calls."""
pass pass
def err_handle(error): def err_handle(error):
""" Just a dummy function needed for asynchronous dbus calls. """ """Just a dummy function needed for asynchronous dbus calls."""
pass pass
def main(): def main():
""" Starts the connection monitor. """Starts the connection monitor.
Starts a ConnectionStatus instance, sets the status to update Starts a ConnectionStatus instance, sets the status to update
an amount of time determined by the active backend. an amount of time determined by the active backend.

View File

@@ -1,7 +1,4 @@
#!/usr/bin/env python3 """networking - Provides wrappers for common network operations
# -*- coding: utf-8 -*-
""" networking - Provides wrappers for common network operations
This module provides wrappers of the common network tasks as well as This module provides wrappers of the common network tasks as well as
threads to perform the actual connecting to networks. threads to perform the actual connecting to networks.
@@ -51,10 +48,9 @@ from signal import SIGTERM
from functools import cmp_to_key from functools import cmp_to_key
# wicd imports # wicd imports
from . import misc from wicd import misc
from . import wpath from wicd import wpath
from .backend import BackendManager from wicd.backend import BackendManager
from .translations import _
if __name__ == '__main__': if __name__ == '__main__':
wpath.chdir(__file__) wpath.chdir(__file__)
@@ -62,8 +58,9 @@ if __name__ == '__main__':
BACKEND = None BACKEND = None
BACKEND_MGR = BackendManager() BACKEND_MGR = BackendManager()
def abortable(func): 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 This decorator runs a check that will abort the connection thread
if necessary before running a given method. if necessary before running a given method.
@@ -79,39 +76,45 @@ def abortable(func):
wrapper.__module = func.__module__ wrapper.__module = func.__module__
return wrapper return wrapper
def get_backend_list(): def get_backend_list():
""" Returns a list of available backends. """ """Returns a list of available backends."""
if BACKEND_MGR: if BACKEND_MGR:
return BACKEND_MGR.get_available_backends() return BACKEND_MGR.get_available_backends()
else: else:
return [""] return [""]
def get_backend_update_interval(): def get_backend_update_interval():
""" Returns the suggested connection status update interval. """ """Returns the suggested connection status update interval."""
if BACKEND_MGR: if BACKEND_MGR:
return BACKEND_MGR.get_update_interval() return BACKEND_MGR.get_update_interval()
else: else:
return 5 # Seconds, this should never happen though. return 5 # Seconds, this should never happen though.
def get_current_backend(): def get_current_backend():
""" Returns the current backend instance. """ """Returns the current backend instance."""
if BACKEND_MGR: if BACKEND_MGR:
return BACKEND_MGR.get_current_backend() return BACKEND_MGR.get_current_backend()
else: else:
return None return None
def get_backend_description(backend_name): 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) return BACKEND_MGR.get_backend_description(backend_name)
def get_backend_description_dict(): def get_backend_description_dict():
""" Returns a dict of all available backend descriptions. """ """Returns a dict of all available backend descriptions."""
d = {} d = {}
for be in get_backend_list(): for be in get_backend_list():
if be: if be:
d[be] = get_backend_description(be) d[be] = get_backend_description(be)
return d return d
def expand_script_macros(script, msg, bssid, essid): def expand_script_macros(script, msg, bssid, essid):
"""Expands any supported macros in a script. """Expands any supported macros in a script.
@@ -129,9 +132,9 @@ def expand_script_macros(script, msg, bssid, essid):
print(('Warning: found illegal macro %s in %s script' % (macro, msg))) print(('Warning: found illegal macro %s in %s script' % (macro, msg)))
return match.group() return match.group()
macro_dict = { 'script' : msg, macro_dict = {'script': msg,
'bssid' : bssid, 'bssid': bssid,
'essid' : essid } 'essid': essid}
regex = re.compile(r'%\{([a-zA-Z0-9]+)\}') regex = re.compile(r'%\{([a-zA-Z0-9]+)\}')
expanded = regex.sub(repl, script) expanded = regex.sub(repl, script)
print(("Expanded '%s' to '%s'" % (script, expanded))) print(("Expanded '%s' to '%s'" % (script, expanded)))
@@ -139,9 +142,9 @@ def expand_script_macros(script, msg, bssid, essid):
class Controller(object): class Controller(object):
""" Parent class for the different interface types. """ """Parent class for the different interface types."""
def __init__(self, debug=False): def __init__(self, debug=False):
""" Initialise the class. """ """Initialise the class."""
self.global_dns_1 = None self.global_dns_1 = None
self.global_dns_2 = None self.global_dns_2 = None
self.global_dns_3 = None self.global_dns_3 = None
@@ -160,37 +163,40 @@ class Controller(object):
self.iface = None self.iface = None
def get_debug(self): def get_debug(self):
""" Getter for debug property. """ """Getter for debug property."""
return self._debug return self._debug
def set_debug(self, value): def set_debug(self, value):
""" Setter for debug property. """ """Setter for debug property."""
self._debug = value self._debug = value
if self.iface: if self.iface:
self.iface.SetDebugMode(value) self.iface.SetDebugMode(value)
debug = property(get_debug, set_debug) debug = property(get_debug, set_debug)
def set_dhcp_client(self, value): def set_dhcp_client(self, value):
""" Setter for dhcp_client property. """ """Setter for dhcp_client property."""
self._dhcp_client = value self._dhcp_client = value
if self.iface: if self.iface:
self.iface.DHCP_CLIENT = value self.iface.DHCP_CLIENT = value
def get_dhcp_client(self): def get_dhcp_client(self):
""" Getter for dhcp_client property. """ """Getter for dhcp_client property."""
return self._dhcp_client return self._dhcp_client
dhcp_client = property(get_dhcp_client, set_dhcp_client) dhcp_client = property(get_dhcp_client, set_dhcp_client)
def set_flush_tool(self, value): def set_flush_tool(self, value):
""" Setter for flush_tool property. """ """Setter for flush_tool property."""
self._flush_tool = value self._flush_tool = value
if self.iface: if self.iface:
self.iface.flush_tool = value self.iface.flush_tool = value
def get_flush_tool(self): def get_flush_tool(self):
""" Getter for flush_tool property. """ """Getter for flush_tool property."""
return self._flush_tool return self._flush_tool
flush_tool = property(get_flush_tool, set_flush_tool) flush_tool = property(get_flush_tool, set_flush_tool)
def LoadBackend(self, backend_name): def LoadBackend(self, backend_name):
""" Load the given networking backend. """ """Load the given networking backend."""
global BACKEND global BACKEND
if backend_name == self._backend: if backend_name == self._backend:
return return
@@ -198,14 +204,14 @@ class Controller(object):
BACKEND = self._backend BACKEND = self._backend
def NeedsExternalCalls(self): def NeedsExternalCalls(self):
""" Returns true if the loaded backend needs external calls. """ """Returns true if the loaded backend needs external calls."""
if self._backend: if self._backend:
return self._backend.NeedsExternalCalls() return self._backend.NeedsExternalCalls()
else: else:
return True return True
def GetIP(self, ifconfig=""): def GetIP(self, ifconfig=""):
""" Get the IP of the interface. """Get the IP of the interface.
Returns: Returns:
The IP address of the interface in dotted notation. The IP address of the interface in dotted notation.
@@ -214,7 +220,7 @@ class Controller(object):
return self.iface.GetIP(ifconfig) return self.iface.GetIP(ifconfig)
def Disconnect(self, nettype, name, mac): def Disconnect(self, nettype, name, mac):
""" Disconnect from the network. """ """Disconnect from the network."""
iface = self.iface iface = self.iface
# mac and name need to be strings # mac and name need to be strings
if mac in (None, ''): if mac in (None, ''):
@@ -239,17 +245,18 @@ class Controller(object):
extra_parameters=(nettype, name, mac)) extra_parameters=(nettype, name, mac))
if self.post_disconnect_script: if self.post_disconnect_script:
print('Running 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', 'post-disconnection',
mac, name), mac, name),
self.debug) self.debug)
def ReleaseDHCP(self): def ReleaseDHCP(self):
""" Release the DHCP lease for this interface. """ """Release the DHCP lease for this interface."""
return self.iface.ReleaseDHCP() return self.iface.ReleaseDHCP()
def KillDHCP(self): 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.') print('running kill dhcp.')
if (self.connecting_thread.is_connecting and if (self.connecting_thread.is_connecting and
self.iface.dhcp_object): self.iface.dhcp_object):
@@ -258,7 +265,7 @@ class Controller(object):
self.iface.dhcp_object = None self.iface.dhcp_object = None
def IsUp(self): def IsUp(self):
""" Calls the IsUp method for the wired interface. """Calls the IsUp method for the wired interface.
Returns: Returns:
True if the interface is up, False otherwise. True if the interface is up, False otherwise.
@@ -267,7 +274,7 @@ class Controller(object):
return self.iface.IsUp() return self.iface.IsUp()
def EnableInterface(self): def EnableInterface(self):
""" Puts the interface up. """Puts the interface up.
Returns: Returns:
True if the interface was put up succesfully, False otherwise. True if the interface was put up succesfully, False otherwise.
@@ -276,7 +283,7 @@ class Controller(object):
return self.iface.Up() return self.iface.Up()
def DisableInterface(self): def DisableInterface(self):
""" Puts the interface down. """Puts the interface down.
Returns: Returns:
True if the interface was put down succesfully, False otherwise. True if the interface was put down succesfully, False otherwise.
@@ -285,12 +292,12 @@ class Controller(object):
return self.iface.Down() return self.iface.Down()
def AppAvailable(self, app): def AppAvailable(self, app):
""" Determine if the given application is installed. """ """Determine if the given application is installed."""
return self.iface.AppAvailable(app) return self.iface.AppAvailable(app)
class ConnectThread(threading.Thread): 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 Useless on it's own, this class provides the generic functions
necessary for connecting using a separate thread. necessary for connecting using a separate thread.
@@ -305,7 +312,7 @@ class ConnectThread(threading.Thread):
pre_disconnect_script, post_disconnect_script, gdns1, pre_disconnect_script, post_disconnect_script, gdns1,
gdns2, gdns3, gdns_dom, gsearch_dom, iface, gdns2, gdns3, gdns_dom, gsearch_dom, iface,
debug): debug):
""" Initialise the required object variables and the thread. """Initialise the required object variables and the thread.
Keyword arguments: Keyword arguments:
network -- the network to connect to network -- the network to connect to
@@ -358,19 +365,20 @@ class ConnectThread(threading.Thread):
self.is_connecting = False self.is_connecting = False
def set_should_die(self, val): def set_should_die(self, val):
""" Setter for should_die property. """ """Setter for should_die property."""
self.lock.acquire() self.lock.acquire()
try: try:
self._should_die = val self._should_die = val
finally: finally:
self.lock.release() self.lock.release()
def get_should_die(self): def get_should_die(self):
""" Getter for should_die property. """ """Getter for should_die property."""
return self._should_die return self._should_die
should_die = property(get_should_die, set_should_die) should_die = property(get_should_die, set_should_die)
def SetStatus(self, status): 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: Keyword arguments:
status -- the current connection status status -- the current connection status
@@ -383,7 +391,7 @@ class ConnectThread(threading.Thread):
self.lock.release() self.lock.release()
def GetStatus(self): 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: Returns:
The current connection status. The current connection status.
@@ -398,7 +406,7 @@ class ConnectThread(threading.Thread):
@abortable @abortable
def reset_ip_addresses(self, iface): 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 Sets a false ip so that when we set the real one, the correct
routing entry is created. routing entry is created.
@@ -410,20 +418,20 @@ class ConnectThread(threading.Thread):
@abortable @abortable
def put_iface_down(self, iface): def put_iface_down(self, iface):
""" Puts the given interface down. """ """Puts the given interface down."""
print('Putting interface down') print('Putting interface down')
self.SetStatus('interface_down') self.SetStatus('interface_down')
iface.Down() iface.Down()
@abortable @abortable
def run_global_scripts_if_needed(self, script_dir, extra_parameters=()): def run_scripts(self, script_dir, extra_parameters=()):
""" Run global scripts if needed. '""" """Execute all script in provided script_dir."""
misc.ExecuteScripts(script_dir, verbose=self.debug, misc.ExecuteScripts(script_dir, verbose=self.debug,
extra_parameters=extra_parameters) extra_parameters=extra_parameters)
@abortable @abortable
def run_script_if_needed(self, script, msg, bssid='wired', essid='wired'): 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: Keyword arguments:
script -- the script to execute, or None/'' if there isn't one. script -- the script to execute, or None/'' if there isn't one.
@@ -437,22 +445,23 @@ class ConnectThread(threading.Thread):
@abortable @abortable
def flush_routes(self, iface): 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') self.SetStatus('flushing_routing_table')
print('Flushing the routing table...') print('Flushing the routing table...')
iface.FlushRoutes() iface.FlushRoutes()
@abortable @abortable
def set_broadcast_address(self, iface): def set_broadcast_address(self, iface):
""" Set the broadcast address for the given interface. """ """Set the broadcast address for the given interface."""
if not self.network.get('broadcast') == None: if self.network.get('broadcast') is not None:
self.SetStatus('setting_broadcast_address') 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']) iface.SetAddress(broadcast=self.network['broadcast'])
@abortable @abortable
def set_ip_address(self, iface): 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. Assigns a static IP if one is requested, otherwise calls DHCP.
@@ -467,9 +476,9 @@ class ConnectThread(threading.Thread):
else: else:
# Run dhcp... # Run dhcp...
self.SetStatus('running_dhcp') self.SetStatus('running_dhcp')
if self.network.get('usedhcphostname') == None: if self.network.get('usedhcphostname') is None:
self.network['usedhcphostname'] = False self.network['usedhcphostname'] = False
if self.network.get('dhcphostname') == None: if self.network.get('dhcphostname') is None:
self.network['dhcphostname'] = os.uname()[1] self.network['dhcphostname'] = os.uname()[1]
if self.network['usedhcphostname']: if self.network['usedhcphostname']:
hname = self.network['dhcphostname'] hname = self.network['dhcphostname']
@@ -478,9 +487,14 @@ class ConnectThread(threading.Thread):
hname = None hname = None
print("Running DHCP with NO hostname") 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 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 staticdns = True
dhcp_status = iface.StartDHCP(hname, staticdns) dhcp_status = iface.StartDHCP(hname, staticdns)
@@ -491,7 +505,7 @@ class ConnectThread(threading.Thread):
@abortable @abortable
def flush_dns_addresses(self, iface): 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 This is only useful when using resolvconf, since we effectively have no
foolproof way of removing added DNS addresses from a non-resolvconf foolproof way of removing added DNS addresses from a non-resolvconf
@@ -502,7 +516,7 @@ class ConnectThread(threading.Thread):
@abortable @abortable
def set_dns_addresses(self, iface): 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. If static DNS servers or global DNS servers are specified, set them.
Otherwise do nothing. Otherwise do nothing.
@@ -514,8 +528,9 @@ class ConnectThread(threading.Thread):
misc.Noneify(self.global_dns_3), misc.Noneify(self.global_dns_3),
misc.Noneify(self.global_dns_dom), misc.Noneify(self.global_dns_dom),
misc.Noneify(self.global_search_dom)) misc.Noneify(self.global_search_dom))
elif self.network.get('use_static_dns') and (self.network.get('dns1') or elif (self.network.get('use_static_dns') and
self.network.get('dns2') or self.network.get('dns3')): (self.network.get('dns1') or self.network.get('dns2')
or self.network.get('dns3'))):
self.SetStatus('setting_static_dns') self.SetStatus('setting_static_dns')
iface.SetDNS(self.network.get('dns1'), iface.SetDNS(self.network.get('dns1'),
self.network.get('dns2'), self.network.get('dns2'),
@@ -525,12 +540,12 @@ class ConnectThread(threading.Thread):
@abortable @abortable
def release_dhcp_clients(self, iface): def release_dhcp_clients(self, iface):
""" Release all running dhcp clients. """ """Release all running dhcp clients."""
print("Releasing DHCP leases...") print("Releasing DHCP leases...")
iface.ReleaseDHCP() iface.ReleaseDHCP()
def connect_aborted(self, reason): def connect_aborted(self, reason):
""" Sets the thread status to aborted. """ """Sets the thread status to aborted."""
if self.abort_reason: if self.abort_reason:
reason = self.abort_reason reason = self.abort_reason
self.connecting_status = reason self.connecting_status = reason
@@ -540,12 +555,12 @@ class ConnectThread(threading.Thread):
print('exiting connection thread') print('exiting connection thread')
def abort_connection(self, reason=""): 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.abort_reason = reason
self.should_die = True self.should_die = True
def abort_if_needed(self): def abort_if_needed(self):
""" Abort the thread is it has been requested. """ """Abort the thread is it has been requested."""
self.lock.acquire() self.lock.acquire()
try: try:
if self._should_die: if self._should_die:
@@ -556,13 +571,13 @@ class ConnectThread(threading.Thread):
@abortable @abortable
def stop_wpa(self, iface): def stop_wpa(self, iface):
""" Stops wpa_supplicant. """ """Stops wpa_supplicant."""
print('Stopping wpa_supplicant') print('Stopping wpa_supplicant')
iface.StopWPA() iface.StopWPA()
@abortable @abortable
def put_iface_up(self, iface): def put_iface_up(self, iface):
""" Bring up given interface. """ """Bring up given interface."""
print('Putting interface up...') print('Putting interface up...')
self.SetStatus('interface_up') self.SetStatus('interface_up')
iface.Up() iface.Up()
@@ -577,10 +592,10 @@ class ConnectThread(threading.Thread):
class Wireless(Controller): class Wireless(Controller):
""" A wrapper for common wireless interface functions. """ """A wrapper for common wireless interface functions."""
def __init__(self, debug=False): def __init__(self, debug=False):
""" Initialize the class. """ """Initialize the class."""
Controller.__init__(self, debug=debug) Controller.__init__(self, debug=debug)
self._wpa_driver = None self._wpa_driver = None
self._wireless_interface = None self._wireless_interface = None
@@ -588,35 +603,38 @@ class Wireless(Controller):
self.should_verify_ap = True self.should_verify_ap = True
def set_wireless_iface(self, value): def set_wireless_iface(self, value):
""" Setter for wireless_interface property. """ """Setter for wireless_interface property."""
self._wireless_interface = value self._wireless_interface = value
if self.wiface: if self.wiface:
self.wiface.SetInterface(value) self.wiface.SetInterface(value)
def get_wireless_iface(self): def get_wireless_iface(self):
""" Getter for wireless_interface property. """ """Getter for wireless_interface property."""
return self._wireless_interface 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): def set_wpa_driver(self, value):
""" Setter for wpa_driver property. """ """Setter for wpa_driver property."""
self._wpa_driver = value self._wpa_driver = value
if self.wiface: if self.wiface:
self.SetWPADriver(value) self.SetWPADriver(value)
def get_wpa_driver(self): def get_wpa_driver(self):
""" Getter for wpa_driver property. """ """Getter for wpa_driver property."""
return self._wpa_driver return self._wpa_driver
wpa_driver = property(get_wpa_driver, set_wpa_driver) wpa_driver = property(get_wpa_driver, set_wpa_driver)
def set_iface(self, value): def set_iface(self, value):
""" Setter for iface property. """ """Setter for iface property."""
self.wiface = value self.wiface = value
def get_iface(self): def get_iface(self):
""" Getter for iface property. """ """Getter for iface property."""
return self.wiface return self.wiface
iface = property(get_iface, set_iface) iface = property(get_iface, set_iface)
def LoadBackend(self, backend): def LoadBackend(self, backend):
""" Load a given backend. """Load a given backend.
Load up a backend into the backend manager and associate with Load up a backend into the backend manager and associate with
the networking interface. the networking interface.
@@ -626,10 +644,11 @@ class Wireless(Controller):
backend = self._backend backend = self._backend
if backend: if backend:
self.wiface = backend.WirelessInterface(self.wireless_interface, self.wiface = backend.WirelessInterface(self.wireless_interface,
self.debug, self.wpa_driver) self.debug,
self.wpa_driver)
def Scan(self, essid=None): def Scan(self, essid=None):
""" Scan for available wireless networks. """Scan for available wireless networks.
Keyword arguments: Keyword arguments:
essid -- The essid of a hidden network essid -- The essid of a hidden network
@@ -639,13 +658,14 @@ class Wireless(Controller):
""" """
def comp(x, y): def comp(x, y):
""" Custom sorting function. """ """Custom sorting function."""
if 'quality' in x: if 'quality' in x:
key = 'quality' key = 'quality'
else: else:
key = 'strength' 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: if not self.wiface:
return [] return []
@@ -656,7 +676,8 @@ class Wireless(Controller):
# If there is a hidden essid then set it now, so that when it is # If there is a hidden essid then set it now, so that when it is
# scanned it will be recognized. # 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) essid = misc.Noneify(essid)
if essid is not None: if essid is not None:
print(('Setting hidden essid ' + essid)) print(('Setting hidden essid ' + essid))
@@ -670,7 +691,7 @@ class Wireless(Controller):
return aps return aps
def Connect(self, network, debug=False): 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: Keyword arguments:
network -- network to connect to network -- network to connect to
@@ -679,19 +700,19 @@ class Wireless(Controller):
if not self.wiface: if not self.wiface:
return False return False
self.connecting_thread = WirelessConnectThread(network, self.connecting_thread = WirelessConnectThread(
self.wireless_interface, self.wpa_driver, self.before_script, network, self.wireless_interface, self.wpa_driver,
self.after_script, self.pre_disconnect_script, self.before_script, self.after_script, self.pre_disconnect_script,
self.post_disconnect_script, self.global_dns_1, self.post_disconnect_script, self.global_dns_1, self.global_dns_2,
self.global_dns_2, self.global_dns_3, self.global_dns_dom, self.global_dns_3, self.global_dns_dom, self.global_search_dom,
self.global_search_dom, self.wiface, self.should_verify_ap, self.wiface, self.should_verify_ap, self.bitrate,
self.bitrate, self.allow_lower_bitrates, debug) self.allow_lower_bitrates, debug)
self.connecting_thread.setDaemon(True) self.connecting_thread.setDaemon(True)
self.connecting_thread.start() self.connecting_thread.start()
return True return True
def GetSignalStrength(self, iwconfig=""): def GetSignalStrength(self, iwconfig=""):
""" Get signal strength of the current network. """Get signal strength of the current network.
Returns: Returns:
The current signal strength. The current signal strength.
@@ -700,7 +721,7 @@ class Wireless(Controller):
return self.wiface.GetSignalStrength(iwconfig) return self.wiface.GetSignalStrength(iwconfig)
def GetDBMStrength(self, iwconfig=""): def GetDBMStrength(self, iwconfig=""):
""" Get the dBm signal strength of the current network. """Get the dBm signal strength of the current network.
Returns: Returns:
The current dBm signal strength. The current dBm signal strength.
@@ -709,7 +730,7 @@ class Wireless(Controller):
return self.wiface.GetDBMStrength(iwconfig) return self.wiface.GetDBMStrength(iwconfig)
def GetCurrentNetwork(self, iwconfig=""): def GetCurrentNetwork(self, iwconfig=""):
""" Get current network name. """Get current network name.
Returns: Returns:
The name of the currently connected network. The name of the currently connected network.
@@ -720,7 +741,7 @@ class Wireless(Controller):
return self.wiface.GetCurrentNetwork(iwconfig) return self.wiface.GetCurrentNetwork(iwconfig)
def GetBSSID(self): def GetBSSID(self):
""" Get the BSSID of the current access point. """Get the BSSID of the current access point.
Returns: Returns:
The MAC Adress of the active access point as a string, or The MAC Adress of the active access point as a string, or
@@ -730,7 +751,7 @@ class Wireless(Controller):
return self.wiface.GetBSSID() return self.wiface.GetBSSID()
def GetCurrentBitrate(self, iwconfig): def GetCurrentBitrate(self, iwconfig):
""" Get the current bitrate of the interface. """Get the current bitrate of the interface.
Returns: Returns:
The bitrate of the active access point as a string, or The bitrate of the active access point as a string, or
@@ -740,7 +761,7 @@ class Wireless(Controller):
return self.wiface.GetCurrentBitrate(iwconfig) return self.wiface.GetCurrentBitrate(iwconfig)
def GetOperationalMode(self, iwconfig): def GetOperationalMode(self, iwconfig):
""" Get the current operational mode of the interface. """Get the current operational mode of the interface.
Returns: Returns:
The operational mode of the interface as a string, or The operational mode of the interface as a string, or
@@ -750,7 +771,7 @@ class Wireless(Controller):
return self.wiface.GetOperationalMode(iwconfig) return self.wiface.GetOperationalMode(iwconfig)
def GetAvailableAuthMethods(self, iwlistauth): def GetAvailableAuthMethods(self, iwlistauth):
""" Get the available authentication methods for the interface. """Get the available authentication methods for the interface.
Returns: Returns:
The available authentication methods of the interface as a string, or The available authentication methods of the interface as a string, or
@@ -760,7 +781,7 @@ class Wireless(Controller):
return self.wiface.GetAvailableAuthMethods(iwlistauth) return self.wiface.GetAvailableAuthMethods(iwlistauth)
def GetAvailableBitrates(self): def GetAvailableBitrates(self):
""" Get the available bitrates for the interface. """Get the available bitrates for the interface.
Returns: Returns:
The available bitrates of the interface as a string, or None if the The available bitrates of the interface as a string, or None if the
@@ -769,20 +790,19 @@ class Wireless(Controller):
return self.wiface.GetAvailableBitrates() return self.wiface.GetAvailableBitrates()
def GetIwconfig(self): def GetIwconfig(self):
""" Get the out of iwconfig. """ """Get the out of iwconfig."""
return self.wiface.GetIwconfig() return self.wiface.GetIwconfig()
def GetWpaSupplicantDrivers(self): def GetWpaSupplicantDrivers(self):
""" Returns all valid wpa_supplicant drivers on the system. """ """Returns all valid wpa_supplicant drivers on the system."""
return BACKEND.GetWpaSupplicantDrivers() return BACKEND.GetWpaSupplicantDrivers()
def StopWPA(self): def StopWPA(self):
""" Stop wpa_supplicant. """ """Stop wpa_supplicant."""
return self.wiface.StopWPA() return self.wiface.StopWPA()
def CreateAdHocNetwork(self, essid, channel, ip, enctype, key, def CreateAdHocNetwork(self, essid, channel, ip, enctype, key, enc_used):
enc_used): """Create an ad-hoc wireless network.
""" Create an ad-hoc wireless network.
Keyword arguments: Keyword arguments:
essid -- essid of the ad-hoc network essid -- essid of the ad-hoc network
@@ -814,7 +834,7 @@ class Wireless(Controller):
wiface.SetAddress(ip, '255.255.255.0') wiface.SetAddress(ip, '255.255.255.0')
def DetectWirelessInterface(self): def DetectWirelessInterface(self):
""" Detect available wireless interfaces. """Detect available wireless interfaces.
Returns: Returns:
The first available wireless interface. The first available wireless interface.
@@ -827,7 +847,7 @@ class Wireless(Controller):
return None return None
def GetKillSwitchStatus(self): def GetKillSwitchStatus(self):
""" Get the current status of the Killswitch. """Get the current status of the Killswitch.
Returns: Returns:
True if the killswitch is on, False otherwise. True if the killswitch is on, False otherwise.
@@ -836,7 +856,7 @@ class Wireless(Controller):
return self.wiface.GetKillSwitchStatus() return self.wiface.GetKillSwitchStatus()
def SwitchRfKill(self): def SwitchRfKill(self):
""" Switches the rfkill on/off for wireless cards. """ """Switches the rfkill on/off for wireless cards."""
types = ['wifi', 'wlan', 'wimax', 'wwan'] types = ['wifi', 'wlan', 'wimax', 'wwan']
try: try:
if self.GetRfKillStatus(): if self.GetRfKillStatus():
@@ -853,21 +873,22 @@ class Wireless(Controller):
return False return False
def GetRfKillStatus(self): def GetRfKillStatus(self):
""" Determines if rfkill switch is active or not. """Determines if rfkill switch is active or not.
Returns: Returns:
True if rfkill (soft-)switch is enabled. True if rfkill (soft-)switch is enabled.
""" """
cmd = 'rfkill list' cmd = 'rfkill list'
rfkill_out = misc.Run(cmd) 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]: for line in [x.strip() for x in soft_blocks]:
if line.endswith('yes'): if line.endswith('yes'):
return True return True
return False return False
def Disconnect(self): def Disconnect(self):
""" Disconnect the given iface. """Disconnect the given iface.
Executes the disconnect script associated with a given interface, Executes the disconnect script associated with a given interface,
Resets it's IP address, and puts the interface down then up. Resets it's IP address, and puts the interface down then up.
@@ -884,12 +905,12 @@ class Wireless(Controller):
self.StopWPA() self.StopWPA()
def SetWPADriver(self, driver): 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) self.wiface.SetWpaDriver(driver)
class WirelessConnectThread(ConnectThread): 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 This thread, when run, will perform the necessary steps to connect
to the specified network. to the specified network.
@@ -900,7 +921,7 @@ class WirelessConnectThread(ConnectThread):
after_script, pre_disconnect_script, post_disconnect_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): should_verify_ap, bitrate, allow_lower_bitrates, debug=False):
""" Initialise the thread with network information. """Initialise the thread with network information.
Keyword arguments: Keyword arguments:
network -- the network to connect to network -- the network to connect to
@@ -927,7 +948,7 @@ class WirelessConnectThread(ConnectThread):
self.allow_lower_bitrates = allow_lower_bitrates self.allow_lower_bitrates = allow_lower_bitrates
def _connect(self): 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 This function performs the necessary calls to connect to the
specified network, using the information provided. The following specified network, using the information provided. The following
@@ -944,15 +965,12 @@ class WirelessConnectThread(ConnectThread):
self.is_connecting = True self.is_connecting = True
# Run pre-connection script. # Run pre-connection script.
self.run_global_scripts_if_needed(wpath.preconnectscripts, self.run_scripts(wpath.preconnectscripts,
extra_parameters=('wireless', extra_parameters=('wireless', self.network['essid'],
self.network['essid'], self.network['bssid']))
self.network['bssid'])
)
self.run_script_if_needed(self.before_script, 'pre-connection', self.run_script_if_needed(self.before_script, 'pre-connection',
self.network['bssid'], self.network['essid']) self.network['bssid'], self.network['essid'])
# Take down interface and clean up previous connections. # Take down interface and clean up previous connections.
self.put_iface_down(wiface) self.put_iface_down(wiface)
self.release_dhcp_clients(wiface) self.release_dhcp_clients(wiface)
@@ -995,11 +1013,9 @@ class WirelessConnectThread(ConnectThread):
self.verify_association(wiface) self.verify_association(wiface)
# Run post-connection script. # Run post-connection script.
self.run_global_scripts_if_needed(wpath.postconnectscripts, self.run_scripts(wpath.postconnectscripts,
extra_parameters=('wireless', extra_parameters=('wireless', self.network['essid'],
self.network['essid'], self.network['bssid']))
self.network['bssid'])
)
self.run_script_if_needed(self.after_script, 'post-connection', self.run_script_if_needed(self.after_script, 'post-connection',
self.network['bssid'], self.network['essid']) self.network['bssid'], self.network['essid'])
@@ -1012,7 +1028,7 @@ class WirelessConnectThread(ConnectThread):
@abortable @abortable
def verify_association(self, iface): 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 Try to ping the gateway we have set to see if we're
really associated with it. This is only done if really associated with it. This is only done if
@@ -1024,12 +1040,13 @@ class WirelessConnectThread(ConnectThread):
print("Verifying AP association...") print("Verifying AP association...")
for tries in range(1, 11): for tries in range(1, 11):
print(("Attempt %d of 10..." % tries)) print(("Attempt %d of 10..." % tries))
retcode = self.iface.VerifyAPAssociation(self.network['gateway']) retcode = self.iface.VerifyAPAssociation(self.
network['gateway'])
if retcode == 0: if retcode == 0:
print("Successfully associated.") print("Successfully associated.")
break break
time.sleep(1) time.sleep(1)
#TODO this should be in wnettools.py # TODO this should be in wnettools.py
if retcode: if retcode:
print("Connection Failed: Failed to ping the access point!") print("Connection Failed: Failed to ping the access point!")
# Clean up before aborting. # Clean up before aborting.
@@ -1044,7 +1061,7 @@ class WirelessConnectThread(ConnectThread):
@abortable @abortable
def generate_psk_and_authenticate(self, wiface): 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 Generates a PSK, and starts the authentication process
if encryption is on. if encryption is on.
@@ -1062,9 +1079,9 @@ class WirelessConnectThread(ConnectThread):
if not self.network.get('psk'): if not self.network.get('psk'):
self.network['psk'] = self.network['key'] self.network['psk'] = self.network['key']
print(('WARNING: PSK generation failed! Falling back to ' + \ print('WARNING: PSK generation failed! Falling back to '
'wireless key.\nPlease report this error to the wicd ' + \ 'wireless key.\nPlease report this error to the wicd '
'developers!')) 'developers!')
# Generate the wpa_supplicant file... # Generate the wpa_supplicant file...
if self.network.get('enctype'): if self.network.get('enctype'):
self.SetStatus('generating_wpa_config') self.SetStatus('generating_wpa_config')
@@ -1073,54 +1090,59 @@ class WirelessConnectThread(ConnectThread):
class Wired(Controller): class Wired(Controller):
""" A wrapper for common wired interface functions. """ """A wrapper for common wired interface functions."""
def __init__(self, debug=False): def __init__(self, debug=False):
""" Initialise the class. """ """Initialise the class."""
Controller.__init__(self, debug=debug) Controller.__init__(self, debug=debug)
self.wpa_driver = None self.wpa_driver = None
self._link_detect = None self._link_detect = None
self._wired_interface = None self._wired_interface = None
self.liface = None self.liface = None
def set_link_detect(self, value): @property
""" Setter for link_detect 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 self._link_detect = value
if self.liface: if self.liface:
self.liface.link_detect = value 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)
@property
def wired_iface(self):
"""Getter for wired_interface property."""
return self._wired_interface
def set_wired_iface(self, value): @wired_iface.setter
""" Setter for wired_interface property. """ def wired_iface(self, value):
"""Setter for wired_interface property."""
self._wired_interface = value self._wired_interface = value
if self.liface: if self.liface:
self.liface.SetInterface(value) 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): @property
""" Setter for iface property. """ def iface(self):
self.liface = value """Getter for iface property."""
def get_iface(self):
""" Getter for iface property. """
return self.liface 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): def LoadBackend(self, backend):
""" Load the backend up. """ """Load the backend up."""
Controller.LoadBackend(self, backend) Controller.LoadBackend(self, backend)
if self._backend: if self._backend:
self.liface = self._backend.WiredInterface(self.wired_interface, self.liface = self._backend.WiredInterface(self.wired_interface,
self.debug) self.debug)
def CheckPluggedIn(self): def CheckPluggedIn(self):
""" Check whether the wired connection is plugged in. """Check whether the wired connection is plugged in.
Returns: Returns:
The status of the physical connection link. The status of the physical connection link.
@@ -1129,7 +1151,7 @@ class Wired(Controller):
return self.liface.GetPluggedIn() return self.liface.GetPluggedIn()
def Connect(self, network, debug=False): 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: Keyword arguments:
network -- network to connect to network -- network to connect to
@@ -1137,12 +1159,12 @@ class Wired(Controller):
""" """
if not self.liface: if not self.liface:
return False return False
self.connecting_thread = WiredConnectThread(network, self.connecting_thread = WiredConnectThread(
self.wired_interface, self.before_script, self.after_script, network, self.wired_interface, self.before_script,
self.pre_disconnect_script, self.post_disconnect_script, self.after_script, self.pre_disconnect_script,
self.global_dns_1, self.global_dns_2, self.global_dns_3, self.post_disconnect_script, self.global_dns_1, self.global_dns_2,
self.global_dns_dom, self.global_search_dom, self.liface, self.global_dns_3, self.global_dns_dom, self.global_search_dom,
debug) self.liface, debug)
self.connecting_thread.setDaemon(True) self.connecting_thread.setDaemon(True)
self.connecting_thread.start() self.connecting_thread.start()
return self.connecting_thread return self.connecting_thread
@@ -1152,11 +1174,11 @@ class Wired(Controller):
self.StopWPA() self.StopWPA()
def StopWPA(self): def StopWPA(self):
""" Stop wpa_supplicant. """ """Stop wpa_supplicant."""
self.liface.StopWPA() self.liface.StopWPA()
def DetectWiredInterface(self): def DetectWiredInterface(self):
""" Attempts to automatically detect a wired interface. """ """Attempts to automatically detect a wired interface."""
try: try:
return BACKEND.GetWiredInterfaces()[0] return BACKEND.GetWiredInterfaces()[0]
except IndexError: except IndexError:
@@ -1164,7 +1186,7 @@ class Wired(Controller):
class WiredConnectThread(ConnectThread): 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 This thread, when run, will perform the necessary steps to connect
to the specified network. to the specified network.
@@ -1173,7 +1195,7 @@ class WiredConnectThread(ConnectThread):
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, pre_disconnect_script, post_disconnect_script, gdns1,
gdns2, gdns3, gdns_dom, gsearch_dom, liface, debug=False): gdns2, gdns3, gdns_dom, gsearch_dom, liface, debug=False):
""" Initialise the thread with network information. """Initialise the thread with network information.
Keyword arguments: Keyword arguments:
network -- the network to connect to network -- the network to connect to
@@ -1195,7 +1217,7 @@ class WiredConnectThread(ConnectThread):
debug) debug)
def _connect(self): 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 This function performs the necessary calls to connect to the
specified network, using the information provided. The following specified network, using the information provided. The following
@@ -1213,12 +1235,11 @@ class WiredConnectThread(ConnectThread):
self.is_connecting = True self.is_connecting = True
# Run pre-connection script. # Run pre-connection script.
self.run_global_scripts_if_needed(wpath.preconnectscripts, self.run_scripts(wpath.preconnectscripts,
extra_parameters=('wired', 'wired', extra_parameters=('wired', 'wired',
self.network['profilename']) self.network['profilename']))
) self.run_script_if_needed(self.before_script, 'pre-connection',
self.run_script_if_needed(self.before_script, 'pre-connection', 'wired', 'wired', 'wired')
'wired')
# Take down interface and clean up previous connections. # Take down interface and clean up previous connections.
self.put_iface_down(liface) self.put_iface_down(liface)
@@ -1241,12 +1262,11 @@ class WiredConnectThread(ConnectThread):
self.set_dns_addresses(liface) self.set_dns_addresses(liface)
# Run post-connection script. # Run post-connection script.
self.run_global_scripts_if_needed(wpath.postconnectscripts, self.run_scripts(wpath.postconnectscripts,
extra_parameters=('wired', 'wired', extra_parameters=('wired', 'wired',
self.network['profilename']) self.network['profilename']))
) self.run_script_if_needed(self.after_script, 'post-connection',
self.run_script_if_needed(self.after_script, 'post-connection', 'wired', 'wired', 'wired')
'wired')
self.SetStatus('done') self.SetStatus('done')
print('Connecting thread exiting.') print('Connecting thread exiting.')

View File

@@ -1,6 +1,6 @@
#!/usr/bin/env python3 #!/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. Sets a flag in the daemon that will stop it from monitoring network status.
Used for when a laptop enters hibernation/suspension. 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 # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
# #
import sys
import dbus import dbus
import dbus.service import dbus.service
import sys
try: try:
bus = dbus.SystemBus() bus = dbus.SystemBus()

View File

@@ -1,7 +1,7 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# -* coding: utf-8 -*- # -* 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 Adam Blackburn
# Copyright (C) 2007 - 2009 Dan O'Reilly # Copyright (C) 2007 - 2009 Dan O'Reilly
@@ -21,12 +21,12 @@
# #
import locale import locale
import os import os
from . import wpath from wicd import wpath
import gettext import gettext
def get_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 # Borrowed from an excellent post on how to do this at
# http://www.learningpython.com/2006/12/03/translating-your-pythonpygtk-application/ # http://www.learningpython.com/2006/12/03/translating-your-pythonpygtk-application/
local_path = wpath.translations local_path = wpath.translations
@@ -54,7 +54,7 @@ def get_gettext():
fallback=True) fallback=True)
return lang.gettext return lang.gettext
_ = get_gettext() _ = get_gettext() # noqa
# language[] should contain only strings in encryption templates, which # 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. # 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 # Leaving here for future reference, they should be removed whenever
# possible. # possible.
#language['cannot_start_daemon'] = _('Unable to connect to wicd daemon ' + \ # language['cannot_start_daemon'] = _('Unable to connect to wicd daemon '
# 'DBus interface. This typically means there was a problem starting ' + \ # 'DBus interface. This typically means '
# 'the daemon. Check the wicd log for more information.') # 'there was a problem starting the '
#language['backend_alert'] = _('Changes to your backend won't occur until ' + \ # 'daemon. Check the wicd log for more '
# 'information.')
# language['backend_alert'] = _('Changes to your backend won't occur until '
# 'the daemon is restarted.') # 'the daemon is restarted.')
#language['about_help'] = _('Stop a network connection in progress') # language['about_help'] = _('Stop a network connection in progress')
#language['connect'] = _('Connect') # language['connect'] = _('Connect')
# from templates, dict populated with: # from templates, dict populated with:
# grep -R "*" encryption/templates/ | tr " " "\n" | grep "^*" | \ # grep -R "*" encryption/templates/ | tr " " "\n" | grep "^*" | \

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff