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

Style changes for python files

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

View File

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

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

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,9 +1,8 @@
""" Path configuration and functions for the wicd daemon and gui clients.
"""Path configuration and functions for the wicd daemon and gui clients.
chdir() -- Change directory to the location of the current file.
"""
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.

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

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,13 +169,15 @@ class TestMisc(unittest.TestCase):
def test_string_to_none_4(self):
self.assertEqual(misc.stringToNone('abcdef'), 'abcdef')
def suite():
suite = unittest.TestSuite()
tests = []
[ tests.append(test) for test in dir(TestMisc) if test.startswith('test') ]
for test in tests:
suite.addTest(TestMisc(test))
return suite
suite = unittest.TestSuite()
tests = []
[tests.append(test) for test in dir(TestMisc) if test.startswith('test')]
for test in tests:
suite.addTest(TestMisc(test))
return suite
if __name__ == '__main__':
unittest.main()
unittest.main()

View File

@@ -2,71 +2,78 @@ import unittest
from unittest import mock
from wicd import wnettools
class TestWnettools(unittest.TestCase):
def setUp(self):
self.interface = wnettools.BaseInterface('eth0')
def setUp(self):
self.interface = wnettools.BaseInterface('eth0')
def test_find_wireless_interface(self):
interfaces = wnettools.GetWirelessInterfaces()
# wlan0 may change depending on your system
#self.assertTrue('wlan0' in interfaces)
self.assertTrue(type(interfaces) == list)
def test_find_wireless_interface(self):
interfaces = wnettools.GetWirelessInterfaces()
# wlan0 may change depending on your system
# self.assertTrue('wlan0' in interfaces)
self.assertTrue(type(interfaces) == list)
@mock.patch('wicd.wnettools.os')
@mock.patch('wicd.wnettools.open')
def test_find_wired_interface(self, mock_f, mock_os):
mock_os.listdir.return_value = ['eth0']
mock_os.path.isdir.return_value = True
mock_f.return_value.readlines.return_value = "1"
interfaces = wnettools.GetWiredInterfaces()
self.assertTrue('eth0' in interfaces)
@mock.patch('wicd.wnettools.os')
@mock.patch('wicd.wnettools.open')
def test_find_wired_interface(self, mock_f, mock_os):
mock_os.listdir.return_value = ['eth0']
mock_os.path.isdir.return_value = True
mock_f.return_value.readlines.return_value = "1"
interfaces = wnettools.GetWiredInterfaces()
self.assertTrue('eth0' in interfaces)
@mock.patch('wicd.misc.Run')
def test_wext_is_valid_wpasupplicant_driver(self, mock_syscall):
self.assertTrue(wnettools.IsValidWpaSuppDriver('wext'))
mock_syscall.assert_called_once()
@mock.patch('wicd.misc.Run')
def test_wext_is_valid_wpasupplicant_driver(self, mock_syscall):
self.assertTrue(wnettools.IsValidWpaSuppDriver('wext'))
mock_syscall.assert_called_once()
def test_needs_external_calls_not_implemented(self):
self.assertRaises(NotImplementedError, wnettools.NeedsExternalCalls)
def test_needs_external_calls_not_implemented(self):
self.assertRaises(NotImplementedError, wnettools.NeedsExternalCalls)
def test_is_up_boolean(self):
self.assertTrue(type(self.interface.IsUp()) == bool)
def test_is_up_boolean(self):
self.assertTrue(type(self.interface.IsUp()) == bool)
def test_enable_debug_mode(self):
self.interface.SetDebugMode(True)
self.assertTrue(self.interface.verbose)
def test_enable_debug_mode(self):
self.interface.SetDebugMode(True)
self.assertTrue(self.interface.verbose)
def test_disable_debug_mode(self):
self.interface.SetDebugMode(False)
self.assertFalse(self.interface.verbose)
def test_disable_debug_mode(self):
self.interface.SetDebugMode(False)
self.assertFalse(self.interface.verbose)
def test_interface_name_sanitation(self):
interface = wnettools.BaseInterface('blahblah; uptime > /tmp/blah | cat')
self.assertEqual(interface.iface, 'blahblahuptimetmpblahcat')
def test_interface_name_sanitation(self):
interface = wnettools.BaseInterface('blahblah; uptime > /tmp/blah | '
'cat')
self.assertEqual(interface.iface, 'blahblahuptimetmpblahcat')
def test_freq_translation_low(self):
freq = '2.412 GHz'
interface = wnettools.BaseWirelessInterface('wlan0')
self.assertEqual(interface._FreqToChannel(freq), 1)
def test_freq_translation_low(self):
freq = '2.412 GHz'
interface = wnettools.BaseWirelessInterface('wlan0')
self.assertEqual(interface._FreqToChannel(freq), 1)
def test_freq_translation_high(self):
freq = '2.484 GHz'
interface = wnettools.BaseWirelessInterface('wlan0')
self.assertEqual(interface._FreqToChannel(freq), 14)
def test_freq_translation_high(self):
freq = '2.484 GHz'
interface = wnettools.BaseWirelessInterface('wlan0')
self.assertEqual(interface._FreqToChannel(freq), 14)
def test_generate_psk(self):
interface = wnettools.BaseWirelessInterface('wlan0')
if 'wlan0' in wnettools.GetWirelessInterfaces():
psk = interface.GeneratePSK({'essid': 'Network 1',
'key': 'arandompassphrase'})
self.assertEqual(psk, 'd70463014514f4b4ebb8e3aebbdec13f4437ac3a9a'
'f084b3433f3710e658a7be')
def 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')
def suite():
suite = unittest.TestSuite()
tests = []
[ tests.append(test) for test in dir(TestWnettools) if test.startswith('test') ]
for test in tests:
suite.addTest(TestWnettools(test))
return suite
suite = unittest.TestSuite()
tests = []
[tests.append(test) for test in dir(TestWnettools)
if test.startswith('test')]
for test in tests:
suite.addTest(TestWnettools(test))
return suite
if __name__ == '__main__':
unittest.main()
unittest.main()

View File

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

View File

@@ -1,6 +1,6 @@
#!/usr/bin/env python3
""" autoconnect -- Triggers an automatic connection attempt. """
"""autoconnect -- Triggers an automatic connection attempt."""
#
# Copyright (C) 2007 - 2009 Adam Blackburn
@@ -18,19 +18,18 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <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. """
"""No-op handler."""
pass
def error_handler(*args):
""" Error handler. """
"""Error handler."""
print('Async error autoconnecting.', file=sys.stderr)
sys.exit(3)
if __name__ == '__main__':
try:
time.sleep(2)

View File

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

View File

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

View File

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

View File

@@ -1,7 +1,7 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" ioctl Network interface control tools for wicd.
"""ioctl Network interface control tools for wicd.
This module implements functions to control and obtain information from
network interfaces. It utilizes ioctl calls and python modules to
@@ -30,18 +30,33 @@ class WirelessInterface() -- Control a wireless network interface.
# along with this program. If not, see <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
@@ -90,7 +97,7 @@ SIOCGIFFLAGS = 0x8913
def get_iw_ioctl_result(iface, call):
""" Makes the given ioctl call and returns the results.
"""Makes the given ioctl call and returns the results.
Keyword arguments:
call -- The ioctl call to make
@@ -112,15 +119,16 @@ def get_iw_ioctl_result(iface, call):
return None
return buff.tostring()
def NeedsExternalCalls(*args, **kargs):
""" Return False, since this backend doesn't use any external apps. """
"""Return False, since this backend doesn't use any external apps."""
return False
class Interface(BaseInterface):
""" Control a network interface. """
"""Control a network interface."""
def __init__(self, iface, verbose=False):
""" Initialise the object.
"""Initialise the object.
Keyword arguments:
iface -- the name of the interface
@@ -132,13 +140,13 @@ class Interface(BaseInterface):
self.Check()
def CheckWirelessTools(self):
""" Check for the existence needed wireless tools """
"""Check for the existence needed wireless tools"""
if not WPACTRL_AVAIL:
BaseInterface.CheckWirelessTools(self)
@neediface("")
def GetIP(self, ifconfig=""):
""" Get the IP address of the interface.
"""Get the IP address of the interface.
Returns:
The IP address of the interface in dotted quad form.
@@ -156,7 +164,7 @@ class Interface(BaseInterface):
@neediface(False)
def IsUp(self, ifconfig=None):
""" Determines if the interface is up.
"""Determines if the interface is up.
Returns:
True if the interface is up, False otherwise.
@@ -175,9 +183,9 @@ class Interface(BaseInterface):
class WiredInterface(Interface, BaseWiredInterface):
""" Control a wired network interface. """
"""Control a wired network interface."""
def __init__(self, iface, verbose=False):
""" Initialise the wired network interface class.
"""Initialise the wired network interface class.
Keyword arguments:
iface -- name of the interface
@@ -189,7 +197,7 @@ class WiredInterface(Interface, BaseWiredInterface):
@neediface(False)
def GetPluggedIn(self):
""" Get the current physical connection state.
"""Get the current physical connection state.
The method will first attempt to use ethtool do determine
physical connection state. Should ethtool fail to run properly,
@@ -201,7 +209,8 @@ class WiredInterface(Interface, BaseWiredInterface):
"""
if self.ethtool_cmd and self.link_detect in [misc.ETHTOOL, misc.AUTO]:
return self._eth_get_plugged_in()
elif self.miitool_cmd and self.link_detect in [misc.MIITOOL, misc.AUTO]:
elif self.miitool_cmd and self.link_detect in [misc.MIITOOL,
misc.AUTO]:
return self._mii_get_plugged_in()
else:
print(('Error: No way of checking for a wired connection. Make' +
@@ -209,7 +218,7 @@ class WiredInterface(Interface, BaseWiredInterface):
return False
def _eth_get_plugged_in(self):
""" Use ethtool to determine the physical connection state.
"""Use ethtool to determine the physical connection state.
Returns:
True if a link is detected, False otherwise.
@@ -231,7 +240,7 @@ class WiredInterface(Interface, BaseWiredInterface):
return bool(buff.tolist()[1])
def _mii_get_plugged_in(self):
""" Use mii-tool to determine the physical connection state.
"""Use mii-tool to determine the physical connection state.
Returns:
True if a link is detected, False otherwise.
@@ -253,24 +262,23 @@ class WiredInterface(Interface, BaseWiredInterface):
class WirelessInterface(Interface, BaseWirelessInterface):
""" Control a wireless network interface. """
"""Control a wireless network interface."""
def __init__(self, iface, verbose=False, wpa_driver='wext'):
""" Initialise the wireless network interface class.
"""Initialise the wireless network interface class.
Keyword arguments:
iface -- name of the interface
verbose -- print all commands
"""
BaseWirelessInterface.__init__(self, iface, verbose,
wpa_driver)
BaseWirelessInterface.__init__(self, iface, verbose, wpa_driver)
Interface.__init__(self, iface, verbose)
self.scan_iface = None
self.CheckWirelessTools()
@neediface([])
def GetNetworks(self, essid=None):
""" Get a list of available wireless networks.
"""Get a list of available wireless networks.
NOTE: the essid parameter is not used here,
it was added for the iwlist scan for hidden networks.
@@ -298,7 +306,7 @@ class WirelessInterface(Interface, BaseWirelessInterface):
return [_f for _f in [self._parse_ap(cell) for cell in results] if _f]
def _parse_ap(self, cell):
""" Parse a single cell from the python-iwscan list. """
"""Parse a single cell from the python-iwscan list."""
ap = {}
try:
ap['essid'] = misc.to_unicode(cell['essid'])
@@ -306,7 +314,7 @@ class WirelessInterface(Interface, BaseWirelessInterface):
print('Unicode problem with the current network essid, ignoring!!')
return None
if ap['essid'] in [ "", '<hidden>']:
if ap['essid'] in ["", '<hidden>']:
ap['essid'] = '<hidden>'
ap['hidden'] = True
else:
@@ -344,13 +352,14 @@ class WirelessInterface(Interface, BaseWirelessInterface):
# quality displayed or it isn't found)
if misc.RunRegex(signaldbm_pattern, cell["stats"]):
ap['strength'] = misc.RunRegex(signaldbm_pattern, cell["stats"])
elif self.wpa_driver != RALINK_DRIVER: # This is already set for ralink
# This is already set for ralink
elif self.wpa_driver != RALINK_DRIVER:
ap['strength'] = -1
return ap
def _connect_to_wpa_ctrl_iface(self):
""" Connect to the wpa ctrl interface. """
"""Connect to the wpa ctrl interface."""
ctrl_iface = '/var/run/wpa_supplicant'
socket_loc = os.path.join(ctrl_iface, self.iface)
if os.path.exists(socket_loc):
@@ -360,12 +369,12 @@ class WirelessInterface(Interface, BaseWirelessInterface):
print(("Couldn't open ctrl_interface: %s" % e))
return None
else:
print(("Couldn't find a wpa_supplicant ctrl_interface for iface %s" \
% self.iface))
print(f"Couldn't find a wpa_supplicant ctrl_interface for iface "
f"{self.iface}")
return None
def ValidateAuthentication(self, auth_time):
""" Validate WPA authentication.
"""Validate WPA authentication.
Validate that the wpa_supplicant authentication
process was successful.
@@ -384,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
@@ -431,7 +441,7 @@ class WirelessInterface(Interface, BaseWirelessInterface):
@neediface(False)
def StopWPA(self):
""" Terminates wpa_supplicant using its ctrl interface. """
"""Terminates wpa_supplicant using its ctrl interface."""
if not WPACTRL_AVAIL:
return BaseWirelessInterface.StopWPA(self)
wpa = self._connect_to_wpa_ctrl_iface()
@@ -440,7 +450,7 @@ class WirelessInterface(Interface, BaseWirelessInterface):
wpa.request("TERMINATE")
def _AuthenticateRalinkLegacy(self, network):
""" Authenticate with the specified wireless network.
"""Authenticate with the specified wireless network.
This function handles Ralink legacy cards that cannot use
wpa_supplicant.
@@ -449,58 +459,60 @@ class WirelessInterface(Interface, BaseWirelessInterface):
network -- dictionary containing network info
"""
if network.get('key') != None:
lines = self._GetRalinkInfo()
for x in lines:
info = x.split()
if len(info) < 5:
break
if info[2] == network.get('essid'):
if info[5] == 'WEP' or (info[5] == 'OPEN' and \
info[4] == 'WEP'):
if network.get('key') is None:
return
lines = self._GetRalinkInfo()
for x in lines:
info = x.split()
if len(info) < 5:
break
if info[2] == network.get('essid'):
if info[5] == 'WEP' or (info[5] == 'OPEN' and
info[4] == 'WEP'):
print('Setting up WEP')
cmd = ''.join(['iwconfig ', self.iface, ' key ',
network.get('key')])
if self.verbose:
print(cmd)
misc.Run(cmd)
else:
if info[5] == 'SHARED' and info[4] == 'WEP':
print('Setting up WEP')
cmd = ''.join(['iwconfig ', self.iface, ' key ',
network.get('key')])
auth_mode = 'SHARED'
key_name = 'Key1'
elif info[5] == 'WPA-PSK':
print('Setting up WPA-PSK')
auth_mode = 'WPAPSK'
key_name = 'WPAPSK'
elif info[5] == 'WPA2-PSK':
print('Setting up WPA2-PSK')
auth_mode = 'WPA2PSK'
key_name = 'WPAPSK'
else:
print("Unknown AuthMode, can\'t complete connection "
"process!")
return
cmd_list = []
cmd_list.append('NetworkType=' + info[6])
cmd_list.append('AuthMode=' + auth_mode)
cmd_list.append('EncrypType=' + info[4])
cmd_list.append('SSID=' + info[2])
cmd_list.append(key_name + '=' + network.get('key'))
if info[5] == 'SHARED' and info[4] == 'WEP':
cmd_list.append('DefaultKeyID=1')
cmd_list.append('SSID=' + info[2])
for cmd in cmd_list:
cmd = 'iwpriv ' + self.iface + ' '
if self.verbose:
print(cmd)
misc.Run(cmd)
else:
if info[5] == 'SHARED' and info[4] == 'WEP':
print('Setting up WEP')
auth_mode = 'SHARED'
key_name = 'Key1'
elif info[5] == 'WPA-PSK':
print('Setting up WPA-PSK')
auth_mode = 'WPAPSK'
key_name = 'WPAPSK'
elif info[5] == 'WPA2-PSK':
print('Setting up WPA2-PSK')
auth_mode = 'WPA2PSK'
key_name = 'WPAPSK'
else:
print(('Unknown AuthMode, can\'t complete ' + \
'connection process!'))
return
cmd_list = []
cmd_list.append('NetworkType=' + info[6])
cmd_list.append('AuthMode=' + auth_mode)
cmd_list.append('EncrypType=' + info[4])
cmd_list.append('SSID=' + info[2])
cmd_list.append(key_name + '=' + network.get('key'))
if info[5] == 'SHARED' and info[4] == 'WEP':
cmd_list.append('DefaultKeyID=1')
cmd_list.append('SSID=' + info[2])
for cmd in cmd_list:
cmd = 'iwpriv ' + self.iface + ' '
if self.verbose:
print(cmd)
misc.Run(cmd)
@neediface("")
def GetBSSID(self, iwconfig=None):
""" Get the MAC address for the interface. """
"""Get the MAC address for the interface."""
data = (self.iface + '\0' * 32)[:32]
try:
result = fcntl.ioctl(self.sock.fileno(), SIOCGIWAP, data)[16:]
@@ -513,7 +525,7 @@ class WirelessInterface(Interface, BaseWirelessInterface):
@neediface("")
def GetCurrentBitrate(self, iwconfig=None):
""" Get the current bitrate for the interface. """
"""Get the current bitrate for the interface."""
data = (self.iface + '\0' * 32)[:32]
fmt = "ihbb"
size = struct.calcsize(fmt)
@@ -526,19 +538,19 @@ class WirelessInterface(Interface, BaseWirelessInterface):
f, e, x, x = struct.unpack(fmt, result[:size])
return "%s %s" % ((f / 1000000), 'Mb/s')
#def GetOperationalMode(self, iwconfig=None):
# """ Get the operational mode for the interface. """
# TODO: implement me
# return ''
# def GetOperationalMode(self, iwconfig=None):
# """ Get the operational mode for the interface."""
# TODO: implement me
# return ''
#def GetAvailableAuthMethods(self, iwlistauth=None):
# """ Get the authentication methods for the interface. """
# TODO: Implement me
# return ''
# def GetAvailableAuthMethods(self, iwlistauth=None):
# """ Get the authentication methods for the interface."""
# TODO: Implement me
# return ''
@neediface(-1)
def GetSignalStrength(self, iwconfig=None):
""" Get the signal strength of the current network.
"""Get the signal strength of the current network.
Returns:
The signal strength.
@@ -555,7 +567,7 @@ class WirelessInterface(Interface, BaseWirelessInterface):
return None
def _get_max_strength(self):
""" Gets the maximum possible strength from the wireless driver. """
"""Gets the maximum possible strength from the wireless driver."""
buff = array.array('c', '\0' * 700)
addr, length = buff.buffer_info()
arg = struct.pack('Pi', addr, length)
@@ -576,7 +588,7 @@ class WirelessInterface(Interface, BaseWirelessInterface):
@neediface(-100)
def GetDBMStrength(self, iwconfig=None):
""" Get the dBm signal strength of the current network.
"""Get the dBm signal strength of the current network.
Returns:
The dBm signal strength.
@@ -590,7 +602,7 @@ class WirelessInterface(Interface, BaseWirelessInterface):
@neediface("")
def GetCurrentNetwork(self, iwconfig=None):
""" Get the essid of the current network.
"""Get the essid of the current network.
Returns:
The current network essid.

View File

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

View File

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

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. """
"""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')
@@ -70,7 +75,7 @@ class LogFile(io.FileIO):
raise SizeError
def get_time(self):
""" Return a string with the current time nicely formatted.
"""Return a string with the current time nicely formatted.
The format of the returned string is yyyy/mm/dd HH:MM:SS
@@ -82,7 +87,7 @@ class LogFile(io.FileIO):
str(x[4]).rjust(2, '0'), ':', str(x[5]).rjust(2, '0')])
def rotate(self):
""" Rotate logfile. """
"""Rotate logfile."""
return rotate(self)
def note(self, text):
@@ -112,25 +117,25 @@ class ManagedLog(object):
self._lf.maxsize, self.maxsave)
def write(self, data):
""" Write logfile. """
"""Write logfile."""
try:
self._lf.write(data)
except SizeError:
self._lf = rotate(self._lf, self.maxsave)
def note(self, data):
""" Write a note to the logfile. """
"""Write a note to the logfile."""
try:
self._lf.note(data)
except SizeError:
self._lf = rotate(self._lf, self.maxsave)
def written(self):
""" Return whether the logfile was written. """
"""Return whether the logfile was written."""
return self._lf.written
def rotate(self):
""" Rotate logfile. """
"""Rotate logfile."""
self._lf = rotate(self._lf, self.maxsave)
# auto-delegate remaining methods (but you should not read or seek an open
@@ -141,9 +146,9 @@ class ManagedLog(object):
# useful for logged stdout for daemon processes
class ManagedStdio(ManagedLog):
""" Manage stdout/stderr. """
"""Manage stdout/stderr."""
def write(self, data):
""" Write logfile to disk. """
"""Write logfile to disk."""
try:
self._lf.write(data)
except SizeError:
@@ -157,7 +162,7 @@ class ManagedStdio(ManagedLog):
def rotate(fileobj, maxsave=9):
""" Rotate fileobj. """
"""Rotate fileobj."""
name = fileobj.name
mode = fileobj.mode
maxsize = fileobj.maxsize
@@ -168,7 +173,7 @@ def rotate(fileobj, maxsave=9):
# assumes basename logfile is closed.
def shiftlogs(basename, maxsave):
""" Shift logfiles. """
"""Shift logfiles."""
topname = "%s.%d" % (basename, maxsave)
if os.path.isfile(topname):
os.unlink(topname)
@@ -187,11 +192,12 @@ def shiftlogs(basename, maxsave):
def open(name, maxsize=360000, maxsave=9):
""" Open logfile. """
"""Open logfile."""
return ManagedLog(name, maxsize, maxsave)
def writelog(logobj, data):
""" Write logfile. """
"""Write logfile."""
try:
logobj.write(data)
except SizeError:

View File

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

View File

@@ -1,6 +1,6 @@
#!/usr/bin/env python3
""" monitor -- connection monitoring process
"""monitor -- connection monitoring process
This process is spawned as a child of the daemon, and is responsible
for monitoring connection status and initiating autoreconnection
@@ -24,9 +24,9 @@ when appropriate.
# along with this program. If not, see <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,10 +70,11 @@ def diewithdbus(func):
wrapper.__doc__ = func.__doc__
return wrapper
class ConnectionStatus(object):
""" Class for monitoring the computer's connection status. """
"""Class for monitoring the computer's connection status."""
def __init__(self):
""" Initialize variables needed for the connection status methods. """
"""Initialize variables needed for the connection status methods."""
self.last_strength = -2
self.last_state = misc.NOT_CONNECTED
self.last_reconnect_time = time.time()
@@ -99,13 +101,13 @@ class ConnectionStatus(object):
"SignalBackendChanged", "org.wicd.daemon")
def _update_timeout_interval(self, interval):
""" Update the callback interval when signaled by the daemon. """
"""Update the callback interval when signaled by the daemon."""
self._to_time = interval
gobject.source_remove(self.update_callback)
self.add_poll_callback()
def _force_update_connection_status(self):
""" Run a connection status update on demand.
"""Run a connection status update on demand.
Removes the scheduled update_connection_status()
call, explicitly calls the function, and reschedules
@@ -117,7 +119,7 @@ class ConnectionStatus(object):
self.add_poll_callback()
def add_poll_callback(self):
""" Registers a polling call at a predetermined interval.
"""Registers a polling call at a predetermined interval.
The polling interval is determined by the backend in use.
@@ -126,7 +128,7 @@ class ConnectionStatus(object):
self.update_connection_status)
def check_for_wired_connection(self, wired_ip):
""" Checks for a wired connection.
"""Checks for a wired connection.
Checks for two states:
1) A wired connection is not in use, but a cable is plugged
@@ -157,7 +159,7 @@ class ConnectionStatus(object):
return False
def check_for_wireless_connection(self, wireless_ip):
""" Checks for an active wireless connection.
"""Checks for an active wireless connection.
Checks for an active wireless connection. Also notes
if the signal strength is 0, and if it remains there
@@ -197,7 +199,7 @@ class ConnectionStatus(object):
self.connection_lost_counter = 0
if (wifi_signal != self.last_strength or
self.network != self.last_network):
self.network != self.last_network):
self.last_strength = wifi_signal
self.last_network = self.network
self.signal_changed = True
@@ -207,7 +209,7 @@ class ConnectionStatus(object):
@diewithdbus
def update_connection_status(self):
""" Updates the tray icon and current connection status.
"""Updates the tray icon and current connection status.
Determines the current connection state and sends a dbus signal
announcing when the status changes. Also starts the automatic
@@ -253,8 +255,8 @@ class ConnectionStatus(object):
if not daemon.GetGUIOpen():
print('Killing wireless connection to switch to wired...')
wireless.DisconnectWireless()
daemon.AutoConnect(False, reply_handler=lambda *a:None,
error_handler=lambda *a:None)
daemon.AutoConnect(False, reply_handler=lambda *a: None,
error_handler=lambda *a: None)
return self.update_state(misc.NOT_CONNECTED)
return self.update_state(misc.WIRELESS, wifi_ip=wifi_ip)
@@ -267,7 +269,7 @@ class ConnectionStatus(object):
return self.update_state(state)
def update_state(self, state, wired_ip=None, wifi_ip=None):
""" Set the current connection state. """
"""Set the current connection state."""
# Set our connection state/info.
iwconfig = self.iwconfig
if state == misc.NOT_CONNECTED:
@@ -278,15 +280,18 @@ class ConnectionStatus(object):
if wired.CheckIfWiredConnecting():
info = ["wired"]
else:
info = ["wireless",
misc.noneToBlankString(wireless.GetCurrentNetwork(iwconfig))]
info = ["wireless", misc.
noneToBlankString(wireless.
GetCurrentNetwork(iwconfig))]
elif state == misc.WIRELESS:
self.reconnect_tries = 0
info = [str(wifi_ip),
misc.noneToBlankString(wireless.GetCurrentNetwork(iwconfig)),
str(self._get_printable_sig_strength()),
str(wireless.GetCurrentNetworkID(iwconfig)),
misc.noneToBlankString(wireless.GetCurrentBitrate(iwconfig))]
misc.noneToBlankString(wireless.
GetCurrentNetwork(iwconfig)),
str(self._get_printable_sig_strength()),
str(wireless.GetCurrentNetworkID(iwconfig)),
misc.noneToBlankString(wireless.
GetCurrentBitrate(iwconfig))]
elif state == misc.WIRED:
self.reconnect_tries = 0
info = [str(wired_ip)]
@@ -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
@@ -311,7 +316,7 @@ class ConnectionStatus(object):
return True
def _get_printable_sig_strength(self, always_positive=False):
""" Get the correct signal strength format. """
"""Get the correct signal strength format."""
try:
if daemon.GetSignalDisplayType() == 0:
signal = wireless.GetCurrentSignalStrength(self.iwconfig)
@@ -332,7 +337,7 @@ class ConnectionStatus(object):
return wifi_signal
def auto_reconnect(self, from_wireless=None):
""" Automatically reconnects to a network if needed.
"""Automatically reconnects to a network if needed.
If automatic reconnection is turned on, this method will
attempt to first reconnect to the last used wireless network, and
@@ -344,7 +349,7 @@ class ConnectionStatus(object):
# Some checks to keep reconnect retries from going crazy.
if (self.reconnect_tries > 3 and
(time.time() - self.last_reconnect_time) < 200):
(time.time() - self.last_reconnect_time) < 200):
print("Throttling autoreconnect")
return
@@ -364,24 +369,26 @@ class ConnectionStatus(object):
# before we reconnect
print('Disconnecting from network')
wireless.DisconnectWireless()
print(('Trying to reconnect to last used wireless ' + \
'network'))
print('Trying to reconnect to last used wireless network')
wireless.ConnectWireless(cur_net_id)
else:
daemon.AutoConnect(True, reply_handler=reply_handle,
error_handler=err_handle)
self.reconnecting = False
def reply_handle():
""" Just a dummy function needed for asynchronous dbus calls. """
"""Just a dummy function needed for asynchronous dbus calls."""
pass
def err_handle(error):
""" Just a dummy function needed for asynchronous dbus calls. """
"""Just a dummy function needed for asynchronous dbus calls."""
pass
def main():
""" Starts the connection monitor.
"""Starts the connection monitor.
Starts a ConnectionStatus instance, sets the status to update
an amount of time determined by the active backend.

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff