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

@@ -17,9 +17,11 @@
# MA 02110-1301, USA.
import optparse
import sys
import dbus
import dbus.service
import sys
from wicd import misc
from wicd.translations import _
@@ -52,13 +54,13 @@ try:
'org.wicd.daemon.config'
)
except dbus.DBusException:
print(('Error: Could not connect to the daemon. ' + \
'Please make sure it is running.'))
print('Error: Could not connect to the daemon. Please make sure it is '
'running.')
sys.exit(3)
if not daemon:
print(('Error connecting to wicd via D-Bus. ' + \
'Please make sure the wicd service is running.'))
print('Error connecting to wicd via D-Bus. Please make sure the wicd '
'service is running.')
sys.exit(3)
parser = optparse.OptionParser()
@@ -71,7 +73,8 @@ parser.add_option('--name', '-m')
parser.add_option('--scan', '-S', default=False, action='store_true')
parser.add_option('--save', '-w', default=False, action='store_true')
parser.add_option('--list-networks', '-l', default=False, action='store_true')
parser.add_option('--network-details', '-d', default=False, action='store_true')
parser.add_option('--network-details', '-d', default=False,
action='store_true')
parser.add_option('--disconnect', '-x', default=False, action='store_true')
parser.add_option('--connect', '-c', default=False, action='store_true')
parser.add_option('--list-encryption-types', '-e', default=False,
@@ -88,8 +91,8 @@ options, arguments = parser.parse_args()
op_performed = False
if not (options.wireless or options.wired) and not options.status:
print(("Please use --wireless or --wired to specify " + \
"the type of connection to operate on."))
print("Please use --wireless or --wired to specify the type of "
"connection to operate on.")
if options.status:
status, info = daemon.GetConnectionStatus()
@@ -109,46 +112,47 @@ if options.status:
print((_('Connection type') + ': ' + conn_type))
if status == misc.WIRELESS:
strength = daemon.FormatSignalForPrinting(info[2])
print((_('Connected to $A at $B (IP: $C)') \
.replace('$A', info[1]) \
.replace('$B', strength) \
.replace('$C', info[0])))
print((_('Network ID: $A') \
.replace('$A', info[3])))
print(_('Connected to $A at $B (IP: $C)')
.replace('$A', info[1])
.replace('$B', strength)
.replace('$C', info[0]))
print(_('Network ID: $A').replace('$A', info[3]))
else:
print((_('Connected to wired network (IP: $A)') \
.replace('$A', info[0])))
print(_('Connected to wired network (IP: $A)')
.replace('$A', info[0]))
else:
if status == misc.CONNECTING:
if info[0] == 'wired':
print((_('Connecting to wired network.')))
print(_('Connecting to wired network.'))
elif info[0] == 'wireless':
print((_('Connecting to wireless network "$A".') \
.replace('$A', info[1])))
print(_('Connecting to wireless network "$A".')
.replace('$A', info[1]))
op_performed = True
# functions
def is_valid_wireless_network_id(network_id):
""" Check if it's a valid wireless network. '"""
if not (network_id >= 0 \
and network_id < wireless.GetNumberOfNetworks()):
"""Check if it's a valid wireless network."""
if not (network_id >= 0 and
network_id < wireless.GetNumberOfNetworks()):
print('Invalid wireless network identifier.')
sys.exit(1)
def is_valid_wired_network_id(network_id):
""" Check if it's a valid wired network. '"""
"""Check if it's a valid wired network. """
num = len(wired.GetWiredProfileList())
if not (network_id < num and \
network_id >= 0):
if not (network_id < num and network_id >= 0):
print('Invalid wired network identifier.')
sys.exit(4)
def is_valid_wired_network_profile(profile_name):
""" Check if it's a valid wired network profile. '"""
if not profile_name in wired.GetWiredProfileList():
"""Check if it's a valid wired network profile. """
if profile_name not in wired.GetWiredProfileList():
print('Profile of that name does not exist.')
sys.exit(5)
if options.scan and options.wireless:
# synchronized scan
wireless.Scan(True)
@@ -163,10 +167,11 @@ if options.list_networks:
if options.wireless:
print('#\tBSSID\t\t\tChannel\tESSID')
for network_id in range(0, wireless.GetNumberOfNetworks()):
print(('%s\t%s\t%s\t%s' % (network_id,
print('%s\t%s\t%s\t%s' %
(network_id,
wireless.GetWirelessProperty(network_id, 'bssid'),
wireless.GetWirelessProperty(network_id, 'channel'),
wireless.GetWirelessProperty(network_id, 'essid'))))
wireless.GetWirelessProperty(network_id, 'essid')))
elif options.wired:
print('#\tProfile name')
i = 0
@@ -186,22 +191,22 @@ if options.network_details:
# we're connected to a network, print IP
print(("IP: %s" % wireless.GetWirelessIP(0)))
print(("Essid: %s" % wireless.GetWirelessProperty(network_id, "essid")))
print(("Bssid: %s" % wireless.GetWirelessProperty(network_id, "bssid")))
print("Essid: %s" % wireless.GetWirelessProperty(network_id, "essid"))
print("Bssid: %s" % wireless.GetWirelessProperty(network_id, "bssid"))
if wireless.GetWirelessProperty(network_id, "encryption"):
print("Encryption: On")
print(("Encryption Method: %s" % \
wireless.GetWirelessProperty(network_id, "encryption_method")))
print("Encryption Method: %s" %
wireless.GetWirelessProperty(network_id,
"encryption_method"))
else:
print("Encryption: Off")
print(("Quality: %s" % \
wireless.GetWirelessProperty(network_id, "quality")))
print(("Mode: %s" % \
wireless.GetWirelessProperty(network_id, "mode")))
print(("Channel: %s" % \
wireless.GetWirelessProperty(network_id, "channel")))
print(("Bit Rates: %s" % \
wireless.GetWirelessProperty(network_id, "bitrates")))
print("Quality: %s" %
wireless.GetWirelessProperty(network_id, "quality"))
print("Mode: %s" % wireless.GetWirelessProperty(network_id, "mode"))
print("Channel: %s" %
wireless.GetWirelessProperty(network_id, "channel"))
print("Bit Rates: %s" %
wireless.GetWirelessProperty(network_id, "bitrates"))
op_performed = True
# network properties
@@ -216,11 +221,11 @@ if options.network_property:
network_id = wireless.GetCurrentNetworkID(0)
is_valid_wireless_network_id(network_id)
if not options.set_to:
print((wireless.GetWirelessProperty(network_id,
options.network_property)))
print(wireless.GetWirelessProperty(network_id,
options.network_property))
else:
wireless.SetWirelessProperty(network_id, \
options.network_property, options.set_to)
wireless.SetWirelessProperty(network_id, options.network_property,
options.set_to)
elif options.wired:
if not options.set_to:
print((wired.GetWiredProperty(options.network_property)))
@@ -232,13 +237,13 @@ if options.disconnect:
daemon.Disconnect()
if options.wireless:
if wireless.GetCurrentNetworkID(0) > -1:
print(("Disconnecting from %s on %s" % \
print("Disconnecting from %s on %s" %
(wireless.GetCurrentNetwork(0),
wireless.DetectWirelessInterface())))
wireless.DetectWirelessInterface()))
elif options.wired:
if wired.CheckPluggedIn():
print(("Disconnecting from wired connection on %s" % \
wired.DetectWiredInterface()))
print("Disconnecting from wired connection on %s" %
wired.DetectWiredInterface())
op_performed = True
if options.connect:
@@ -247,16 +252,16 @@ if options.connect:
is_valid_wireless_network_id(options.network)
name = wireless.GetWirelessProperty(options.network, 'essid')
encryption = wireless.GetWirelessProperty(options.network, 'enctype')
print(("Connecting to %s with %s on %s" % (name, encryption,
wireless.DetectWirelessInterface())))
print("Connecting to %s with %s on %s" %
(name, encryption, wireless.DetectWirelessInterface()))
wireless.ConnectWireless(options.network)
check = wireless.CheckIfWirelessConnecting
status = wireless.CheckWirelessConnectingStatus
message = wireless.CheckWirelessConnectingMessage
elif options.wired:
print(("Connecting to wired connection on %s" % \
wired.DetectWiredInterface()))
print("Connecting to wired connection on %s" %
wired.DetectWiredInterface())
wired.ConnectWired()
check = wired.CheckIfWiredConnecting
@@ -273,8 +278,8 @@ if options.connect:
while check():
next_ = status()
if next_ != last:
# avoid a race condition where status is updated to "done" after
# the loop check
# avoid a race condition where status is updated to "done"
# after the loop check
if next_ == "done":
break
print((message()))
@@ -284,6 +289,7 @@ if options.connect:
exit_status = 6
op_performed = True
def str_properties(prop):
"""Pretty print optional and required properties."""
if len(prop) == 0:
@@ -292,6 +298,7 @@ def str_properties(prop):
tmp = [(x[0], x[1].replace('_', ' ')) for x in type['required']]
return ', '.join("%s (%s)" % (x, y) for x, y in tmp)
if options.wireless and options.list_encryption_types:
et = misc.LoadEncryptionMethods()
# print 'Installed encryption templates:'
@@ -318,4 +325,3 @@ if not op_performed:
print("No operations performed.")
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,
# MA 02110-1301, USA.
import sys
import os
import urwid
import urwid.curses_display
from wicd.translations import _
from configscript import write_scripts, get_script_info
from configscript import none_to_blank, blank_to_none
import urwid
import urwid.curses_display
import sys
import os
ui = None
frame = None
pre_entry = None
@@ -49,13 +50,11 @@ def main(argv):
sys.exit(1)
ui = urwid.curses_display.Screen()
ui.register_palette([
('body', 'default', 'default'),
ui.register_palette([('body', 'default', 'default'),
('focus', 'dark magenta', 'light gray'),
('editcp', 'default', 'default', 'standout'),
('editbx', 'light gray', 'dark blue'),
('editfc', 'white', 'dark blue', 'bold'),
])
('editfc', 'white', 'dark blue', 'bold')])
network = argv[1]
network_type = argv[2]
@@ -70,28 +69,28 @@ def main(argv):
global pre_entry, post_entry, pre_disconnect_entry, post_disconnect_entry
pre_entry = urwid.AttrWrap(urwid.Edit(pre_entry_t,
none_to_blank(script_info.get('pre_entry'))),
none_to_blank(script_info.
get('pre_entry'))),
'editbx', 'editfc')
post_entry = urwid.AttrWrap(urwid.Edit(post_entry_t,
none_to_blank(script_info.get('post_entry'))),
none_to_blank(script_info.
get('post_entry'))),
'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'))),
'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'))),
'editbx', 'editfc')
# The buttons
ok_button = urwid.AttrWrap(
urwid.Button(_('OK'), ok_callback),
'body', 'focus'
)
cancel_button = urwid.AttrWrap(
urwid.Button(_('Cancel'), cancel_callback),
'body', 'focus'
)
ok_button = urwid.AttrWrap(urwid.Button(_('OK'), ok_callback), 'body',
'focus')
cancel_button = urwid.AttrWrap(urwid.Button(_('Cancel'), cancel_callback),
'body', 'focus')
button_cols = urwid.Columns([ok_button, cancel_button], dividechars=1)
@@ -101,20 +100,20 @@ def main(argv):
('fixed', 2, urwid.Filler(pre_disconnect_entry)),
('fixed', 2, urwid.Filler(post_disconnect_entry)),
# blank, blank, blank, blank, blank,
urwid.Filler(button_cols, 'bottom')
])
urwid.Filler(button_cols, 'bottom')])
frame = urwid.Frame(lbox)
result = ui.run_wrapper(run)
if result:
script_info["pre_entry"] = blank_to_none(pre_entry.get_edit_text())
script_info["post_entry"] = blank_to_none(post_entry.get_edit_text())
script_info["pre_disconnect_entry"] = \
blank_to_none(pre_disconnect_entry.get_edit_text())
script_info["post_disconnect_entry"] = \
blank_to_none(post_disconnect_entry.get_edit_text())
script_info["pre_disconnect_entry"] = blank_to_none(
pre_disconnect_entry.get_edit_text())
script_info["post_disconnect_entry"] = blank_to_none(
post_disconnect_entry.get_edit_text())
write_scripts(network, network_type, script_info)
OK_PRESSED = False
CANCEL_PRESSED = False
@@ -159,6 +158,7 @@ def run():
if OK_PRESSED or 'meta enter' in keys:
return True
if __name__ == '__main__':
if os.getuid() != 0:
print("Root privileges are required to configure scripts. Exiting.")

View File

@@ -163,7 +163,7 @@ class MaskingEdit(urwid.Edit):
mask_mode="always", mask_char='*'):
self.mask_mode = mask_mode
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!')
self.mask_char = mask_char
# pylint: disable-msg=E1101
@@ -195,8 +195,8 @@ class MaskingEdit(urwid.Edit):
if self.mask_mode == "off" or (self.mask_mode == 'no_focus' and focus):
# pylint: disable-msg=E1101
canv = self.__super.render((maxcol, ), focus)
# The cache messes this thing up, because I am totally changing what
# is displayed.
# The cache messes this thing up, because I am totally changing
# what is displayed.
self._invalidate()
return canv
@@ -226,7 +226,8 @@ class TabColumns(urwid.WidgetWrap):
# FIXME Make the bottom_part optional
# pylint: disable-msg=W0231
def __init__(self, tab_str, tab_wid, title, bottom_part=None,
attr=('body', 'focus'), attrsel='tab active', attrtitle='header'):
attr=('body', 'focus'), attrsel='tab active',
attrtitle='header'):
# self.bottom_part = bottom_part
# title_wid = urwid.Text((attrtitle, title), align='right')
column_list = []
@@ -247,11 +248,11 @@ class TabColumns(urwid.WidgetWrap):
def gen_pile(self, lbox, firstrun=False):
"""Make the pile in the middle."""
self.pile = urwid.Pile([
('fixed', 1, urwid.Filler(self.columns, 'top')),
urwid.Filler(lbox, 'top', height=('relative', 99)),
#('fixed', 1, urwid.Filler(self.bottom_part, 'bottom'))
])
self.pile = urwid.Pile([('fixed', 1,
urwid.Filler(self.columns, 'top')),
urwid.Filler(lbox, 'top',
height=('relative', 99))])
# ('fixed', 1, urwid.Filler(self.bottom_part, 'bottom'))])
if not firstrun:
self.frame.set_body(self.pile)
self._w = self.frame
@@ -314,11 +315,11 @@ class ComboBox(urwid.WidgetWrap):
class ComboSpace(urwid.WidgetWrap):
"""The actual menu-like space that comes down from the ComboBox"""
# pylint: disable-msg=W0231
def __init__(self, l, body, ui, show_first, pos=(0, 0),
def __init__(self, data, body, ui, show_first, pos=(0, 0),
attr=('body', 'focus')):
"""
body : parent widget
l : stuff to include in the combobox
data : stuff to include in the combobox
ui : the screen
show_first: index of the element in the list to pick first
pos : a tuple of (row,col) where to put the list
@@ -326,18 +327,19 @@ class ComboBox(urwid.WidgetWrap):
"""
# Calculate width and height of the menu widget:
height = len(l)
height = len(data)
width = 0
for entry in l:
for entry in data:
if len(entry) > width:
width = len(entry)
content = [urwid.AttrWrap(SelText(w), attr[0], attr[1])
for w in l]
for w in data]
self._listbox = urwid.ListBox(content)
self._listbox.set_focus(show_first)
overlay = urwid.Overlay(self._listbox, body, ('fixed left', pos[0]),
width + 2, ('fixed top', pos[1]), height)
overlay = urwid.Overlay(self._listbox, body,
('fixed left', pos[0]), width + 2,
('fixed top', pos[1]), height)
# pylint: disable-msg=E1101
self.__super.__init__(overlay)
@@ -369,13 +371,13 @@ class ComboBox(urwid.WidgetWrap):
# def get_size(self):
# 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,
user_args=None):
"""
label : bit of text that preceeds the combobox. If it is "", then
ignore it
l : stuff to include in the combobox
data : stuff to include in the combobox
body : parent widget
ui : the screen
row : where this object is to be found onscreen
@@ -388,9 +390,9 @@ class ComboBox(urwid.WidgetWrap):
self.label = urwid.Text(label)
self.attrs = attrs
self.focus_attr = focus_attr
if l is None:
l = []
self.list = l
if data is None:
data = []
self.list = data
s, trash = self.label.get_text()
@@ -424,9 +426,9 @@ class ComboBox(urwid.WidgetWrap):
self.ui = None
self.row = None
def set_list(self, l):
def set_list(self, data):
"""Populate widget list."""
self.list = l
self.list = data
def set_focus(self, index):
"""Set widget focus."""
@@ -508,7 +510,7 @@ class ComboBox(urwid.WidgetWrap):
if urwid.VERSION < (1, 1, 0):
return None, self.focus
else:
return None, self._w.focus_position # pylint: disable-msg=E1103
return None, self._w.focus_position
def get_sensitive(self):
"""Return widget sensitivity."""
@@ -554,16 +556,16 @@ class Dialog2(urwid.WidgetWrap):
# buttons: tuple of name,exitcode
def add_buttons(self, buttons):
"""Add buttons."""
l = []
data = []
maxlen = 0
for name, exitcode in buttons:
b = urwid.Button(name, self.button_press)
b.exitcode = exitcode
b = urwid.AttrWrap(b, 'body', 'focus')
l.append(b)
data.append(b)
maxlen = max(len(name), maxlen)
maxlen += 4 # because of '< ... >'
self.buttons = urwid.GridFlow(l, maxlen, 3, 1, 'center')
self.buttons = urwid.GridFlow(data, maxlen, 3, 1, 'center')
self.frame.footer = urwid.Pile([
urwid.Divider(),
self.buttons
@@ -622,8 +624,8 @@ class TextDialog(Dialog2):
"""Simple dialog with text and "OK" button."""
def __init__(self, text, height, width, header=None, align='left',
buttons=(_('OK'), 1)):
l = [urwid.Text(text)]
body = urwid.ListBox(l)
data = [urwid.Text(text)]
body = urwid.ListBox(data)
body = urwid.AttrWrap(body, 'body')
Dialog2.__init__(self, header, height + 2, width + 2, body)
@@ -681,7 +683,8 @@ class ClickCols(urwid.WidgetWrap):
def mouse_event(self, size, event, button, x, y, focus):
"""Handle mouse events."""
if event == "mouse press":
# The keypress dealie in wicd-curses.py expects a list of keystrokes
# The keypress dealie in wicd-curses.py expects a list of
# keystrokes
self.callback([self.args])
@@ -692,7 +695,8 @@ class OptCols(urwid.WidgetWrap):
# handler = function passed the key of the "button" pressed
# mentions of 'left' and right will be converted to <- and -> respectively
# pylint: disable-msg=W0231
def __init__(self, tuples, handler, attrs=('body', 'infobar'), debug=False):
def __init__(self, tuples, handler, attrs=('body', 'infobar'),
debug=False):
# Find the longest string. Keys for this bar should be no greater than
# 2 characters long (e.g., -> for left)
# maxlen = 6

View File

@@ -20,6 +20,7 @@
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
import os
import urwid
from curses_misc import DynWrap, MaskingEdit, ComboBox, error
@@ -27,7 +28,6 @@ import wicd.misc as misc
from wicd.misc import noneToString, stringToNone, noneToBlankString, to_bool
from wicd.translations import language, _
import os
daemon = None
wired = None
@@ -47,10 +47,10 @@ class AdvancedSettingsDialog(urwid.WidgetWrap):
"""
Settings dialog.
Both the wired and the wireless settings preferences dialogs use some of the
same fields.
This will be used to produce the individual network settings dialogs way far
below.
Both the wired and the wireless settings preferences dialogs use some of
the same fields.
This will be used to produce the individual network settings dialogs way
far below.
"""
# pylint: disable-msg=W0231
def __init__(self):
@@ -84,28 +84,20 @@ class AdvancedSettingsDialog(urwid.WidgetWrap):
cancel_t = _('Cancel')
ok_t = _('OK')
self.static_ip_cb = urwid.CheckBox(static_ip_t,
on_state_change=self.static_ip_toggle)
self.static_ip_cb = urwid.CheckBox(
static_ip_t, on_state_change=self.static_ip_toggle)
self.ip_edit = DynWrap(urwid.Edit(ip_t), False)
self.netmask_edit = DynWrap(urwid.Edit(netmask_t), False)
self.gateway_edit = DynWrap(urwid.Edit(gateway_t), False)
self.static_dns_cb = DynWrap(
urwid.CheckBox(use_static_dns_t, on_state_change=self.dns_toggle),
True,
('body', 'editnfc'),
None
)
True, ('body', 'editnfc'), None)
self.global_dns_cb = DynWrap(
urwid.CheckBox(use_global_dns_t, on_state_change=self.dns_toggle),
False,
('body', 'editnfc'),
None
)
self.checkb_cols = urwid.Columns([
self.static_dns_cb,
self.global_dns_cb
])
False, ('body', 'editnfc'), None)
self.checkb_cols = urwid.Columns([self.static_dns_cb,
self.global_dns_cb])
self.dns_dom_edit = DynWrap(urwid.Edit(dns_dom_t), False)
self.search_dom_edit = DynWrap(urwid.Edit(search_dom_t), False)
self.dns1 = DynWrap(urwid.Edit(dns1_t), False)
@@ -113,10 +105,8 @@ class AdvancedSettingsDialog(urwid.WidgetWrap):
self.dns3 = DynWrap(urwid.Edit(dns3_t), False)
self.use_dhcp_h = urwid.CheckBox(
use_dhcp_h_t,
False,
on_state_change=self.use_dhcp_h_toggle
)
use_dhcp_h_t, False,
on_state_change=self.use_dhcp_h_toggle)
self.dhcp_h = DynWrap(urwid.Edit(dhcp_h_t), False)
_blank = urwid.Text('')
@@ -174,8 +164,8 @@ class AdvancedSettingsDialog(urwid.WidgetWrap):
self.global_dns_cb.set_sensitive(new_state)
# use_global_dns_cb is DynWrapped
if checkb == self.global_dns_cb.get_w():
for w in [self.dns_dom_edit, self.search_dom_edit,
self.dns1, self.dns2, self.dns3 ]:
for w in [self.dns_dom_edit, self.search_dom_edit, self.dns1,
self.dns2, self.dns3]:
w.set_sensitive(not new_state)
def set_net_prop(self, option, value):
@@ -219,12 +209,13 @@ class AdvancedSettingsDialog(urwid.WidgetWrap):
self.set_net_prop('dns_domain',
noneToString(self.dns_dom_edit.get_edit_text()))
self.set_net_prop("search_domain",
noneToString(self.search_dom_edit.get_edit_text()))
noneToString(self.search_dom_edit
.get_edit_text()))
self.set_net_prop("dns1", noneToString(self.dns1.get_edit_text()))
self.set_net_prop("dns2", noneToString(self.dns2.get_edit_text()))
self.set_net_prop("dns3", noneToString(self.dns3.get_edit_text()))
elif self.static_dns_cb.get_state() and \
self.global_dns_cb.get_state():
elif (self.static_dns_cb.get_state() and
self.global_dns_cb.get_state()):
self.set_net_prop('use_static_dns', True)
self.set_net_prop('use_global_dns', True)
else:
@@ -288,18 +279,18 @@ class AdvancedSettingsDialog(urwid.WidgetWrap):
wired.GetWiredProperty(field[0])))
else:
edit.set_edit_text(noneToBlankString(
wireless.GetWirelessProperty(self.networkid, field[0])))
wireless.GetWirelessProperty(self.networkid,
field[0])))
# FIXME: This causes the entire pile to light up upon use.
# Make this into a listbox?
self.pile_encrypt = DynWrap(
urwid.Pile(theList),
attrs=('editbx', 'editnfc')
)
self.pile_encrypt = DynWrap(urwid.Pile(theList),
attrs=('editbx', 'editnfc'))
self.pile_encrypt.set_sensitive(self.encryption_chkbox.get_state())
self._w.body.body.insert(self._w.body.body.__len__(), self.pile_encrypt)
self._w.body.body.insert(self._w.body.body.__len__(),
self.pile_encrypt)
# self._w.body.body.append(self.pile_encrypt)
def encryption_toggle(self, chkbox, new_state, user_data=None):
@@ -315,8 +306,7 @@ class WiredSettingsDialog(AdvancedSettingsDialog):
self.wired = True
self.set_default = urwid.CheckBox(
_('Use as default profile (overwrites any previous default)')
)
_('Use as default profile (overwrites any previous default)'))
# self.cur_default =
# Add widgets to listbox
self._w.body.body.append(self.set_default)
@@ -375,13 +365,13 @@ class WiredSettingsDialog(AdvancedSettingsDialog):
self.set_default.set_state(to_bool(wired.GetWiredProperty("default")))
# Throw the encryption stuff into a list
l = []
combo_items = []
activeID = -1 # Set the menu to this item when we are done
for x, enc_type in enumerate(self.encrypt_types):
l.append(enc_type['name'])
combo_items.append(enc_type['name'])
if enc_type['type'] == wired.GetWiredProperty("enctype"):
activeID = x
self.encryption_combo.set_list(l)
self.encryption_combo.set_list(combo_items)
self.encryption_combo.set_focus(activeID)
if wired.GetWiredProperty("encryption_enabled"):
@@ -502,17 +492,21 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
self.encrypt_types = misc.LoadEncryptionMethods()
self.set_values()
title = _('Configuring preferences for wireless network "$A" ($B)'). \
replace('$A', wireless.GetWirelessProperty(networkID, 'essid')). \
replace('$B', wireless.GetWirelessProperty(networkID, 'bssid'))
title = (_('Configuring preferences for wireless network "$A" ($B)')
.replace('$A', wireless.GetWirelessProperty(networkID,
'essid'))
.replace('$B', wireless.GetWirelessProperty(networkID,
'bssid')))
self._w.header = urwid.Text(('header', title), align='right')
def set_values(self):
"""Set the various network settings to the right values."""
networkID = self.networkid
self.ip_edit.set_edit_text(self.format_entry(networkID, "ip"))
self.netmask_edit.set_edit_text(self.format_entry(networkID, "netmask"))
self.gateway_edit.set_edit_text(self.format_entry(networkID, "gateway"))
self.netmask_edit.set_edit_text(self.format_entry(networkID,
"netmask"))
self.gateway_edit.set_edit_text(self.format_entry(networkID,
"gateway"))
self.global_dns_cb.set_state(
bool(wireless.GetWirelessProperty(networkID, 'use_global_dns')))
@@ -552,21 +546,18 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
bool(wireless.GetWirelessProperty(networkID, 'encryption')),
do_callback=False)
self.global_settings_chkbox.set_state(
bool(wireless.GetWirelessProperty(
networkID,
'use_settings_globally')
)
)
bool(wireless.GetWirelessProperty(networkID,
'use_settings_globally')))
# Throw the encryption stuff into a list
l = []
combo_items = []
activeID = -1 # Set the menu to this item when we are done
for x, enc_type in enumerate(self.encrypt_types):
l.append(enc_type['name'])
if enc_type['type'] == \
wireless.GetWirelessProperty(networkID, "enctype"):
combo_items.append(enc_type['name'])
if enc_type['type'] == wireless.GetWirelessProperty(networkID,
"enctype"):
activeID = x
self.encryption_combo.set_list(l)
self.encryption_combo.set_list(combo_items)
self.encryption_combo.set_focus(activeID)
if activeID != -1:
@@ -592,7 +583,8 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
def format_entry(self, networkid, label):
"""Helper method for fetching/formatting wireless properties."""
return noneToBlankString(wireless.GetWirelessProperty(networkid, label))
return noneToBlankString(wireless.GetWirelessProperty(networkid,
label))
# Ripped from netentry.py
def save_settings(self):
@@ -607,29 +599,21 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
)
# Make sure all required fields are filled in.
for entry_info in list(encrypt_info.values()):
if entry_info[0].get_edit_text() == "" \
and entry_info[1] == 'required':
error(
self.ui,
self.parent,
"%s (%s)" % (
_('Required encryption information is missing.'),
entry_info[0].get_caption()[0:-2]
)
)
if (entry_info[0].get_edit_text() == "" and
entry_info[1] == 'required'):
error(self.ui, self.parent, "%s (%s)" %
(_('Required encryption information is missing.'),
entry_info[0].get_caption()[0:-2]))
return False
for entry_key, entry_info in list(encrypt_info.items()):
self.set_net_prop(entry_key, noneToString(entry_info[0].
get_edit_text()))
elif not self.encryption_chkbox.get_state() and \
wireless.GetWirelessProperty(self.networkid, "encryption"):
elif (not self.encryption_chkbox.get_state() and
wireless.GetWirelessProperty(self.networkid, "encryption")):
# Encrypt checkbox is off, but the network needs it.
error(
self.ui,
self.parent,
_('This network requires encryption to be enabled.')
)
error(self.ui, self.parent,
_('This network requires encryption to be enabled.'))
return False
else:
self.set_net_prop("enctype", "None")

View File

@@ -55,7 +55,8 @@ class PrefsDialog(urwid.WidgetWrap):
header0_t = _('General Settings')
header1_t = _('External Programs')
header2_t = _('Advanced Settings')
self.header0 = urwid.AttrWrap(SelText(header0_t), 'tab active', 'focus')
self.header0 = urwid.AttrWrap(SelText(header0_t), 'tab active',
'focus')
self.header1 = urwid.AttrWrap(SelText(header1_t), 'body', 'focus')
self.header2 = urwid.AttrWrap(SelText(header2_t), 'body', 'focus')
title = ('Preferences')
@@ -63,9 +64,7 @@ class PrefsDialog(urwid.WidgetWrap):
# Blank line
_blank = urwid.Text('')
####
#### Text in the widgets
####
# Text in the widgets
# General Settings
net_cat_t = ('header', ('Network Interfaces'))
@@ -90,7 +89,7 @@ class PrefsDialog(urwid.WidgetWrap):
auto_reconn_cat_t = ('header', _('Automatic Reconnection'))
auto_reconn_t = _('Automatically reconnect on connection loss')
#### External Programs
# External Programs
automatic_t = _('Automatic (recommended)')
dhcp_header_t = ('header', _('DHCP Client'))
@@ -108,12 +107,12 @@ class PrefsDialog(urwid.WidgetWrap):
flush1_t = 'ip'
flush2_t = 'route'
#### Advanced Settings
# Advanced Settings
wpa_cat_t = ('header', _('WPA Supplicant'))
wpa_t = ('editcp', 'Driver:')
wpa_list = []
wpa_warn_t = ('important',
_('You should almost always use wext as the WPA supplicant driver'))
wpa_warn_t = ('important', _('You should almost always use wext as '
'the WPA supplicant driver'))
backend_cat_t = ('header', _('Backend'))
backend_t = _('Backend') + ':'
@@ -124,12 +123,10 @@ class PrefsDialog(urwid.WidgetWrap):
wless_cat_t = ('header', _('Wireless Interface'))
use_dbm_t = _('Use dBm to measure signal strength')
verify_ap_t = \
_('Ping static gateways after connecting to verify association')
verify_ap_t = _('Ping static gateways after connecting to verify '
'association')
####
#### UI Widgets
####
# UI Widgets
# General Settings
self.net_cat = urwid.Text(net_cat_t)
@@ -142,10 +139,9 @@ class PrefsDialog(urwid.WidgetWrap):
# Default the global DNS settings to off. They will be reenabled later
# if so required.
global_dns_state = False
self.global_dns_checkb = urwid.CheckBox(global_dns_t,
global_dns_state,
on_state_change=self.global_dns_trigger
)
self.global_dns_checkb = urwid.CheckBox(global_dns_t, global_dns_state,
on_state_change=self.
global_dns_trigger)
self.search_dom = DynWrap(urwid.Edit(search_dom_t), global_dns_state)
self.dns_dom = DynWrap(urwid.Edit(dns_dom_t), global_dns_state)
self.dns1 = DynWrap(urwid.Edit(dns1_t), global_dns_state)
@@ -156,9 +152,12 @@ class PrefsDialog(urwid.WidgetWrap):
self.wired_auto_l = []
self.wired_auto_cat = urwid.Text(wired_auto_cat_t)
self.wired_auto_1 = urwid.RadioButton(self.wired_auto_l, wired_auto_1_t)
self.wired_auto_2 = urwid.RadioButton(self.wired_auto_l, wired_auto_2_t)
self.wired_auto_3 = urwid.RadioButton(self.wired_auto_l, wired_auto_3_t)
self.wired_auto_1 = urwid.RadioButton(self.wired_auto_l,
wired_auto_1_t)
self.wired_auto_2 = urwid.RadioButton(self.wired_auto_l,
wired_auto_2_t)
self.wired_auto_3 = urwid.RadioButton(self.wired_auto_l,
wired_auto_2_t)
self.auto_reconn_cat = urwid.Text(auto_reconn_cat_t)
self.auto_reconn_checkb = urwid.CheckBox(auto_reconn_t)
@@ -180,7 +179,8 @@ class PrefsDialog(urwid.WidgetWrap):
self.auto_reconn_checkb
])
#### External Programs tab
# External Programs tab
automatic_t = _('Automatic (recommended)')
self.dhcp_header = urwid.Text(dhcp_header_t)
@@ -223,7 +223,8 @@ class PrefsDialog(urwid.WidgetWrap):
self.flush0, self.flush1, self.flush2
])
#### Advanced settings
# Advanced settings
self.wpa_cat = urwid.Text(wpa_cat_t)
self.wpa_cbox = ComboBox(wpa_t)
self.wpa_warn = urwid.Text(wpa_warn_t)
@@ -257,6 +258,7 @@ class PrefsDialog(urwid.WidgetWrap):
self.header1: externalLB,
self.header2: advancedLB
}
# self.load_settings()
self.tabs = TabColumns(headerList, lbList, _('Preferences'))
@@ -265,7 +267,7 @@ class PrefsDialog(urwid.WidgetWrap):
def load_settings(self):
"""Load settings to be used in the dialog."""
### General Settings
# General Settings
# ComboBox does not like dbus.Strings as text markups. My fault. :/
wless_iface = str(daemon.GetWirelessInterface())
wired_iface = str(daemon.GetWiredInterface())
@@ -280,7 +282,8 @@ class PrefsDialog(urwid.WidgetWrap):
theDNS = daemon.GetGlobalDNSAddresses()
i = 0
for w in self.dns1, self.dns2, self.dns3, self.dns_dom, self.search_dom:
for w in (self.dns1, self.dns2, self.dns3, self.dns_dom,
self.search_dom):
w.set_edit_text(misc.noneToBlankString(theDNS[i]))
i += 1
@@ -293,7 +296,7 @@ class PrefsDialog(urwid.WidgetWrap):
for app in apps[1:]:
app.set_sensitive(daemon.GetAppAvailable(app.get_label()))
### External Programs
# External Programs
find_avail(self.dhcp_l)
dhcp_method = daemon.GetDHCPClient()
self.dhcp_l[dhcp_method].set_state(True)
@@ -306,7 +309,7 @@ class PrefsDialog(urwid.WidgetWrap):
flush_method = daemon.GetFlushTool()
self.flush_l[flush_method].set_state(True)
### Advanced settings
# Advanced settings
# wpa_supplicant janx
self.wpadrivers = wireless.GetWpaSupplicantDrivers()
self.wpadrivers.append("ralink_legacy")
@@ -405,7 +408,8 @@ class PrefsDialog(urwid.WidgetWrap):
def global_dns_trigger(self, check_box, new_state, user_data=None):
"""DNS CheckBox callback."""
for w in self.dns1, self.dns2, self.dns3, self.dns_dom, self.search_dom:
for w in (self.dns1, self.dns2, self.dns3, self.dns_dom,
self.search_dom):
w.set_sensitive(new_state)
def ready_widgets(self, ui, body):

View File

@@ -35,29 +35,20 @@ at least get a network connection. Or those who don't like using X and/or GTK.
# Filter out a confusing urwid warning in python 2.6.
# This is valid as of urwid version 0.9.8.4
from optparse import OptionParser
import signal
import sys
import warnings
warnings.filterwarnings(
"ignore",
"The popen2 module is deprecated. Use the subprocess module."
)
# UI stuff
import urwid
# DBus communication stuff
import urwid
from dbus import DBusException
# It took me a while to figure out that I have to use this.
from gi.repository import GLib as gobject
# Other important wicd-related stuff
from wicd import wpath
from wicd import misc
from wicd import dbusmanager
# Internal Python stuff
import sys
# SIGQUIT signal handling
import signal
from wicd.translations import _
# Curses UIs for other stuff
from curses_misc import ComboBox, Dialog2, NSelListBox, SelText, OptCols
@@ -67,8 +58,6 @@ from prefs_curses import PrefsDialog
import netentry_curses
from netentry_curses import WirelessSettingsDialog, WiredSettingsDialog
from optparse import OptionParser
# Stuff about getting the script configurer running
# from grp import getgrgid
# from os import getgroups, system
@@ -80,15 +69,16 @@ CURSES_REV = wpath.curses_revision
# Fix strings in wicd-curses
# from wicd.translations import language
from wicd.translations import _
warnings.filterwarnings(
"ignore",
"The popen2 module is deprecated. Use the subprocess module."
)
ui = None
loop = None
bus = daemon = wireless = wired = None
########################################
##### SUPPORT CLASSES
########################################
# Yay for decorators!
def wrap_exceptions(func):
"""Decorator to wrap exceptions."""
@@ -104,12 +94,12 @@ def wrap_exceptions(func):
except DBusException:
loop.quit()
ui.stop()
print("\n" + _('DBus failure! '
'This is most likely caused by the wicd daemon '
'stopping while wicd-curses is running. '
'Please restart the daemon, and then restart wicd-curses.'), file=sys.stderr)
print("\n" + _('DBus failure! This is most likely caused by the '
'wicd daemon stopping while wicd-curses is '
'running. Please restart the daemon, and then '
'restart wicd-curses.'), file=sys.stderr)
raise
except:
except Exception:
# Quit the loop
# if 'loop' in locals():
loop.quit()
@@ -133,19 +123,14 @@ def wrap_exceptions(func):
return wrapper
########################################
##### SUPPORT FUNCTIONS
########################################
# Look familiar? These two functions are clones of functions found in wicd's
# gui.py file, except that now set_status is a function passed to them.
@wrap_exceptions
def check_for_wired(wired_ip, set_status):
"""Determine if wired is active, and if yes, set the status."""
if wired_ip and wired.CheckPluggedIn():
set_status(
_('Connected to wired network (IP: $A)').replace('$A',wired_ip)
)
set_status(_('Connected to wired network (IP: $A)')
.replace('$A', wired_ip))
return True
else:
return False
@@ -171,10 +156,10 @@ def check_for_wireless(iwconfig, wireless_ip, set_status):
return False
strength = misc.to_unicode(daemon.FormatSignalForPrinting(strength))
ip = misc.to_unicode(wireless_ip)
set_status(_('Connected to $A at $B (IP: $C)').replace
('$A', network).replace
('$B', strength).replace
('$C', ip))
set_status(_('Connected to $A at $B (IP: $C)')
.replace('$A', network)
.replace('$B', strength)
.replace('$C', ip))
return True
@@ -188,10 +173,10 @@ def gen_network_list():
wlessL = []
# This one makes a list of NetLabels
for network_id in range(0, wireless.GetNumberOfNetworks()):
is_active = \
wireless.GetCurrentSignalStrength("") != 0 and \
wireless.GetCurrentNetworkID(wireless.GetIwconfig()) == network_id \
and wireless.GetWirelessIP('') is not None
is_active = (wireless.GetCurrentSignalStrength("") != 0 and
wireless.GetCurrentNetworkID(wireless.GetIwconfig()) ==
network_id and
wireless.GetWirelessIP('') is not None)
label = NetLabel(network_id, is_active)
wlessL.append(label)
@@ -203,20 +188,24 @@ def about_dialog(body):
# This looks A LOT better when it is actually displayed. I promise :-).
# The ASCII Art "Wicd" was made from the "smslant" font on one of those
# online ASCII big text generators.
theText = [
('green', " /// \\\\\\"), " _ ___ __\n",
('green', " /// \\\\\\"), " | | /| / (_)______/ /\n",
('green', " /// \\\\\\"), " | |/ |/ / / __/ _ / \n",
('green', "/|| // \\\\ ||\\"), " |__/|__/_/\__/\_,_/ \n",
theText = [('green', " /// \\\\\\"),
" _ ___ __\n",
('green', " /// \\\\\\"),
" | | /| / (_)______/ /\n",
('green', " /// \\\\\\"),
" | |/ |/ / / __/ _ / \n",
('green', "/|| // \\\\ ||\\"),
" |__/|__/_/\__/\_,_/ \n",
('green', "||| ||"), "(|^|)", ('green', "|| |||"),
" ($VERSION) \n".replace("$VERSION", daemon.Hello()),
" ($VERSION) \n".replace("$VERSION",
daemon.Hello()),
('green', "\\|| \\\\"), " |+| ", ('green', "// ||/ \n"),
('green', " \\\\\\"), " |+| ", ('green', "///"),
" http://launchpad.net/wicd\n",
('green', " \\\\\\"), " |+| ", ('green', "///"), " ",
_('Brought to you by:'), "\n",
('green', " \\\\\\"), " |+| ", ('green', "///"), " * Tom Van Braeckel\n",
('green', " \\\\\\"), " |+| ",
('green', "///"), " * Tom Van Braeckel\n",
" __|+|__ * Adam Blackburn\n",
" ___|+|___ * Dan O'Reilly\n",
" ____|+|____ * Andrew Psaltis\n",
@@ -234,32 +223,41 @@ def help_dialog(body):
' using wicd ', str(daemon.Hello()), '\n'
])
textH = urwid.Text([
_('For more detailed help, consult the wicd-curses(8) man page.') + "\n",
('bold', '->'), ' and ', ('bold', '<-'),
" are the right and left arrows respectively.\n"
])
textH = urwid.Text([_('For more detailed help, consult the wicd-curses(8) '
'man page.') + "\n", ('bold', '->'), ' and ',
('bold', '<-'), " are the right and left arrows "
"respectively.\n"])
text1 = urwid.Text([
('bold', ' H h ?'), ": " + _('Display this help dialog') + "\n",
('bold', 'enter C'), ": " + _('Connect to selected network') + "\n",
('bold', ' D'), ": " + _('Disconnect from all networks') + "\n",
('bold', ' ESC'), ": " + _('Stop a connection in progress') + "\n",
('bold', ' F5 R'), ": " + _('Refresh network list') + "\n",
('bold', ' P'), ": " + _('Preferences dialog') + "\n",
])
text2 = urwid.Text([
('bold', ' I'), ": " + _('Scan for hidden networks') + "\n",
('bold', ' S'), ": " + _('Select scripts') + "\n",
('bold', ' O'), ": " + _('Set up Ad-hoc network') + "\n",
('bold', ' X'), ": " + _('Remove settings for saved networks') + "\n",
('bold', ' ->'), ": " + _('Configure selected network') + "\n",
('bold', ' A'), ": " + _("Display 'about' dialog") + "\n",
('bold', ' F8 q Q'), ": " + _('Quit wicd-curses') + "\n",
])
text1 = urwid.Text([('bold', ' H h ?'),
": " + _('Display this help dialog') + "\n",
('bold', 'enter C'),
": " + _('Connect to selected network') + "\n",
('bold', ' D'),
": " + _('Disconnect from all networks') + "\n",
('bold', ' ESC'),
": " + _('Stop a connection in progress') + "\n",
('bold', ' F5 R'),
": " + _('Refresh network list') + "\n",
('bold', ' P'),
": " + _('Preferences dialog') + "\n"])
text2 = urwid.Text([('bold', ' I'),
": " + _('Scan for hidden networks') + "\n",
('bold', ' S'),
": " + _('Select scripts') + "\n",
('bold', ' O'),
": " + _('Set up Ad-hoc network') + "\n",
('bold', ' X'),
": " + _('Remove settings for saved networks') + "\n",
('bold', ' ->'),
": " + _('Configure selected network') + "\n",
('bold', ' A'),
": " + _("Display 'about' dialog") + "\n",
('bold', ' F8 q Q'),
": " + _('Quit wicd-curses') + "\n"])
textF = urwid.Text(_('Press any key to return.'))
#textJ = urwid.Text(('important', 'Nobody expects the Spanish Inquisition!'))
# textJ = urwid.Text(('important',
# 'Nobody expects the Spanish Inquisition!'))
blank = urwid.Text('')
@@ -301,22 +299,25 @@ def run_configscript(parent, netname, nettype):
profname = nettype
else:
profname = wireless.GetWirelessProperty(int(netname), 'bssid')
theText = [
_('To avoid various complications, wicd-curses does not support directly '
'editing the scripts. However, you can edit them manually. First, (as root), '
'open the "$A" config file, and look for the section labeled by the $B in '
'question. In this case, this is:').
replace('$A', configfile).replace('$B', header),
theText = [_('To avoid various complications, wicd-curses does not '
'support directly editing the scripts. However, you can '
'edit them manually. First, (as root), open the "$A" config '
'file, and look for the section labeled by the $B in '
'question. In this case, this is:')
.replace('$A', configfile)
.replace('$B', header),
"\n\n[" + profname + "]\n\n",
_('You can also configure the wireless networks by looking for the "[<ESSID>]" '
'field in the config file.'),
_('Once there, you can adjust (or add) the "beforescript", "afterscript", '
'"predisconnectscript" and "postdisconnectscript" variables as needed, to '
'change the preconnect, postconnect, predisconnect and postdisconnect scripts '
'respectively. Note that you will be specifying the full path to the scripts '
'- not the actual script contents. You will need to add/edit the script '
'contents separately. Refer to the wicd manual page for more information.')
]
_('You can also configure the wireless networks by looking '
'for the "[<ESSID>]" field in the config file.'),
_('Once there, you can adjust (or add) the "beforescript", '
'"afterscript", "predisconnectscript" and '
'"postdisconnectscript" variables as needed, to change the '
'preconnect, postconnect, predisconnect and postdisconnect '
'scripts respectively. Note that you will be specifying '
'the full path to the scripts - not the actual script '
'contents. You will need to add/edit the script contents '
'separately. Refer to the wicd manual page for more '
'information.')]
dialog = TextDialog(theText, 20, 80)
dialog.run(ui, parent)
# This code works with many distributions, but not all of them. So, to
@@ -363,14 +364,12 @@ def gen_list_header():
return 'C %s %*s %9s %17s %6s %s' % \
('STR ', essidgap, 'ESSID', 'ENCRYPT', 'BSSID', 'MODE', 'CHNL')
""" Some people use CTRL-\ to quit the application (SIGQUIT) """
def handle_sigquit(signal_number, stack_frame):
"""Some people use CTRL-\ to quit the application (SIGQUIT)"""
loop.quit()
ui.stop()
########################################
##### URWID SUPPORT CLASSES
########################################
class NetLabel(urwid.WidgetWrap):
"""Wireless network label."""
@@ -434,22 +433,22 @@ class WiredComboBox(ComboBox):
list : the list of wired network profiles. The rest is self-explanitory.
"""
# pylint: disable-msg=W0231
def __init__(self, l):
def __init__(self, wired_list):
self.ADD_PROFILE = '---' + _('Add a new profile') + '---'
# pylint: disable-msg=E1101
self.__super.__init__(use_enter=False)
self.theList = []
self.set_list(l)
self.set_list(wired_list)
def set_list(self, l):
def set_list(self, wired_list):
"""Set contents of the combobox."""
self.theList = l
self.theList = wired_list
i = 0
wiredL = []
is_active = \
wireless.GetWirelessIP('') is None and \
wired.GetWiredIP('') is not None
for profile in l:
for profile in wired_list:
theString = '%4s %25s' % (i, profile)
# Tag if no wireless IP present, and wired one is
if is_active:
@@ -474,10 +473,8 @@ class WiredComboBox(ComboBox):
key = ComboBox.keypress(self, size, key)
if key == ' ':
if self.get_focus()[1] == len(self.list) - 1:
dialog = InputDialog(
('header', _('Add a new wired profile')),
7, 30
)
dialog = InputDialog(('header', _('Add a new wired profile')),
7, 30)
exitcode, name = dialog.run(ui, self.parent)
if exitcode == 0:
name = name.strip()
@@ -494,12 +491,9 @@ class WiredComboBox(ComboBox):
wired.ReadWiredNetworkProfile(self.get_selected_profile())
if key == 'delete':
if len(self.theList) == 1:
error(
self.ui,
self.parent,
_('wicd-curses does not support deleting the last wired '
'profile. Try renaming it ("F2")')
)
error(self.ui, self.parent,
_('wicd-curses does not support deleting the last '
'wired profile. Try renaming it ("F2")'))
return key
wired.DeleteWiredNetworkProfile(self.get_selected_profile())
# Return to the top of the list if something is deleted.
@@ -551,8 +545,8 @@ class AdHocDialog(Dialog2):
self.key_edit = DynEdit(key_t, sensitive=False)
self.use_ics_chkb = urwid.CheckBox(use_ics_t)
self.use_encrypt_chkb = urwid.CheckBox(use_encrypt_t,
on_state_change=self.encrypt_callback)
self.use_encrypt_chkb = urwid.CheckBox(
use_encrypt_t, on_state_change=self.encrypt_callback)
blank = urwid.Text('')
@@ -561,9 +555,9 @@ class AdHocDialog(Dialog2):
self.ip_edit.set_edit_text("169.254.12.10")
self.channel_edit.set_edit_text("3")
l = [self.essid_edit, self.ip_edit, self.channel_edit, blank,
lb = [self.essid_edit, self.ip_edit, self.channel_edit, blank,
self.use_ics_chkb, self.use_encrypt_chkb, self.key_edit]
body = urwid.ListBox(l)
body = urwid.ListBox(lb)
header = ('header', _('Create an Ad-Hoc Network'))
Dialog2.__init__(self, header, 15, 50, body)
@@ -608,7 +602,7 @@ class ForgetDialog(Dialog2):
'listbar'
)
title = urwid.Text(_('Please select the networks to forget'))
l = [title, header]
lb = [title, header]
for entry in wireless.GetSavedWirelessNetworks():
label = '%20s %20s'
if entry[1] != 'None':
@@ -623,8 +617,8 @@ class ForgetDialog(Dialog2):
on_state_change=self.update_to_remove,
user_data=data
)
l.append(cb)
body = urwid.ListBox(l)
lb.append(cb)
body = urwid.ListBox(lb)
header = ('header', _('List of saved networks'))
Dialog2.__init__(self, header, 15, 50, body)
@@ -657,9 +651,6 @@ class ForgetDialog(Dialog2):
return exitcode, self.to_remove
########################################
##### APPLICATION INTERFACE CLASS
########################################
# The Whole Shebang
class appGUI():
"""The UI itself, all glory belongs to it!"""
@@ -686,7 +677,8 @@ class appGUI():
self.WIRED_IDX = 1
self.WLESS_IDX = 3
header = urwid.AttrWrap(urwid.Text(self.TITLE, align='right'), 'header')
header = urwid.AttrWrap(urwid.Text(self.TITLE, align='right'),
'header')
self.wiredH = urwid.Filler(urwid.Text(_('Wired Networks')))
self.list_header = urwid.AttrWrap(
urwid.Text(gen_list_header()), 'listbar'
@@ -713,8 +705,7 @@ class appGUI():
self.update_netlist(force_check=True, firstrun=True)
# Keymappings proposed by nanotube in #wicd
keys = [
('H', _('Help'), None),
keys = [('H', _('Help'), None),
('right', _('Config'), None),
# (' ', ' ', None),
('K', _('RfKill'), None),
@@ -724,8 +715,7 @@ class appGUI():
('P', _('Prefs'), None),
('I', _('Hidden'), None),
('A', _('About'), None),
('Q', _('Quit'), loop.quit)
]
('Q', _('Quit'), loop.quit)]
self.primaryCols = OptCols(keys, self.handle_keys)
self.status_label = urwid.AttrWrap(urwid.Text(''), 'important')
@@ -745,7 +735,8 @@ class appGUI():
self.prev_state = False
self.connecting = False
self.screen_locked = False
self.do_diag_lock = False # Whether the screen is locked beneath a dialog
# Whether the screen is locked beneath a dialog
self.do_diag_lock = False
self.diag_type = 'none' # The type of dialog that is up
self.scanning = False
@@ -762,16 +753,12 @@ class appGUI():
def init_other_optcols(self):
"""Init "tabbed" preferences dialog."""
self.prefCols = OptCols([
('S', _('Save')),
self.prefCols = OptCols([('S', _('Save')),
('page up', _('Tab Left'), ),
('page down', _('Tab Right')),
('esc', _('Cancel'))
], self.handle_keys)
self.confCols = OptCols([
('S', _('Save')),
('esc', _('Cancel'))
], self.handle_keys)
('esc', _('Cancel'))], self.handle_keys)
self.confCols = OptCols([('S', _('Save')),
('esc', _('Cancel'))], self.handle_keys)
def lock_screen(self):
"""Lock the screen."""
@@ -872,8 +859,10 @@ class appGUI():
get_body().set_focus(self.focusloc[1])
else:
if self.wlessLB != self.no_wlan:
# Set the focus to the last selected item, but never past the length of the list
self.thePile.get_focus().set_focus(min(self.focusloc[1], len(wlessL) - 1))
# Set the focus to the last selected item, but never
# past the length of the list
self.thePile.get_focus().set_focus(
min(self .focusloc[1], len(wlessL) - 1))
else:
self.thePile.set_focus(self.wiredCB)
else:
@@ -886,8 +875,10 @@ class appGUI():
if self.focusloc[1] is None:
self.focusloc[1] = 0
if self.wlessLB != self.no_wlan:
# Set the focus to the last selected item, but never past the length of the list
self.wlessLB.set_focus(min(self.focusloc[1], len(wlessL) - 1))
# Set the focus to the last selected item, but never past
# the length of the list
self.wlessLB.set_focus(min(self.focusloc[1],
len(wlessL) - 1))
self.prev_state = state
if not firstrun:
@@ -896,9 +887,7 @@ class appGUI():
if wired.GetDefaultWiredNetwork() is not None:
self.wiredCB.get_body().set_focus(
wired.GetWiredProfileList().index(
wired.GetDefaultWiredNetwork()
)
)
wired.GetDefaultWiredNetwork()))
@wrap_exceptions
def update_status(self):
@@ -941,8 +930,8 @@ class appGUI():
stat = wireless.CheckWirelessConnectingMessage()
return self.set_status("%s: %s" % (essid, stat), True)
if wired_connecting:
return self.set_status(_('Wired Network') +
': ' + wired.CheckWiredConnectingMessage(), True)
return self.set_status(_('Wired Network') + ': ' +
wired.CheckWiredConnectingMessage(), True)
else:
self.conn_status = False
return False
@@ -1065,7 +1054,8 @@ class appGUI():
)
self.pref.load_settings()
self.pref.ready_widgets(ui, self.frame)
self.frame.set_footer(urwid.Pile([self.prefCols, self.footer2]))
self.frame.set_footer(urwid.Pile([self.prefCols,
self.footer2]))
self.diag = self.pref
self.diag_type = 'pref'
self.frame.set_body(self.diag)
@@ -1108,9 +1098,10 @@ class appGUI():
text = _('Are you sure you want to discard settings for '
'the selected networks?')
text += '\n\n' + '\n'.join(data['essid'])
confirm, trash = TextDialog(text, 20, 50,
buttons=[(_('OK'), 1), (_('Cancel'), -1)],
).run(ui, self.frame)
confirm, trash = TextDialog(
text, 20, 50,
buttons=[(_('OK'), 1),
(_('Cancel'), -1)],).run(ui, self.frame)
if confirm == 1:
for x in data['bssid']:
wireless.DeleteWirelessNetwork(x)
@@ -1132,7 +1123,8 @@ class appGUI():
break
# F10 has been changed to S to avoid using function keys,
# which are often caught by the terminal emulator.
# But F10 still works, because it doesn't hurt and some users might be used to it.
# But F10 still works, because it doesn't hurt and some users
# might be used to it.
if k == 'f10' or k == 'S' or k == 's':
self.diag.save_settings()
self.restore_primary()
@@ -1175,9 +1167,6 @@ class appGUI():
self.update_status()
########################################
##### INITIALIZATION FUNCTIONS
########################################
def main():
"""Main function."""
global ui, dlogger
@@ -1216,7 +1205,8 @@ def main():
('red', 'dark red', 'default'),
('bold', 'white', 'black', 'bold')
])
# Handle SIGQUIT correctly (otherwise urwid leaves the terminal in a bad state)
# Handle SIGQUIT correctly (otherwise urwid leaves the terminal in a bad
# state)
signal.signal(signal.SIGQUIT, handle_sigquit)
# This is a wrapper around a function that calls another a function that
# is a wrapper around a infinite loop. Fun.
@@ -1259,7 +1249,8 @@ def setup_dbus(force=True):
try:
dbusmanager.connect_to_dbus()
except DBusException:
print(_("Can't connect to the daemon, trying to start it automatically..."), file=sys.stderr)
print(_("Can't connect to the daemon, trying to start it "
"automatically..."), file=sys.stderr)
try:
bus = dbusmanager.get_bus()
@@ -1268,33 +1259,31 @@ def setup_dbus(force=True):
wireless = dbus_ifaces['wireless']
wired = dbus_ifaces['wired']
except DBusException:
print(_("Can't automatically start the daemon, this error is fatal..."), file=sys.stderr)
print(_("Can't automatically start the daemon, this error is "
"fatal..."), file=sys.stderr)
if not daemon:
print('Error connecting to wicd via D-Bus. ' \
'Please make sure the wicd service is running.')
print('Error connecting to wicd via D-Bus.\nPlease make sure the '
'wicd service is running.')
sys.exit(3)
netentry_curses.dbus_init(dbus_ifaces)
return True
setup_dbus()
########################################
##### MAIN ENTRY POINT
########################################
if __name__ == '__main__':
try:
parser = OptionParser(
version="wicd-curses-%s (using wicd %s)" %
parser = OptionParser(version="wicd-curses-%s (using wicd %s)" %
(CURSES_REV, daemon.Hello()),
prog="wicd-curses"
)
prog="wicd-curses")
except Exception as e:
if "DBus.Error.AccessDenied" in e.get_dbus_name():
print(_('ERROR: wicd-curses was denied access to the wicd daemon: '
'please check that your user is in the "$A" group.'). \
replace('$A', '\033[1;34m' + wpath.wicd_group + '\033[0m'))
'please check that your user is in the "$A" group.')
.replace('$A', '\033[1;34m' + wpath.wicd_group + '\033[0m'))
sys.exit(1)
else:
raise

View File

@@ -1,5 +1,4 @@
#!/usr/bin/env python3
"""configscript -- Configure the scripts for a particular network.
Script for configuring the scripts for a network passed in as a
@@ -8,7 +7,6 @@ editing scripts requires root access, and the GUI/Tray are typically
run as the current user.
"""
#
# Copyright (C) 2007-2009 Adam Blackburn
# Copyright (C) 2007-2009 Dan O'Reilly
@@ -57,6 +55,7 @@ def none_to_blank(text):
else:
return str(text)
def blank_to_none(text):
"""Convert an empty or null string to 'None'."""
if text in ("", None):
@@ -64,30 +63,30 @@ def blank_to_none(text):
else:
return str(text)
def get_script_info(network, network_type):
""" Read script info from disk and load it into the configuration dialog """
"""
Read script info from disk and load it into the configuration dialog
"""
info = {}
if network_type == "wired":
con = ConfigManager(wired_conf)
if con.has_section(network):
info["pre_entry"] = con.get(network, "beforescript", None)
info["post_entry"] = con.get(network, "afterscript", None)
info["pre_disconnect_entry"] = con.get(network,
"predisconnectscript", None)
info["post_disconnect_entry"] = con.get(network,
"postdisconnectscript", None)
section = network
else:
bssid = wireless.GetWirelessProperty(int(network), "bssid")
con = ConfigManager(wireless_conf)
if con.has_section(bssid):
info["pre_entry"] = con.get(bssid, "beforescript", None)
info["post_entry"] = con.get(bssid, "afterscript", None)
info["pre_disconnect_entry"] = con.get(bssid,
section = bssid
if con.has_section(section):
info["pre_entry"] = con.get(section, "beforescript", None)
info["post_entry"] = con.get(section, "afterscript", None)
info["pre_disconnect_entry"] = con.get(section,
"predisconnectscript", None)
info["post_disconnect_entry"] = con.get(bssid,
info["post_disconnect_entry"] = con.get(section,
"postdisconnectscript", None)
return info
def write_scripts(network, network_type, script_info):
"""Writes script info to disk and loads it into the daemon."""
if network_type == "wired":

View File

@@ -1,5 +1,4 @@
#!/usr/bin/env python3
"""gui -- The main wicd GUI module.
Module containing the code for the main wicd GUI.
@@ -26,6 +25,7 @@ Module containing the code for the main wicd GUI.
import os
import sys
import time
from gi.repository import GLib as gobject
import gtk
from itertools import chain
@@ -65,11 +65,8 @@ def setup_dbus(force=True):
try:
dbusmanager.connect_to_dbus()
except DBusException:
error(
None,
_("Could not connect to wicd's D-Bus interface. "
"Check the wicd log for error messages.")
)
error(None, _("Could not connect to wicd's D-Bus interface. "
"Check the wicd log for error messages."))
return False
else:
return False
@@ -92,12 +89,8 @@ def handle_no_dbus(from_tray=False):
if from_tray:
return False
print("Wicd daemon is shutting down!")
error(
None,
_('The wicd daemon has shut down. The UI will not function '
'properly until it is restarted.'),
block=False
)
error(None, _('The wicd daemon has shut down. The UI will not function '
'properly until it is restarted.'), block=False)
return False
@@ -166,6 +159,7 @@ def get_wireless_prop(net_id, prop):
"""Get wireless property."""
return wireless.GetWirelessProperty(net_id, prop)
class appGui(object):
"""The main wicd GUI class."""
def __init__(self, standalone=False, tray=None):
@@ -336,8 +330,8 @@ class appGui(object):
"WEP",
self.key_entry.entry.get_text(),
self.chkbox_use_encryption.get_active(),
False # chkbox_use_ics.get_active())
)
False) # chkbox_use_ics.get_active())
dialog.destroy()
def forget_network(self, widget=None):
@@ -359,7 +353,8 @@ class appGui(object):
if entry[1] != 'None':
networks.append(entry)
else:
networks.append((entry[0], _('Global settings for this ESSID')))
networks.append((entry[0],
_('Global settings for this ESSID')))
tree = gtk.TreeView(model=networks)
tree.get_selection().set_mode(gtk.SELECTION_MULTIPLE)
@@ -395,9 +390,8 @@ class appGui(object):
flags=gtk.DIALOG_MODAL,
type=gtk.MESSAGE_INFO,
buttons=gtk.BUTTONS_YES_NO,
message_format=_('Are you sure you want to discard' +
' settings for the selected networks?')
)
message_format=_('Are you sure you want to discard '
'settings for the selected networks?'))
confirm.format_secondary_text('\n'.join(to_remove['essid']))
response = confirm.run()
if response == gtk.RESPONSE_YES:
@@ -486,8 +480,7 @@ class appGui(object):
def cancel_connect(self, widget):
"""Alerts the daemon to cancel the connection process."""
#should cancel a connection if there
#is one in progress
# should cancel a connection if there is one in progress
cancel_button = self.wTree.get_object("cancel_button")
cancel_button.set_sensitive(False)
daemon.CancelConnect()
@@ -502,7 +495,7 @@ class appGui(object):
return True
try:
gobject.idle_add(self.wTree.get_object("progressbar").pulse)
except:
except Exception:
pass
return True
@@ -595,8 +588,8 @@ class appGui(object):
stat = wireless.CheckWirelessConnectingMessage()
gobject.idle_add(self.set_status, "%s: %s" % (info[1], stat))
elif info[0] == "wired":
gobject.idle_add(self.set_status, _('Wired Network') + ': '
+ wired.CheckWiredConnectingMessage())
gobject.idle_add(self.set_status, _('Wired Network') + ': ' +
wired.CheckWiredConnectingMessage())
return True
def update_connect_buttons(self, state=None, x=None, force_check=False):
@@ -797,7 +790,8 @@ class appGui(object):
dialog.set_values()
dialog.show_all()
while True:
if self.run_settings_dialog(dialog, ttype, networkid, networkentry):
if self.run_settings_dialog(dialog, ttype, networkid,
networkentry):
break
dialog.hide()
@@ -824,20 +818,15 @@ class appGui(object):
for entry_info in list(encryption_info.values()):
if entry_info[0].entry.get_text() == "" and \
entry_info[1] == 'required':
error(
self.window,
"%s (%s)" %
error(self.window, "%s (%s)" %
(_('Required encryption information is missing.'),
entry_info[0].label.get_label())
)
entry_info[0].label.get_label()))
return False
# Make sure the checkbox is checked when it should be
elif not entry.chkbox_encryption.get_active() and \
wireless.GetWirelessProperty(networkid, "encryption"):
error(
self.window,
_('This network requires encryption to be enabled.')
)
elif (not entry.chkbox_encryption.get_active() and
wireless.GetWirelessProperty(networkid, "encryption")):
error(self.window, _('This network requires encryption to be '
'enabled.'))
return False
return True

View File

@@ -23,9 +23,9 @@ contained within them.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import os
import gtk
import os
import wicd.misc as misc
import wicd.wpath as wpath
@@ -239,14 +239,14 @@ class AdvancedSettingsDialog(gtk.Dialog):
self.chkbox_global_dns.set_sensitive(self.chkbox_static_dns.
get_active())
l = [self.txt_dns_1, self.txt_dns_2, self.txt_dns_3, self.txt_domain,
self.txt_search_dom]
search_list = [self.txt_dns_1, self.txt_dns_2, self.txt_dns_3,
self.txt_domain, self.txt_search_dom]
if self.chkbox_static_dns.get_active():
# If global dns is on, don't use local dns
for w in l:
for w in search_list:
w.set_sensitive(not self.chkbox_global_dns.get_active())
else:
for w in l:
for w in search_list:
w.set_sensitive(False)
self.chkbox_global_dns.set_active(False)
@@ -270,7 +270,9 @@ class AdvancedSettingsDialog(gtk.Dialog):
w.set_sensitive(not self.chkbox_global_dns.get_active())
def toggle_encryption(self, widget=None):
""" Toggle the encryption combobox based on the encryption checkbox. """
"""
Toggle the encryption combobox based on the encryption checkbox.
"""
active = self.chkbox_encryption.get_active()
self.vbox_encrypt_info.set_sensitive(active)
self.combo_encryption.set_sensitive(active)
@@ -305,8 +307,8 @@ class AdvancedSettingsDialog(gtk.Dialog):
self.set_net_prop("dns1", noneToString(self.txt_dns_1.get_text()))
self.set_net_prop("dns2", noneToString(self.txt_dns_2.get_text()))
self.set_net_prop("dns3", noneToString(self.txt_dns_3.get_text()))
elif self.chkbox_static_dns.get_active() and \
self.chkbox_global_dns.get_active():
elif (self.chkbox_static_dns.get_active() and
self.chkbox_global_dns.get_active()):
self.set_net_prop('use_static_dns', True)
self.set_net_prop('use_global_dns', True)
else:
@@ -319,8 +321,8 @@ class AdvancedSettingsDialog(gtk.Dialog):
self.set_net_prop("dns3", '')
self.set_net_prop('usedhcphostname',
self.chkbox_use_dhcp_hostname.get_active())
self.set_net_prop(
"dhcphostname",noneToString(self.txt_dhcp_hostname.get_text()))
self.set_net_prop("dhcphostname", noneToString(self.txt_dhcp_hostname.
get_text()))
def change_encrypt_method(self, widget=None):
"""Load all the entries for a given encryption method."""
@@ -358,8 +360,10 @@ class AdvancedSettingsDialog(gtk.Dialog):
box.entry.set_text(noneToBlankString(
wired.GetWiredProperty(field[0])))
else:
box.entry.set_text(noneToBlankString(
wireless.GetWirelessProperty(self.networkID, field[0])))
box.entry.set_text(
noneToBlankString(wireless.
GetWirelessProperty(self.networkID,
field[0])))
self.vbox_encrypt_info.show_all()
@@ -373,8 +377,9 @@ class WiredSettingsDialog(AdvancedSettingsDialog):
# change_encrypt_method())
self.wired = True
## This section is largely copied from WirelessSettingsDialog, but with
## some changes
# This section is largely copied from WirelessSettingsDialog, but with
# some changes
#
# Set up encryption stuff
self.combo_encryption = gtk.combo_box_new_text()
self.chkbox_encryption = gtk.CheckButton(_('Use Encryption'))
@@ -418,12 +423,11 @@ class WiredSettingsDialog(AdvancedSettingsDialog):
prog_num=daemon.GetSudoApp()
)
if not cmdbase:
error(None,
_('Could not find a graphical sudo program. '
'The script editor could not be launched. '
"You'll have to edit scripts directly your configuration "
"file.")
)
error(None, _("Could not find a graphical sudo program. "
"The script editor could not be launched. "
"You'll have to edit scripts directly your "
"configuration "
"file."))
return
cmdbase.extend(cmdend)
misc.LaunchAndWait(cmdbase)
@@ -555,8 +559,8 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
activeID = -1 # Set the menu to this item when we are done
for x, enc_type in enumerate(self.encrypt_types):
self.combo_encryption.append_text(enc_type['name'])
if enc_type['type'] == \
wireless.GetWirelessProperty(networkID, "enctype"):
if enc_type['type'] == wireless.GetWirelessProperty(networkID,
"enctype"):
activeID = x
self.combo_encryption.set_active(activeID)
if activeID != -1:
@@ -596,13 +600,10 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
prog_num=daemon.GetSudoApp()
)
if not cmdbase:
error(
None,
_('Could not find a graphical sudo program. '
'The script editor could not be launched. '
"You'll have to edit scripts directly your "
"configuration file.")
)
error(None, _("Could not find a graphical sudo program. The "
"script editor could not be launched. You'll "
"have to edit scripts directly your "
"configuration file."))
return
cmdbase.extend(cmdend)
misc.LaunchAndWait(cmdbase)
@@ -636,15 +637,12 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
self.chkbox_encryption.set_active(
bool(wireless.GetWirelessProperty(networkID, 'encryption')))
self.chkbox_global_settings.set_active(
bool(
wireless.GetWirelessProperty(networkID, 'use_settings_globally')
)
)
bool(wireless.GetWirelessProperty(networkID,
'use_settings_globally')))
self.chkbox_use_dhcp_hostname.set_active(
bool(wireless.GetWirelessProperty(networkID, 'usedhcphostname')))
dhcphname = wireless.GetWirelessProperty(networkID, "dhcphostname")
if dhcphname is None:
dhcphname = os.uname()[1]
@@ -704,8 +702,8 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
for entry_key, entry_info in list(encrypt_info.items()):
self.set_net_prop(entry_key,
noneToString(entry_info[0].entry.get_text()))
elif not self.chkbox_encryption.get_active() and \
wireless.GetWirelessProperty(networkid, "encryption"):
elif (not self.chkbox_encryption.get_active() and
wireless.GetWirelessProperty(networkid, "encryption")):
# Encrypt checkbox is off, but the network needs it.
error(self, _('This network requires encryption to be enabled.'))
return False
@@ -736,7 +734,8 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
def format_entry(self, networkid, label):
"""Helper method for fetching/formatting wireless properties."""
return noneToBlankString(wireless.GetWirelessProperty(networkid, label))
return noneToBlankString(wireless.GetWirelessProperty(networkid,
label))
class NetworkEntry(gtk.HBox):
@@ -819,13 +818,15 @@ class WiredNetworkEntry(NetworkEntry):
self.button_add = gtk.Button(stock=gtk.STOCK_ADD)
self.button_delete = gtk.Button(stock=gtk.STOCK_DELETE)
self.profile_help = gtk.Label(
_('To connect to a wired network, you must create a network '
'profile. To create a network profile, type a name that describes '
'this network, and press Add.')
)
self.chkbox_default_profile = gtk.CheckButton(
_('Use as default profile (overwrites any previous default)'))
self.profile_help = gtk.Label(_('To connect to a wired network, you '
'must create a network profile. To '
'create a network profile, type a '
'name that describes this network, '
'and press Add.'))
self.chkbox_default_profile = gtk.CheckButton(_('Use as default '
'profile (overwrites '
'any previous '
'default)'))
self.combo_profile_names = gtk.combo_box_new_text()
# Format the profile help label.
@@ -1176,7 +1177,8 @@ class WirelessNetworkEntry(NetworkEntry):
def format_entry(self, networkid, label):
"""Helper method for fetching/formatting wireless properties."""
return noneToBlankString(wireless.GetWirelessProperty(networkid, label))
return noneToBlankString(wireless.GetWirelessProperty(networkid,
label))
class WirelessInformationDialog(gtk.Dialog):
@@ -1305,4 +1307,5 @@ class WirelessInformationDialog(gtk.Dialog):
def format_entry(self, networkid, label):
"""Helper method for fetching/formatting wireless properties."""
return noneToBlankString(wireless.GetWirelessProperty(networkid, label))
return noneToBlankString(wireless.GetWirelessProperty(networkid,
label))

View File

@@ -23,10 +23,14 @@ handles recieving/sendings the settings from/to the daemon.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import os
import gtk
from gi.repository import GObject as gobject
import os
try:
import pynotify
except ImportError:
pynotify = None
from wicd import misc
from wicd import wpath
@@ -208,9 +212,7 @@ class PreferencesDialog(object):
))
# if pynotify isn't installed disable the option
try:
import pynotify
except ImportError:
if not pynotify:
self.notificationscheckbox.set_active(False)
self.notificationscheckbox.set_sensitive(False)
@@ -354,12 +356,18 @@ class PreferencesDialog(object):
return widget
# External Programs tab
# self.wTree.get_object("gen_settings_label").set_label(_('General Settings'))
# self.wTree.get_object("ext_prog_label").set_label(_('External Programs'))
# self.wTree.get_object("dhcp_client_label").set_label(_('DHCP Client'))
# self.wTree.get_object("wired_detect_label").set_label(_('Wired Link Detection'))
# self.wTree.get_object("route_flush_label").set_label(_('Route Table Flushing'))
# self.wTree.get_object("pref_backend_label").set_label(_('Backend') + ":")
# self.wTree.get_object("gen_settings_label").set_label(_('General '
# 'Settings'))
# self.wTree.get_object("ext_prog_label").set_label(_('External '
# 'Programs'))
# self.wTree.get_object("dhcp_client_label").set_label(_('DHCP '
# 'Client'))
# self.wTree.get_object("wired_detect_label").set_label(_('Wired Link '
# 'Detection'))
# self.wTree.get_object("route_flush_label").set_label(_('Route Table '
# 'Flushing'))
# self.wTree.get_object("pref_backend_label").set_label(_('Backend') +
# ":")
# entryWiredAutoMethod = self.wTree.get_object("pref_wired_auto_label")
# entryWiredAutoMethod.set_label('Wired Autoconnect Setting:')
@@ -374,7 +382,8 @@ class PreferencesDialog(object):
# self.set_label("pref_search_dom_label", "%s:" % _('Search domain'))
# self.set_label("pref_wifi_label", "%s:" % _('Wireless Interface'))
# self.set_label("pref_wired_label", "%s:" % _('Wired Interface'))
# self.set_label("pref_driver_label", "%s:" % _('WPA Supplicant Driver'))
# self.set_label("pref_driver_label", "%s:" % _('WPA Supplicant '
# 'Driver'))
self.dialog = self.wTree.get_object("pref_dialog")
self.dialog.set_title(_('Preferences'))
@@ -384,46 +393,36 @@ class PreferencesDialog(object):
width = 450
self.dialog.resize(width, int(gtk.gdk.screen_height() / 2))
self.wiredcheckbox = setup_label(
"pref_always_check",
_('''Always show wired interface''')
)
self.wiredcheckbox = setup_label("pref_always_check",
_('''Always show wired interface'''))
self.preferwiredcheckbox = setup_label("pref_prefer_wired_check",
"prefer_wired")
self.reconnectcheckbox = setup_label("pref_auto_check",
_('Automatically reconnect on connection loss'))
_('Automatically reconnect on '
'connection loss'))
self.showneverconnectcheckbox = setup_label(
"pref_show_never_connect_check",
_('Show never connect networks')
)
"pref_show_never_connect_check", _('Show never connect networks'))
self.debugmodecheckbox = setup_label("pref_debug_check",
_('Enable debug mode'))
self.displaytypecheckbox = setup_label(
"pref_dbm_check",
_('Use dBm to measure signal strength')
)
"pref_dbm_check", _('Use dBm to measure signal strength'))
self.verifyapcheckbox = setup_label(
"pref_verify_ap_check",
_('Ping static gateways after connecting to verify association')
)
_('Ping static gateways after connecting to verify association'))
self.usedefaultradiobutton = setup_label(
"pref_use_def_radio",
_('Use default profile on wired autoconnect')
)
_('Use default profile on wired autoconnect'))
self.showlistradiobutton = setup_label(
"pref_prompt_radio",
_('Prompt for profile on wired autoconnect')
)
_('Prompt for profile on wired autoconnect'))
self.lastusedradiobutton = setup_label(
"pref_use_last_radio",
_('Use last used profile on wired autoconnect')
)
_('Use last used profile on wired autoconnect'))
self.notificationscheckbox = setup_label(
"pref_use_libnotify",
_('Display notifications about connection status')
)
_('Display notifications about connection status'))
# DHCP Clients
self.dhcpautoradio = setup_label(
@@ -434,8 +433,8 @@ class PreferencesDialog(object):
self.udhcpcradio = self.wTree.get_object("udhcpc_radio")
# Wired Link Detection Apps
self.linkautoradio = setup_label(
"link_auto_radio", _('Automatic (recommended)'))
self.linkautoradio = setup_label("link_auto_radio",
_('Automatic (recommended)'))
self.linkautoradio = setup_label("link_auto_radio")
self.ethtoolradio = setup_label("ethtool_radio")
self.miitoolradio = setup_label("miitool_radio")
@@ -447,8 +446,8 @@ class PreferencesDialog(object):
self.routeflushradio = setup_label("route_flush_radio")
# Graphical Sudo Apps
self.sudoautoradio = setup_label(
"sudo_auto_radio", _('Automatic (recommended)'))
self.sudoautoradio = setup_label("sudo_auto_radio",
_('Automatic (recommended)'))
self.gksudoradio = setup_label("gksudo_radio")
self.kdesuradio = setup_label("kdesu_radio")
self.ktsussradio = setup_label("ktsuss_radio")
@@ -489,5 +488,4 @@ class PreferencesDialog(object):
def be_combo_changed(self, combo):
"""Update the description label for the given backend."""
self.backendcombo.set_tooltip_text(
self.be_descriptions[self.backends[combo.get_active()]]
)
self.be_descriptions[self.backends[combo.get_active()]])

View File

@@ -1,5 +1,4 @@
#!/usr/bin/env python3
"""wicd - wireless connection daemon frontend implementation
This module implements a usermode frontend for wicd. It updates connection
@@ -11,7 +10,8 @@ class TrayIcon() -- Parent class of TrayIconGUI and IconConnectionInfo.
and updates connection status.
class TrayIconGUI() -- Child class of TrayIcon which implements the tray.
icon itself. Parent class of StatusTrayIconGUI and EggTrayIconGUI.
class IndicatorTrayIconGUI() -- Implements the tray icon using appindicator.Indicator.
class IndicatorTrayIconGUI() -- Implements the tray icon using
appindicator.Indicator.
class StatusTrayIconGUI() -- Implements the tray icon using a
gtk.StatusIcon.
class EggTrayIconGUI() -- Implements the tray icon using egg.trayicon.
@@ -37,31 +37,27 @@ class TrayIcon() -- Parent class of TrayIconGUI and IconConnectionInfo.
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import sys
import gtk
from gi.repository import GLib as gobject
import atexit
import getopt
import os
import pango
import atexit
import sys
from dbus import DBusException
import gtk
from gi.repository import GLib as gobject
import pango
import pygtk
pygtk.require('2.0')
USE_APP_INDICATOR = True
try:
import appindicator
except ImportError:
USE_APP_INDICATOR = False
appindicator = None
HAS_NOTIFY = True
try:
import pynotify
if not pynotify.init("Wicd"):
HAS_NOTIFY = False
except ImportError:
HAS_NOTIFY = False
pynotify = None
# Wicd specific imports
from wicd import wpath
@@ -72,6 +68,12 @@ from guiutil import error, can_use_notify
from wicd.translations import _
pygtk.require('2.0')
if pynotify and not pynotify.init("Wicd"):
pynotify = None
ICON_AVAIL = True
USE_EGG = False
# Import egg.trayicon if we're using an older gtk version
@@ -80,8 +82,8 @@ if not hasattr(gtk, "StatusIcon"):
import egg.trayicon
USE_EGG = True
except ImportError:
print(('Unable to load tray icon: Missing both egg.trayicon and ' + \
'gtk.StatusIcon modules.'))
print('Unable to load tray icon: Missing both egg.trayicon and '
'gtk.StatusIcon modules.')
ICON_AVAIL = False
misc.RenameProcess("wicd-client")
@@ -104,14 +106,11 @@ def catchdbus(func):
except DBusException as e:
if e.get_dbus_name() is not None and \
"DBus.Error.AccessDenied" in e.get_dbus_name():
error(
None,
error(None,
_('Unable to contact the Wicd daemon due to an access '
'denied error from DBus. Please check that your user is '
'in the $A group.').
replace("$A", "<b>" + wpath.wicd_group + "</b>")
)
#raise
'denied error from DBus. Please check that your user '
'is in the $A group.').replace("$A", "<b>%s</b>" %
wpath.wicd_group))
raise DBusException(e)
else:
print(("warning: ignoring exception %s" % e))
@@ -152,7 +151,7 @@ class TrayIcon(object):
self.max_snd_gain = 10000
self.max_rcv_gain = 10000
if USE_APP_INDICATOR:
if appindicator:
self.tr = self.IndicatorTrayIconGUI(self)
elif USE_EGG:
self.tr = self.EggTrayIconGUI(self)
@@ -333,8 +332,7 @@ class TrayIcon(object):
wired = True
else:
cur_network = info[1]
status_string = _('Connecting') + " to " + \
cur_network + "..."
status_string = _('Connecting') + " to " + cur_network + "..."
self.update_tooltip()
# self.tr.set_tooltip(status_string)
self.tr.set_from_name('no-signal')
@@ -538,7 +536,7 @@ class TrayIcon(object):
self.current_icon_name = None
self._is_scanning = False
net_menuitem = self.manager.get_widget("/Menubar/Menu/Connect/")
if not USE_APP_INDICATOR:
if not appindicator:
net_menuitem.connect("activate", self.on_net_menu_activate)
self.parent = parent
@@ -625,7 +623,7 @@ class TrayIcon(object):
window.destroy()
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"""
if (self.cont == "Stop"):
return False
@@ -635,19 +633,12 @@ class TrayIcon(object):
# Choose info for the data
if state == misc.WIRED:
text = (_('''$A
$B KB/s
$C KB/s''')
text = (_("$A\n$B KB/s\n$C KB/s")
.replace('$A', str(info[0])) # IP
.replace('$B', str(rx)) # RX
.replace('$C', str(tx))) # TX
elif state == misc.WIRELESS:
text = (_('''$A
$B
$C
$D
$E KB/s
$F KB/s''')
text = (_("$A\n$B\n$C\n$D\n$E KB/s\n$F KB/s")
.replace('$A', str(info[1])) # SSID
.replace('$B', str(info[4])) # Speed
.replace('$C', str(info[0])) # IP
@@ -661,18 +652,10 @@ $F KB/s''')
# Choose info for the labels
self.list[0].set_text('\n' + text)
if state == misc.WIRED:
self.list[1].set_text(_('''Wired
IP:
RX:
TX:'''))
self.list[1].set_text(_("Wired\nIP:\nRX:\nTX:"))
elif state == misc.WIRELESS:
self.list[1].set_text(_('''Wireless
SSID:
Speed:
IP:
Strength:
RX:
TX:'''))
self.list[1].set_text(_("Wireless\nSSID:\nSpeed:\nIP:\n"
"Strength:\nRX:\nTX:"))
elif state == misc.CONNECTING:
self.list[1].set_text(_('Connecting'))
elif state in (misc.SUSPENDED, misc.NOT_CONNECTED):
@@ -812,8 +795,8 @@ TX:'''))
is_active = True
else:
is_active = False
self._add_item_to_menu(submenu, "Wired Network", "__wired__", 0,
is_connecting, is_active)
self._add_item_to_menu(submenu, "Wired Network", "__wired__",
0, is_connecting, is_active)
sep = gtk.SeparatorMenuItem()
submenu.append(sep)
sep.show()
@@ -821,8 +804,8 @@ TX:'''))
if num_networks > 0:
skip_never_connect = not daemon.GetShowNeverConnect()
for x in range(0, num_networks):
if skip_never_connect and \
misc.to_bool(get_prop(x,"never")):
if (skip_never_connect and
misc.to_bool(get_prop(x, "never"))):
continue
essid = get_prop(x, "essid")
if status == misc.WIRELESS and info[1] == essid:
@@ -968,7 +951,7 @@ TX:'''))
"""
self.set_visible(val)
if USE_APP_INDICATOR:
if appindicator:
class IndicatorTrayIconGUI(gtk.StatusIcon, TrayIconGUI):
"""Class for creating the wicd AppIndicator.
This is required on recent versions of Unity (>=13.04).
@@ -978,8 +961,10 @@ TX:'''))
"""
def __init__(self, parent):
TrayIcon.TrayIconGUI.__init__(self, parent)
self.ind = appindicator.Indicator(
"wicd", "wicd-gtk", appindicator.CATEGORY_SYSTEM_SERVICES, wpath.images)
self.ind = appindicator.Indicator("wicd", "wicd-gtk",
appindicator.
CATEGORY_SYSTEM_SERVICES,
wpath.images)
self.current_icon_name = ''
# Rescaning when hovering over the net_menu doesn't work.
@@ -1008,7 +993,9 @@ TX:'''))
self.ind.set_menu(self.menu)
def on_rescan(self, *data):
""" Triggers a network rescan that updates the 'Connect' menu when the 'Rescan' menu item is selected. """
"""Triggers a network rescan that updates the 'Connect' menu
when the 'Rescan' menu item is selected.
"""
self.init_network_menu()
wireless.Scan(False)
@@ -1031,7 +1018,8 @@ TX:'''))
hides the tray icon.
"""
self.ind.set_status(val and appindicator.STATUS_ACTIVE or appindicator.STATUS_PASSIVE)
self.ind.set_status(val and appindicator.STATUS_ACTIVE or
appindicator.STATUS_PASSIVE)
def set_tooltip(self, str):
"""Set the tooltip for this tray icon.
@@ -1046,7 +1034,7 @@ TX:'''))
def usage():
"""Print usage information."""
print(("""
print("""
wicd %s
wireless (and wired) connection daemon front-end.
@@ -1056,7 +1044,7 @@ Arguments:
\t-h\t--help\t\tPrint this help information.
\t-a\t--no-animate\tRun the tray without network traffic tray animations.
\t-o\t--only-notifications\tDon't display anything except notifications.
""" % wpath.version))
""" % wpath.version)
def setup_dbus(force=True):
@@ -1067,16 +1055,14 @@ def setup_dbus(force=True):
dbusmanager.connect_to_dbus()
except DBusException:
if force:
print(("Can't connect to the daemon, trying to start it " + \
"automatically..."))
print("Can't connect to the daemon, trying to start it "
"automatically...")
misc.PromptToStartDaemon()
try:
dbusmanager.connect_to_dbus()
except DBusException:
error(None,
_("Could not connect to wicd's D-Bus interface. Check "
"the wicd log for error messages.")
)
error(None, _("Could not connect to wicd's D-Bus interface. "
"Check the wicd log for error messages."))
return False
else:
return False
@@ -1108,13 +1094,10 @@ def handle_no_dbus():
DBUS_AVAIL = False
gui.handle_no_dbus(from_tray=True)
print("Wicd daemon is shutting down!")
lost_dbus_id = misc.timeout_add(5,
lambda: error(None,
_('The wicd daemon has shut down. The UI will not function '
'properly until it is restarted.'),
block=False
)
)
err_msg = _('The wicd daemon has shut down. The UI will not function '
'properly until it is restarted.')
lost_dbus_id = misc.timeout_add(5, lambda: error(None, err_msg,
block=False))
return False

View File

@@ -3,7 +3,6 @@
chdir() -- Change directory to the location of the current file.
"""
import os
# The path containing the wpath.py file.
@@ -90,6 +89,7 @@ no_install_cli = %NO_INSTALL_CLI%
no_install_gnome_shell_extensions = %NO_INSTALL_GNOME_SHELL_EXTENSIONS%
no_use_notifications = %NO_USE_NOTIFICATIONS%
def chdir(f):
"""Change directory to the location of the specified file.

251
setup.py
View File

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

View File

@@ -4,6 +4,7 @@
import unittest
from wicd import misc
class TestMisc(unittest.TestCase):
def test_misc_run(self):
output = misc.Run(['echo', 'hi']).strip()
@@ -25,10 +26,12 @@ class TestMisc(unittest.TestCase):
self.assertTrue(misc.IsValidIP('::1'))
def test_valid_ip_6(self):
self.assertTrue(misc.IsValidIP('FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF'))
self.assertTrue(misc.
IsValidIP('FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF'))
def test_valid_ip_7(self):
self.assertTrue(misc.IsValidIP('2001:0db8:85a3:0000:0000:8a2e:0370:7334'))
self.assertTrue(misc.
IsValidIP('2001:0db8:85a3:0000:0000:8a2e:0370:7334'))
def test_invalid_ip_1(self):
self.assertFalse(misc.IsValidIP('-10.0.-1.-1'))
@@ -46,10 +49,12 @@ class TestMisc(unittest.TestCase):
self.assertFalse(misc.IsValidIP('1:'))
def test_invalid_ip_6(self):
self.assertFalse(misc.IsValidIP('ZZZZ:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF'))
self.assertFalse(misc.
IsValidIP('ZZZZ:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF'))
def test_invalid_ip_7(self):
self.assertFalse(misc.IsValidIP('2001:0db8:85Z3:0000:0000:8a2e:0370:7334'))
self.assertFalse(misc.
IsValidIP('2001:0db8:85Z3:0000:0000:8a2e:0370:7334'))
def test_run_valid_regex(self):
import re
@@ -72,7 +77,7 @@ class TestMisc(unittest.TestCase):
def test_to_boolean_true(self):
self.assertTrue(misc.to_bool('True'))
def test_to_boolean_true(self):
def test_to_boolean_true_int(self):
self.assertTrue(misc.to_bool('1'))
def test_noneify_1(self):
@@ -137,7 +142,8 @@ class TestMisc(unittest.TestCase):
self.assertEqual(misc.to_unicode('abcdef'), 'abcdef')
def test_to_unicode_4(self):
self.assertEqual(type(misc.to_unicode('abcdef'.encode('latin-1'))), bytes)
self.assertEqual(type(misc.to_unicode('abcdef'.encode('latin-1'))),
bytes)
def test_to_unicode_5(self):
self.assertEqual(misc.to_unicode("berkåk"), "berkåk")
@@ -163,6 +169,7 @@ class TestMisc(unittest.TestCase):
def test_string_to_none_4(self):
self.assertEqual(misc.stringToNone('abcdef'), 'abcdef')
def suite():
suite = unittest.TestSuite()
tests = []
@@ -171,5 +178,6 @@ def suite():
suite.addTest(TestMisc(test))
return suite
if __name__ == '__main__':
unittest.main()

View File

@@ -2,6 +2,7 @@ import unittest
from unittest import mock
from wicd import wnettools
class TestWnettools(unittest.TestCase):
def setUp(self):
self.interface = wnettools.BaseInterface('eth0')
@@ -41,7 +42,8 @@ class TestWnettools(unittest.TestCase):
self.assertFalse(self.interface.verbose)
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')
def test_freq_translation_low(self):
@@ -57,16 +59,21 @@ class TestWnettools(unittest.TestCase):
def test_generate_psk(self):
interface = wnettools.BaseWirelessInterface('wlan0')
if 'wlan0' in wnettools.GetWirelessInterfaces():
psk = interface.GeneratePSK({'essid' : 'Network 1', 'key' : 'arandompassphrase'})
self.assertEqual(psk, 'd70463014514f4b4ebb8e3aebbdec13f4437ac3a9af084b3433f3710e658a7be')
psk = interface.GeneratePSK({'essid': 'Network 1',
'key': 'arandompassphrase'})
self.assertEqual(psk, 'd70463014514f4b4ebb8e3aebbdec13f4437ac3a9a'
'f084b3433f3710e658a7be')
def suite():
suite = unittest.TestSuite()
tests = []
[ tests.append(test) for test in dir(TestWnettools) if test.startswith('test') ]
[tests.append(test) for test in dir(TestWnettools)
if test.startswith('test')]
for test in tests:
suite.addTest(TestWnettools(test))
return suite
if __name__ == '__main__':
unittest.main()

View File

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

View File

@@ -29,6 +29,7 @@ import os
import wicd.wpath as wpath
def fail(backend_name, reason):
"""Helper to warn the user about failure in loading backend."""
print(("Failed to load backend %s: %s" % (backend_name, reason)))

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/>.
#
from wicd.wnettools import GetDefaultGateway, GetWiredInterfaces, \
GetWirelessInterfaces, IsValidWpaSuppDriver, BaseWirelessInterface, \
BaseWiredInterface, BaseInterface, GetWpaSupplicantDrivers
from wicd.wnettools import BaseInterface
from wicd.wnettools import BaseWiredInterface
from wicd.wnettools import BaseWirelessInterface
from wicd.wnettools import GetDefaultGateway
from wicd.wnettools import GetWiredInterfaces
from wicd.wnettools import GetWirelessInterfaces
from wicd.wnettools import GetWpaSupplicantDrivers
from wicd.wnettools import IsValidWpaSuppDriver
NAME = "external"
UPDATE_INTERVAL = 5

View File

@@ -30,18 +30,33 @@ class WirelessInterface() -- Control a wireless network interface.
# 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 wpath
from wicd.wnettools import GetDefaultGateway, GetWiredInterfaces, \
GetWirelessInterfaces, IsValidWpaSuppDriver, BaseWirelessInterface, \
BaseWiredInterface, BaseInterface, GetWpaSupplicantDrivers, wep_pattern, \
signaldbm_pattern, neediface
from wicd.wnettools import BaseInterface
from wicd.wnettools import BaseWiredInterface
from wicd.wnettools import BaseWirelessInterface
from wicd.wnettools import GetDefaultGateway
from wicd.wnettools import GetWiredInterfaces
from wicd.wnettools import GetWirelessInterfaces
from wicd.wnettools import GetWpaSupplicantDrivers
from wicd.wnettools import IsValidWpaSuppDriver
from wicd.wnettools import neediface
from wicd.wnettools import signaldbm_pattern
from wicd.wnettools import wep_pattern
try:
import iwscan
IWSCAN_AVAIL = True
except ImportError:
print("WARNING: python-iwscan not found, falling back to using iwlist scan.")
print("WARNING: python-iwscan not found, falling back to using iwlist "
"scan.")
IWSCAN_AVAIL = False
try:
import wpactrl
@@ -50,14 +65,6 @@ except ImportError:
print("WARNING: python-wpactrl not found, falling back to using wpa_cli.")
WPACTRL_AVAIL = False
import re
import os
import time
import socket
import fcntl
import struct
import array
NAME = "ioctl"
UPDATE_INTERVAL = 4
@@ -112,6 +119,7 @@ def get_iw_ioctl_result(iface, call):
return None
return buff.tostring()
def NeedsExternalCalls(*args, **kargs):
"""Return False, since this backend doesn't use any external apps."""
return False
@@ -201,7 +209,8 @@ class WiredInterface(Interface, BaseWiredInterface):
"""
if self.ethtool_cmd and self.link_detect in [misc.ETHTOOL, misc.AUTO]:
return self._eth_get_plugged_in()
elif self.miitool_cmd and self.link_detect in [misc.MIITOOL, misc.AUTO]:
elif self.miitool_cmd and self.link_detect in [misc.MIITOOL,
misc.AUTO]:
return self._mii_get_plugged_in()
else:
print(('Error: No way of checking for a wired connection. Make' +
@@ -262,8 +271,7 @@ class WirelessInterface(Interface, BaseWirelessInterface):
verbose -- print all commands
"""
BaseWirelessInterface.__init__(self, iface, verbose,
wpa_driver)
BaseWirelessInterface.__init__(self, iface, verbose, wpa_driver)
Interface.__init__(self, iface, verbose)
self.scan_iface = None
self.CheckWirelessTools()
@@ -344,7 +352,8 @@ class WirelessInterface(Interface, BaseWirelessInterface):
# quality displayed or it isn't found)
if misc.RunRegex(signaldbm_pattern, cell["stats"]):
ap['strength'] = misc.RunRegex(signaldbm_pattern, cell["stats"])
elif self.wpa_driver != RALINK_DRIVER: # This is already set for ralink
# This is already set for ralink
elif self.wpa_driver != RALINK_DRIVER:
ap['strength'] = -1
return ap
@@ -360,8 +369,8 @@ class WirelessInterface(Interface, BaseWirelessInterface):
print(("Couldn't open ctrl_interface: %s" % e))
return None
else:
print(("Couldn't find a wpa_supplicant ctrl_interface for iface %s" \
% self.iface))
print(f"Couldn't find a wpa_supplicant ctrl_interface for iface "
f"{self.iface}")
return None
def ValidateAuthentication(self, auth_time):
@@ -384,7 +393,8 @@ class WirelessInterface(Interface, BaseWirelessInterface):
"""
if not WPACTRL_AVAIL:
# If we don't have python-wpactrl, use the slow version.
return BaseWirelessInterface.ValidateAuthentication(self, auth_time)
return BaseWirelessInterface.ValidateAuthentication(self,
auth_time)
# Right now there's no way to do this for ralink drivers
if self.wpa_driver == RALINK_DRIVER:
@@ -401,16 +411,16 @@ class WirelessInterface(Interface, BaseWirelessInterface):
while (time.time() - auth_time) < MAX_TIME:
try:
status = wpa.request("STATUS").split("\n")
except:
except Exception:
print("wpa_supplicant status query failed.")
return False
if self.verbose:
print(('wpa_supplicant ctrl_interface status query is %s' \
% str(status)))
print(f'wpa_supplicant ctrl_interface status query is '
f'{status}')
try:
[result] = [l for l in status if l.startswith("wpa_state=")]
[result] = [s for s in status if s.startswith("wpa_state=")]
except ValueError:
return False
@@ -449,14 +459,16 @@ class WirelessInterface(Interface, BaseWirelessInterface):
network -- dictionary containing network info
"""
if network.get('key') != None:
if network.get('key') is None:
return
lines = self._GetRalinkInfo()
for x in lines:
info = x.split()
if len(info) < 5:
break
if info[2] == network.get('essid'):
if info[5] == 'WEP' or (info[5] == 'OPEN' and \
if info[5] == 'WEP' or (info[5] == 'OPEN' and
info[4] == 'WEP'):
print('Setting up WEP')
cmd = ''.join(['iwconfig ', self.iface, ' key ',
@@ -478,8 +490,8 @@ class WirelessInterface(Interface, BaseWirelessInterface):
auth_mode = 'WPA2PSK'
key_name = 'WPAPSK'
else:
print(('Unknown AuthMode, can\'t complete ' + \
'connection process!'))
print("Unknown AuthMode, can\'t complete connection "
"process!")
return
cmd_list = []

View File

@@ -25,14 +25,15 @@ reusable for other purposes as well.
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import sys, os
from configparser import RawConfigParser, ParsingError
import codecs
import configparser
import os
import sys
from dbus import Int32
from wicd.misc import Noneify, to_unicode
from dbus import Int32
def sanitize_config_file(path):
"""Remove invalid lines from config file."""
@@ -46,10 +47,11 @@ def sanitize_config_file(path):
conf.write(newconf)
conf.close()
class ConfigManager(RawConfigParser):
class ConfigManager(configparser.RawConfigParser):
"""A class that can be used to manage a given configuration file."""
def __init__(self, path, debug=False, mark_whitespace="`'`"):
RawConfigParser.__init__(self)
configparser.RawConfigParser.__init__(self)
self.config_file = path
self.debug = debug
self.mrk_ws = mark_whitespace
@@ -57,11 +59,11 @@ class ConfigManager(RawConfigParser):
sanitize_config_file(path)
try:
self.read(path)
except ParsingError:
except configparser.ParsingError:
self.write()
try:
self.read(path)
except ParsingError as p:
except configparser.ParsingError as p:
print(("Could not start wicd: %s" % p.message))
sys.exit(1)
@@ -91,7 +93,7 @@ class ConfigManager(RawConfigParser):
if value.startswith(' ') or value.endswith(' '):
value = "%(ws)s%(value)s%(ws)s" % {"value": value,
"ws": self.mrk_ws}
RawConfigParser.set(self, section, str(option), value)
configparser.RawConfigParser.set(self, section, str(option), value)
if write:
self.write()
@@ -114,7 +116,7 @@ class ConfigManager(RawConfigParser):
return None
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)
and ret.endswith(self.mrk_ws)):
ret = ret[3:-3]
@@ -122,18 +124,16 @@ class ConfigManager(RawConfigParser):
if default:
if self.debug:
# mask out sensitive information
if option in ['apsk', 'password', 'identity', \
'private_key', 'private_key_passwd', \
if option in ['apsk', 'password', 'identity',
'private_key', 'private_key_passwd',
'key', 'passphrase']:
print((''.join(['found ', option, \
' in configuration *****'])))
print(f'found {option} in configuration *****')
else:
print((''.join(['found ', option, ' in configuration ',
str(ret)])))
print(f'found {option} in configuration {ret}')
else: # Use the default, unless no default was provided
if default != "__None__":
print(('did not find %s in configuration, setting default %s' \
% (option, str(default))))
print(f'did not find {option} in configuration, setting '
f'default {default}')
self.set(section, option, str(default), write=True)
ret = default
else:
@@ -163,7 +163,7 @@ class ConfigManager(RawConfigParser):
if not section:
self.remove_section(section)
configfile = open(self.config_file, 'w')
RawConfigParser.write(self, configfile)
configparser.RawConfigParser.write(self, configfile)
configfile.close()
def remove_section(self, section):
@@ -174,7 +174,7 @@ class ConfigManager(RawConfigParser):
"""
if self.has_section(section):
RawConfigParser.remove_section(self, section)
configparser.RawConfigParser.remove_section(self, section)
def reload(self):
"""Re-reads the config file, in case it was edited out-of-band."""
@@ -187,7 +187,8 @@ class ConfigManager(RawConfigParser):
entries in these files override entries in the main file.
"""
if os.path.exists(path):
RawConfigParser.readfp(self, codecs.open(path, 'r', 'utf-8'))
configparser.RawConfigParser.readfp(self, codecs.open(path, 'r',
'utf-8'))
path_d = path + ".d"
files = []
@@ -197,7 +198,7 @@ class ConfigManager(RawConfigParser):
files.sort()
for fname in files:
p = RawConfigParser()
p = configparser.RawConfigParser()
p.readfp(codecs.open(fname, 'r', 'utf-8'))
for section_name in p.sections():
# New files override old, so remove first to avoid
@@ -209,7 +210,6 @@ class ConfigManager(RawConfigParser):
# Store the filename this section was read from.
self.set(section_name, '_filename_', fname)
def _copy_section(self, name):
"""Copy whole section from config file."""
p = ConfigManager("", self.debug, self.mrk_ws)
@@ -243,4 +243,3 @@ class ConfigManager(RawConfigParser):
p.set(sname, iname, value)
p.remove_option(sname, '_filename_')
p._write_one()

View File

@@ -1,5 +1,3 @@
#!/usr/bin/env python3
"""The wicd DBus Manager.
A module for managing wicd's dbus interfaces.
@@ -32,26 +30,32 @@ else:
DBUS_MANAGER = None
def get_dbus_ifaces():
"""Return available DBus interfaces."""
return DBUS_MANAGER.get_dbus_ifaces()
def get_interface(iface):
"""Return specified interface."""
return DBUS_MANAGER.get_interface(iface)
def get_bus():
"""Return the loaded System Bus."""
return DBUS_MANAGER.get_bus()
def set_mainloop(loop):
"""Set DBus main loop."""
return DBUS_MANAGER.set_mainloop(loop)
def connect_to_dbus():
"""Connect to DBus."""
return DBUS_MANAGER.connect_to_dbus()
def threads_init():
"""Init GLib threads."""
dbus.mainloop.glib.threads_init()
@@ -99,4 +103,5 @@ class DBusManager(object):
self._dbus_ifaces = {"daemon": daemon, "wireless": wireless,
"wired": wired}
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) 2008-2009 Dan O'Reilly <oreilldf@gmail.com>
@@ -14,22 +21,17 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
"""
Managing logfile rotation. A ManagedLog object is a file-like object that
rotates itself when a maximum size is reached.
"""
import sys
import os
import time
import io
import os
import sys
import time
class SizeError(IOError):
"""Custom error class."""
pass
class LogFile(io.FileIO):
"""LogFile(name, [mode="w"], [maxsize=360000])
@@ -49,19 +51,22 @@ class LogFile(io.FileIO):
def write(self, data):
self.written += len(data)
# TODO(gryf): revisit need for encode/decode madness
data = data.encode('utf-8')
if len(data) <= 0:
return
if self.eol:
super(LogFile, self).write(self.get_time().encode("utf-8") + b' :: ')
super(LogFile, self).write(self.get_time().encode("utf-8") +
b' :: ')
self.eol = False
if data[-1] == '\n':
self.eol = True
data = data[:-1]
super(LogFile, self).write(data.replace(
b'\n', b'\n' + self.get_time().encode("utf-8") + b' :: '))
super(LogFile, self).write(data.replace(b'\n', b'\n' + self.get_time()
.encode("utf-8") + b' :: '))
if self.eol:
super(LogFile, self).write('\n')
@@ -190,6 +195,7 @@ def open(name, maxsize=360000, maxsave=9):
"""Open logfile."""
return ManagedLog(name, maxsize, maxsave)
def writelog(logobj, data):
"""Write logfile."""
try:

View File

@@ -22,23 +22,24 @@ throughout wicd.
# 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
import locale
import os
import re
from pipes import quote
import socket
import string
from subprocess import Popen, STDOUT, PIPE, call
from subprocess import getoutput
import sys
from threading import Thread
from gi.repository import GLib as gobject
from wicd.translations import _
# wicd imports
from . import wpath
from wicd import wpath
# Connection state constants
NOT_CONNECTED = 0
@@ -46,13 +47,11 @@ CONNECTING = 1
WIRELESS = 2
WIRED = 3
SUSPENDED = 4
_const_status_dict = {
NOT_CONNECTED: _('Not connected'),
_const_status_dict = {NOT_CONNECTED: _('Not connected'),
CONNECTING: _('Connection in progress'),
WIRELESS: _('Connected to a wireless network'),
WIRED: _('Connected to a wired network'),
SUSPENDED: _('Connection suspended'),
}
SUSPENDED: _('Connection suspended')}
# Automatic app selection constant
AUTO = 0
@@ -75,16 +74,14 @@ ROUTE = 2
GKSUDO = 1
KDESU = 2
KTSUSS = 3
_sudo_dict = {
AUTO : "",
_sudo_dict = {AUTO: "",
GKSUDO: "gksudo",
KDESU: "kdesu",
KTSUSS: "ktsuss",
}
KTSUSS: "ktsuss"}
_status_dict = {
'aborted': _('Connection Cancelled'),
'association_failed': _('Connection failed: Could not contact the ' + \
'association_failed': _('Connection failed: Could not contact the '
'wireless access point.'),
'bad_pass': _('Connection Failed: Bad password'),
'configuring_interface': _('Configuring wireless interface...'),
@@ -107,6 +104,7 @@ _status_dict = {
'verifying_association': _('Verifying access point association...'),
}
class WicdError(Exception):
"""Custom Exception type."""
pass
@@ -165,6 +163,7 @@ def Run(cmd, include_stderr=False, return_pipe=False,
else:
return f.communicate()[0].decode()
def LaunchAndWait(cmd):
"""Launches the given program with the given arguments, then blocks.
@@ -179,6 +178,7 @@ def LaunchAndWait(cmd):
p = Popen(cmd, shell=False, stdout=PIPE, stderr=STDOUT, stdin=None)
return p.wait()
def IsValidIP(ip):
"""Make sure an entered IP is valid."""
if not ip:
@@ -189,6 +189,7 @@ def IsValidIP(ip):
return False
return True
def IsValidIPv4(ip):
''' Make sure an entered IP is a valid IPv4. '''
try:
@@ -197,6 +198,7 @@ def IsValidIPv4(ip):
return False
return True
def IsValidIPv6(ip):
''' Make sure an entered IP is a valid IPv6. '''
try:
@@ -205,6 +207,7 @@ def IsValidIPv6(ip):
return False
return True
def PromptToStartDaemon():
"""Prompt the user to start the daemon"""
daemonloc = wpath.sbin + 'wicd'
@@ -221,6 +224,7 @@ def PromptToStartDaemon():
os.spawnvpe(os.P_WAIT, sudo_prog, sudo_args, os.environ)
return True
def RunRegex(regex, s):
"""runs a regex search on a string"""
m = regex.search(s)
@@ -229,10 +233,12 @@ def RunRegex(regex, s):
else:
return None
def WriteLine(my_file, text):
"""write a line to a file"""
my_file.write(text + "\n")
def ExecuteScripts(scripts_dir, verbose=False, extra_parameters=()):
"""Execute every executable file in a given directory."""
if not os.path.exists(scripts_dir):
@@ -245,6 +251,7 @@ def ExecuteScripts(scripts_dir, verbose=False, extra_parameters=()):
ExecuteScript(os.path.abspath(obj), verbose=verbose,
extra_parameters=extra_parameters)
def ExecuteScript(script, verbose=False, extra_parameters=()):
"""Execute a command and send its output to the bit bucket."""
extra_parameters = [quote(s) for s in extra_parameters]
@@ -257,6 +264,7 @@ def ExecuteScript(script, verbose=False, extra_parameters=()):
if verbose:
print(("%s returned %s" % (script, ret)))
def ReadFile(filename):
"""read in a file and return it's contents as a string"""
if not os.path.exists(filename):
@@ -266,6 +274,7 @@ def ReadFile(filename):
my_file.close()
return str(data)
def to_bool(var):
"""Convert a string to type bool, but make "False"/"0" become False."""
if var in ("False", "0"):
@@ -274,6 +283,7 @@ def to_bool(var):
var = bool(var)
return var
def Noneify(variable, convert_to_bool=True):
"""Convert string types to either None or booleans"""
# set string Nones to real Nones
@@ -287,6 +297,7 @@ def Noneify(variable, convert_to_bool=True):
return True
return variable
def ParseEncryption(network):
"""Parse through an encryption template file
@@ -310,7 +321,7 @@ def ParseEncryption(network):
# This is the last line, so we just write it.
config_file = ''.join([config_file, line])
elif "$_" in line:
for cur_val in re.findall('\$_([A-Z0-9_]+)', line):
for cur_val in re.findall(r'\$_([A-Z0-9_]+)', line):
if cur_val:
rep_val = network.get(cur_val.lower())
if not rep_val:
@@ -344,6 +355,7 @@ def ParseEncryption(network):
f.write(config_file)
f.close()
def LoadEncryptionMethods(wired=False):
"""Load encryption methods from configuration files
@@ -370,6 +382,7 @@ def LoadEncryptionMethods(wired = False):
encryptionTypes.append(parsed_template)
return encryptionTypes
def __parse_field_ent(fields, field_type='require'):
fields = fields.split(" ")
ret = []
@@ -383,6 +396,7 @@ def __parse_field_ent(fields, field_type='require'):
ret.append([val, disp_val[1:]])
return ret
def _parse_enc_template(enctype):
"""Parse an encryption template."""
def parse_ent(line, key):
@@ -405,10 +419,12 @@ def _parse_enc_template(enctype):
if line.startswith("name") and not cur_type["name"]:
cur_type["name"] = parse_ent(line, "name")
elif line.startswith("require"):
cur_type["required"] = __parse_field_ent(parse_ent(line, "require"))
cur_type["required"] = __parse_field_ent(parse_ent(line,
"require"))
if not cur_type["required"]:
# An error occured parsing the require line.
print(("Invalid 'required' line found in template %s" % enctype))
print("Invalid 'required' line found in template %s" %
enctype)
continue
elif line.startswith("optional"):
cur_type["optional"] = __parse_field_ent(parse_ent(line,
@@ -416,30 +432,32 @@ def _parse_enc_template(enctype):
field_type="optional")
if not cur_type["optional"]:
# An error occured parsing the optional line.
print(("Invalid 'optional' line found in template %s" % enctype))
print("Invalid 'optional' line found in template %s" %
enctype)
continue
elif line.startswith("protected"):
cur_type["protected"] = __parse_field_ent(
parse_ent(line, "protected"),
field_type="protected"
)
cur_type["protected"] = __parse_field_ent(parse_ent(line,
"protected"),
field_type="protected")
if not cur_type["protected"]:
# An error occured parsing the protected line.
print(("Invalid 'protected' line found in template %s" % enctype))
print("Invalid 'protected' line found in template %s" %
enctype)
continue
elif line.startswith("----"):
# We're done.
break
f.close()
if not cur_type["required"]:
print(("Failed to find a 'require' line in template %s" % enctype))
print("Failed to find a 'require' line in template %s" % enctype)
return None
if not cur_type["name"]:
print(("Failed to find a 'name' line in template %s" % enctype))
print("Failed to find a 'name' line in template %s" % enctype)
return None
else:
return cur_type
def noneToString(text):
"""Convert None, "None", or "" to string type "None"
@@ -452,6 +470,7 @@ def noneToString(text):
else:
return to_unicode(text)
def sanitize_config(s):
"""Sanitize property names to be used in config-files."""
allowed = string.ascii_letters + '_' + string.digits
@@ -461,6 +480,7 @@ def sanitize_config(s):
# make it simple.
return s.encode('ascii', 'replace').translate(None, table)
def sanitize_escaped(s):
"""Sanitize double-escaped unicode strings."""
lastpos = -1
@@ -473,6 +493,7 @@ def sanitize_escaped(s):
s = s.replace('\\x'+c, chr(int(c, 16)))
return s
def to_unicode(x):
"""Attempts to convert a string to utf-8."""
# If this is a unicode string, encode it and return
@@ -498,6 +519,7 @@ def to_unicode(x):
return ret
def RenameProcess(new_name):
"""Renames the process calling the function to the given name."""
if 'linux' not in sys.platform:
@@ -509,10 +531,11 @@ def RenameProcess(new_name):
libc = ctypes.CDLL(find_library('c'))
libc.prctl(15, new_name, 0, 0, 0)
return True
except:
except Exception:
print("rename failed")
return False
def detect_desktop_environment():
"""Try to determine which desktop environment is in use.
@@ -534,6 +557,7 @@ def detect_desktop_environment():
pass
return desktop_environment
def get_sudo_cmd(msg, prog_num=0):
"""Returns a graphical sudo command for generic use."""
sudo_prog = choose_sudo_prog(prog_num)
@@ -545,6 +569,7 @@ def get_sudo_cmd(msg, prog_num=0):
msg_flag = "--caption"
return [sudo_prog, msg_flag, msg]
def choose_sudo_prog(prog_num=0):
"""Try to intelligently decide which graphical sudo program to use."""
if prog_num:
@@ -566,6 +591,7 @@ def choose_sudo_prog(prog_num=0):
return path
return ""
def find_path(cmd):
"""Try to find a full path for a given file name.
@@ -583,6 +609,7 @@ def find_path(cmd):
return os.path.join(path, cmd)
return None
def noneToBlankString(text):
"""Converts NoneType or "None" to a blank string."""
if text in (None, "None"):
@@ -590,6 +617,7 @@ def noneToBlankString(text):
else:
return str(text)
def stringToNone(text):
"""Performs opposite function of noneToString."""
if text in ("", None, "None"):
@@ -597,12 +625,14 @@ def stringToNone(text):
else:
return str(text)
def checkboxTextboxToggle(checkbox, textboxes):
"""Manage {de,}activation of textboxes depending on checkboxes."""
# FIXME: should be moved to UI-specific files?
for textbox in textboxes:
textbox.set_sensitive(checkbox.get_active())
def threaded(f):
"""A decorator that will make any function run in a new thread."""
@@ -618,6 +648,7 @@ def threaded(f):
return wrapper
def timeout_add(time, func, milli=False):
"""Convience function for running a function on a timer."""
if hasattr(gobject, "timeout_add_seconds") and not milli:
@@ -627,6 +658,7 @@ def timeout_add(time, func, milli=False):
time = time * 1000
return gobject.timeout_add(time, func)
def izip_longest(*args, **kwds):
"""Implement the itertools.izip_longest method.
@@ -635,8 +667,10 @@ def izip_longest(*args, **kwds):
"""
# izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
fillvalue = kwds.get('fillvalue')
def sentinel(counter=([fillvalue]*(len(args)-1)).pop):
yield counter() # yields the fillvalue, or raises IndexError
fillers = repeat(fillvalue)
iters = [chain(it, sentinel(), fillers) for it in args]
try:
@@ -645,6 +679,7 @@ def izip_longest(*args, **kwds):
except IndexError:
pass
def grouper(n, iterable, fillvalue=None):
"""Iterate over several elements at once

View File

@@ -24,9 +24,9 @@ when appropriate.
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from gi.repository import GLib as gobject
import time
from gi.repository import GLib as gobject
from dbus import DBusException
from wicd import wpath
@@ -46,6 +46,7 @@ wireless = dbus_dict["wireless"]
mainloop = None
def diewithdbus(func):
"""
Decorator catching DBus exceptions, making wicd quit.
@@ -69,6 +70,7 @@ def diewithdbus(func):
wrapper.__doc__ = func.__doc__
return wrapper
class ConnectionStatus(object):
"""Class for monitoring the computer's connection status."""
def __init__(self):
@@ -278,15 +280,18 @@ class ConnectionStatus(object):
if wired.CheckIfWiredConnecting():
info = ["wired"]
else:
info = ["wireless",
misc.noneToBlankString(wireless.GetCurrentNetwork(iwconfig))]
info = ["wireless", misc.
noneToBlankString(wireless.
GetCurrentNetwork(iwconfig))]
elif state == misc.WIRELESS:
self.reconnect_tries = 0
info = [str(wifi_ip),
misc.noneToBlankString(wireless.GetCurrentNetwork(iwconfig)),
misc.noneToBlankString(wireless.
GetCurrentNetwork(iwconfig)),
str(self._get_printable_sig_strength()),
str(wireless.GetCurrentNetworkID(iwconfig)),
misc.noneToBlankString(wireless.GetCurrentBitrate(iwconfig))]
misc.noneToBlankString(wireless.
GetCurrentBitrate(iwconfig))]
elif state == misc.WIRED:
self.reconnect_tries = 0
info = [str(wired_ip)]
@@ -301,8 +306,8 @@ class ConnectionStatus(object):
self.signal_changed)):
daemon.EmitStatusChanged(state, info)
if (state != self.last_state) and (state == misc.NOT_CONNECTED) and \
(not daemon.GetForcedDisconnect()):
if (state != self.last_state and state == misc.NOT_CONNECTED and
not daemon.GetForcedDisconnect()):
daemon.Disconnect()
# Disconnect() sets forced disconnect = True
# so we'll revert that
@@ -364,22 +369,24 @@ class ConnectionStatus(object):
# before we reconnect
print('Disconnecting from network')
wireless.DisconnectWireless()
print(('Trying to reconnect to last used wireless ' + \
'network'))
print('Trying to reconnect to last used wireless network')
wireless.ConnectWireless(cur_net_id)
else:
daemon.AutoConnect(True, reply_handler=reply_handle,
error_handler=err_handle)
self.reconnecting = False
def reply_handle():
"""Just a dummy function needed for asynchronous dbus calls."""
pass
def err_handle(error):
"""Just a dummy function needed for asynchronous dbus calls."""
pass
def main():
"""Starts the connection monitor.

View File

@@ -1,6 +1,3 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""networking - Provides wrappers for common network operations
This module provides wrappers of the common network tasks as well as
@@ -51,10 +48,9 @@ from signal import SIGTERM
from functools import cmp_to_key
# wicd imports
from . import misc
from . import wpath
from .backend import BackendManager
from .translations import _
from wicd import misc
from wicd import wpath
from wicd.backend import BackendManager
if __name__ == '__main__':
wpath.chdir(__file__)
@@ -62,6 +58,7 @@ if __name__ == '__main__':
BACKEND = None
BACKEND_MGR = BackendManager()
def abortable(func):
"""Mark a method in a ConnectionThread as abortable.
@@ -79,6 +76,7 @@ def abortable(func):
wrapper.__module = func.__module__
return wrapper
def get_backend_list():
"""Returns a list of available backends."""
if BACKEND_MGR:
@@ -86,6 +84,7 @@ def get_backend_list():
else:
return [""]
def get_backend_update_interval():
"""Returns the suggested connection status update interval."""
if BACKEND_MGR:
@@ -93,6 +92,7 @@ def get_backend_update_interval():
else:
return 5 # Seconds, this should never happen though.
def get_current_backend():
"""Returns the current backend instance."""
if BACKEND_MGR:
@@ -100,10 +100,12 @@ def get_current_backend():
else:
return None
def get_backend_description(backend_name):
"""Returns the description of the currently loaded backend."""
return BACKEND_MGR.get_backend_description(backend_name)
def get_backend_description_dict():
"""Returns a dict of all available backend descriptions."""
d = {}
@@ -112,6 +114,7 @@ def get_backend_description_dict():
d[be] = get_backend_description(be)
return d
def expand_script_macros(script, msg, bssid, essid):
"""Expands any supported macros in a script.
@@ -162,6 +165,7 @@ class Controller(object):
def get_debug(self):
"""Getter for debug property."""
return self._debug
def set_debug(self, value):
"""Setter for debug property."""
self._debug = value
@@ -174,6 +178,7 @@ class Controller(object):
self._dhcp_client = value
if self.iface:
self.iface.DHCP_CLIENT = value
def get_dhcp_client(self):
"""Getter for dhcp_client property."""
return self._dhcp_client
@@ -184,6 +189,7 @@ class Controller(object):
self._flush_tool = value
if self.iface:
self.iface.flush_tool = value
def get_flush_tool(self):
"""Getter for flush_tool property."""
return self._flush_tool
@@ -239,7 +245,8 @@ class Controller(object):
extra_parameters=(nettype, name, mac))
if self.post_disconnect_script:
print('Running post-disconnect script')
misc.ExecuteScript(expand_script_macros(self.post_disconnect_script,
misc.ExecuteScript(expand_script_macros(self.
post_disconnect_script,
'post-disconnection',
mac, name),
self.debug)
@@ -364,6 +371,7 @@ class ConnectThread(threading.Thread):
self._should_die = val
finally:
self.lock.release()
def get_should_die(self):
"""Getter for should_die property."""
return self._should_die
@@ -416,8 +424,8 @@ class ConnectThread(threading.Thread):
iface.Down()
@abortable
def run_global_scripts_if_needed(self, script_dir, extra_parameters=()):
""" Run global scripts if needed. '"""
def run_scripts(self, script_dir, extra_parameters=()):
"""Execute all script in provided script_dir."""
misc.ExecuteScripts(script_dir, verbose=self.debug,
extra_parameters=extra_parameters)
@@ -445,9 +453,10 @@ class ConnectThread(threading.Thread):
@abortable
def set_broadcast_address(self, iface):
"""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')
print(('Setting the broadcast address...' + self.network['broadcast']))
print('Setting the broadcast address...' +
self.network['broadcast'])
iface.SetAddress(broadcast=self.network['broadcast'])
@abortable
@@ -467,9 +476,9 @@ class ConnectThread(threading.Thread):
else:
# Run dhcp...
self.SetStatus('running_dhcp')
if self.network.get('usedhcphostname') == None:
if self.network.get('usedhcphostname') is None:
self.network['usedhcphostname'] = False
if self.network.get('dhcphostname') == None:
if self.network.get('dhcphostname') is None:
self.network['dhcphostname'] = os.uname()[1]
if self.network['usedhcphostname']:
hname = self.network['dhcphostname']
@@ -478,9 +487,14 @@ class ConnectThread(threading.Thread):
hname = None
print("Running DHCP with NO hostname")
# Check if a global DNS is configured. If it is, then let the DHCP know *not* to update resolv.conf
# Check if a global DNS is configured. If it is, then let the DHCP
# know *not* to update resolv.conf
staticdns = False
if self.network.get('use_global_dns') or (self.network.get('use_static_dns') and (self.network.get('dns1') or self.network.get('dns2') or self.network.get('dns3'))):
if (self.network.get('use_global_dns') or
(self.network.get('use_static_dns') and
(self.network.get('dns1') or
self.network.get('dns2') or
self.network.get('dns3')))):
staticdns = True
dhcp_status = iface.StartDHCP(hname, staticdns)
@@ -514,8 +528,9 @@ class ConnectThread(threading.Thread):
misc.Noneify(self.global_dns_3),
misc.Noneify(self.global_dns_dom),
misc.Noneify(self.global_search_dom))
elif self.network.get('use_static_dns') and (self.network.get('dns1') or
self.network.get('dns2') or self.network.get('dns3')):
elif (self.network.get('use_static_dns') and
(self.network.get('dns1') or self.network.get('dns2')
or self.network.get('dns3'))):
self.SetStatus('setting_static_dns')
iface.SetDNS(self.network.get('dns1'),
self.network.get('dns2'),
@@ -592,6 +607,7 @@ class Wireless(Controller):
self._wireless_interface = value
if self.wiface:
self.wiface.SetInterface(value)
def get_wireless_iface(self):
"""Getter for wireless_interface property."""
return self._wireless_interface
@@ -602,6 +618,7 @@ class Wireless(Controller):
self._wpa_driver = value
if self.wiface:
self.SetWPADriver(value)
def get_wpa_driver(self):
"""Getter for wpa_driver property."""
return self._wpa_driver
@@ -610,6 +627,7 @@ class Wireless(Controller):
def set_iface(self, value):
"""Setter for iface property."""
self.wiface = value
def get_iface(self):
"""Getter for iface property."""
return self.wiface
@@ -626,7 +644,8 @@ class Wireless(Controller):
backend = self._backend
if backend:
self.wiface = backend.WirelessInterface(self.wireless_interface,
self.debug, self.wpa_driver)
self.debug,
self.wpa_driver)
def Scan(self, essid=None):
"""Scan for available wireless networks.
@@ -644,8 +663,9 @@ class Wireless(Controller):
key = 'quality'
else:
key = 'strength'
return ((x[key] > y[key]) - (x[key] < y[key])) # cmp(x[key], y[key])
return ((x[key] > y[key]) -
(x[key] < y[key])) # cmp(x[key], y[key])
if not self.wiface:
return []
@@ -656,7 +676,8 @@ class Wireless(Controller):
# If there is a hidden essid then set it now, so that when it is
# scanned it will be recognized.
# Note: this does not always work, sometimes we have to pass it with "iwlist wlan0 scan essid -- XXXXX"
# Note: this does not always work, sometimes we have to pass it with
# "iwlist wlan0 scan essid -- XXXXX"
essid = misc.Noneify(essid)
if essid is not None:
print(('Setting hidden essid ' + essid))
@@ -679,13 +700,13 @@ class Wireless(Controller):
if not self.wiface:
return False
self.connecting_thread = WirelessConnectThread(network,
self.wireless_interface, self.wpa_driver, self.before_script,
self.after_script, self.pre_disconnect_script,
self.post_disconnect_script, self.global_dns_1,
self.global_dns_2, self.global_dns_3, self.global_dns_dom,
self.global_search_dom, self.wiface, self.should_verify_ap,
self.bitrate, self.allow_lower_bitrates, debug)
self.connecting_thread = WirelessConnectThread(
network, self.wireless_interface, self.wpa_driver,
self.before_script, self.after_script, self.pre_disconnect_script,
self.post_disconnect_script, self.global_dns_1, self.global_dns_2,
self.global_dns_3, self.global_dns_dom, self.global_search_dom,
self.wiface, self.should_verify_ap, self.bitrate,
self.allow_lower_bitrates, debug)
self.connecting_thread.setDaemon(True)
self.connecting_thread.start()
return True
@@ -780,8 +801,7 @@ class Wireless(Controller):
"""Stop wpa_supplicant."""
return self.wiface.StopWPA()
def CreateAdHocNetwork(self, essid, channel, ip, enctype, key,
enc_used):
def CreateAdHocNetwork(self, essid, channel, ip, enctype, key, enc_used):
"""Create an ad-hoc wireless network.
Keyword arguments:
@@ -860,7 +880,8 @@ class Wireless(Controller):
"""
cmd = 'rfkill list'
rfkill_out = misc.Run(cmd)
soft_blocks = [x for x in rfkill_out.split('\t') if x.startswith('Soft')]
soft_blocks = [x for x in rfkill_out.split('\t')
if x.startswith('Soft')]
for line in [x.strip() for x in soft_blocks]:
if line.endswith('yes'):
return True
@@ -944,15 +965,12 @@ class WirelessConnectThread(ConnectThread):
self.is_connecting = True
# Run pre-connection script.
self.run_global_scripts_if_needed(wpath.preconnectscripts,
extra_parameters=('wireless',
self.network['essid'],
self.network['bssid'])
)
self.run_scripts(wpath.preconnectscripts,
extra_parameters=('wireless', self.network['essid'],
self.network['bssid']))
self.run_script_if_needed(self.before_script, 'pre-connection',
self.network['bssid'], self.network['essid'])
# Take down interface and clean up previous connections.
self.put_iface_down(wiface)
self.release_dhcp_clients(wiface)
@@ -995,11 +1013,9 @@ class WirelessConnectThread(ConnectThread):
self.verify_association(wiface)
# Run post-connection script.
self.run_global_scripts_if_needed(wpath.postconnectscripts,
extra_parameters=('wireless',
self.network['essid'],
self.network['bssid'])
)
self.run_scripts(wpath.postconnectscripts,
extra_parameters=('wireless', self.network['essid'],
self.network['bssid']))
self.run_script_if_needed(self.after_script, 'post-connection',
self.network['bssid'], self.network['essid'])
@@ -1024,7 +1040,8 @@ class WirelessConnectThread(ConnectThread):
print("Verifying AP association...")
for tries in range(1, 11):
print(("Attempt %d of 10..." % tries))
retcode = self.iface.VerifyAPAssociation(self.network['gateway'])
retcode = self.iface.VerifyAPAssociation(self.
network['gateway'])
if retcode == 0:
print("Successfully associated.")
break
@@ -1062,9 +1079,9 @@ class WirelessConnectThread(ConnectThread):
if not self.network.get('psk'):
self.network['psk'] = self.network['key']
print(('WARNING: PSK generation failed! Falling back to ' + \
'wireless key.\nPlease report this error to the wicd ' + \
'developers!'))
print('WARNING: PSK generation failed! Falling back to '
'wireless key.\nPlease report this error to the wicd '
'developers!')
# Generate the wpa_supplicant file...
if self.network.get('enctype'):
self.SetStatus('generating_wpa_config')
@@ -1083,34 +1100,39 @@ class Wired(Controller):
self._wired_interface = None
self.liface = None
def set_link_detect(self, value):
@property
def link_detect(self):
"""Getter for link_detect property."""
return self._link_detect
@link_detect.setter
def link_detect(self, value):
"""Setter for link_detect property."""
self._link_detect = value
if self.liface:
self.liface.link_detect = value
def get_link_detect(self):
""" Getter for link_detect property. """
return self._link_detect
link_detect = property(get_link_detect, set_link_detect)
@property
def wired_iface(self):
"""Getter for wired_interface property."""
return self._wired_interface
def set_wired_iface(self, value):
@wired_iface.setter
def wired_iface(self, value):
"""Setter for wired_interface property."""
self._wired_interface = value
if self.liface:
self.liface.SetInterface(value)
def get_wired_iface(self):
""" Getter for wired_interface property. """
return self._wired_interface
wired_interface = property(get_wired_iface, set_wired_iface)
def set_iface(self, value):
""" Setter for iface property. """
self.liface = value
def get_iface(self):
@property
def iface(self):
"""Getter for iface property."""
return self.liface
iface = property(get_iface, set_iface)
@iface.setter
def iface(self, value):
"""Setter for iface property."""
self.liface = value
def LoadBackend(self, backend):
"""Load the backend up."""
@@ -1137,12 +1159,12 @@ class Wired(Controller):
"""
if not self.liface:
return False
self.connecting_thread = WiredConnectThread(network,
self.wired_interface, self.before_script, self.after_script,
self.pre_disconnect_script, self.post_disconnect_script,
self.global_dns_1, self.global_dns_2, self.global_dns_3,
self.global_dns_dom, self.global_search_dom, self.liface,
debug)
self.connecting_thread = WiredConnectThread(
network, self.wired_interface, self.before_script,
self.after_script, self.pre_disconnect_script,
self.post_disconnect_script, self.global_dns_1, self.global_dns_2,
self.global_dns_3, self.global_dns_dom, self.global_search_dom,
self.liface, debug)
self.connecting_thread.setDaemon(True)
self.connecting_thread.start()
return self.connecting_thread
@@ -1213,12 +1235,11 @@ class WiredConnectThread(ConnectThread):
self.is_connecting = True
# Run pre-connection script.
self.run_global_scripts_if_needed(wpath.preconnectscripts,
self.run_scripts(wpath.preconnectscripts,
extra_parameters=('wired', 'wired',
self.network['profilename'])
)
self.run_script_if_needed(self.before_script, 'pre-connection', 'wired',
'wired')
self.network['profilename']))
self.run_script_if_needed(self.before_script, 'pre-connection',
'wired', 'wired')
# Take down interface and clean up previous connections.
self.put_iface_down(liface)
@@ -1241,12 +1262,11 @@ class WiredConnectThread(ConnectThread):
self.set_dns_addresses(liface)
# Run post-connection script.
self.run_global_scripts_if_needed(wpath.postconnectscripts,
self.run_scripts(wpath.postconnectscripts,
extra_parameters=('wired', 'wired',
self.network['profilename'])
)
self.run_script_if_needed(self.after_script, 'post-connection', 'wired',
'wired')
self.network['profilename']))
self.run_script_if_needed(self.after_script, 'post-connection',
'wired', 'wired')
self.SetStatus('done')
print('Connecting thread exiting.')

View File

@@ -23,10 +23,10 @@ Used for when a laptop enters hibernation/suspension.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import sys
import dbus
import dbus.service
import sys
try:
bus = dbus.SystemBus()

View File

@@ -21,7 +21,7 @@
#
import locale
import os
from . import wpath
from wicd import wpath
import gettext
@@ -54,7 +54,7 @@ def get_gettext():
fallback=True)
return lang.gettext
_ = get_gettext()
_ = get_gettext() # noqa
# language[] should contain only strings in encryption templates, which
@@ -66,10 +66,12 @@ language = {}
# FIXME: these were present in wicd 1.7.0, can't find where they are.
# Leaving here for future reference, they should be removed whenever
# possible.
#language['cannot_start_daemon'] = _('Unable to connect to wicd daemon ' + \
# 'DBus interface. This typically means there was a problem starting ' + \
# 'the daemon. Check the wicd log for more information.')
#language['backend_alert'] = _('Changes to your backend won't occur until ' + \
# language['cannot_start_daemon'] = _('Unable to connect to wicd daemon '
# 'DBus interface. This typically means '
# 'there was a problem starting the '
# 'daemon. Check the wicd log for more '
# 'information.')
# language['backend_alert'] = _('Changes to your backend won't occur until '
# 'the daemon is restarted.')
# language['about_help'] = _('Stop a network connection in progress')
# language['connect'] = _('Connect')

View File

@@ -71,6 +71,7 @@ wireless_conf = os.path.join(wpath.etc, "wireless-settings.conf")
wired_conf = os.path.join(wpath.etc, "wired-settings.conf")
dhclient_conf = os.path.join(wpath.etc, "dhclient.conf.template")
class WicdDaemon(dbus.service.Object, object):
"""The main wicd daemon class.
@@ -140,6 +141,7 @@ class WicdDaemon(dbus.service.Object, object):
def get_debug_mode(self):
"""Getter for debug_mode property."""
return self._debug_mode
def set_debug_mode(self, mode):
"""Setter for debug_mode property."""
self._debug_mode = mode
@@ -162,7 +164,8 @@ class WicdDaemon(dbus.service.Object, object):
def SetWiredInterface(self, interface):
"""Sets the wired interface for the daemon to use."""
print("setting wired interface %s" % (str(interface)))
# Set it to a blank string, otherwise a network card named "None" will be searched
# Set it to a blank string, otherwise a network card named "None" will
# be searched
self.wired.wired_interface = noneToBlankString(interface)
self.config.set("Settings", "wired_interface", interface, write=True)
@@ -170,9 +173,11 @@ class WicdDaemon(dbus.service.Object, object):
def SetWirelessInterface(self, interface):
"""Sets the wireless interface the daemon will use."""
print("setting wireless interface %s" % (str(interface)))
# Set it to a blank string, otherwise a network card named "None" will be searched
# Set it to a blank string, otherwise a network card named "None" will
# be searched
self.wifi.wireless_interface = noneToBlankString(interface)
self.config.set("Settings", "wireless_interface", interface, write=True)
self.config.set("Settings", "wireless_interface", interface,
write=True)
@dbus.service.method('org.wicd.daemon')
def SetWPADriver(self, driver):
@@ -192,8 +197,8 @@ class WicdDaemon(dbus.service.Object, object):
self.wired.use_global_dns = use
@dbus.service.method('org.wicd.daemon')
def SetGlobalDNS(self, dns1=None, dns2=None, dns3=None,
dns_dom =None, search_dom=None):
def SetGlobalDNS(self, dns1=None, dns2=None, dns3=None, dns_dom=None,
search_dom=None):
"""Sets the global dns addresses."""
print("setting global dns")
self.config.set("Settings", "global_dns_1", misc.noneToString(dns1))
@@ -229,8 +234,8 @@ class WicdDaemon(dbus.service.Object, object):
print("setting backend to %s" % backend)
backends = networking.BACKEND_MGR.get_available_backends()
if backend not in backends:
print("backend %s not available, trying to fallback to another" \
% backend)
print(f"backend {backend} not available, trying to fallback to "
f"another")
try:
backend = backends[0]
except IndexError:
@@ -392,7 +397,7 @@ class WicdDaemon(dbus.service.Object, object):
and wait for the user to initiate reconnection.
"""
print('setting automatically reconnect when connection drops %s' % value)
print(f'setting automatically reconnect when connection drops {value}')
self.config.set("Settings", "auto_reconnect", misc.to_bool(value),
write=True)
self.auto_reconnect = misc.to_bool(value)
@@ -648,7 +653,8 @@ class WicdDaemon(dbus.service.Object, object):
@dbus.service.method("org.wicd.daemon")
def GetAppAvailable(self, app):
"""Determine if a given application is available."""
return bool(self.wifi.AppAvailable(app) or self.wired.AppAvailable(app))
return bool(self.wifi.AppAvailable(app) or
self.wired.AppAvailable(app))
@dbus.service.method('org.wicd.daemon')
def GetDHCPClient(self):
@@ -740,8 +746,8 @@ class WicdDaemon(dbus.service.Object, object):
elif self.GetWiredAutoConnectMethod() == 1:
network = wiredb.GetDefaultWiredNetwork()
if not network:
print("Couldn't find a default wired connection," + \
" wired autoconnect failed.")
print("Couldn't find a default wired connection, wired "
"autoconnect failed.")
self.wireless_bus._wireless_autoconnect(fresh)
return
@@ -749,7 +755,7 @@ class WicdDaemon(dbus.service.Object, object):
else:
network = wiredb.GetLastUsedWiredNetwork()
if not network:
print("no previous wired profile available, wired " + \
print("no previous wired profile available, wired "
"autoconnect failed.")
self.wireless_bus._wireless_autoconnect(fresh)
return
@@ -791,8 +797,8 @@ class WicdDaemon(dbus.service.Object, object):
"""Return whether connection results are available."""
wired_thread = self.wired.connecting_thread
wifi_thread = self.wifi.connecting_thread
if ((wired_thread and wired_thread.connect_result) or
(wifi_thread and wifi_thread.connect_result)):
if (wired_thread and wired_thread.connect_result or
wifi_thread and wifi_thread.connect_result):
return True
else:
return False
@@ -881,7 +887,8 @@ class WicdDaemon(dbus.service.Object, object):
iface = self.wireless_bus.DetectWirelessInterface()
if not iface:
iface = 'wlan0'
self.SetWirelessInterface(app_conf.get("Settings", "wireless_interface",
self.SetWirelessInterface(app_conf.get("Settings",
"wireless_interface",
default=iface))
iface = self.wired_bus.DetectWiredInterface()
if not iface:
@@ -891,7 +898,8 @@ class WicdDaemon(dbus.service.Object, object):
self.SetWPADriver(app_conf.get("Settings", "wpa_driver",
default="wext"))
self.SetAlwaysShowWiredInterface(app_conf.get("Settings",
self.SetAlwaysShowWiredInterface(app_conf.
get("Settings",
"always_show_wired_interface",
default=False))
self.SetUseGlobalDNS(app_conf.get("Settings", "use_global_dns",
@@ -905,7 +913,8 @@ class WicdDaemon(dbus.service.Object, object):
self.SetGlobalDNS(dns1, dns2, dns3, dns_dom, search_dom)
self.SetAutoReconnect(app_conf.get("Settings", "auto_reconnect",
default=True))
self.SetDebugMode(app_conf.get("Settings", "debug_mode", default=False))
self.SetDebugMode(app_conf.get("Settings", "debug_mode",
default=False))
self.SetWiredAutoConnectMethod(app_conf.get("Settings",
"wired_connect_mode",
default=1))
@@ -959,9 +968,6 @@ class WicdDaemon(dbus.service.Object, object):
print("Using wireless interface..." + self.GetWirelessInterface())
print("Using wired interface..." + self.GetWiredInterface())
##############################
###### Wireless Daemon #######
##############################
class WirelessDaemon(dbus.service.Object, object):
"""DBus interface for wireless connection operations."""
@@ -980,6 +986,7 @@ class WirelessDaemon(dbus.service.Object, object):
def get_debug_mode(self):
"""Getter for the debug_mode property."""
return self._debug_mode
def set_debug_mode(self, mode):
"""Setter for the debug_mode property."""
self._debug_mode = mode
@@ -1115,8 +1122,8 @@ class WirelessDaemon(dbus.service.Object, object):
# We don't write script settings here.
prop = misc.sanitize_config(prop)
if prop.endswith('script'):
print('Setting script properties through the daemon' \
+ ' is not permitted.')
print('Setting script properties through the daemon is not '
'permitted.')
return False
# whitelist some props that need different handling
if prop in ('key_index', ):
@@ -1160,7 +1167,7 @@ class WirelessDaemon(dbus.service.Object, object):
"""Returns the current dbm signal strength."""
try:
dbm_strength = int(self.wifi.GetDBMStrength(iwconfig))
except:
except Exception:
dbm_strength = 0
return dbm_strength
@@ -1178,7 +1185,8 @@ class WirelessDaemon(dbus.service.Object, object):
if self.LastScan[x]['essid'] == currentESSID:
return x
if self.debug_mode:
print('GetCurrentNetworkID: Returning -1, current network not found')
print('GetCurrentNetworkID: Returning -1, current network not '
'found')
return -1
@dbus.service.method('org.wicd.daemon.wireless')
@@ -1202,15 +1210,14 @@ class WirelessDaemon(dbus.service.Object, object):
# is done.
self.wifi.before_script = self.GetWirelessProperty(nid, 'beforescript')
self.wifi.after_script = self.GetWirelessProperty(nid, 'afterscript')
self.wifi.pre_disconnect_script = self.GetWirelessProperty(nid,
'predisconnectscript')
self.wifi.post_disconnect_script = self.GetWirelessProperty(nid,
'postdisconnectscript')
self.wifi.pre_disconnect_script = (
self.GetWirelessProperty(nid, 'predisconnectscript'))
self.wifi.post_disconnect_script = (
self.GetWirelessProperty(nid, 'postdisconnectscript'))
self.wifi.bitrate = self.GetWirelessProperty(nid, 'bitrate')
self.wifi.allow_lower_bitrates = self.GetWirelessProperty(nid,
'allow_lower_bitrates')
print('Connecting to wireless network ' + \
str(self.LastScan[nid]['essid']))
self.wifi.allow_lower_bitrates = (
self.GetWirelessProperty(nid, 'allow_lower_bitrates'))
print(f"Connecting to wireless network {self.LastScan[nid]['essid']}")
# disconnect to make sure that scripts are run
self.wifi.Disconnect()
self.daemon.wired_bus.wired.Disconnect()
@@ -1220,7 +1227,9 @@ class WirelessDaemon(dbus.service.Object, object):
@dbus.service.method('org.wicd.daemon.wireless')
def CheckIfWirelessConnecting(self):
"""Returns True if wireless interface is connecting, otherwise False."""
"""
Returns True if wireless interface is connecting, otherwise False.
"""
if self.wifi.connecting_thread:
return self.wifi.connecting_thread.is_connecting
else:
@@ -1325,8 +1334,8 @@ class WirelessDaemon(dbus.service.Object, object):
"""Writes a particular wireless property to disk."""
option = misc.sanitize_config(option)
if option.endswith("script"):
print('You cannot save script information to disk through ' + \
'the daemon.')
print('You cannot save script information to disk through the '
'daemon.')
return
config = self.config
cur_network = self.LastScan[nid]
@@ -1376,18 +1385,18 @@ class WirelessDaemon(dbus.service.Object, object):
def DeleteWirelessNetwork(self, section):
"""Deletes a wireless network section."""
section = misc.to_unicode(section)
print("Deleting wireless settings for %s (%s)" % \
print("Deleting wireless settings for %s (%s)" %
(self.config.get(section, 'essid'), str(section)))
self.config.remove_section(section)
self.config.write()
@dbus.service.signal(dbus_interface='org.wicd.daemon.wireless', \
@dbus.service.signal(dbus_interface='org.wicd.daemon.wireless',
signature='')
def SendStartScanSignal(self):
"""Emits a signal announcing a scan has started."""
self._scanning = True
@dbus.service.signal(dbus_interface='org.wicd.daemon.wireless', \
@dbus.service.signal(dbus_interface='org.wicd.daemon.wireless',
signature='')
def SendEndScanSignal(self):
"""Emits a signal announcing a scan has finished."""
@@ -1395,10 +1404,11 @@ class WirelessDaemon(dbus.service.Object, object):
def _wireless_autoconnect(self, fresh=True):
"""Attempts to autoconnect to a wireless network."""
print("No wired connection present, attempting to autoconnect " + \
"to wireless network")
print("No wired connection present, attempting to autoconnect to "
"wireless network")
if self.wifi.wireless_interface is None:
print('Autoconnect failed because wireless interface returned None')
print('Autoconnect failed because wireless interface returned '
'None')
return
if fresh:
self.Scan(sync=True)
@@ -1409,20 +1419,17 @@ class WirelessDaemon(dbus.service.Object, object):
print(network["essid"] + ' has profile')
if bool(network.get('automatic')):
if network.get('never'):
print(network["essid"],'marked never connect')
print(f'{network["essid"]} marked never connect')
continue
else:
print(network["essid"],'has no never connect value')
print('trying to automatically connect to...' + \
network["essid"])
print(f'{network["essid"]} has no never connect value')
print(f'trying to automatically connect to... '
f'{network["essid"]}')
self.ConnectWireless(x)
time.sleep(1)
return
print("Unable to autoconnect, you'll have to manually connect")
###########################
###### Wired Daemon #######
###########################
class WiredDaemon(dbus.service.Object, object):
"""DBus interface for wired connection operations."""
@@ -1440,6 +1447,7 @@ class WiredDaemon(dbus.service.Object, object):
def get_debug_mode(self):
"""Getter for debug_mode property."""
return self._debug_mode
def set_debug_mode(self, mode):
"""Setter for debug_mode property."""
self._debug_mode = mode
@@ -1492,8 +1500,8 @@ class WiredDaemon(dbus.service.Object, object):
if self.WiredNetwork:
prop = misc.sanitize_config(prop)
if prop.endswith('script'):
print('Setting script properties through the daemon' \
+ ' is not permitted.')
print('Setting script properties through the daemon is not '
'permitted.')
return False
self.WiredNetwork[prop] = misc.to_unicode(misc.Noneify(value))
return True
@@ -1562,7 +1570,8 @@ class WiredDaemon(dbus.service.Object, object):
self.wired.Disconnect()
self.daemon.SetForcedDisconnect(False)
self.UnsetWiredLastUsed()
self.config.set(self._cur_wired_prof_name, "lastused", True, write=True)
self.config.set(self._cur_wired_prof_name, "lastused", True,
write=True)
self.wired.Connect(self.WiredNetwork, debug=self.debug_mode)
self.daemon.UpdateState()
@@ -1576,9 +1585,9 @@ class WiredDaemon(dbus.service.Object, object):
if self.config.has_section(profilename):
return False
for option in ["ip", "broadcast", "netmask", "gateway", "search_domain",
"dns_domain", "dns1", "dns2", "dns3", "beforescript",
"afterscript", "predisconnectscript",
for option in ["ip", "broadcast", "netmask", "gateway",
"search_domain", "dns_domain", "dns1", "dns2", "dns3",
"beforescript", "afterscript", "predisconnectscript",
"postdisconnectscript", "encryption_enabled"]:
self.config.set(profilename, option, None)
self.config.set(profilename, "default", default)
@@ -1696,6 +1705,7 @@ class WiredDaemon(dbus.service.Object, object):
''' Returns a list of wireless interfaces on the system. '''
return wnettools.GetWiredInterfaces()
def usage():
"""Print help screen."""
print("""
@@ -1712,6 +1722,7 @@ Arguments:
\t-h\t--help\t\tPrint this help.
""" % (wpath.version + ' (bzr-r%s)' % wpath.revision))
def daemonize():
"""Disconnect from the controlling terminal.
@@ -1730,7 +1741,8 @@ def daemonize():
if pid > 0:
sys.exit(0)
except OSError as e:
print("Fork #1 failed: %d (%s)" % (e.errno, e.strerror), file=sys.stderr)
print("Fork #1 failed: %d (%s)" % (e.errno, e.strerror),
file=sys.stderr)
sys.exit(1)
# Decouple from parent environment to stop us from being a zombie.
@@ -1752,7 +1764,8 @@ def daemonize():
os.umask(0)
os.chdir('/')
except OSError as e:
print("Fork #2 failed: %d (%s)" % (e.errno, e.strerror), file=sys.stderr)
print("Fork #2 failed: %d (%s)" % (e.errno, e.strerror),
file=sys.stderr)
sys.exit(1)
sys.stdin.close()
@@ -1787,9 +1800,12 @@ def main(argv):
# back up resolv.conf before we do anything else
try:
backup_location = wpath.varlib + 'resolv.conf.orig'
# Don't back up if the backup already exists, either as a regular file or a symlink
# The backup file should have been cleaned up by wicd, so perhaps it didn't exit cleanly...
if not os.path.exists(backup_location) and not os.path.islink(backup_location):
# Don't back up if the backup already exists, either as a regular file
# or a symlink
# The backup file should have been cleaned up by wicd, so perhaps it
# didn't exit cleanly...
if (not os.path.exists(backup_location) and
not os.path.islink(backup_location)):
if os.path.islink('/etc/resolv.conf'):
dest = os.readlink('/etc/resolv.conf')
os.symlink(dest, backup_location)
@@ -1808,9 +1824,9 @@ def main(argv):
try:
opts, args = getopt.getopt(sys.argv[1:], 'fenoahkc',
['help', 'no-daemon', 'no-poll', 'no-stderr',
'no-stdout', 'no-autoconnect', 'kill',
'keep-connection'])
['help', 'no-daemon', 'no-poll',
'no-stderr', 'no-stdout', 'no-autoconnect',
'kill', 'keep-connection'])
except getopt.GetoptError:
# Print help information and exit
usage()
@@ -1930,6 +1946,7 @@ def main(argv):
pass
daemon.DaemonClosing()
def on_exit(child_pid):
"""Called when a SIGTERM is caught, kills monitor.py before exiting."""
if child_pid:
@@ -1947,8 +1964,8 @@ def on_exit(child_pid):
if __name__ == '__main__':
if os.getuid() != 0:
print(("Root privileges are required for the daemon to run properly." +
" Exiting."))
print("Root privileges are required for the daemon to run properly. "
"Exiting.")
sys.exit(1)
# No more needed since PyGObject 3.11, c.f.
# https://wiki.gnome.org/PyGObject/Threading

View File

@@ -31,29 +31,30 @@ class BaseWirelessInterface() -- Control a wireless network interface.
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import os
import re
import random
import time
import dbus
import socket, fcntl
import fcntl
import functools
import os
import random
import re
import shutil
from functools import cmp_to_key
import socket
import time
from . import wpath
from . import misc
from .misc import find_path
from wicd import wpath
from wicd import misc
from wicd.misc import find_path
# Regular expressions.
_re_mode = (re.I | re.M | re.S)
essid_pattern = re.compile('.*ESSID:"?(.*?)".*\n', _re_mode)
ap_mac_pattern = re.compile('.*Address: (.*?)\n', _re_mode)
channel_pattern = re.compile('.*Channel:?=? ?(\d+)', _re_mode)
strength_pattern = re.compile('.*Quality:?=? ?(\d+)\s*/?\s*(\d*)', _re_mode)
altstrength_pattern = re.compile('.*Signal level:?=? ?(\d+)\s*/?\s*(\d*)',
channel_pattern = re.compile(r'.*Channel:?=? ?(\d+)', _re_mode)
strength_pattern = re.compile(r'.*Quality:?=? ?(\d+)\s*/?\s*(\d*)', _re_mode)
altstrength_pattern = re.compile(r'.*Signal level:?=? ?(\d+)\s*/?\s*(\d*)',
_re_mode)
signaldbm_pattern = re.compile('.*Signal level:?=? ?(-\d\d*)', _re_mode)
bitrates_pattern = re.compile('([\d\.]+)\s+\S+/s', _re_mode)
signaldbm_pattern = re.compile(r'.*Signal level:?=? ?(-\d\d*)', _re_mode)
bitrates_pattern = re.compile(r'([\d\.]+)\s+\S+/s', _re_mode)
mode_pattern = re.compile('.*Mode:([A-Za-z-]*?)\n', _re_mode)
freq_pattern = re.compile('.*Frequency:(.*?)\n', _re_mode)
wep_pattern = re.compile('.*Encryption key:(.*?)\n', _re_mode)
@@ -66,11 +67,11 @@ ip_up = re.compile(r'flags=[0.9]*<([^>]*)>', re.S)
ip_pattern = re.compile(r'inet [Aa]d?dr[^.]*:([^.]*\.[^.]*\.[^.]*\.[0-9]*)',
re.S)
ip_pattern1 = re.compile(r'inet ([^.]*\.[^.]*\.[^.]*\.[0-9]*)', re.S)
bssid_pattern = re.compile('.*[(Access Point)|(Cell)]: ' + \
bssid_pattern = re.compile('.*[(Access Point)|(Cell)]: '
'(([0-9A-Z]{2}:){5}[0-9A-Z]{2})', _re_mode)
bitrate_pattern = re.compile('.*Bit Rate[=:](.*?/s)', _re_mode)
opmode_pattern = re.compile('.*Mode:(.*?) ', _re_mode)
authmethods_pattern = re.compile('.*Authentication capabilities ' + \
authmethods_pattern = re.compile('.*Authentication capabilities '
':\n(.*?)Current', _re_mode)
# Regular expressions for wpa_cli output
@@ -85,6 +86,9 @@ blacklist_norm = list(";`$!*|><&\\")
blacklist_strict_t = str.maketrans(dict.fromkeys(blacklist_strict, None))
blacklist_norm_t = str.maketrans(dict.fromkeys(blacklist_norm, None))
_cache = {}
def _sanitize_string(string):
"""Sanitize string."""
if string:
@@ -92,6 +96,7 @@ def _sanitize_string(string):
else:
return string
def _sanitize_string_strict(string):
"""Sanitize string in a stricter way."""
if string:
@@ -99,7 +104,7 @@ def _sanitize_string_strict(string):
else:
return string
_cache = {}
def timedcache(duration=5):
"""A caching decorator for use with wnettools methods.
@@ -124,6 +129,7 @@ def timedcache(duration=5):
return _timedcache
def GetDefaultGateway():
"""Attempts to determine the default gateway by parsing route -n."""
route_info = misc.Run("route -n")
@@ -142,6 +148,7 @@ def GetDefaultGateway():
print('couldn\'t retrieve default gateway from route -n')
return gateway
def isWireless(devname):
"""
Classic-style wifi device classification using linux/wireless.h
@@ -167,6 +174,7 @@ def isWireless(devname):
sk.close()
return we is not None
def GetWirelessInterfaces():
"""Get available wireless interfaces.
@@ -177,21 +185,25 @@ def GetWirelessInterfaces():
"""
dev_dir = '/sys/class/net/'
ifnames = [iface for iface in os.listdir(dev_dir) if isWireless(str(iface))]
ifnames = [iface for iface in os.listdir(dev_dir)
if isWireless(str(iface))]
return ifnames
def GetWiredInterfaces():
"""Returns a list of wired interfaces on the system."""
basedir = '/sys/class/net/'
return [iface for iface in os.listdir(basedir)
if os.path.isdir(basedir + iface) and not 'wireless'
in os.listdir(basedir + iface) and
if os.path.isdir(basedir + iface) and
'wireless' not in os.listdir(basedir + iface) and
open(basedir + iface + "/type").readlines()[0].strip() == "1"]
def NeedsExternalCalls():
"""Returns True if the backend needs to use an external program."""
raise NotImplementedError
def GetWpaSupplicantDrivers():
"""Returns a list of all valid wpa_supplicant drivers."""
output = misc.Run(["wpa_supplicant", "-h"])
@@ -200,17 +212,20 @@ def GetWpaSupplicantDrivers():
except KeyError:
print("Warning: Couldn't get list of valid wpa_supplicant drivers")
return [""]
patt = re.compile("(\S+)\s+=.*")
patt = re.compile(r"(\S+)\s+=.*")
drivers = patt.findall(output) or [""]
# We cannot use the "wired" driver for wireless interfaces.
if 'wired' in drivers:
drivers.remove('wired')
return drivers
def IsValidWpaSuppDriver(driver):
"""Returns True if given string is a valid wpa_supplicant driver."""
output = misc.Run(["wpa_supplicant", "-D%s" % driver, "-iolan19",
"-c/etc/abcd%sdefzz.zconfz" % random.randint(1, 1000)])
return not "Unsupported driver" in output
return "Unsupported driver" not in output
def neediface(default_response):
"""A decorator for only running a method if self.iface is defined.
@@ -297,7 +312,6 @@ class BaseInterface(object):
print("WARNING: No path found for %s" % program)
return path
def _get_dhcp_command(self, flavor=None, hostname=None, staticdns=False):
"""Returns the correct DHCP client command.
@@ -328,36 +342,34 @@ class BaseInterface(object):
return (client, cmd)
# probably /var/lib/wicd/dhclient.conf with defaults
dhclient_conf_path = os.path.join(
wpath.varlib,
'dhclient.conf'
)
dhclient_conf_path = os.path.join(wpath.varlib, 'dhclient.conf')
client_dict = {
"dhclient":
{'connect' : r"%(cmd)s -cf %(dhclientconf)s %(extra)s %(iface)s",
'connect_with_hostname' : r"%(cmd)s -cf %(dhclientconf)s %(extra)s %(iface)s",
{'connect': r"%(cmd)s -cf %(dhclientconf)s "
r"%(extra)s %(iface)s",
'connect_with_hostname': r"%(cmd)s -cf %(dhclientconf)s "
r"%(extra)s %(iface)s",
'release': r"%(cmd)s -r %(iface)s",
'id' : misc.DHCLIENT,
},
'id': misc.DHCLIENT},
"pump":
{'connect': r"%(cmd)s -i %(iface)s %(extra)s",
'connect_with_hostname' : r"%(cmd)s -i %(iface)s -h %(hostname)s %(extra)s",
'connect_with_hostname': r"%(cmd)s -i %(iface)s -h "
r"%(hostname)s %(extra)s",
'release': r"%(cmd)s -r -i %(iface)s",
'id' : misc.PUMP,
},
'id': misc.PUMP},
"dhcpcd":
{'connect': r"%(cmd)s --noipv4ll %(extra)s %(iface)s",
'connect_with_hostname' : r"%(cmd)s -h %(hostname)s --noipv4ll %(extra)s %(iface)s ",
'connect_with_hostname': r"%(cmd)s -h %(hostname)s "
r"--noipv4ll %(extra)s %(iface)s ",
'release': r"%(cmd)s -k %(iface)s",
'id' : misc.DHCPCD,
},
'id': misc.DHCPCD},
"udhcpc":
{'connect': r"%(cmd)s -n -i %(iface)s %(extra)s",
'connect_with_hostname' : r"%(cmd)s -n -i %(iface)s -H %(hostname)s %(extra)s",
'connect_with_hostname': r"%(cmd)s -n -i %(iface)s -H "
r"%(hostname)s %(extra)s",
'release': r"killall -SIGUSR2 %(cmd)s",
'id' : misc.UDHCPC,
},
'id': misc.UDHCPC},
}
(client_name, cmd) = get_client_name(self.DHCP_CLIENT)
@@ -366,21 +378,24 @@ class BaseInterface(object):
if client_name == "dhclient" and flavor:
if hostname:
print('attempting to set hostname with dhclient')
print('using dhcpcd or another supported client may work better')
print('using dhcpcd or another supported client may work '
'better')
dhclient_template = \
open(os.path.join(wpath.etc, 'dhclient.conf.template'), 'r')
dhclient_template = open(os.path.
join(wpath.etc,
'dhclient.conf.template'), 'r')
output_conf = open(dhclient_conf_path, 'w')
for line in dhclient_template.readlines():
line = line.replace('# <WICDHOSTNAME>', 'send host-name "%s";' \
% hostname)
line = line.replace('# <WICDHOSTNAME>', 'send host-name '
'"%s";' % hostname)
output_conf.write(line)
output_conf.close()
dhclient_template.close()
else:
shutil.copy(os.path.join(wpath.etc, 'dhclient.conf.template'), \
shutil.copy(os.path.join(wpath.etc,
'dhclient.conf.template'),
dhclient_conf_path)
os.chmod(dhclient_conf_path, 0o644)
@@ -398,21 +413,21 @@ class BaseInterface(object):
extra_args = "--nohook resolv.conf"
if hostname:
return client_dict[client_name]['connect_with_hostname'] % \
return (client_dict[client_name]['connect_with_hostname'] %
{"cmd": cmd,
"iface": self.iface,
"hostname": hostname,
'extra': extra_args,
'dhclientconf' : dhclient_conf_path }
'dhclientconf': dhclient_conf_path})
else:
return client_dict[client_name]['connect'] % \
return (client_dict[client_name]['connect'] %
{"cmd": cmd,
"iface": self.iface,
'extra': extra_args,
'dhclientconf' : dhclient_conf_path }
'dhclientconf': dhclient_conf_path})
elif flavor == "release":
return client_dict[client_name]['release'] % \
{"cmd": cmd, "iface": self.iface}
return client_dict[client_name]['release'] % {"cmd": cmd,
"iface": self.iface}
else:
return client_dict[client_name]['id']
@@ -450,7 +465,7 @@ class BaseInterface(object):
"""
self.dhclient_cmd = self._find_program_path("dhclient")
if self.dhclient_cmd != None:
if self.dhclient_cmd is not None:
output = misc.Run(self.dhclient_cmd + " --version",
include_stderr=True)
if '4.' in output:
@@ -685,8 +700,7 @@ class BaseInterface(object):
client_dict = {misc.DHCLIENT: self._parse_dhclient,
misc.DHCPCD: self._parse_dhcpcd,
misc.PUMP: self._parse_pump,
misc.UDHCPC : self._parse_udhcpc,
}
misc.UDHCPC: self._parse_udhcpc}
DHCP_CLIENT = self._get_dhcp_command()
if DHCP_CLIENT in client_dict:
@@ -762,7 +776,8 @@ class BaseInterface(object):
print('Setting DNS : ' + dns)
valid_dns_list.append("nameserver %s\n" % dns)
else:
print('DNS IP %s is not a valid IP address, skipping' % dns)
print('DNS IP %s is not a valid IP address, skipping' %
dns)
if valid_dns_list:
resolv_params += ''.join(valid_dns_list)
@@ -862,8 +877,8 @@ class BaseInterface(object):
try:
flags = open(flags_file, "r").read().strip()
except IOError:
print("Could not open %s, using ifconfig to determine status" \
% flags_file)
print("Could not open %s, using ifconfig to determine status" %
flags_file)
return self._slow_is_up(ifconfig)
return bool(int(flags, 16) & 1)
@@ -875,7 +890,6 @@ class BaseInterface(object):
print(cmd)
misc.Run(cmd)
def _slow_is_up(self, ifconfig=None):
"""Determine if an interface is up using ifconfig."""
if not ifconfig:
@@ -944,12 +958,13 @@ class BaseWiredInterface(BaseInterface):
elif link == 0:
return False
except (IOError, ValueError, TypeError):
print('Error checking link using /sys/class/net/%s/carrier' \
% self.iface)
print('Error checking link using /sys/class/net/%s/carrier' %
self.iface)
if self.ethtool_cmd and self.link_detect in [misc.ETHTOOL, misc.AUTO]:
return self._eth_get_plugged_in()
elif self.miitool_cmd and self.link_detect in [misc.MIITOOL, misc.AUTO]:
elif self.miitool_cmd and self.link_detect in [misc.MIITOOL,
misc.AUTO]:
return self._mii_get_plugged_in()
else:
print(('Error: No way of checking for a wired connection. Make ' +
@@ -971,10 +986,8 @@ class BaseWiredInterface(BaseInterface):
if self.verbose:
print(cmd)
tool_data = misc.Run(cmd, include_stderr=True)
if misc.RunRegex(
re.compile('(Link detected: yes)', re.I | re.M | re.S),
tool_data
):
if misc.RunRegex(re.compile('(Link detected: yes)',
re.I | re.M | re.S), tool_data):
return True
else:
return False
@@ -1015,6 +1028,7 @@ class BaseWiredInterface(BaseInterface):
print(cmd)
misc.Run(cmd)
class BaseWirelessInterface(BaseInterface):
"""Control a wireless network interface."""
def __init__(self, iface, verbose=False, wpa_driver='wext'):
@@ -1095,7 +1109,8 @@ class BaseWirelessInterface(BaseInterface):
try:
ret = freq_dict[freq]
except KeyError:
print("Couldn't determine channel number for frequency:", str(freq))
print("Couldn't determine channel number for frequency:",
str(freq))
return ret
@@ -1277,7 +1292,7 @@ class BaseWirelessInterface(BaseInterface):
wpa_pass_path = misc.find_path('wpa_passphrase')
if not wpa_pass_path:
return None
key_pattern = re.compile('network={.*?\spsk=(.*?)\n}.*',
key_pattern = re.compile(r'network={.*?\spsk=(.*?)\n}.*',
re.I | re.M | re.S)
cmd = [wpa_pass_path, str(network['essid']), str(network['key'])]
if self.verbose:
@@ -1318,11 +1333,11 @@ class BaseWirelessInterface(BaseInterface):
network -- dictionary containing network info
"""
if network.get('key') != None:
if network.get('key') is not None:
try:
info = self._GetRalinkInfo()[network.get('bssid')]
except KeyError:
print("Could not find current network in iwpriv " + \
print("Could not find current network in iwpriv "
"get_site_survey results. Cannot authenticate.")
return
@@ -1360,8 +1375,10 @@ class BaseWirelessInterface(BaseInterface):
cmd = 'iwlist ' + self.iface + ' scan'
# If there is a hidden essid then it was set earlier, with iwconfig wlan0 essid,
# but on some drivers (iwlwifi, in my case) we have to pass it to iwlist scan.
# If there is a hidden essid then it was set earlier, with
# iwconfig wlan0 essid,
# but on some drivers (iwlwifi, in my case) we have to pass it to
# iwlist scan.
essid = misc.Noneify(essid)
if essid is not None:
print('Passing hidden essid to iwlist scan: ' + essid)
@@ -1436,7 +1453,7 @@ class BaseWirelessInterface(BaseInterface):
# Channel - For cards that don't have a channel number,
# convert the frequency.
ap['channel'] = misc.RunRegex(channel_pattern, cell)
if ap['channel'] == None:
if ap['channel'] is None:
freq = misc.RunRegex(freq_pattern, cell)
ap['channel'] = self._FreqToChannel(freq)
@@ -1445,7 +1462,10 @@ class BaseWirelessInterface(BaseInterface):
m = re.findall(bitrates_pattern, bitrates)
if m:
# numeric sort
ap['bitrates'] = sorted(m, key=cmp_to_key(lambda x, y: int(float(x) - float(y))))
ap['bitrates'] = sorted(m,
key=functools.
cmp_to_key(lambda x, y:
int(float(x) - float(y))))
else:
ap['bitrates'] = None
@@ -1487,7 +1507,8 @@ class BaseWirelessInterface(BaseInterface):
# quality displayed or it isn't found)
if misc.RunRegex(signaldbm_pattern, cell):
ap['strength'] = misc.RunRegex(signaldbm_pattern, cell)
elif self.wpa_driver != RALINK_DRIVER: # This is already set for ralink
# This is already set for ralink
elif self.wpa_driver != RALINK_DRIVER:
ap['strength'] = -1
return ap
@@ -1544,7 +1565,6 @@ class BaseWirelessInterface(BaseInterface):
print('wpa_supplicant authentication may have failed.')
return False
def _ForceSupplicantScan(self):
"""Force wpa_supplicant to rescan available networks.
@@ -1634,7 +1654,8 @@ class BaseWirelessInterface(BaseInterface):
if strength in ['', None]:
try:
[(strength, max_strength)] = altstrength_pattern.findall(output)
[(strength,
max_strength)] = altstrength_pattern.findall(output)
except ValueError:
# if the pattern was unable to match anything
# we'll return 101, which will allow us to stay