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

More pylint fixes

This commit is contained in:
David Paleino
2012-11-17 19:12:25 +01:00
parent 5c4a9c327b
commit 64c6328241
11 changed files with 2107 additions and 1323 deletions

View File

@@ -12,21 +12,20 @@ Also recycles a lot of configscript.py, too. :-)
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or # the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA. # MA 02110-1301, USA.
from wicd import misc
from wicd.translations import _ from wicd.translations import _
import configscript
from configscript import write_scripts, get_script_info, get_val from configscript import write_scripts, get_script_info
from configscript import none_to_blank, blank_to_none from configscript import none_to_blank, blank_to_none
import urwid import urwid
@@ -41,6 +40,7 @@ post_entry = None
pre_disconnect_entry = None pre_disconnect_entry = None
post_disconnect_entry = None post_disconnect_entry = None
def main(argv): def main(argv):
""" Main function. """ """ Main function. """
global ui, frame global ui, frame
@@ -54,17 +54,17 @@ def main(argv):
('focus', 'dark magenta', 'light gray'), ('focus', 'dark magenta', 'light gray'),
('editcp', 'default', 'default', 'standout'), ('editcp', 'default', 'default', 'standout'),
('editbx', 'light gray', 'dark blue'), ('editbx', 'light gray', 'dark blue'),
('editfc', 'white','dark blue', 'bold'), ('editfc', 'white', 'dark blue', 'bold'),
]) ])
network = argv[1] network = argv[1]
network_type = argv[2] network_type = argv[2]
script_info = get_script_info(network, network_type) script_info = get_script_info(network, network_type)
blank = urwid.Text('') blank = urwid.Text('')
pre_entry_t = ('body', _('Pre-connection Script') + ': ') pre_entry_t = ('body', _('Pre-connection Script') + ': ')
post_entry_t = ('body', _('Post-connection Script') + ': ') post_entry_t = ('body', _('Post-connection Script') + ': ')
pre_disconnect_entry_t = ('body', _('Pre-disconnection Script') + ': ') pre_disconnect_entry_t = ('body', _('Pre-disconnection Script') + ': ')
post_disconnect_entry_t = ('body', _('Post-disconnection Script') + ': ') post_disconnect_entry_t = ('body', _('Post-disconnection Script') + ': ')
@@ -74,23 +74,23 @@ def main(argv):
'editbx', 'editfc') 'editbx', 'editfc')
post_entry = urwid.AttrWrap(urwid.Edit(post_entry_t, post_entry = urwid.AttrWrap(urwid.Edit(post_entry_t,
none_to_blank(script_info.get('post_entry'))), none_to_blank(script_info.get('post_entry'))),
'editbx','editfc') 'editbx', 'editfc')
pre_disconnect_entry = urwid.AttrWrap(urwid.Edit(pre_disconnect_entry_t, pre_disconnect_entry = urwid.AttrWrap(urwid.Edit(pre_disconnect_entry_t,
none_to_blank(script_info.get('pre_disconnect_entry'))), none_to_blank(script_info.get('pre_disconnect_entry'))),
'editbx', 'editfc') 'editbx', 'editfc')
post_disconnect_entry = urwid.AttrWrap(urwid.Edit(post_disconnect_entry_t, post_disconnect_entry = urwid.AttrWrap(urwid.Edit(post_disconnect_entry_t,
none_to_blank(script_info.get('post_disconnect_entry'))), none_to_blank(script_info.get('post_disconnect_entry'))),
'editbx','editfc') 'editbx', 'editfc')
# The buttons # The buttons
ok_button = urwid.AttrWrap( ok_button = urwid.AttrWrap(
urwid.Button(_('OK'), ok_callback), urwid.Button(_('OK'), ok_callback),
'body','focus' 'body', 'focus'
) )
cancel_button = urwid.AttrWrap( cancel_button = urwid.AttrWrap(
urwid.Button(_('Cancel'), cancel_callback), urwid.Button(_('Cancel'), cancel_callback),
'body','focus' 'body', 'focus'
) )
button_cols = urwid.Columns([ok_button, cancel_button], dividechars=1) button_cols = urwid.Columns([ok_button, cancel_button], dividechars=1)
@@ -101,12 +101,12 @@ def main(argv):
('fixed', 2, urwid.Filler(pre_disconnect_entry)), ('fixed', 2, urwid.Filler(pre_disconnect_entry)),
('fixed', 2, urwid.Filler(post_disconnect_entry)), ('fixed', 2, urwid.Filler(post_disconnect_entry)),
#blank, blank, blank, blank, blank, #blank, blank, blank, blank, blank,
urwid.Filler(button_cols,'bottom') urwid.Filler(button_cols, 'bottom')
]) ])
frame = urwid.Frame(lbox) frame = urwid.Frame(lbox)
result = ui.run_wrapper(run) result = ui.run_wrapper(run)
if result == True: if result:
script_info["pre_entry"] = blank_to_none(pre_entry.get_edit_text()) script_info["pre_entry"] = blank_to_none(pre_entry.get_edit_text())
script_info["post_entry"] = blank_to_none(post_entry.get_edit_text()) script_info["post_entry"] = blank_to_none(post_entry.get_edit_text())
script_info["pre_disconnect_entry"] = \ script_info["pre_disconnect_entry"] = \
@@ -117,13 +117,22 @@ def main(argv):
OK_PRESSED = False OK_PRESSED = False
CANCEL_PRESSED = False CANCEL_PRESSED = False
def ok_callback(button_object, user_data=None): def ok_callback(button_object, user_data=None):
""" Callback. """
global OK_PRESSED global OK_PRESSED
OK_PRESSED = True OK_PRESSED = True
def cancel_callback(button_object, user_data=None): def cancel_callback(button_object, user_data=None):
""" Callback. """
global CANCEL_PRESSED global CANCEL_PRESSED
CANCEL_PRESSED = True CANCEL_PRESSED = True
def run(): def run():
""" Run the UI. """
dim = ui.get_cols_rows() dim = ui.get_cols_rows()
ui.set_mouse_tracking() ui.set_mouse_tracking()

View File

@@ -1,7 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -* coding: utf-8 -*- # -* coding: utf-8 -*-
""" curses_misc.py: Module for various widgets that are used throughout """ curses_misc.py: Module for various widgets that are used throughout
wicd-curses. wicd-curses.
""" """
@@ -11,12 +11,12 @@ wicd-curses.
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or # the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
@@ -26,6 +26,7 @@ import urwid
from wicd.translations import _ from wicd.translations import _
# Uses code that is towards the bottom # Uses code that is towards the bottom
def error(ui, parent, message): def error(ui, parent, message):
"""Shows an error dialog (or something that resembles one)""" """Shows an error dialog (or something that resembles one)"""
@@ -35,6 +36,7 @@ def error(ui, parent, message):
dialog = TextDialog(message, 6, 40, ('important', 'ERROR')) dialog = TextDialog(message, 6, 40, ('important', 'ERROR'))
return dialog.run(ui, parent) return dialog.run(ui, parent)
class SelText(urwid.Text): class SelText(urwid.Text):
"""A selectable text widget. See urwid.Text.""" """A selectable text widget. See urwid.Text."""
@@ -46,11 +48,13 @@ class SelText(urwid.Text):
"""Don't handle any keys.""" """Don't handle any keys."""
return key return key
class NSelListBox(urwid.ListBox): class NSelListBox(urwid.ListBox):
""" Non-selectable ListBox. """ """ Non-selectable ListBox. """
def selectable(self): def selectable(self):
return False return False
# This class is annoying. :/ # This class is annoying. :/
class DynWrap(urwid.AttrWrap): class DynWrap(urwid.AttrWrap):
""" """
@@ -62,8 +66,8 @@ class DynWrap(urwid.AttrWrap):
attrs = tuple of (attr_sens,attr_not_sens) attrs = tuple of (attr_sens,attr_not_sens)
attrfoc = attributes when in focus, defaults to nothing attrfoc = attributes when in focus, defaults to nothing
""" """
# pylint: disable-msg=W0231
def __init__(self, w, sensitive=True, attrs=('editbx', 'editnfc'), \ def __init__(self, w, sensitive=True, attrs=('editbx', 'editnfc'),
focus_attr='editfc'): focus_attr='editfc'):
self._attrs = attrs self._attrs = attrs
self._sensitive = sensitive self._sensitive = sensitive
@@ -73,11 +77,13 @@ class DynWrap(urwid.AttrWrap):
else: else:
cur_attr = attrs[1] cur_attr = attrs[1]
# pylint: disable-msg=E1101
self.__super.__init__(w, cur_attr, focus_attr) self.__super.__init__(w, cur_attr, focus_attr)
def get_sensitive(self): def get_sensitive(self):
""" Getter for sensitive property. """ """ Getter for sensitive property. """
return self._sensitive return self._sensitive
def set_sensitive(self, state): def set_sensitive(self, state):
""" Setter for sensitive property. """ """ Setter for sensitive property. """
if state: if state:
@@ -90,6 +96,7 @@ class DynWrap(urwid.AttrWrap):
def get_attrs(self): def get_attrs(self):
""" Getter for attrs property. """ """ Getter for attrs property. """
return self._attrs return self._attrs
def set_attrs(self, attrs): def set_attrs(self, attrs):
""" Setter for attrs property. """ """ Setter for attrs property. """
self._attrs = attrs self._attrs = attrs
@@ -98,36 +105,47 @@ class DynWrap(urwid.AttrWrap):
def selectable(self): def selectable(self):
return self._sensitive return self._sensitive
class DynEdit(DynWrap): class DynEdit(DynWrap):
""" Edit DynWrap'ed to the most common specifications. """ """ Edit DynWrap'ed to the most common specifications. """
# pylint: disable-msg=W0231
def __init__(self, caption='', edit_text='', sensitive=True, def __init__(self, caption='', edit_text='', sensitive=True,
attrs=('editbx', 'editnfc'), focus_attr='editfc'): attrs=('editbx', 'editnfc'), focus_attr='editfc'):
caption = ('editcp', caption + ': ') caption = ('editcp', caption + ': ')
edit = urwid.Edit(caption, edit_text) edit = urwid.Edit(caption, edit_text)
# pylint: disable-msg=E1101
self.__super.__init__(edit, sensitive, attrs, focus_attr) self.__super.__init__(edit, sensitive, attrs, focus_attr)
class DynIntEdit(DynWrap): class DynIntEdit(DynWrap):
""" IntEdit DynWrap'ed to the most common specifications. """ """ IntEdit DynWrap'ed to the most common specifications. """
# pylint: disable-msg=W0231
def __init__(self, caption='', edit_text='', sensitive=True, def __init__(self, caption='', edit_text='', sensitive=True,
attrs=('editbx', 'editnfc'), focus_attr='editfc'): attrs=('editbx', 'editnfc'), focus_attr='editfc'):
caption = ('editcp', caption + ':') caption = ('editcp', caption + ':')
edit = urwid.IntEdit(caption, edit_text) edit = urwid.IntEdit(caption, edit_text)
# pylint: disable-msg=E1101
self.__super.__init__(edit, sensitive, attrs, focus_attr) self.__super.__init__(edit, sensitive, attrs, focus_attr)
class DynRadioButton(DynWrap): class DynRadioButton(DynWrap):
""" RadioButton DynWrap'ed to the most common specifications. """ """ RadioButton DynWrap'ed to the most common specifications. """
# pylint: disable-msg=W0231
def __init__(self, group, label, state='first True', on_state_change=None, def __init__(self, group, label, state='first True', on_state_change=None,
user_data=None, sensitive=True, attrs=('body', 'editnfc'), user_data=None, sensitive=True, attrs=('body', 'editnfc'),
focus_attr='body'): focus_attr='body'):
#caption = ('editcp', caption + ':') #caption = ('editcp', caption + ':')
button = urwid.RadioButton(group, label, state, on_state_change, button = urwid.RadioButton(group, label, state, on_state_change,
user_data) user_data)
# pylint: disable-msg=E1101
self.__super.__init__(button, sensitive, attrs, focus_attr) self.__super.__init__(button, sensitive, attrs, focus_attr)
class MaskingEditException(Exception): class MaskingEditException(Exception):
""" Custom exception. """ """ Custom exception. """
pass pass
# Password-style edit # Password-style edit
class MaskingEdit(urwid.Edit): class MaskingEdit(urwid.Edit):
""" """
@@ -135,37 +153,47 @@ class MaskingEdit(urwid.Edit):
"always" : everything is a '*' all of the time "always" : everything is a '*' all of the time
"no_focus" : everything is a '*' only when not in focus "no_focus" : everything is a '*' only when not in focus
"off" : everything is always unmasked "off" : everything is always unmasked
mask_char = the single character that masks all other characters in the field mask_char = the single character that masks all other characters in the
field
""" """
def __init__(self, caption = "", edit_text = "", multiline = False, # pylint: disable-msg=W0231
align = 'left', wrap = 'space', allow_tab = False, def __init__(self, caption="", edit_text="", multiline=False, align='left',
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 self.mask_mode = mask_mode
if len(mask_char) > 1: if len(mask_char) > 1:
raise MaskingEditException('Masks of more than one character are' +\ raise MaskingEditException('Masks of more than one character are' +
' not supported!') ' not supported!')
self.mask_char = mask_char self.mask_char = mask_char
# pylint: disable-msg=E1101
self.__super.__init__(caption, edit_text, multiline, align, wrap, self.__super.__init__(caption, edit_text, multiline, align, wrap,
allow_tab, edit_pos, layout) allow_tab, edit_pos, layout)
def get_caption(self): def get_caption(self):
""" Return caption. """
return self.caption return self.caption
def get_mask_mode(self): def get_mask_mode(self):
""" Getter for mask_mode property. """
return self.mask_mode return self.mask_mode
def set_mask_mode(self, mode): def set_mask_mode(self, mode):
""" Setter for mask_mode property."""
self.mask_mode = mode self.mask_mode = mode
def get_masked_text(self): def get_masked_text(self):
return self.mask_char*len(self.get_edit_text()) """ Get masked out text. """
return self.mask_char * len(self.get_edit_text())
def render(self, (maxcol, ), focus=False): def render(self, (maxcol, ), focus=False):
""" """
Render edit widget and return canvas. Include cursor when in Render edit widget and return canvas. Include cursor when in
focus. focus.
""" """
# If we aren't masking anything ATM, then act like an Edit. # If we aren't masking anything ATM, then act like an Edit.
# No problems. # No problems.
if self.mask_mode == "off" or (self.mask_mode == 'no_focus' and focus): if self.mask_mode == "off" or (self.mask_mode == 'no_focus' and focus):
# pylint: disable-msg=E1101
canv = self.__super.render((maxcol, ), focus) canv = self.__super.render((maxcol, ), focus)
# The cache messes this thing up, because I am totally changing what # The cache messes this thing up, because I am totally changing what
# is displayed. # is displayed.
@@ -173,7 +201,7 @@ class MaskingEdit(urwid.Edit):
return canv return canv
# Else, we have a slight mess to deal with... # Else, we have a slight mess to deal with...
self._shift_view_to_cursor = not not focus # force bool self._shift_view_to_cursor = not not focus # force bool
text, attr = self.get_text() text, attr = self.get_text()
text = text[:len(self.caption)] + self.get_masked_text() text = text[:len(self.caption)] + self.get_masked_text()
@@ -186,6 +214,7 @@ class MaskingEdit(urwid.Edit):
return canv return canv
class TabColumns(urwid.WidgetWrap): class TabColumns(urwid.WidgetWrap):
""" """
Tabbed interface, mostly for use in the Preferences Dialog Tabbed interface, mostly for use in the Preferences Dialog
@@ -195,13 +224,14 @@ class TabColumns(urwid.WidgetWrap):
attrsel = attribute when active attrsel = attribute when active
""" """
# FIXME Make the bottom_part optional # FIXME Make the bottom_part optional
# pylint: disable-msg=W0231
def __init__(self, tab_str, tab_wid, title, bottom_part=None, def __init__(self, tab_str, tab_wid, title, bottom_part=None,
attr=('body', 'focus'), attrsel='tab active', attrtitle='header'): attr=('body', 'focus'), attrsel='tab active', attrtitle='header'):
#self.bottom_part = bottom_part #self.bottom_part = bottom_part
#title_wid = urwid.Text((attrtitle, title), align='right') #title_wid = urwid.Text((attrtitle, title), align='right')
column_list = [] column_list = []
for w in tab_str: for w in tab_str:
text, _ = w.get_text() text, trash = w.get_text()
column_list.append(('fixed', len(text), w)) column_list.append(('fixed', len(text), w))
column_list.append(urwid.Text((attrtitle, title), align='right')) column_list.append(urwid.Text((attrtitle, title), align='right'))
@@ -212,6 +242,7 @@ class TabColumns(urwid.WidgetWrap):
#self.listbox = urwid.ListBox(walker) #self.listbox = urwid.ListBox(walker)
self.gen_pile(tab_wid[0], True) self.gen_pile(tab_wid[0], True)
self.frame = urwid.Frame(self.pile) self.frame = urwid.Frame(self.pile)
# pylint: disable-msg=E1101
self.__super.__init__(self.frame) self.__super.__init__(self.frame)
def gen_pile(self, lbox, firstrun=False): def gen_pile(self, lbox, firstrun=False):
@@ -271,6 +302,7 @@ class ComboBoxException(Exception):
""" Custom exception. """ """ Custom exception. """
pass pass
# A "combo box" of SelTexts # A "combo box" of SelTexts
# I based this off of the code found here: # I based this off of the code found here:
# http://excess.org/urwid/browser/contrib/trunk/rbreu_menus.py # http://excess.org/urwid/browser/contrib/trunk/rbreu_menus.py
@@ -281,6 +313,7 @@ class ComboBox(urwid.WidgetWrap):
"""A ComboBox of text objects""" """A ComboBox of text objects"""
class ComboSpace(urwid.WidgetWrap): class ComboSpace(urwid.WidgetWrap):
"""The actual menu-like space that comes down from the ComboBox""" """The actual menu-like space that comes down from the ComboBox"""
# pylint: disable-msg=W0231
def __init__(self, l, body, ui, show_first, pos=(0, 0), def __init__(self, l, body, ui, show_first, pos=(0, 0),
attr=('body', 'focus')): attr=('body', 'focus')):
""" """
@@ -291,7 +324,7 @@ class ComboBox(urwid.WidgetWrap):
pos : a tuple of (row,col) where to put the list pos : a tuple of (row,col) where to put the list
attr : a tuple of (attr_no_focus,attr_focus) attr : a tuple of (attr_no_focus,attr_focus)
""" """
#Calculate width and height of the menu widget: #Calculate width and height of the menu widget:
height = len(l) height = len(l)
width = 0 width = 0
@@ -305,13 +338,14 @@ class ComboBox(urwid.WidgetWrap):
overlay = urwid.Overlay(self._listbox, body, ('fixed left', pos[0]), overlay = urwid.Overlay(self._listbox, body, ('fixed left', pos[0]),
width + 2, ('fixed top', pos[1]), height) width + 2, ('fixed top', pos[1]), height)
# pylint: disable-msg=E1101
self.__super.__init__(overlay) self.__super.__init__(overlay)
def show(self, ui, display): def show(self, ui, display):
""" Show widget. """ """ Show widget. """
dim = ui.get_cols_rows() dim = ui.get_cols_rows()
keys = True keys = True
#Event loop: #Event loop:
while True: while True:
if keys: if keys:
@@ -334,11 +368,12 @@ class ComboBox(urwid.WidgetWrap):
#def get_size(self): #def get_size(self):
def __init__(self, label='', l=[], attrs=('body', 'editnfc'), # pylint: disable-msg=W0231
def __init__(self, label='', l=None, attrs=('body', 'editnfc'),
focus_attr='focus', use_enter=True, focus=0, callback=None, focus_attr='focus', use_enter=True, focus=0, callback=None,
user_args=None): user_args=None):
""" """
label : bit of text that preceeds the combobox. If it is "", then label : bit of text that preceeds the combobox. If it is "", then
ignore it ignore it
l : stuff to include in the combobox l : stuff to include in the combobox
body : parent widget body : parent widget
@@ -348,14 +383,16 @@ class ComboBox(urwid.WidgetWrap):
callback : function that takes (combobox,sel_index,user_args=None) callback : function that takes (combobox,sel_index,user_args=None)
user_args : user_args in the callback user_args : user_args in the callback
""" """
self.DOWN_ARROW = ' vvv' self.DOWN_ARROW = ' vvv'
self.label = urwid.Text(label) self.label = urwid.Text(label)
self.attrs = attrs self.attrs = attrs
self.focus_attr = focus_attr self.focus_attr = focus_attr
if l is None:
l = []
self.list = l self.list = l
s, _ = self.label.get_text() s, trash = self.label.get_text()
self.overlay = None self.overlay = None
self.cbox = DynWrap(SelText(self.DOWN_ARROW), attrs=attrs, self.cbox = DynWrap(SelText(self.DOWN_ARROW), attrs=attrs,
@@ -368,6 +405,7 @@ class ComboBox(urwid.WidgetWrap):
) )
else: else:
w = urwid.Columns([self.cbox]) w = urwid.Columns([self.cbox])
# pylint: disable-msg=E1101
self.__super.__init__(w) self.__super.__init__(w)
# We need this to pick our keypresses # We need this to pick our keypresses
@@ -387,9 +425,11 @@ class ComboBox(urwid.WidgetWrap):
self.row = None self.row = None
def set_list(self, l): def set_list(self, l):
""" Populate widget list. """
self.list = l self.list = l
def set_focus(self, index): def set_focus(self, index):
""" Set widget focus. """
if urwid.VERSION < (1, 1, 0): if urwid.VERSION < (1, 1, 0):
self.focus = index self.focus = index
else: else:
@@ -407,15 +447,17 @@ class ComboBox(urwid.WidgetWrap):
self.overlay._listbox.set_focus(index) self.overlay._listbox.set_focus(index)
def rebuild_combobox(self): def rebuild_combobox(self):
""" Rebuild combobox. """
self.build_combobox(self.parent, self.ui, self.row) self.build_combobox(self.parent, self.ui, self.row)
def build_combobox(self, parent, ui, row): def build_combobox(self, parent, ui, row):
s, _ = self.label.get_text() """ Build combobox. """
s, trash = self.label.get_text()
if urwid.VERSION < (1, 1, 0): if urwid.VERSION < (1, 1, 0):
index = self.focus index = self.focus
else: else:
index = self._w.focus_position index = self._w.focus_position # pylint: disable-msg=E1103
self.cbox = DynWrap(SelText([self.list[index] + self.DOWN_ARROW]), 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)
@@ -437,45 +479,57 @@ class ComboBox(urwid.WidgetWrap):
# If we press space or enter, be a combo box! # If we press space or enter, be a combo box!
def keypress(self, size, key): def keypress(self, size, key):
""" Handle keypresses. """
activate = key == ' ' activate = key == ' '
if self.use_enter: if self.use_enter:
activate = activate or key == 'enter' activate = activate or key == 'enter'
if activate: if activate:
# Die if the user didn't prepare the combobox overlay # Die if the user didn't prepare the combobox overlay
if self.overlay == None: if self.overlay is None:
raise ComboBoxException('ComboBox must be built before use!') raise ComboBoxException('ComboBox must be built before use!')
retval = self.overlay.show(self.ui, self.parent) retval = self.overlay.show(self.ui, self.parent)
if retval != None: if retval is not None:
self.set_focus(self.list.index(retval)) self.set_focus(self.list.index(retval))
#self.cbox.set_w(SelText(retval+' vvv')) #self.cbox.set_w(SelText(retval+' vvv'))
if self.callback != None: if self.callback is not None:
self.callback(self, self.overlay._listbox.get_focus()[1], self.callback(self, self.overlay._listbox.get_focus()[1],
self.user_args) self.user_args)
return self._w.keypress(size, key) return self._w.keypress(size, key)
def selectable(self): def selectable(self):
""" Return whether the widget is selectable. """
return self.cbox.selectable() return self.cbox.selectable()
def get_focus(self): def get_focus(self):
""" Return widget focus. """
if self.overlay: if self.overlay:
return self.overlay._listbox.get_focus() return self.overlay._listbox.get_focus()
else: else:
if urwid.VERSION < (1, 1, 0): if urwid.VERSION < (1, 1, 0):
return None, self.focus return None, self.focus
else: else:
return None, self._w.focus_position return None, self._w.focus_position # pylint: disable-msg=E1103
def get_sensitive(self): def get_sensitive(self):
""" Return widget sensitivity. """
return self.cbox.get_sensitive() return self.cbox.get_sensitive()
def set_sensitive(self, state): def set_sensitive(self, state):
""" Set widget sensitivity. """
self.cbox.set_sensitive(state) self.cbox.set_sensitive(state)
# This is a h4x3d copy of some of the code in Ian Ward's dialog.py example. # This is a h4x3d copy of some of the code in Ian Ward's dialog.py example.
class DialogExit(Exception): class DialogExit(Exception):
""" Custom exception. """
pass pass
class Dialog2(urwid.WidgetWrap): class Dialog2(urwid.WidgetWrap):
def __init__(self, text, height, width, body=None ): """ Base class for other dialogs. """
def __init__(self, text, height, width, body=None):
self.buttons = None
self.width = int(width) self.width = int(width)
if width <= 0: if width <= 0:
self.width = ('relative', 80) self.width = ('relative', 80)
@@ -499,6 +553,7 @@ class Dialog2(urwid.WidgetWrap):
# buttons: tuple of name,exitcode # buttons: tuple of name,exitcode
def add_buttons(self, buttons): def add_buttons(self, buttons):
""" Add buttons. """
l = [] l = []
maxlen = 0 maxlen = 0
for name, exitcode in buttons: for name, exitcode in buttons:
@@ -507,7 +562,7 @@ class Dialog2(urwid.WidgetWrap):
b = urwid.AttrWrap(b, 'body', 'focus') b = urwid.AttrWrap(b, 'body', 'focus')
l.append(b) l.append(b)
maxlen = max(len(name), maxlen) maxlen = max(len(name), maxlen)
maxlen += 4 # because of '< ... >' maxlen += 4 # because of '< ... >'
self.buttons = urwid.GridFlow(l, maxlen, 3, 1, 'center') self.buttons = urwid.GridFlow(l, maxlen, 3, 1, 'center')
self.frame.footer = urwid.Pile([ self.frame.footer = urwid.Pile([
urwid.Divider(), urwid.Divider(),
@@ -515,9 +570,11 @@ class Dialog2(urwid.WidgetWrap):
], focus_item=1) ], focus_item=1)
def button_press(self, button): def button_press(self, button):
""" Handle button press. """
raise DialogExit(button.exitcode) raise DialogExit(button.exitcode)
def run(self, ui, parent): def run(self, ui, parent):
""" Run the UI. """
ui.set_mouse_tracking() ui.set_mouse_tracking()
size = ui.get_cols_rows() size = ui.get_cols_rows()
overlay = urwid.Overlay( overlay = urwid.Overlay(
@@ -551,15 +608,18 @@ class Dialog2(urwid.WidgetWrap):
self.unhandled_key(size, k) self.unhandled_key(size, k)
except DialogExit, e: except DialogExit, e:
return self.on_exit(e.args[0]) return self.on_exit(e.args[0])
def on_exit(self, exitcode): def on_exit(self, exitcode):
""" Handle dialog exit. """
return exitcode, "" return exitcode, ""
def unhandled_key(self, size, key): def unhandled_key(self, size, key):
""" Handle keypresses. """
pass pass
# Simple dialog with text in it and "OK"
class TextDialog(Dialog2): class TextDialog(Dialog2):
""" Simple dialog with text and "OK" button. """
def __init__(self, text, height, width, header=None, align='left', def __init__(self, text, height, width, header=None, align='left',
buttons=(_('OK'), 1)): buttons=(_('OK'), 1)):
l = [urwid.Text(text)] l = [urwid.Text(text)]
@@ -573,23 +633,27 @@ class TextDialog(Dialog2):
self.add_buttons([buttons]) self.add_buttons([buttons])
def unhandled_key(self, size, k): def unhandled_key(self, size, k):
""" Handle keys. """
if k in ('up', 'page up', 'down', 'page down'): if k in ('up', 'page up', 'down', 'page down'):
self.frame.set_focus('body') self.frame.set_focus('body')
self.view.keypress( size, k ) self.view.keypress(size, k)
self.frame.set_focus('footer') self.frame.set_focus('footer')
class InputDialog(Dialog2): class InputDialog(Dialog2):
""" Simple dialog with text and entry. """
def __init__(self, text, height, width, ok_name=_('OK'), edit_text=''): def __init__(self, text, height, width, ok_name=_('OK'), edit_text=''):
self.edit = urwid.Edit(wrap='clip', edit_text=edit_text) self.edit = urwid.Edit(wrap='clip', edit_text=edit_text)
body = urwid.ListBox([self.edit]) body = urwid.ListBox([self.edit])
body = urwid.AttrWrap(body, 'editbx', 'editfc') body = urwid.AttrWrap(body, 'editbx', 'editfc')
Dialog2.__init__(self, text, height, width, body) Dialog2.__init__(self, text, height, width, body)
self.frame.set_focus('body') self.frame.set_focus('body')
self.add_buttons([(ok_name, 0), (_('Cancel'), -1)]) self.add_buttons([(ok_name, 0), (_('Cancel'), -1)])
def unhandled_key(self, size, k): def unhandled_key(self, size, k):
""" Handle keys. """
if k in ('up', 'page up'): if k in ('up', 'page up'):
self.frame.set_focus('body') self.frame.set_focus('body')
if k in ('down', 'page down'): if k in ('down', 'page down'):
@@ -598,28 +662,36 @@ class InputDialog(Dialog2):
# pass enter to the "ok" button # pass enter to the "ok" button
self.frame.set_focus('footer') self.frame.set_focus('footer')
self.view.keypress(size, k) self.view.keypress(size, k)
def on_exit(self, exitcode): def on_exit(self, exitcode):
""" Handle dialog exit. """
return exitcode, self.edit.get_edit_text() return exitcode, self.edit.get_edit_text()
class ClickCols(urwid.WidgetWrap): class ClickCols(urwid.WidgetWrap):
""" Clickable menubar. """
# pylint: disable-msg=W0231
def __init__(self, items, callback=None, args=None): def __init__(self, items, callback=None, args=None):
cols = urwid.Columns(items) cols = urwid.Columns(items)
# pylint: disable-msg=E1101
self.__super.__init__(cols) self.__super.__init__(cols)
self.callback = callback self.callback = callback
self.args = args self.args = args
def mouse_event(self, size, event, button, x, y, focus): def mouse_event(self, size, event, button, x, y, focus):
""" Handle mouse events. """
if event == "mouse press": if event == "mouse press":
# The keypress dealie in wicd-curses.py expects a list of keystrokes # The keypress dealie in wicd-curses.py expects a list of keystrokes
self.callback([self.args]) self.callback([self.args])
# htop-style menu menu-bar on the bottom of the screen
class OptCols(urwid.WidgetWrap): class OptCols(urwid.WidgetWrap):
""" Htop-style menubar on the bottom of the screen. """
# tuples = [(key,desc)], on_event gets passed a key # tuples = [(key,desc)], on_event gets passed a key
# attrs = (attr_key,attr_desc) # attrs = (attr_key,attr_desc)
# handler = function passed the key of the "button" pressed # handler = function passed the key of the "button" pressed
# mentions of 'left' and right will be converted to <- and -> respectively # mentions of 'left' and right will be converted to <- and -> respectively
# pylint: disable-msg=W0231
def __init__(self, tuples, handler, attrs=('body', 'infobar'), debug=False): def __init__(self, tuples, handler, attrs=('body', 'infobar'), debug=False):
# Find the longest string. Keys for this bar should be no greater than # Find the longest string. Keys for this bar should be no greater than
# 2 characters long (e.g., -> for left) # 2 characters long (e.g., -> for left)
@@ -628,18 +700,18 @@ class OptCols(urwid.WidgetWrap):
# newmax = len(i[0])+len(i[1]) # newmax = len(i[0])+len(i[1])
# if newmax > maxlen: # if newmax > maxlen:
# maxlen = newmax # maxlen = newmax
# Construct the texts # Construct the texts
textList = [] textList = []
i = 0 i = 0
# callbacks map the text contents to its assigned callback. # callbacks map the text contents to its assigned callback.
self.callbacks = [] self.callbacks = []
for cmd in tuples: for cmd in tuples:
key = reduce(lambda s, (f, t): s.replace(f, t), [ \ key = reduce(lambda s, (f, t): s.replace(f, t), [
('ctrl ', 'Ctrl+'), ('meta ', 'Alt+'), \ ('ctrl ', 'Ctrl+'), ('meta ', 'Alt+'),
('left', '<-'), ('right', '->'), \ ('left', '<-'), ('right', '->'),
('page up', 'Page Up'), ('page down', 'Page Down'), \ ('page up', 'Page Up'), ('page down', 'Page Down'),
('esc', 'ESC'), ('enter', 'Enter'), ('f10','F10')], cmd[0]) ('esc', 'ESC'), ('enter', 'Enter'), ('f10', 'F10')], cmd[0])
if debug: if debug:
callback = self.debugClick callback = self.debugClick
@@ -657,12 +729,17 @@ class OptCols(urwid.WidgetWrap):
if debug: if debug:
self.debug = urwid.Text("DEBUG_MODE") self.debug = urwid.Text("DEBUG_MODE")
textList.append(('fixed', 10, self.debug)) textList.append(('fixed', 10, self.debug))
cols = urwid.Columns(textList) cols = urwid.Columns(textList)
# pylint: disable-msg=E1101
self.__super.__init__(cols) self.__super.__init__(cols)
def debugClick(self, args): def debugClick(self, args):
""" Debug clicks. """
self.debug.set_text(args) self.debug.set_text(args)
def mouse_event(self, size, event, button, x, y, focus): def mouse_event(self, size, event, button, x, y, focus):
""" Handle mouse events. """
# Widgets are evenly long (as of current), so... # Widgets are evenly long (as of current), so...
return self._w.mouse_event(size, event, button, x, y, focus) return self._w.mouse_event(size, event, button, x, y, focus)

View File

@@ -10,19 +10,19 @@
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or # the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA. # MA 02110-1301, USA.
import urwid import urwid
from curses_misc import TextDialog,DynWrap,MaskingEdit,ComboBox,error from curses_misc import DynWrap, MaskingEdit, ComboBox, error
import wicd.misc as misc import wicd.misc as misc
from wicd.misc import noneToString, stringToNone, noneToBlankString, to_bool from wicd.misc import noneToString, stringToNone, noneToBlankString, to_bool
@@ -32,88 +32,124 @@ import os
daemon = None daemon = None
wired = None wired = None
wireless = None wireless = None
# Call this first! # Call this first!
def dbus_init(dbus_ifaces): def dbus_init(dbus_ifaces):
global daemon,wired,wireless """ Initialize DBus interfaces. """
global daemon, wired, wireless
daemon = dbus_ifaces['daemon'] daemon = dbus_ifaces['daemon']
wired = dbus_ifaces['wired'] wired = dbus_ifaces['wired']
wireless = dbus_ifaces['wireless'] wireless = dbus_ifaces['wireless']
# 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
class AdvancedSettingsDialog(urwid.WidgetWrap): 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.
"""
# pylint: disable-msg=W0231
def __init__(self): def __init__(self):
self.ui=None self.ui = None
self.body = None
self.wired = None
self.networkid = None
self.encryption_info = None
self.encryption_combo = None
self.encrypt_types = None
self.encryption_chkbox = None
static_ip_t = _('Use Static IPs') static_ip_t = _('Use Static IPs')
ip_t = ('editcp',_('IP')+': ') ip_t = ('editcp', _('IP') + ': ')
netmask_t = ('editcp',_('Netmask')+':') netmask_t = ('editcp', _('Netmask') + ':')
gateway_t = ('editcp',_('Gateway')+':') gateway_t = ('editcp', _('Gateway') + ':')
use_static_dns_t = _('Use Static DNS') use_static_dns_t = _('Use Static DNS')
use_global_dns_t = _('Use global DNS servers') use_global_dns_t = _('Use global DNS servers')
dns_dom_t = ('editcp',_('DNS domain')+': ') dns_dom_t = ('editcp', _('DNS domain') + ': ')
search_dom_t = ('editcp',_('Search domain')+':') search_dom_t = ('editcp', _('Search domain') + ':')
dns1_t = ('editcp',_('DNS server')+ ' 1'+':'+' '*8) dns1_t = ('editcp', _('DNS server') + ' 1' + ':' + ' ' * 8)
dns2_t = ('editcp',_('DNS server')+ ' 2'+':'+' '*8) dns2_t = ('editcp', _('DNS server') + ' 2' + ':' + ' ' * 8)
dns3_t = ('editcp',_('DNS server')+ ' 3'+':'+' '*8) dns3_t = ('editcp', _('DNS server') + ' 3' + ':' + ' ' * 8)
use_dhcp_h_t = _('Use DHCP Hostname') use_dhcp_h_t = _('Use DHCP Hostname')
dhcp_h_t = ('editcp',_('DHCP Hostname')+': ') dhcp_h_t = ('editcp', _('DHCP Hostname') + ': ')
cancel_t = _('Cancel') cancel_t = _('Cancel')
ok_t = _('OK') ok_t = _('OK')
self.static_ip_cb = urwid.CheckBox(static_ip_t, self.static_ip_cb = urwid.CheckBox(static_ip_t,
on_state_change=self.static_ip_toggle) on_state_change=self.static_ip_toggle)
self.ip_edit = DynWrap(urwid.Edit(ip_t),False) self.ip_edit = DynWrap(urwid.Edit(ip_t), False)
self.netmask_edit = DynWrap(urwid.Edit(netmask_t),False) self.netmask_edit = DynWrap(urwid.Edit(netmask_t), False)
self.gateway_edit = DynWrap(urwid.Edit(gateway_t),False) self.gateway_edit = DynWrap(urwid.Edit(gateway_t), False)
self.static_dns_cb = DynWrap(
urwid.CheckBox(use_static_dns_t, on_state_change=self.dns_toggle),
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
])
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)
self.dns2 = DynWrap(urwid.Edit(dns2_t), False)
self.dns3 = DynWrap(urwid.Edit(dns3_t), False)
self.static_dns_cb = DynWrap(urwid.CheckBox(use_static_dns_t, self.use_dhcp_h = urwid.CheckBox(
on_state_change=self.dns_toggle),True,('body','editnfc'),None) use_dhcp_h_t,
self.global_dns_cb = DynWrap(urwid.CheckBox(use_global_dns_t, False,
on_state_change=self.dns_toggle),False,('body','editnfc'),None) on_state_change=self.use_dhcp_h_toggle
self.checkb_cols = urwid.Columns([self.static_dns_cb, )
self.global_dns_cb]) self.dhcp_h = DynWrap(urwid.Edit(dhcp_h_t), False)
self.dns_dom_edit = DynWrap(urwid.Edit(dns_dom_t) ,False)
self.search_dom_edit = DynWrap(urwid.Edit(search_dom_t),False)
self.dns1 = DynWrap(urwid.Edit(dns1_t) ,False)
self.dns2 = DynWrap(urwid.Edit(dns2_t) ,False)
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)
self.dhcp_h = DynWrap(urwid.Edit(dhcp_h_t),False)
_blank = urwid.Text('') _blank = urwid.Text('')
walker = urwid.SimpleListWalker([self.static_ip_cb, walker = urwid.SimpleListWalker([
self.ip_edit, self.static_ip_cb,
self.netmask_edit, self.ip_edit,
self.gateway_edit, self.netmask_edit,
_blank, self.gateway_edit,
self.checkb_cols, _blank,
self.dns_dom_edit,self.search_dom_edit, self.checkb_cols,
self.dns1,self.dns2,self.dns3, self.dns_dom_edit,
_blank, self.search_dom_edit,
self.use_dhcp_h, self.dns1, self.dns2, self.dns3,
self.dhcp_h, _blank,
_blank self.use_dhcp_h,
]) self.dhcp_h,
_blank
])
self._listbox = urwid.ListBox(walker) self._listbox = urwid.ListBox(walker)
self._frame = urwid.Frame(self._listbox) self._frame = urwid.Frame(self._listbox)
# pylint: disable-msg=E1101
self.__super.__init__(self._frame) self.__super.__init__(self._frame)
def use_dhcp_h_toggle(self,checkb,new_state,user_data=None): def use_dhcp_h_toggle(self, checkb, new_state, user_data=None):
""" Set sensitivity of widget. """
self.dhcp_h.set_sensitive(new_state) self.dhcp_h.set_sensitive(new_state)
def static_ip_toggle(self,checkb,new_state,user_data=None): def static_ip_toggle(self, checkb, new_state, user_data=None):
for w in [ self.ip_edit,self.netmask_edit,self.gateway_edit ]: """ Set sensitivity of widget. """
for w in [self.ip_edit, self.netmask_edit, self.gateway_edit]:
w.set_sensitive(new_state) w.set_sensitive(new_state)
self.static_dns_cb.set_state(new_state) self.static_dns_cb.set_state(new_state)
self.static_dns_cb.set_sensitive(not new_state) self.static_dns_cb.set_sensitive(not new_state)
@@ -122,31 +158,46 @@ class AdvancedSettingsDialog(urwid.WidgetWrap):
else: else:
self.checkb_cols.set_focus(self.static_dns_cb) self.checkb_cols.set_focus(self.static_dns_cb)
def dns_toggle(self, checkb, new_state, user_data=None):
def dns_toggle(self,checkb,new_state,user_data=None): """ Set sensitivity of widget. """
if checkb == self.static_dns_cb.get_w(): if checkb == self.static_dns_cb.get_w():
for w in [ self.dns_dom_edit,self.search_dom_edit, for w in [
self.dns1,self.dns2,self.dns3 ]: self.dns_dom_edit,
self.search_dom_edit,
self.dns1,
self.dns2,
self.dns3
]:
w.set_sensitive(new_state) w.set_sensitive(new_state)
if not new_state: if not new_state:
self.global_dns_cb.set_state(False,do_callback=False) self.global_dns_cb.set_state(False, do_callback=False)
self.global_dns_cb.set_sensitive(new_state) self.global_dns_cb.set_sensitive(new_state)
# use_global_dns_cb is DynWrapped # use_global_dns_cb is DynWrapped
if checkb == self.global_dns_cb.get_w(): if checkb == self.global_dns_cb.get_w():
for w in [self.dns_dom_edit,self.search_dom_edit, for w in [self.dns_dom_edit, self.search_dom_edit,
self.dns1,self.dns2,self.dns3 ]: self.dns1, self.dns2, self.dns3 ]:
w.set_sensitive(not new_state) w.set_sensitive(not new_state)
def set_net_prop(self, option, value):
""" Set network property. MUST BE OVERRIDEN. """
raise NotImplementedError
# Code totally yanked from netentry.py # Code totally yanked from netentry.py
def save_settings(self): def save_settings(self):
""" Save settings common to wired and wireless settings dialogs. """ """ Save settings common to wired and wireless settings dialogs. """
if self.static_ip_cb.get_state(): if self.static_ip_cb.get_state():
for i in [self.ip_edit,self.netmask_edit,self.gateway_edit]: for i in [
self.ip_edit,
self.netmask_edit,
self.gateway_edit
]:
i.set_edit_text(i.get_edit_text().strip()) i.set_edit_text(i.get_edit_text().strip())
self.set_net_prop("ip", noneToString(self.ip_edit.get_edit_text())) self.set_net_prop("ip", noneToString(self.ip_edit.get_edit_text()))
self.set_net_prop("netmask", noneToString(self.netmask_edit.get_edit_text())) self.set_net_prop("netmask",
self.set_net_prop("gateway", noneToString(self.gateway_edit.get_edit_text())) noneToString(self.netmask_edit.get_edit_text()))
self.set_net_prop("gateway",
noneToString(self.gateway_edit.get_edit_text()))
else: else:
self.set_net_prop("ip", '') self.set_net_prop("ip", '')
self.set_net_prop("netmask", '') self.set_net_prop("netmask", '')
@@ -157,11 +208,18 @@ class AdvancedSettingsDialog(urwid.WidgetWrap):
self.set_net_prop('use_static_dns', True) self.set_net_prop('use_static_dns', True)
self.set_net_prop('use_global_dns', False) self.set_net_prop('use_global_dns', False)
# Strip addressses before checking them in the daemon. # Strip addressses before checking them in the daemon.
for i in [self.dns1, self.dns2, for i in [
self.dns3,self.dns_dom_edit, self.search_dom_edit]: self.dns1,
self.dns2,
self.dns3,
self.dns_dom_edit,
self.search_dom_edit
]:
i.set_edit_text(i.get_edit_text().strip()) i.set_edit_text(i.get_edit_text().strip())
self.set_net_prop('dns_domain', noneToString(self.dns_dom_edit.get_edit_text())) self.set_net_prop('dns_domain',
self.set_net_prop("search_domain", noneToString(self.search_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()))
self.set_net_prop("dns1", noneToString(self.dns1.get_edit_text())) self.set_net_prop("dns1", noneToString(self.dns1.get_edit_text()))
self.set_net_prop("dns2", noneToString(self.dns2.get_edit_text())) self.set_net_prop("dns2", noneToString(self.dns2.get_edit_text()))
self.set_net_prop("dns3", noneToString(self.dns3.get_edit_text())) self.set_net_prop("dns3", noneToString(self.dns3.get_edit_text()))
@@ -177,28 +235,32 @@ class AdvancedSettingsDialog(urwid.WidgetWrap):
self.set_net_prop("dns1", '') self.set_net_prop("dns1", '')
self.set_net_prop("dns2", '') self.set_net_prop("dns2", '')
self.set_net_prop("dns3", '') self.set_net_prop("dns3", '')
self.set_net_prop('dhcphostname',self.dhcp_h.get_edit_text()) self.set_net_prop('dhcphostname', self.dhcp_h.get_edit_text())
self.set_net_prop('usedhcphostname',self.use_dhcp_h.get_state()) self.set_net_prop('usedhcphostname', self.use_dhcp_h.get_state())
# Prevent comboboxes from dying. # Prevent comboboxes from dying.
def ready_widgets(self,ui,body): def ready_widgets(self, ui, body):
""" Build comboboxes. """
self.ui = ui self.ui = ui
self.body = body self.body = body
self.encryption_combo.build_combobox(body,ui,14) self.encryption_combo.build_combobox(body, ui, 14)
self.change_encrypt_method() self.change_encrypt_method()
def combo_on_change(self,combobox,new_index,user_data=None): def combo_on_change(self, combobox, new_index, user_data=None):
""" Handle change of item in the combobox. """
self.change_encrypt_method() self.change_encrypt_method()
# More or less ripped from netentry.py # More or less ripped from netentry.py
def change_encrypt_method(self): def change_encrypt_method(self):
""" Change encrypt method based on combobox. """
#self.lbox_encrypt = urwid.ListBox() #self.lbox_encrypt = urwid.ListBox()
self.encryption_info = {} self.encryption_info = {}
wid,ID = self.encryption_combo.get_focus() wid, ID = self.encryption_combo.get_focus()
methods = self.encrypt_types methods = self.encrypt_types
# pylint: disable-msg=E0203
if self._w.body.body.__contains__(self.pile_encrypt): if self._w.body.body.__contains__(self.pile_encrypt):
self._w.body.body.pop(self._w.body.body.__len__()-1) self._w.body.body.pop(self._w.body.body.__len__() - 1)
# If nothing is selected, select the first entry. # If nothing is selected, select the first entry.
if ID == -1: if ID == -1:
@@ -210,16 +272,17 @@ class AdvancedSettingsDialog(urwid.WidgetWrap):
fields = methods[ID][type_] fields = methods[ID][type_]
for field in fields: for field in fields:
try: try:
edit = MaskingEdit(('editcp',language[field[1].lower().replace(' ','_')]+': ')) text = language[field[1].lower().replace(' ', '_')]
except KeyError: except KeyError:
edit = MaskingEdit(('editcp',field[1].replace(' ','_')+': ')) text = field[1].replace(' ', '_')
edit = MaskingEdit(('editcp', text + ': '))
edit.set_mask_mode('no_focus') edit.set_mask_mode('no_focus')
theList.append(edit) theList.append(edit)
# Add the data to any array, so that the information # Add the data to any array, so that the information
# can be easily accessed by giving the name of the wanted # can be easily accessed by giving the name of the wanted
# data. # data.
self.encryption_info[field[0]] = [edit, type_] self.encryption_info[field[0]] = [edit, type_]
if self.wired: if self.wired:
edit.set_edit_text(noneToBlankString( edit.set_edit_text(noneToBlankString(
wired.GetWiredProperty(field[0]))) wired.GetWiredProperty(field[0])))
@@ -229,78 +292,100 @@ class AdvancedSettingsDialog(urwid.WidgetWrap):
#FIXME: This causes the entire pile to light up upon use. #FIXME: This causes the entire pile to light up upon use.
# Make this into a listbox? # Make this into a listbox?
self.pile_encrypt = DynWrap(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.pile_encrypt.set_sensitive(self.encryption_chkbox.get_state())
self._w.body.body.insert(self._w.body.body.__len__(),self.pile_encrypt) self._w.body.body.insert(self._w.body.body.__len__(), self.pile_encrypt)
#self._w.body.body.append(self.pile_encrypt) #self._w.body.body.append(self.pile_encrypt)
def encryption_toggle(self,chkbox,new_state,user_data=None): def encryption_toggle(self, chkbox, new_state, user_data=None):
""" Set sensitivity of widget. """
self.encryption_combo.set_sensitive(new_state) self.encryption_combo.set_sensitive(new_state)
self.pile_encrypt.set_sensitive(new_state) self.pile_encrypt.set_sensitive(new_state)
class WiredSettingsDialog(AdvancedSettingsDialog): class WiredSettingsDialog(AdvancedSettingsDialog):
def __init__(self,name,parent): """ Settings dialog for wired interface. """
global wired, daemon def __init__(self, name, parent):
AdvancedSettingsDialog.__init__(self) AdvancedSettingsDialog.__init__(self)
self.wired = True self.wired = True
self.set_default = urwid.CheckBox(_('Use as default profile (overwrites any previous default)')) self.set_default = urwid.CheckBox(
#self.cur_default = _('Use as default profile (overwrites any previous default)')
)
#self.cur_default =
# Add widgets to listbox # Add widgets to listbox
self._w.body.body.append(self.set_default) self._w.body.body.append(self.set_default)
self.parent = parent self.parent = parent
encryption_t = _('Use Encryption') encryption_t = _('Use Encryption')
self.encryption_chkbox = urwid.CheckBox(encryption_t,on_state_change=self.encryption_toggle) self.encryption_chkbox = urwid.CheckBox(
encryption_t,
on_state_change=self.
encryption_toggle
)
self.encryption_combo = ComboBox(callback=self.combo_on_change) self.encryption_combo = ComboBox(callback=self.combo_on_change)
self.pile_encrypt = None self.pile_encrypt = None
# _w is a Frame, _w.body is a ListBox, _w.body.body is the ListWalker :-) # _w is a Frame, _w.body is a ListBox, _w.body.body is the ListWalker
# pylint: disable-msg=E1103
self._listbox.body.append(self.encryption_chkbox) self._listbox.body.append(self.encryption_chkbox)
# pylint: disable-msg=E1103
self._listbox.body.append(self.encryption_combo) self._listbox.body.append(self.encryption_combo)
self.encrypt_types = misc.LoadEncryptionMethods(wired = True) self.encrypt_types = misc.LoadEncryptionMethods(wired=True)
self.set_values() self.set_values()
self.prof_name = name self.prof_name = name
title = _('Configuring preferences for wired profile "$A"').replace('$A',self.prof_name) title = _('Configuring preferences for wired profile "$A"'). \
self._w.header = urwid.Text( ('header',title),align='right' ) replace('$A', self.prof_name)
self._w.header = urwid.Text(('header', title), align='right')
self.set_values() self.set_values()
def set_net_prop(self,option,value):
wired.SetWiredProperty(option,value) def set_net_prop(self, option, value):
""" Set network property. """
wired.SetWiredProperty(option, value)
def set_values(self): def set_values(self):
""" Load saved values. """
self.ip_edit.set_edit_text(self.format_entry("ip")) self.ip_edit.set_edit_text(self.format_entry("ip"))
self.netmask_edit.set_edit_text(self.format_entry("netmask")) self.netmask_edit.set_edit_text(self.format_entry("netmask"))
self.gateway_edit.set_edit_text(self.format_entry("gateway")) self.gateway_edit.set_edit_text(self.format_entry("gateway"))
self.global_dns_cb.set_state(bool(wired.GetWiredProperty('use_global_dns'))) self.global_dns_cb.set_state(
self.static_dns_cb.set_state(bool(wired.GetWiredProperty('use_static_dns'))) bool(wired.GetWiredProperty('use_global_dns'))
)
self.static_dns_cb.set_state(
bool(wired.GetWiredProperty('use_static_dns'))
)
# Set static ip checkbox. Forgot to do this the first time. # Set static ip checkbox. Forgot to do this the first time.
if stringToNone(self.ip_edit.get_edit_text()): if stringToNone(self.ip_edit.get_edit_text()):
self.static_ip_cb.set_state(True) self.static_ip_cb.set_state(True)
self.dns1.set_edit_text(self.format_entry( "dns1")) self.dns1.set_edit_text(self.format_entry("dns1"))
self.dns2.set_edit_text(self.format_entry( "dns2")) self.dns2.set_edit_text(self.format_entry("dns2"))
self.dns3.set_edit_text(self.format_entry( "dns3")) self.dns3.set_edit_text(self.format_entry("dns3"))
self.dns_dom_edit.set_edit_text(self.format_entry("dns_domain")) self.dns_dom_edit.set_edit_text(self.format_entry("dns_domain"))
self.search_dom_edit.set_edit_text(self.format_entry("search_domain")) self.search_dom_edit.set_edit_text(self.format_entry("search_domain"))
self.set_default.set_state(to_bool(wired.GetWiredProperty("default"))) self.set_default.set_state(to_bool(wired.GetWiredProperty("default")))
# Throw the encryption stuff into a list # Throw the encryption stuff into a list
list = [] l = []
activeID = -1 # Set the menu to this item when we are done activeID = -1 # Set the menu to this item when we are done
for x, enc_type in enumerate(self.encrypt_types): for x, enc_type in enumerate(self.encrypt_types):
list.append(enc_type['name']) l.append(enc_type['name'])
if enc_type['type'] == wired.GetWiredProperty("enctype"): if enc_type['type'] == wired.GetWiredProperty("enctype"):
activeID = x activeID = x
self.encryption_combo.set_list(list) self.encryption_combo.set_list(l)
self.encryption_combo.set_focus(activeID) self.encryption_combo.set_focus(activeID)
if wired.GetWiredProperty("encryption_enabled"): if wired.GetWiredProperty("encryption_enabled"):
self.encryption_chkbox.set_state(True,do_callback=False) self.encryption_chkbox.set_state(True, do_callback=False)
self.encryption_combo.set_sensitive(True) self.encryption_combo.set_sensitive(True)
#self.lbox_encrypt_info.set_sensitive(True) #self.lbox_encrypt_info.set_sensitive(True)
else: else:
@@ -313,26 +398,34 @@ class WiredSettingsDialog(AdvancedSettingsDialog):
if dhcphname is None: if dhcphname is None:
dhcphname = os.uname()[1] dhcphname = os.uname()[1]
self.use_dhcp_h.set_state(bool(wired.GetWiredProperty('usedhcphostname'))) self.use_dhcp_h.set_state(
bool(wired.GetWiredProperty('usedhcphostname'))
)
self.dhcp_h.set_sensitive(self.use_dhcp_h.get_state()) self.dhcp_h.set_sensitive(self.use_dhcp_h.get_state())
self.dhcp_h.set_edit_text(unicode(dhcphname)) self.dhcp_h.set_edit_text(unicode(dhcphname))
def save_settings(self): def save_settings(self):
""" Save settings to disk. """
# Check encryption info # Check encryption info
if self.encryption_chkbox.get_state(): if self.encryption_chkbox.get_state():
encrypt_info = self.encryption_info encrypt_info = self.encryption_info
encrypt_methods = self.encrypt_types encrypt_methods = self.encrypt_types
self.set_net_prop("enctype", self.set_net_prop(
encrypt_methods[self.encryption_combo.get_focus()[1] ]['type']) "enctype",
encrypt_methods[self.encryption_combo.get_focus()[1]]['type'])
self.set_net_prop("encryption_enabled", True) self.set_net_prop("encryption_enabled", True)
# Make sure all required fields are filled in. # Make sure all required fields are filled in.
for entry_info in encrypt_info.itervalues(): for entry_info in encrypt_info.itervalues():
if entry_info[0].get_edit_text() == "" \ if entry_info[0].get_edit_text() == "" \
and entry_info[1] == 'required': and entry_info[1] == 'required':
error(self.ui, self.parent,"%s (%s)" \ error(
% (_('Required encryption information is missing.'), self.ui,
entry_info[0].get_caption()[0:-2] ) self.parent,
) "%s (%s)" % (
_('Required encryption information is missing.'),
entry_info[0].get_caption()[0:-2]
)
)
return False return False
for entry_key, entry_info in encrypt_info.iteritems(): for entry_key, entry_info in encrypt_info.iteritems():
@@ -341,121 +434,157 @@ class WiredSettingsDialog(AdvancedSettingsDialog):
else: else:
self.set_net_prop("enctype", "None") self.set_net_prop("enctype", "None")
self.set_net_prop("encryption_enabled", False) self.set_net_prop("encryption_enabled", False)
AdvancedSettingsDialog.save_settings(self) AdvancedSettingsDialog.save_settings(self)
if self.set_default.get_state(): if self.set_default.get_state():
wired.UnsetWiredDefault() wired.UnsetWiredDefault()
if self.set_default.get_state(): if self.set_default.get_state():
bool = True set_default = True
else: else:
bool = False set_default = False
wired.SetWiredProperty("default",bool) wired.SetWiredProperty("default", set_default)
wired.SaveWiredNetworkProfile(self.prof_name) wired.SaveWiredNetworkProfile(self.prof_name)
return True return True
def format_entry(self, label): def format_entry(self, label):
""" Helper method to fetch and format wired properties. """ """ Helper method to fetch and format wired properties. """
return noneToBlankString(wired.GetWiredProperty(label)) return noneToBlankString(wired.GetWiredProperty(label))
def prerun(self,ui,dim,display):
def prerun(self, ui, dim, display):
pass pass
########################################
class WirelessSettingsDialog(AdvancedSettingsDialog): class WirelessSettingsDialog(AdvancedSettingsDialog):
def __init__(self,networkID,parent): """ Settings dialog for wireless interfaces. """
global wireless, daemon def __init__(self, networkID, parent):
AdvancedSettingsDialog.__init__(self) AdvancedSettingsDialog.__init__(self)
self.wired = False self.wired = False
self.bitrates = None
self.networkid = networkID self.networkid = networkID
self.parent = parent self.parent = parent
global_settings_t = _('Use these settings for all networks sharing this essid') global_settings_t = \
_('Use these settings for all networks sharing this essid')
encryption_t = _('Use Encryption') encryption_t = _('Use Encryption')
autoconnect_t = _('Automatically connect to this network') autoconnect_t = _('Automatically connect to this network')
bitrate_t = _('Wireless bitrate') bitrate_t = _('Wireless bitrate')
allow_lower_bitrates_t = _('Allow lower bitrates') allow_lower_bitrates_t = _('Allow lower bitrates')
self.global_settings_chkbox = urwid.CheckBox(global_settings_t) self.global_settings_chkbox = urwid.CheckBox(global_settings_t)
self.encryption_chkbox = urwid.CheckBox(encryption_t,on_state_change=self.encryption_toggle) self.encryption_chkbox = urwid.CheckBox(
encryption_t,
on_state_change=self.
encryption_toggle
)
self.encryption_combo = ComboBox(callback=self.combo_on_change) self.encryption_combo = ComboBox(callback=self.combo_on_change)
self.autoconnect_chkbox = urwid.CheckBox(autoconnect_t) self.autoconnect_chkbox = urwid.CheckBox(autoconnect_t)
self.bitrate_combo = ComboBox(bitrate_t) self.bitrate_combo = ComboBox(bitrate_t)
self.allow_lower_bitrates_chkbox = urwid.CheckBox(allow_lower_bitrates_t) self.allow_lower_bitrates_chkbox = \
urwid.CheckBox(allow_lower_bitrates_t)
self.pile_encrypt = None self.pile_encrypt = None
# _w is a Frame, _w.body is a ListBox, _w.body.body is the ListWalker :-) # _w is a Frame, _w.body is a ListBox, _w.body.body is the ListWalker
# pylint: disable-msg=E1103
self._listbox.body.append(self.bitrate_combo) self._listbox.body.append(self.bitrate_combo)
# pylint: disable-msg=E1103
self._listbox.body.append(self.allow_lower_bitrates_chkbox) self._listbox.body.append(self.allow_lower_bitrates_chkbox)
# pylint: disable-msg=E1103
self._listbox.body.append(urwid.Text('')) self._listbox.body.append(urwid.Text(''))
# pylint: disable-msg=E1103
self._listbox.body.append(self.global_settings_chkbox) self._listbox.body.append(self.global_settings_chkbox)
# pylint: disable-msg=E1103
self._listbox.body.append(self.autoconnect_chkbox) self._listbox.body.append(self.autoconnect_chkbox)
# pylint: disable-msg=E1103
self._listbox.body.append(self.encryption_chkbox) self._listbox.body.append(self.encryption_chkbox)
# pylint: disable-msg=E1103
self._listbox.body.append(self.encryption_combo) self._listbox.body.append(self.encryption_combo)
self.encrypt_types = misc.LoadEncryptionMethods() self.encrypt_types = misc.LoadEncryptionMethods()
self.set_values() 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)'). \
self._w.header = urwid.Text(('header',title),align='right' ) 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): def set_values(self):
""" Set the various network settings to the right values. """ """ Set the various network settings to the right values. """
networkID = self.networkid networkID = self.networkid
self.ip_edit.set_edit_text(self.format_entry(networkID,"ip")) self.ip_edit.set_edit_text(self.format_entry(networkID, "ip"))
self.netmask_edit.set_edit_text(self.format_entry(networkID,"netmask")) self.netmask_edit.set_edit_text(self.format_entry(networkID, "netmask"))
self.gateway_edit.set_edit_text(self.format_entry(networkID,"gateway")) self.gateway_edit.set_edit_text(self.format_entry(networkID, "gateway"))
self.global_dns_cb.set_state(
bool(wireless.GetWirelessProperty(networkID, 'use_global_dns')))
self.static_dns_cb.set_state(
bool(wireless.GetWirelessProperty(networkID, 'use_static_dns')))
self.global_dns_cb.set_state(bool(wireless.GetWirelessProperty(networkID,
'use_global_dns')))
self.static_dns_cb.set_state(bool(wireless.GetWirelessProperty(networkID,
'use_static_dns')))
if stringToNone(self.ip_edit.get_edit_text()): if stringToNone(self.ip_edit.get_edit_text()):
self.static_ip_cb.set_state(True) self.static_ip_cb.set_state(True)
self.dns1.set_edit_text(self.format_entry(networkID, "dns1")) self.dns1.set_edit_text(self.format_entry(networkID, "dns1"))
self.dns2.set_edit_text(self.format_entry(networkID, "dns2")) self.dns2.set_edit_text(self.format_entry(networkID, "dns2"))
self.dns3.set_edit_text(self.format_entry(networkID, "dns3")) self.dns3.set_edit_text(self.format_entry(networkID, "dns3"))
self.dns_dom_edit.set_edit_text(self.format_entry(networkID, "dns_domain")) self.dns_dom_edit.set_edit_text(
self.search_dom_edit.set_edit_text(self.format_entry(networkID, "search_domain")) self.format_entry(networkID, "dns_domain")
)
self.autoconnect_chkbox.set_state(to_bool(self.format_entry(networkID, "automatic"))) self.search_dom_edit.set_edit_text(
self.format_entry(networkID, "search_domain")
)
self.autoconnect_chkbox.set_state(
to_bool(self.format_entry(networkID, "automatic"))
)
self.bitrates = wireless.GetAvailableBitrates() self.bitrates = wireless.GetAvailableBitrates()
self.bitrates.append('auto') self.bitrates.append('auto')
self.bitrate_combo.set_list(self.bitrates) self.bitrate_combo.set_list(self.bitrates)
self.bitrate_combo.set_focus(self.bitrates.index(wireless.GetWirelessProperty(networkID, 'bitrate'))) self.bitrate_combo.set_focus(
self.allow_lower_bitrates_chkbox.set_state(to_bool(self.format_entry(networkID, 'allow_lower_bitrates'))) self.bitrates.index(
wireless.GetWirelessProperty(networkID, 'bitrate')
)
)
self.allow_lower_bitrates_chkbox.set_state(
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, self.encryption_chkbox.set_state(
'encryption')),do_callback=False) bool(wireless.GetWirelessProperty(networkID, 'encryption')),
self.global_settings_chkbox.set_state(bool(wireless.GetWirelessProperty(networkID do_callback=False)
,'use_settings_globally'))) self.global_settings_chkbox.set_state(
bool(wireless.GetWirelessProperty(
networkID,
'use_settings_globally')
)
)
# Throw the encryption stuff into a list # Throw the encryption stuff into a list
list = [] l = []
activeID = -1 # Set the menu to this item when we are done activeID = -1 # Set the menu to this item when we are done
for x, enc_type in enumerate(self.encrypt_types): for x, enc_type in enumerate(self.encrypt_types):
list.append(enc_type['name']) l.append(enc_type['name'])
if enc_type['type'] == wireless.GetWirelessProperty(networkID, "enctype"): if enc_type['type'] == \
wireless.GetWirelessProperty(networkID, "enctype"):
activeID = x activeID = x
self.encryption_combo.set_list(list) self.encryption_combo.set_list(l)
self.encryption_combo.set_focus(activeID) self.encryption_combo.set_focus(activeID)
if activeID != -1: if activeID != -1:
self.encryption_chkbox.set_state(True,do_callback=False) self.encryption_chkbox.set_state(True, do_callback=False)
self.encryption_combo.set_sensitive(True) self.encryption_combo.set_sensitive(True)
#self.lbox_encrypt_info.set_sensitive(True) #self.lbox_encrypt_info.set_sensitive(True)
else: else:
self.encryption_combo.set_focus(0) self.encryption_combo.set_focus(0)
self.change_encrypt_method() self.change_encrypt_method()
dhcphname = wireless.GetWirelessProperty(networkID,"dhcphostname") dhcphname = wireless.GetWirelessProperty(networkID, "dhcphostname")
if dhcphname is None: if dhcphname is None:
dhcphname = os.uname()[1] dhcphname = os.uname()[1]
self.use_dhcp_h.set_state(bool(wireless.GetWirelessProperty(networkID,'usedhcphostname'))) self.use_dhcp_h.set_state(
bool(wireless.GetWirelessProperty(networkID, 'usedhcphostname'))
)
self.dhcp_h.set_sensitive(self.use_dhcp_h.get_state()) self.dhcp_h.set_sensitive(self.use_dhcp_h.get_state())
self.dhcp_h.set_edit_text(unicode(dhcphname)) self.dhcp_h.set_edit_text(unicode(dhcphname))
def set_net_prop(self, option, value): def set_net_prop(self, option, value):
""" Sets the given option to the given value for this network. """ """ Sets the given option to the given value for this network. """
@@ -467,20 +596,27 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
# Ripped from netentry.py # Ripped from netentry.py
def save_settings(self): def save_settings(self):
""" Save settings to disk. """
# Check encryption info # Check encryption info
if self.encryption_chkbox.get_state(): if self.encryption_chkbox.get_state():
encrypt_info = self.encryption_info encrypt_info = self.encryption_info
encrypt_methods = self.encrypt_types encrypt_methods = self.encrypt_types
self.set_net_prop("enctype", self.set_net_prop(
encrypt_methods[self.encryption_combo.get_focus()[1] ]['type']) "enctype",
encrypt_methods[self.encryption_combo.get_focus()[1]]['type']
)
# Make sure all required fields are filled in. # Make sure all required fields are filled in.
for entry_info in encrypt_info.itervalues(): for entry_info in encrypt_info.itervalues():
if entry_info[0].get_edit_text() == "" \ if entry_info[0].get_edit_text() == "" \
and entry_info[1] == 'required': and entry_info[1] == 'required':
error(self.ui, self.parent,"%s (%s)" \ error(
% (_('Required encryption information is missing.'), self.ui,
entry_info[0].get_caption()[0:-2] ) self.parent,
) "%s (%s)" % (
_('Required encryption information is missing.'),
entry_info[0].get_caption()[0:-2]
)
)
return False return False
for entry_key, entry_info in encrypt_info.iteritems(): for entry_key, entry_info in encrypt_info.iteritems():
@@ -489,7 +625,11 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
elif not self.encryption_chkbox.get_state() and \ elif not self.encryption_chkbox.get_state() and \
wireless.GetWirelessProperty(self.networkid, "encryption"): wireless.GetWirelessProperty(self.networkid, "encryption"):
# Encrypt checkbox is off, but the network needs it. # Encrypt checkbox is off, but the network needs it.
error(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 return False
else: else:
self.set_net_prop("enctype", "None") self.set_net_prop("enctype", "None")
@@ -497,20 +637,27 @@ class WirelessSettingsDialog(AdvancedSettingsDialog):
# Save the autoconnect setting. This is not where it originally was # Save the autoconnect setting. This is not where it originally was
# in the GTK UI. # in the GTK UI.
self.set_net_prop("automatic",self.autoconnect_chkbox.get_state()) self.set_net_prop("automatic", self.autoconnect_chkbox.get_state())
if self.global_settings_chkbox.get_state(): if self.global_settings_chkbox.get_state():
self.set_net_prop('use_settings_globally', True) self.set_net_prop('use_settings_globally', True)
else: else:
self.set_net_prop('use_settings_globally', False) self.set_net_prop('use_settings_globally', False)
wireless.RemoveGlobalEssidEntry(self.networkid) wireless.RemoveGlobalEssidEntry(self.networkid)
self.set_net_prop('bitrate', self.bitrates[self.bitrate_combo.get_focus()[1]]) self.set_net_prop(
self.set_net_prop('allow_lower_bitrates', self.allow_lower_bitrates_chkbox.get_state()) 'bitrate',
self.bitrates[self.bitrate_combo.get_focus()[1]]
)
self.set_net_prop(
'allow_lower_bitrates',
self.allow_lower_bitrates_chkbox.get_state()
)
wireless.SaveWirelessNetworkProfile(self.networkid) wireless.SaveWirelessNetworkProfile(self.networkid)
return True return True
def ready_widgets(self, ui, body): def ready_widgets(self, ui, body):
""" Build comboboxes. """
AdvancedSettingsDialog.ready_widgets(self, ui, body) AdvancedSettingsDialog.ready_widgets(self, ui, body)
self.ui = ui self.ui = ui
self.body = body self.body = body

View File

@@ -8,12 +8,12 @@
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or # the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
@@ -23,25 +23,30 @@ import urwid
import urwid.curses_display import urwid.curses_display
from wicd import misc from wicd import misc
from wicd import dbusmanager
from wicd.translations import _ from wicd.translations import _
from curses_misc import SelText,DynWrap,DynRadioButton,ComboBox,TabColumns from curses_misc import SelText, DynWrap, DynRadioButton, ComboBox, TabColumns
daemon = None daemon = None
wireless = None wireless = None
wired = None wired = None
from wicd.translations import language
class PrefsDialog(urwid.WidgetWrap): class PrefsDialog(urwid.WidgetWrap):
""" Preferences dialog. """
# pylint: disable-msg=W0231
def __init__(self, body, pos, ui, dbus=None): def __init__(self, body, pos, ui, dbus=None):
global daemon, wireless, wired global daemon, wireless, wired
self.thebackends = None
self.backends = None
self.wpadrivers = None
self.thedrivers = None
daemon = dbus['daemon'] daemon = dbus['daemon']
wireless = dbus['wireless'] wireless = dbus['wireless']
wired = dbus['wired'] wired = dbus['wired']
width,height = ui.get_cols_rows() width, height = ui.get_cols_rows()
height -= 3 height -= 3
#width = 80 #width = 80
#height = 20 #height = 20
@@ -53,7 +58,7 @@ class PrefsDialog(urwid.WidgetWrap):
self.header0 = urwid.AttrWrap(SelText(header0_t), 'tab active', 'focus') self.header0 = urwid.AttrWrap(SelText(header0_t), 'tab active', 'focus')
self.header1 = urwid.AttrWrap(SelText(header1_t), 'body', 'focus') self.header1 = urwid.AttrWrap(SelText(header1_t), 'body', 'focus')
self.header2 = urwid.AttrWrap(SelText(header2_t), 'body', 'focus') self.header2 = urwid.AttrWrap(SelText(header2_t), 'body', 'focus')
title = _('Preferences') title = ('Preferences')
# Blank line # Blank line
_blank = urwid.Text('') _blank = urwid.Text('')
@@ -63,22 +68,21 @@ class PrefsDialog(urwid.WidgetWrap):
#### ####
# General Settings # General Settings
net_cat_t = ('header', _('Network Interfaces')) net_cat_t = ('header', ('Network Interfaces'))
wired_t = ('editcp', _('Wired Interface')+': ') wired_t = ('editcp', ('Wired Interface') + ': ')
wless_t = ('editcp', _('Wireless Interface')+':') wless_t = ('editcp', ('Wireless Interface') + ':')
always_show_wired_t = _('''Always show wired interface''') always_show_wired_t = _('Always show wired interface')
prefer_wired_t = _('''Always switch to wired connection when available''') prefer_wired_t = _('Always switch to wired connection when available')
global_dns_cat_t = ('header', _('Global DNS servers')) global_dns_cat_t = ('header', _('Global DNS servers'))
global_dns_t = ('editcp', _('Use global DNS servers')) global_dns_t = ('editcp', _('Use global DNS servers'))
dns_dom_t = ('editcp', ' '+_('DNS domain')+': ') dns_dom_t = ('editcp', ' ' + _('DNS domain') + ': ')
search_dom_t = ('editcp', ' '+_('Search domain')+':') search_dom_t = ('editcp', ' ' + _('Search domain') + ':')
dns1_t = ('editcp', ' '+_('DNS server')+' 1: ') dns1_t = ('editcp', ' ' + _('DNS server') + ' 1: ')
dns2_t = ('editcp', ' '+_('DNS server')+' 2: ') dns2_t = ('editcp', ' ' + _('DNS server') + ' 2: ')
dns3_t = ('editcp', ' '+_('DNS server')+' 3: ') dns3_t = ('editcp', ' ' + _('DNS server') + ' 3: ')
wired_auto_cat_t = ('header', _('Wired Autoconnect Settings'))
wired_auto_cat_t= ('header', _('Wired Autoconnect Settings'))
wired_auto_1_t = _('Use default profile on wired autoconnect') wired_auto_1_t = _('Use default profile on wired autoconnect')
wired_auto_2_t = _('Prompt for profile on wired autoconnect') wired_auto_2_t = _('Prompt for profile on wired autoconnect')
wired_auto_3_t = _('Use last used profile on wired autoconnect') wired_auto_3_t = _('Use last used profile on wired autoconnect')
@@ -91,86 +95,90 @@ class PrefsDialog(urwid.WidgetWrap):
dhcp_header_t = ('header', _('DHCP Client')) dhcp_header_t = ('header', _('DHCP Client'))
# Automatic # Automatic
dhcp1_t = 'dhclient' dhcp1_t = 'dhclient'
dhcp2_t = 'dhcpcd' dhcp2_t = 'dhcpcd'
dhcp3_t = 'pump' dhcp3_t = 'pump'
dhcp4_t = 'udhcpc' dhcp4_t = 'udhcpc'
wired_detect_header_t = ('header', _('Wired Link Detection')) wired_detect_header_t = ('header', _('Wired Link Detection'))
wired1_t = 'ethtool' wired1_t = 'ethtool'
wired2_t = 'mii-tool' wired2_t = 'mii-tool'
flush_header_t = ('header', _('Route Table Flushing')) flush_header_t = ('header', _('Route Table Flushing'))
flush1_t = 'ip' flush1_t = 'ip'
flush2_t = 'route' flush2_t = 'route'
#### Advanced Settings #### Advanced Settings
wpa_cat_t=('header', _('WPA Supplicant')) wpa_cat_t = ('header', _('WPA Supplicant'))
wpa_t=('editcp','Driver:') wpa_t = ('editcp', 'Driver:')
wpa_list = [] wpa_list = []
wpa_warn_t = ('important', _('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_cat_t = ('header', _('Backend'))
backend_t = _('Backend')+':' backend_t = _('Backend') + ':'
backend_list = [] backend_list = []
debug_cat_t = ('header', _('Debugging')) debug_cat_t = ('header', _('Debugging'))
debug_mode_t = _('Enable debug mode') debug_mode_t = _('Enable debug mode')
wless_cat_t = ('header', _('Wireless Interface')) wless_cat_t = ('header', _('Wireless Interface'))
use_dbm_t = _('Use dBm to measure signal strength') use_dbm_t = _('Use dBm to measure signal strength')
verify_ap_t = _('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 # General Settings
self.net_cat = urwid.Text(net_cat_t) self.net_cat = urwid.Text(net_cat_t)
self.wired_edit = urwid.AttrWrap(urwid.Edit(wired_t),'editbx','editfc') self.wired_edit = \
self.wless_edit = urwid.AttrWrap(urwid.Edit(wless_t),'editbx','editfc') urwid.AttrWrap(urwid.Edit(wired_t), 'editbx', 'editfc')
self.wless_edit = \
urwid.AttrWrap(urwid.Edit(wless_t), 'editbx', 'editfc')
self.prefer_wired_chkbx = urwid.CheckBox(prefer_wired_t) self.prefer_wired_chkbx = urwid.CheckBox(prefer_wired_t)
self.global_dns_cat = urwid.Text(global_dns_cat_t) self.global_dns_cat = urwid.Text(global_dns_cat_t)
# Default the global DNS settings to off. They will be reenabled later # Default the global DNS settings to off. They will be reenabled later
# if so required. # if so required.
global_dns_state = False global_dns_state = False
self.global_dns_checkb = urwid.CheckBox(global_dns_t, global_dns_state, self.global_dns_checkb = urwid.CheckBox(global_dns_t,
on_state_change=self.global_dns_trigger) global_dns_state,
on_state_change=self.global_dns_trigger
)
self.search_dom = DynWrap(urwid.Edit(search_dom_t), global_dns_state) self.search_dom = DynWrap(urwid.Edit(search_dom_t), global_dns_state)
self.dns_dom = DynWrap(urwid.Edit(dns_dom_t), global_dns_state) self.dns_dom = DynWrap(urwid.Edit(dns_dom_t), global_dns_state)
self.dns1 = DynWrap(urwid.Edit(dns1_t), global_dns_state) self.dns1 = DynWrap(urwid.Edit(dns1_t), global_dns_state)
self.dns2 = DynWrap(urwid.Edit(dns2_t), global_dns_state) self.dns2 = DynWrap(urwid.Edit(dns2_t), global_dns_state)
self.dns3 = DynWrap(urwid.Edit(dns3_t), global_dns_state) self.dns3 = DynWrap(urwid.Edit(dns3_t), global_dns_state)
self.always_show_wired_checkb = urwid.CheckBox(always_show_wired_t) self.always_show_wired_checkb = urwid.CheckBox(always_show_wired_t)
self.wired_auto_l = [] self.wired_auto_l = []
self.wired_auto_cat= urwid.Text(wired_auto_cat_t) self.wired_auto_cat = urwid.Text(wired_auto_cat_t)
self.wired_auto_1 = urwid.RadioButton(self.wired_auto_l,wired_auto_1_t) self.wired_auto_1 = urwid.RadioButton(self.wired_auto_l, wired_auto_1_t)
self.wired_auto_2 = urwid.RadioButton(self.wired_auto_l,wired_auto_2_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_3 = urwid.RadioButton(self.wired_auto_l, wired_auto_3_t)
self.auto_reconn_cat = urwid.Text(auto_reconn_cat_t) self.auto_reconn_cat = urwid.Text(auto_reconn_cat_t)
self.auto_reconn_checkb = urwid.CheckBox(auto_reconn_t) self.auto_reconn_checkb = urwid.CheckBox(auto_reconn_t)
generalLB = urwid.ListBox([self.net_cat, generalLB = urwid.ListBox([
self.wless_edit,#_blank, self.net_cat,
self.wired_edit, self.wless_edit, # _blank,
self.always_show_wired_checkb, self.wired_edit,
self.prefer_wired_chkbx,_blank, self.always_show_wired_checkb,
self.global_dns_cat, self.prefer_wired_chkbx, _blank,
self.global_dns_checkb,#_blank, self.global_dns_cat,
self.search_dom,self.dns_dom, self.global_dns_checkb, # _blank,
self.dns1,self.dns2,self.dns3,_blank, self.search_dom, self.dns_dom,
self.wired_auto_cat, self.dns1, self.dns2, self.dns3, _blank,
self.wired_auto_1, self.wired_auto_cat,
self.wired_auto_2, self.wired_auto_1,
self.wired_auto_3, _blank, self.wired_auto_2,
self.auto_reconn_cat, self.wired_auto_3, _blank,
self.auto_reconn_checkb self.auto_reconn_cat,
]) self.auto_reconn_checkb
])
#### External Programs tab #### External Programs tab
automatic_t = _('Automatic (recommended)') automatic_t = _('Automatic (recommended)')
@@ -179,81 +187,84 @@ class PrefsDialog(urwid.WidgetWrap):
self.dhcp_l = [] self.dhcp_l = []
# Order of these is flipped in the actual interface, # Order of these is flipped in the actual interface,
# (2,3,1 -> dhcpcd, pump, dhclient), because dhclient often doesn't like # (2, 3, 1 -> dhcpcd, pump, dhclient), because dhclient often doesn't
# to work on several distros. # like to work on several distros.
self.dhcp0 = urwid.RadioButton(self.dhcp_l ,automatic_t) self.dhcp0 = urwid.RadioButton(self.dhcp_l, automatic_t)
self.dhcp1 = DynRadioButton(self.dhcp_l, dhcp1_t) self.dhcp1 = DynRadioButton(self.dhcp_l, dhcp1_t)
self.dhcp2 = DynRadioButton(self.dhcp_l, dhcp2_t) self.dhcp2 = DynRadioButton(self.dhcp_l, dhcp2_t)
self.dhcp3 = DynRadioButton(self.dhcp_l, dhcp3_t) self.dhcp3 = DynRadioButton(self.dhcp_l, dhcp3_t)
self.dhcp4 = DynRadioButton(self.dhcp_l, dhcp4_t) self.dhcp4 = DynRadioButton(self.dhcp_l, dhcp4_t)
self.dhcp_l = [self.dhcp0,self.dhcp1,self.dhcp2,self.dhcp3,self.dhcp4] self.dhcp_l = [
self.dhcp0, self.dhcp1, self.dhcp2, self.dhcp3, self.dhcp4
]
self.wired_l = [] self.wired_l = []
self.wired_detect_header = urwid.Text(wired_detect_header_t) self.wired_detect_header = urwid.Text(wired_detect_header_t)
self.wired0 = urwid.RadioButton(self.wired_l, automatic_t) self.wired0 = urwid.RadioButton(self.wired_l, automatic_t)
self.wired1 = DynRadioButton(self.wired_l, wired1_t) self.wired1 = DynRadioButton(self.wired_l, wired1_t)
self.wired2 = DynRadioButton(self.wired_l, wired2_t) self.wired2 = DynRadioButton(self.wired_l, wired2_t)
self.wired_l = [self.wired0, self.wired1, self.wired2] self.wired_l = [self.wired0, self.wired1, self.wired2]
self.flush_l = [] self.flush_l = []
self.flush_header = urwid.Text(flush_header_t) self.flush_header = urwid.Text(flush_header_t)
self.flush0 = urwid.RadioButton(self.flush_l,automatic_t) self.flush0 = urwid.RadioButton(self.flush_l, automatic_t)
self.flush1 = DynRadioButton(self.flush_l,flush1_t) self.flush1 = DynRadioButton(self.flush_l, flush1_t)
self.flush2 = DynRadioButton(self.flush_l,flush2_t) self.flush2 = DynRadioButton(self.flush_l, flush2_t)
self.flush_l = [self.flush0,self.flush1,self.flush2] self.flush_l = [self.flush0, self.flush1, self.flush2]
externalLB = urwid.ListBox([self.dhcp_header,
self.dhcp0,self.dhcp2,self.dhcp3,self.dhcp1,
self.dhcp4,
_blank,
self.wired_detect_header,
self.wired0,self.wired1,self.wired2,
_blank,
self.flush_header,
self.flush0,self.flush1,self.flush2
])
externalLB = urwid.ListBox([
self.dhcp_header,
self.dhcp0, self.dhcp2, self.dhcp3, self.dhcp1, self.dhcp4,
_blank,
self.wired_detect_header,
self.wired0, self.wired1, self.wired2,
_blank,
self.flush_header,
self.flush0, self.flush1, self.flush2
])
#### Advanced settings #### Advanced settings
self.wpa_cat = urwid.Text(wpa_cat_t) self.wpa_cat = urwid.Text(wpa_cat_t)
self.wpa_cbox = ComboBox(wpa_t) self.wpa_cbox = ComboBox(wpa_t)
self.wpa_warn = urwid.Text(wpa_warn_t) self.wpa_warn = urwid.Text(wpa_warn_t)
self.backend_cat = urwid.Text(backend_cat_t)
self.backend_cbox = ComboBox(backend_t)
self.debug_cat = urwid.Text(debug_cat_t)
self.debug_mode_checkb = urwid.CheckBox(debug_mode_t)
self.wless_cat = urwid.Text(wless_cat_t) self.backend_cat = urwid.Text(backend_cat_t)
self.use_dbm_checkb = urwid.CheckBox(use_dbm_t) self.backend_cbox = ComboBox(backend_t)
self.debug_cat = urwid.Text(debug_cat_t)
self.debug_mode_checkb = urwid.CheckBox(debug_mode_t)
self.wless_cat = urwid.Text(wless_cat_t)
self.use_dbm_checkb = urwid.CheckBox(use_dbm_t)
self.verify_ap_checkb = urwid.CheckBox(verify_ap_t) self.verify_ap_checkb = urwid.CheckBox(verify_ap_t)
advancedLB = urwid.ListBox([
self.wpa_cat,
self.wpa_cbox, self.wpa_warn, _blank,
self.backend_cat,
self.backend_cbox, _blank,
self.debug_cat,
self.debug_mode_checkb, _blank,
self.wless_cat,
self.use_dbm_checkb, _blank,
self.verify_ap_checkb, _blank
])
advancedLB = urwid.ListBox([self.wpa_cat, headerList = [self.header0, self.header1, self.header2]
self.wpa_cbox,self.wpa_warn,_blank, lbList = [generalLB, externalLB, advancedLB]
self.backend_cat, self.tab_map = {
self.backend_cbox,_blank, self.header0: generalLB,
self.debug_cat, self.header1: externalLB,
self.debug_mode_checkb, _blank, self.header2: advancedLB
self.wless_cat, }
self.use_dbm_checkb, _blank,
self.verify_ap_checkb, _blank
])
headerList = [self.header0,self.header1,self.header2]
lbList = [generalLB,externalLB,advancedLB]
self.tab_map = {self.header0 : generalLB,
self.header1 : externalLB,
self.header2 : advancedLB}
#self.load_settings() #self.load_settings()
self.tabs = TabColumns(headerList,lbList,_('Preferences')) self.tabs = TabColumns(headerList, lbList, _('Preferences'))
# pylint: disable-msg=E1101
self.__super.__init__(self.tabs) self.__super.__init__(self.tabs)
def load_settings(self):
def load_settings(self):
""" Load settings to be used in the dialog. """
### General Settings ### General Settings
# ComboBox does not like dbus.Strings as text markups. My fault. :/ # ComboBox does not like dbus.Strings as text markups. My fault. :/
wless_iface = unicode(daemon.GetWirelessInterface()) wless_iface = unicode(daemon.GetWirelessInterface())
@@ -269,15 +280,16 @@ class PrefsDialog(urwid.WidgetWrap):
theDNS = daemon.GetGlobalDNSAddresses() theDNS = daemon.GetGlobalDNSAddresses()
i = 0 i = 0
for w in self.dns1,self.dns2,self.dns3,self.dns_dom,self.search_dom : for w in self.dns1, self.dns2, self.dns3, self.dns_dom, self.search_dom:
w.set_edit_text(misc.noneToBlankString(theDNS[i])) w.set_edit_text(misc.noneToBlankString(theDNS[i]))
i+=1 i += 1
# Wired Automatic Connection # Wired Automatic Connection
self.wired_auto_l[daemon.GetWiredAutoConnectMethod()-1] self.wired_auto_l[daemon.GetWiredAutoConnectMethod() - 1]
self.auto_reconn_checkb.set_state(daemon.GetAutoReconnect()) self.auto_reconn_checkb.set_state(daemon.GetAutoReconnect())
def find_avail(apps): def find_avail(apps):
""" Find available apps. """
for app in apps[1:]: for app in apps[1:]:
app.set_sensitive(daemon.GetAppAvailable(app.get_label())) app.set_sensitive(daemon.GetAppAvailable(app.get_label()))
@@ -285,7 +297,7 @@ class PrefsDialog(urwid.WidgetWrap):
find_avail(self.dhcp_l) find_avail(self.dhcp_l)
dhcp_method = daemon.GetDHCPClient() dhcp_method = daemon.GetDHCPClient()
self.dhcp_l[dhcp_method].set_state(True) self.dhcp_l[dhcp_method].set_state(True)
find_avail(self.wired_l) find_avail(self.wired_l)
wired_link_method = daemon.GetLinkDetectionTool() wired_link_method = daemon.GetLinkDetectionTool()
self.wired_l[wired_link_method].set_state(True) self.wired_l[wired_link_method].set_state(True)
@@ -302,17 +314,17 @@ class PrefsDialog(urwid.WidgetWrap):
# Same as above with the dbus.String # Same as above with the dbus.String
self.thedrivers = [unicode(w) for w in self.wpadrivers] self.thedrivers = [unicode(w) for w in self.wpadrivers]
self.wpa_cbox.set_list(self.thedrivers) self.wpa_cbox.set_list(self.thedrivers)
# Pick where to begin first: # Pick where to begin first:
def_driver = daemon.GetWPADriver() def_driver = daemon.GetWPADriver()
try: try:
self.wpa_cbox.set_focus(self.wpadrivers.index(def_driver)) self.wpa_cbox.set_focus(self.wpadrivers.index(def_driver))
except ValueError: except ValueError:
pass # It defaults to 0 anyway (I hope) pass # It defaults to 0 anyway (I hope)
self.backends = daemon.GetBackendList() self.backends = daemon.GetBackendList()
self.thebackends= [unicode(w) for w in self.backends] self.thebackends = [unicode(w) for w in self.backends]
self.backend_cbox.set_list(self.thebackends) self.backend_cbox.set_list(self.thebackends)
cur_backend = daemon.GetSavedBackend() cur_backend = daemon.GetSavedBackend()
try: try:
self.backend_cbox.set_focus(self.thebackends.index(cur_backend)) self.backend_cbox.set_focus(self.thebackends.index(cur_backend))
@@ -329,17 +341,25 @@ class PrefsDialog(urwid.WidgetWrap):
This exact order is found in prefs.py""" This exact order is found in prefs.py"""
daemon.SetUseGlobalDNS(self.global_dns_checkb.get_state()) daemon.SetUseGlobalDNS(self.global_dns_checkb.get_state())
for i in [self.dns1, self.dns2, for i in [
self.dns3,self.dns_dom, self.search_dom, self.dns_dom]: self.dns1, self.dns2, self.dns3,
self.dns_dom, self.search_dom, self.dns_dom
]:
i.set_edit_text(i.get_edit_text().strip()) i.set_edit_text(i.get_edit_text().strip())
daemon.SetGlobalDNS(self.dns1.get_edit_text(), self.dns2.get_edit_text(), daemon.SetGlobalDNS(
self.dns3.get_edit_text(), self.dns_dom.get_edit_text(), self.dns1.get_edit_text(),
self.search_dom.get_edit_text()) self.dns2.get_edit_text(),
self.dns3.get_edit_text(),
self.dns_dom.get_edit_text(),
self.search_dom.get_edit_text()
)
daemon.SetWirelessInterface(self.wless_edit.get_edit_text()) daemon.SetWirelessInterface(self.wless_edit.get_edit_text())
daemon.SetWiredInterface(self.wired_edit.get_edit_text()) daemon.SetWiredInterface(self.wired_edit.get_edit_text())
daemon.SetWPADriver(self.wpadrivers[self.wpa_cbox.get_focus()[1]]) daemon.SetWPADriver(self.wpadrivers[self.wpa_cbox.get_focus()[1]])
daemon.SetAlwaysShowWiredInterface(self.always_show_wired_checkb.get_state()) daemon.SetAlwaysShowWiredInterface(
self.always_show_wired_checkb.get_state()
)
daemon.SetAutoReconnect(self.auto_reconn_checkb.get_state()) daemon.SetAutoReconnect(self.auto_reconn_checkb.get_state())
daemon.SetDebugMode(self.debug_mode_checkb.get_state()) daemon.SetDebugMode(self.debug_mode_checkb.get_state())
daemon.SetSignalDisplayType(int(self.use_dbm_checkb.get_state())) daemon.SetSignalDisplayType(int(self.use_dbm_checkb.get_state()))
@@ -353,7 +373,7 @@ class PrefsDialog(urwid.WidgetWrap):
daemon.SetWiredAutoConnectMethod(1) daemon.SetWiredAutoConnectMethod(1)
daemon.SetBackend(self.backends[self.backend_cbox.get_focus()[1]]) daemon.SetBackend(self.backends[self.backend_cbox.get_focus()[1]])
# External Programs Tab # External Programs Tab
if self.dhcp0.get_state(): if self.dhcp0.get_state():
dhcp_client = misc.AUTO dhcp_client = misc.AUTO
@@ -366,7 +386,7 @@ class PrefsDialog(urwid.WidgetWrap):
else: else:
dhcp_client = misc.UDHCPC dhcp_client = misc.UDHCPC
daemon.SetDHCPClient(dhcp_client) daemon.SetDHCPClient(dhcp_client)
if self.wired0.get_state(): if self.wired0.get_state():
link_tool = misc.AUTO link_tool = misc.AUTO
elif self.wired1.get_state(): elif self.wired1.get_state():
@@ -374,7 +394,7 @@ class PrefsDialog(urwid.WidgetWrap):
else: else:
link_tool = misc.MIITOOL link_tool = misc.MIITOOL
daemon.SetLinkDetectionTool(link_tool) daemon.SetLinkDetectionTool(link_tool)
if self.flush0.get_state(): if self.flush0.get_state():
flush_tool = misc.AUTO flush_tool = misc.AUTO
elif self.flush1.get_state(): elif self.flush1.get_state():
@@ -383,11 +403,12 @@ class PrefsDialog(urwid.WidgetWrap):
flush_tool = misc.ROUTE flush_tool = misc.ROUTE
daemon.SetFlushTool(flush_tool) daemon.SetFlushTool(flush_tool)
# DNS CheckBox callback def global_dns_trigger(self, check_box, new_state, user_data=None):
def global_dns_trigger(self,check_box,new_state,user_data=None): """ DNS CheckBox callback. """
for w in self.dns1,self.dns2,self.dns3,self.dns_dom,self.search_dom: for w in self.dns1, self.dns2, self.dns3, self.dns_dom, self.search_dom:
w.set_sensitive(new_state) w.set_sensitive(new_state)
def ready_widgets(self,ui,body): def ready_widgets(self, ui, body):
self.wpa_cbox.build_combobox(body,ui,4) """ Build comboboxes. """
self.backend_cbox.build_combobox(body,ui,8) 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

@@ -47,10 +47,10 @@ wired_conf = wpath.etc + 'wired-settings.conf'
def none_to_blank(text): def none_to_blank(text):
""" Converts special string cases to a blank string. """ Converts special string cases to a blank string.
If text is None, 'None', or '' then this method will If text is None, 'None', or '' then this method will
return '', otherwise it will just return str(text). return '', otherwise it will just return str(text).
""" """
if text in (None, "None", ""): if text in (None, "None", ""):
return "" return ""
@@ -63,7 +63,7 @@ def blank_to_none(text):
return "None" return "None"
else: else:
return str(text) return str(text)
def get_script_info(network, network_type): def get_script_info(network, network_type):
""" Read script info from disk and load it into the configuration dialog """ """ Read script info from disk and load it into the configuration dialog """
info = {} info = {}
@@ -72,16 +72,20 @@ def get_script_info(network, network_type):
if con.has_section(network): if con.has_section(network):
info["pre_entry"] = con.get(network, "beforescript", None) info["pre_entry"] = con.get(network, "beforescript", None)
info["post_entry"] = con.get(network, "afterscript", None) info["post_entry"] = con.get(network, "afterscript", None)
info["pre_disconnect_entry"] = con.get(network, "predisconnectscript", None) info["pre_disconnect_entry"] = con.get(network,
info["post_disconnect_entry"] = con.get(network, "postdisconnectscript", None) "predisconnectscript", None)
info["post_disconnect_entry"] = con.get(network,
"postdisconnectscript", None)
else: else:
bssid = wireless.GetWirelessProperty(int(network), "bssid") bssid = wireless.GetWirelessProperty(int(network), "bssid")
con = ConfigManager(wireless_conf) con = ConfigManager(wireless_conf)
if con.has_section(bssid): if con.has_section(bssid):
info["pre_entry"] = con.get(bssid, "beforescript", None) info["pre_entry"] = con.get(bssid, "beforescript", None)
info["post_entry"] = con.get(bssid, "afterscript", None) info["post_entry"] = con.get(bssid, "afterscript", None)
info["pre_disconnect_entry"] = con.get(bssid, "predisconnectscript", None) info["pre_disconnect_entry"] = con.get(bssid,
info["post_disconnect_entry"] = con.get(bssid, "postdisconnectscript", None) "predisconnectscript", None)
info["post_disconnect_entry"] = con.get(bssid,
"postdisconnectscript", None)
return info return info
def write_scripts(network, network_type, script_info): def write_scripts(network, network_type, script_info):
@@ -90,8 +94,10 @@ def write_scripts(network, network_type, script_info):
con = ConfigManager(wired_conf) con = ConfigManager(wired_conf)
con.set(network, "beforescript", script_info["pre_entry"]) con.set(network, "beforescript", script_info["pre_entry"])
con.set(network, "afterscript", script_info["post_entry"]) con.set(network, "afterscript", script_info["post_entry"])
con.set(network, "predisconnectscript", script_info["pre_disconnect_entry"]) con.set(network, "predisconnectscript",
con.set(network, "postdisconnectscript", script_info["post_disconnect_entry"]) script_info["pre_disconnect_entry"])
con.set(network, "postdisconnectscript",
script_info["post_disconnect_entry"])
con.write() con.write()
wired.ReloadConfig() wired.ReloadConfig()
wired.ReadWiredNetworkProfile(network) wired.ReadWiredNetworkProfile(network)
@@ -101,8 +107,10 @@ def write_scripts(network, network_type, script_info):
con = ConfigManager(wireless_conf) con = ConfigManager(wireless_conf)
con.set(bssid, "beforescript", script_info["pre_entry"]) con.set(bssid, "beforescript", script_info["pre_entry"])
con.set(bssid, "afterscript", script_info["post_entry"]) con.set(bssid, "afterscript", script_info["post_entry"])
con.set(bssid, "predisconnectscript", script_info["pre_disconnect_entry"]) con.set(bssid, "predisconnectscript",
con.set(bssid, "postdisconnectscript", script_info["post_disconnect_entry"]) script_info["pre_disconnect_entry"])
con.set(bssid, "postdisconnectscript",
script_info["post_disconnect_entry"])
con.write() con.write()
wireless.ReloadConfig() wireless.ReloadConfig()
wireless.ReadWirelessNetworkProfile(int(network)) wireless.ReadWirelessNetworkProfile(int(network))
@@ -114,12 +122,12 @@ def main (argv):
if len(argv) < 2: if len(argv) < 2:
print 'Network id to configure is missing, aborting.' print 'Network id to configure is missing, aborting.'
sys.exit(1) sys.exit(1)
network = argv[1] network = argv[1]
network_type = argv[2] network_type = argv[2]
script_info = get_script_info(network, network_type) script_info = get_script_info(network, network_type)
gladefile = os.path.join(wpath.gtk, "wicd.ui") gladefile = os.path.join(wpath.gtk, "wicd.ui")
wTree = gtk.Builder() wTree = gtk.Builder()
wTree.set_translation_domain('wicd') wTree.set_translation_domain('wicd')
@@ -127,33 +135,39 @@ def main (argv):
dialog = wTree.get_object("configure_script_dialog") dialog = wTree.get_object("configure_script_dialog")
wTree.get_object("pre_label").set_label(_('Pre-connection Script') + ":") wTree.get_object("pre_label").set_label(_('Pre-connection Script') + ":")
wTree.get_object("post_label").set_label(_('Post-connection Script') + ":") wTree.get_object("post_label").set_label(_('Post-connection Script') + ":")
wTree.get_object("pre_disconnect_label").set_label(_('Pre-disconnection Script') wTree.get_object("pre_disconnect_label").\
+ ":") set_label(_('Pre-disconnection Script') + ":")
wTree.get_object("post_disconnect_label").set_label(_('Post-disconnection Script') wTree.get_object("post_disconnect_label").\
+ ":") set_label(_('Post-disconnection Script') + ":")
wTree.get_object("window1").hide() wTree.get_object("window1").hide()
pre_entry = wTree.get_object("pre_entry") pre_entry = wTree.get_object("pre_entry")
post_entry = wTree.get_object("post_entry") post_entry = wTree.get_object("post_entry")
pre_disconnect_entry = wTree.get_object("pre_disconnect_entry") pre_disconnect_entry = wTree.get_object("pre_disconnect_entry")
post_disconnect_entry = wTree.get_object("post_disconnect_entry") post_disconnect_entry = wTree.get_object("post_disconnect_entry")
pre_entry.set_text(none_to_blank(script_info.get("pre_entry"))) pre_entry.set_text(none_to_blank(script_info.get("pre_entry")))
post_entry.set_text(none_to_blank(script_info.get("post_entry"))) post_entry.set_text(none_to_blank(script_info.get("post_entry")))
pre_disconnect_entry.set_text(none_to_blank(script_info.get("pre_disconnect_entry"))) pre_disconnect_entry.set_text(
post_disconnect_entry.set_text(none_to_blank(script_info.get("post_disconnect_entry"))) none_to_blank(script_info.get("pre_disconnect_entry"))
)
post_disconnect_entry.set_text(
none_to_blank(script_info.get("post_disconnect_entry"))
)
dialog.show_all() dialog.show_all()
result = dialog.run() result = dialog.run()
if result == 1: if result == 1:
script_info["pre_entry"] = blank_to_none(pre_entry.get_text()) script_info["pre_entry"] = blank_to_none(pre_entry.get_text())
script_info["post_entry"] = blank_to_none(post_entry.get_text()) script_info["post_entry"] = blank_to_none(post_entry.get_text())
script_info["pre_disconnect_entry"] = blank_to_none(pre_disconnect_entry.get_text()) script_info["pre_disconnect_entry"] = \
script_info["post_disconnect_entry"] = blank_to_none(post_disconnect_entry.get_text()) blank_to_none(pre_disconnect_entry.get_text())
script_info["post_disconnect_entry"] = \
blank_to_none(post_disconnect_entry.get_text())
write_scripts(network, network_type, script_info) write_scripts(network, network_type, script_info)
dialog.destroy() dialog.destroy()
if __name__ == '__main__': if __name__ == '__main__':
if os.getuid() != 0: if os.getuid() != 0:

View File

@@ -27,7 +27,6 @@ import os
import sys import sys
import time import time
import gobject import gobject
import pango
import gtk import gtk
from itertools import chain from itertools import chain
from dbus import DBusException from dbus import DBusException
@@ -49,22 +48,30 @@ if __name__ == '__main__':
proxy_obj = daemon = wireless = wired = bus = None proxy_obj = daemon = wireless = wired = bus = None
DBUS_AVAIL = False DBUS_AVAIL = False
def setup_dbus(force=True): def setup_dbus(force=True):
""" Initialize DBus. """
global bus, daemon, wireless, wired, DBUS_AVAIL global bus, daemon, wireless, wired, DBUS_AVAIL
try: try:
dbusmanager.connect_to_dbus() dbusmanager.connect_to_dbus()
except DBusException: except DBusException:
if force: 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..."
if not misc.PromptToStartDaemon(): if not misc.PromptToStartDaemon():
print "Failed to find a graphical sudo program, cannot continue." print "Failed to find a graphical sudo program, ' + \
'cannot continue."
return False return False
try: try:
dbusmanager.connect_to_dbus() dbusmanager.connect_to_dbus()
except DBusException: 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 return False
else: else:
return False return False
prefs.setup_dbus() prefs.setup_dbus()
netentry.setup_dbus() netentry.setup_dbus()
@@ -74,18 +81,26 @@ def setup_dbus(force=True):
wireless = dbus_ifaces['wireless'] wireless = dbus_ifaces['wireless']
wired = dbus_ifaces['wired'] wired = dbus_ifaces['wired']
DBUS_AVAIL = True DBUS_AVAIL = True
return True return True
def handle_no_dbus(from_tray=False): def handle_no_dbus(from_tray=False):
""" Handle the case where no DBus is available. """
global DBUS_AVAIL global DBUS_AVAIL
DBUS_AVAIL = False DBUS_AVAIL = False
if from_tray: return False if from_tray:
return False
print "Wicd daemon is shutting down!" 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 return False
class WiredProfileChooser: class WiredProfileChooser:
""" Class for displaying the wired profile chooser. """ """ Class for displaying the wired profile chooser. """
def __init__(self): def __init__(self):
@@ -94,14 +109,19 @@ class WiredProfileChooser:
# functions and widgets it uses. # functions and widgets it uses.
wired_net_entry = WiredNetworkEntry() wired_net_entry = WiredNetworkEntry()
dialog = gtk.Dialog(title = _('Wired connection detected'), dialog = gtk.Dialog(
flags = gtk.DIALOG_MODAL, title=_('Wired connection detected'),
buttons = (gtk.STOCK_CONNECT, 1, flags=gtk.DIALOG_MODAL,
gtk.STOCK_CANCEL, 2)) buttons=(gtk.STOCK_CONNECT, 1, gtk.STOCK_CANCEL, 2)
)
dialog.set_has_separator(False) dialog.set_has_separator(False)
dialog.set_size_request(400, 150) dialog.set_size_request(400, 150)
instruct_label = gtk.Label(_('Select or create a wired profile to connect with') + ':\n') instruct_label = gtk.Label(
stoppopcheckbox = gtk.CheckButton(_('Stop Showing Autoconnect pop-up temporarily')) _('Select or create a wired profile to connect with') + ':\n'
)
stoppopcheckbox = gtk.CheckButton(
_('Stop Showing Autoconnect pop-up temporarily')
)
wired_net_entry.is_full_gui = False wired_net_entry.is_full_gui = False
instruct_label.set_alignment(0, 0) instruct_label.set_alignment(0, 0)
@@ -112,15 +132,19 @@ class WiredProfileChooser:
wired_net_entry.vbox_top.remove(wired_net_entry.hbox_temp) wired_net_entry.vbox_top.remove(wired_net_entry.hbox_temp)
wired_net_entry.vbox_top.remove(wired_net_entry.profile_help) wired_net_entry.vbox_top.remove(wired_net_entry.profile_help)
# pylint: disable-msg=E1101
dialog.vbox.pack_start(instruct_label, fill=False, expand=False) dialog.vbox.pack_start(instruct_label, fill=False, expand=False)
# pylint: disable-msg=E1101
dialog.vbox.pack_start(wired_net_entry.profile_help, False, False) dialog.vbox.pack_start(wired_net_entry.profile_help, False, False)
# pylint: disable-msg=E1101
dialog.vbox.pack_start(wired_net_entry.hbox_temp, False, False) dialog.vbox.pack_start(wired_net_entry.hbox_temp, False, False)
# pylint: disable-msg=E1101
dialog.vbox.pack_start(stoppopcheckbox, False, False) dialog.vbox.pack_start(stoppopcheckbox, False, False)
dialog.show_all() dialog.show_all()
wired_profiles = wired_net_entry.combo_profile_names wired_profiles = wired_net_entry.combo_profile_names
wired_net_entry.profile_help.hide() wired_net_entry.profile_help.hide()
if wired_net_entry.profile_list != None: if wired_net_entry.profile_list is not None:
wired_profiles.set_active(0) wired_profiles.set_active(0)
print "wired profiles found" print "wired profiles found"
else: else:
@@ -139,6 +163,7 @@ class WiredProfileChooser:
def get_wireless_prop(net_id, prop): def get_wireless_prop(net_id, prop):
""" Get wireless property. """
return wireless.GetWirelessProperty(net_id, prop) return wireless.GetWirelessProperty(net_id, prop)
class appGui(object): class appGui(object):
@@ -170,18 +195,19 @@ class appGui(object):
width = 530 width = 530
self.window.resize(width, int(gtk.gdk.screen_height() / 1.7)) self.window.resize(width, int(gtk.gdk.screen_height() / 1.7))
dic = { "refresh_clicked" : self.refresh_clicked, dic = {
"quit_clicked" : self.exit, "refresh_clicked": self.refresh_clicked,
"rfkill_clicked" : self.switch_rfkill, "quit_clicked": self.exit,
"disconnect_clicked" : self.disconnect_all, "rfkill_clicked": self.switch_rfkill,
"main_exit" : self.exit, "disconnect_clicked": self.disconnect_all,
"cancel_clicked" : self.cancel_connect, "main_exit": self.exit,
"hidden_clicked" : self.connect_hidden, "cancel_clicked": self.cancel_connect,
"preferences_clicked" : self.settings_dialog, "hidden_clicked": self.connect_hidden,
"about_clicked" : self.about_dialog, "preferences_clicked": self.settings_dialog,
"create_adhoc_clicked" : self.create_adhoc_network, "about_clicked": self.about_dialog,
"forget_network_clicked" : self.forget_network, "create_adhoc_clicked": self.create_adhoc_network,
} "forget_network_clicked": self.forget_network,
}
self.wTree.connect_signals(dic) self.wTree.connect_signals(dic)
# Set some strings in the GUI - they may be translated # Set some strings in the GUI - they may be translated
@@ -207,7 +233,9 @@ class appGui(object):
self.status_area.hide_all() self.status_area.hide_all()
if os.path.exists(os.path.join(wpath.images, "wicd.png")): if os.path.exists(os.path.join(wpath.images, "wicd.png")):
self.window.set_icon_from_file(os.path.join(wpath.images, "wicd.png")) self.window.set_icon_from_file(
os.path.join(wpath.images, "wicd.png")
)
self.statusID = None self.statusID = None
self.first_dialog_load = True self.first_dialog_load = True
self.is_visible = True self.is_visible = True
@@ -236,32 +264,36 @@ class appGui(object):
'org.wicd.daemon') 'org.wicd.daemon')
bus.add_signal_receiver(self.handle_connection_results, bus.add_signal_receiver(self.handle_connection_results,
'ConnectResultsSent', 'org.wicd.daemon') 'ConnectResultsSent', 'org.wicd.daemon')
bus.add_signal_receiver(lambda: setup_dbus(force=False), bus.add_signal_receiver(lambda: setup_dbus(force=False),
"DaemonStarting", "org.wicd.daemon") "DaemonStarting", "org.wicd.daemon")
bus.add_signal_receiver(self._do_statusbar_update, 'StatusChanged', bus.add_signal_receiver(self._do_statusbar_update, 'StatusChanged',
'org.wicd.daemon') 'org.wicd.daemon')
if standalone: if standalone:
bus.add_signal_receiver(handle_no_dbus, "DaemonClosing", bus.add_signal_receiver(handle_no_dbus, "DaemonClosing",
"org.wicd.daemon") "org.wicd.daemon")
self._do_statusbar_update(*daemon.GetConnectionStatus()) self._do_statusbar_update(*daemon.GetConnectionStatus())
self.wait_for_events(0.1) self.wait_for_events(0.1)
self.update_cb = misc.timeout_add(2, self.update_statusbar) self.update_cb = misc.timeout_add(2, self.update_statusbar)
self.refresh_clicked() self.refresh_clicked()
def handle_connection_results(self, results): def handle_connection_results(self, results):
""" Handle connection results. """
if results not in ['success', 'aborted'] and self.is_visible: if results not in ['success', 'aborted'] and self.is_visible:
error(self.window, language[results], block=False) error(self.window, language[results], block=False)
def create_adhoc_network(self, widget=None): def create_adhoc_network(self, widget=None):
""" Shows a dialog that creates a new adhoc network. """ """ Shows a dialog that creates a new adhoc network. """
print "Starting the Ad-Hoc Network Creation Process..." print "Starting the Ad-Hoc Network Creation Process..."
dialog = gtk.Dialog(title = _('Create an Ad-Hoc Network'), dialog = gtk.Dialog(
flags = gtk.DIALOG_MODAL, title=_('Create an Ad-Hoc Network'),
buttons=(gtk.STOCK_CANCEL, 2, gtk.STOCK_OK, 1)) flags=gtk.DIALOG_MODAL,
buttons=(gtk.STOCK_CANCEL, 2, gtk.STOCK_OK, 1)
)
dialog.set_has_separator(False) dialog.set_has_separator(False)
dialog.set_size_request(400, -1) dialog.set_size_request(400, -1)
self.chkbox_use_encryption = gtk.CheckButton(_('Use Encryption (WEP only)')) self.chkbox_use_encryption = \
gtk.CheckButton(_('Use Encryption (WEP only)'))
self.chkbox_use_encryption.set_active(False) self.chkbox_use_encryption.set_active(False)
ip_entry = LabelEntry(_('IP') + ':') ip_entry = LabelEntry(_('IP') + ':')
essid_entry = LabelEntry(_('ESSID') + ':') essid_entry = LabelEntry(_('ESSID') + ':')
@@ -270,7 +302,8 @@ class appGui(object):
self.key_entry.set_auto_hidden(True) self.key_entry.set_auto_hidden(True)
self.key_entry.set_sensitive(False) self.key_entry.set_sensitive(False)
chkbox_use_ics = gtk.CheckButton( _('Activate Internet Connection Sharing')) chkbox_use_ics = \
gtk.CheckButton(_('Activate Internet Connection Sharing'))
self.chkbox_use_encryption.connect("toggled", self.chkbox_use_encryption.connect("toggled",
self.toggle_encrypt_check) self.toggle_encrypt_check)
@@ -283,22 +316,30 @@ class appGui(object):
vbox_ah.pack_start(self.chkbox_use_encryption, False, False) vbox_ah.pack_start(self.chkbox_use_encryption, False, False)
vbox_ah.pack_start(self.key_entry, False, False) vbox_ah.pack_start(self.key_entry, False, False)
vbox_ah.show() vbox_ah.show()
# pylint: disable-msg=E1101
dialog.vbox.pack_start(essid_entry) dialog.vbox.pack_start(essid_entry)
# pylint: disable-msg=E1101
dialog.vbox.pack_start(ip_entry) dialog.vbox.pack_start(ip_entry)
# pylint: disable-msg=E1101
dialog.vbox.pack_start(channel_entry) dialog.vbox.pack_start(channel_entry)
# pylint: disable-msg=E1101
dialog.vbox.pack_start(chkbox_use_ics) dialog.vbox.pack_start(chkbox_use_ics)
# pylint: disable-msg=E1101
dialog.vbox.pack_start(vbox_ah) dialog.vbox.pack_start(vbox_ah)
# pylint: disable-msg=E1101
dialog.vbox.set_spacing(5) dialog.vbox.set_spacing(5)
dialog.show_all() dialog.show_all()
response = dialog.run() response = dialog.run()
if response == 1: if response == 1:
wireless.CreateAdHocNetwork(essid_entry.entry.get_text(), wireless.CreateAdHocNetwork(
channel_entry.entry.get_text(), essid_entry.entry.get_text(),
ip_entry.entry.get_text().strip(), channel_entry.entry.get_text(),
"WEP", ip_entry.entry.get_text().strip(),
self.key_entry.entry.get_text(), "WEP",
self.chkbox_use_encryption.get_active(), self.key_entry.entry.get_text(),
False) #chkbox_use_ics.get_active()) self.chkbox_use_encryption.get_active(),
False # chkbox_use_ics.get_active())
)
dialog.destroy() dialog.destroy()
def forget_network(self, widget=None): def forget_network(self, widget=None):
@@ -307,9 +348,11 @@ class appGui(object):
delete them. delete them.
""" """
wireless.ReloadConfig() wireless.ReloadConfig()
dialog = gtk.Dialog(title = _('List of saved networks'), dialog = gtk.Dialog(
flags = gtk.DIALOG_MODAL, title=_('List of saved networks'),
buttons=(gtk.STOCK_DELETE, 1, gtk.STOCK_OK, 2)) flags=gtk.DIALOG_MODAL,
buttons=(gtk.STOCK_DELETE, 1, gtk.STOCK_OK, 2)
)
dialog.set_has_separator(True) dialog.set_has_separator(True)
dialog.set_size_request(400, 200) dialog.set_size_request(400, 200)
@@ -324,16 +367,18 @@ class appGui(object):
cell = gtk.CellRendererText() cell = gtk.CellRendererText()
column = gtk.TreeViewColumn(_('ESSID'), cell, text = 0) column = gtk.TreeViewColumn(_('ESSID'), cell, text=0)
tree.append_column(column) tree.append_column(column)
column = gtk.TreeViewColumn(_('BSSID'), cell, text = 1) column = gtk.TreeViewColumn(_('BSSID'), cell, text=1)
tree.append_column(column) tree.append_column(column)
scroll = gtk.ScrolledWindow() scroll = gtk.ScrolledWindow()
scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
scroll.add(tree) scroll.add(tree)
# pylint: disable-msg=E1101
dialog.vbox.pack_start(scroll) dialog.vbox.pack_start(scroll)
# pylint: disable-msg=E1101
dialog.vbox.set_spacing(5) dialog.vbox.set_spacing(5)
dialog.show_all() dialog.show_all()
response = dialog.run() response = dialog.run()
@@ -342,21 +387,24 @@ class appGui(object):
to_remove = dict(essid=[], bssid=[]) to_remove = dict(essid=[], bssid=[])
if pathlist: if pathlist:
for row in pathlist: for row in pathlist:
iter = model.get_iter(path=row) it = model.get_iter(path=row)
to_remove['essid'].append(misc.noneToString(model.get_value(iter, 0))) to_remove['essid'].append(
to_remove['bssid'].append(model.get_value(iter, 1)) misc.noneToString(model.get_value(it, 0))
)
to_remove['bssid'].append(model.get_value(it, 1))
confirm = gtk.MessageDialog( confirm = gtk.MessageDialog(
flags = gtk.DIALOG_MODAL, flags=gtk.DIALOG_MODAL,
type = gtk.MESSAGE_INFO, type=gtk.MESSAGE_INFO,
buttons = gtk.BUTTONS_YES_NO, buttons=gtk.BUTTONS_YES_NO,
message_format = _('Are you sure you want to discard' + message_format=_('Are you sure you want to discard' +
' settings for the selected networks?') ' settings for the selected networks?')
) )
confirm.format_secondary_text('\n'.join(to_remove['essid'])) confirm.format_secondary_text('\n'.join(to_remove['essid']))
response = confirm.run() response = confirm.run()
if response == gtk.RESPONSE_YES: if response == gtk.RESPONSE_YES:
map(wireless.DeleteWirelessNetwork, to_remove['bssid']) for x in to_remove['bssid']:
wireless.DeleteWirelessNetwork(x)
wireless.ReloadConfig() wireless.ReloadConfig()
confirm.destroy() confirm.destroy()
dialog.destroy() dialog.destroy()
@@ -379,7 +427,7 @@ class appGui(object):
""" Disconnects from any active network. """ """ Disconnects from any active network. """
def handler(*args): def handler(*args):
gobject.idle_add(self.all_network_list.set_sensitive, True) gobject.idle_add(self.all_network_list.set_sensitive, True)
self.all_network_list.set_sensitive(False) self.all_network_list.set_sensitive(False)
daemon.Disconnect(reply_handler=handler, error_handler=handler) daemon.Disconnect(reply_handler=handler, error_handler=handler)
@@ -388,17 +436,22 @@ class appGui(object):
dialog = gtk.AboutDialog() dialog = gtk.AboutDialog()
dialog.set_name("Wicd") dialog.set_name("Wicd")
dialog.set_version(daemon.Hello()) dialog.set_version(daemon.Hello())
dialog.set_authors([ "Adam Blackburn", "Dan O'Reilly", "Andrew Psaltis", "David Paleino"]) dialog.set_authors([
"Adam Blackburn",
"Dan O'Reilly",
"Andrew Psaltis",
"David Paleino"
])
dialog.set_website("http://wicd.sourceforge.net") dialog.set_website("http://wicd.sourceforge.net")
dialog.run() dialog.run()
dialog.destroy() dialog.destroy()
def key_event (self, widget, event=None): def key_event(self, widget, event=None):
""" Handle key-release-events. """ """ Handle key-release-events. """
if event.state & gtk.gdk.CONTROL_MASK and \ if event.state & gtk.gdk.CONTROL_MASK and \
gtk.gdk.keyval_name(event.keyval) in ["w", "q"]: gtk.gdk.keyval_name(event.keyval) in ["w", "q"]:
self.exit() self.exit()
def settings_dialog(self, widget, event=None): def settings_dialog(self, widget, event=None):
""" Displays a general settings dialog. """ """ Displays a general settings dialog. """
if not self.pref: if not self.pref:
@@ -411,13 +464,17 @@ class appGui(object):
def connect_hidden(self, widget): def connect_hidden(self, widget):
""" Prompts the user for a hidden network, then scans for it. """ """ Prompts the user for a hidden network, then scans for it. """
dialog = gtk.Dialog(title=('Hidden Network'), dialog = gtk.Dialog(
flags=gtk.DIALOG_MODAL, title=('Hidden Network'),
buttons=(gtk.STOCK_CONNECT, 1, gtk.STOCK_CANCEL, 2)) flags=gtk.DIALOG_MODAL,
buttons=(gtk.STOCK_CONNECT, 1, gtk.STOCK_CANCEL, 2)
)
dialog.set_has_separator(False) dialog.set_has_separator(False)
lbl = gtk.Label(_('Hidden Network ESSID')) lbl = gtk.Label(_('Hidden Network ESSID'))
textbox = gtk.Entry() textbox = gtk.Entry()
# pylint: disable-msg=E1101
dialog.vbox.pack_start(lbl) dialog.vbox.pack_start(lbl)
# pylint: disable-msg=E1101
dialog.vbox.pack_start(textbox) dialog.vbox.pack_start(textbox)
dialog.show_all() dialog.show_all()
button = dialog.run() button = dialog.run()
@@ -454,18 +511,19 @@ class appGui(object):
""" Triggers a status update in wicd-monitor. """ """ Triggers a status update in wicd-monitor. """
if not self.is_visible: if not self.is_visible:
return True return True
daemon.UpdateState() daemon.UpdateState()
if self.connecting: if self.connecting:
# If we're connecting, don't wait for the monitor to send # If we're connecting, don't wait for the monitor to send
# us a signal, since it won't until the connection is made. # us a signal, since it won't until the connection is made.
self._do_statusbar_update(*daemon.GetConnectionStatus()) self._do_statusbar_update(*daemon.GetConnectionStatus())
return True return True
def _do_statusbar_update(self, state, info): def _do_statusbar_update(self, state, info):
""" Actually perform the statusbar update. """
if not self.is_visible: if not self.is_visible:
return True return True
if state == misc.WIRED: if state == misc.WIRED:
return self.set_wired_state(info) return self.set_wired_state(info)
elif state == misc.WIRELESS: elif state == misc.WIRELESS:
@@ -475,15 +533,19 @@ class appGui(object):
elif state in (misc.SUSPENDED, misc.NOT_CONNECTED): elif state in (misc.SUSPENDED, misc.NOT_CONNECTED):
return self.set_not_connected_state(info) return self.set_not_connected_state(info)
return True return True
def set_wired_state(self, info): def set_wired_state(self, info):
""" Set wired state. """
if self.connecting: if self.connecting:
# Adjust our state from connecting->connected. # Adjust our state from connecting->connected.
self._set_not_connecting_state() self._set_not_connecting_state()
self.set_status(_('Connected to wired network (IP: $A)').replace('$A', info[0])) self.set_status(
_('Connected to wired network (IP: $A)').replace('$A', info[0])
)
return True return True
def set_wireless_state(self, info): def set_wireless_state(self, info):
""" Set wireless state. """
if self.connecting: if self.connecting:
# Adjust our state from connecting->connected. # Adjust our state from connecting->connected.
self._set_not_connecting_state() self._set_not_connecting_state()
@@ -492,15 +554,17 @@ class appGui(object):
('$B', daemon.FormatSignalForPrinting(info[2])).replace ('$B', daemon.FormatSignalForPrinting(info[2])).replace
('$C', info[0])) ('$C', info[0]))
return True return True
def set_not_connected_state(self, info): def set_not_connected_state(self, info):
""" Set not connected state. """
if self.connecting: if self.connecting:
# Adjust our state from connecting->not-connected. # Adjust our state from connecting->not-connected.
self._set_not_connecting_state() self._set_not_connecting_state()
self.set_status(_('Not connected')) self.set_status(_('Not connected'))
return True return True
def _set_not_connecting_state(self): def _set_not_connecting_state(self):
""" Set not-connecting state. """
if self.connecting: if self.connecting:
if self.update_cb: if self.update_cb:
gobject.source_remove(self.update_cb) gobject.source_remove(self.update_cb)
@@ -512,12 +576,13 @@ class appGui(object):
gobject.idle_add(self.status_area.hide_all) gobject.idle_add(self.status_area.hide_all)
if self.statusID: if self.statusID:
gobject.idle_add(self.status_bar.remove_message, 1, self.statusID) gobject.idle_add(self.status_bar.remove_message, 1, self.statusID)
def set_connecting_state(self, info): def set_connecting_state(self, info):
""" Set connecting state. """
if not self.connecting: if not self.connecting:
if self.update_cb: if self.update_cb:
gobject.source_remove(self.update_cb) gobject.source_remove(self.update_cb)
self.update_cb = misc.timeout_add(500, self.update_statusbar, self.update_cb = misc.timeout_add(500, self.update_statusbar,
milli=True) milli=True)
self.connecting = True self.connecting = True
if not self.pulse_active: if not self.pulse_active:
@@ -531,56 +596,60 @@ class appGui(object):
stat = wireless.CheckWirelessConnectingMessage() stat = wireless.CheckWirelessConnectingMessage()
gobject.idle_add(self.set_status, "%s: %s" % (info[1], stat)) gobject.idle_add(self.set_status, "%s: %s" % (info[1], stat))
elif info[0] == "wired": elif info[0] == "wired":
gobject.idle_add(self.set_status, _('Wired Network') + ': ' \ gobject.idle_add(self.set_status, _('Wired Network') + ': '
+ wired.CheckWiredConnectingMessage()) + wired.CheckWiredConnectingMessage())
return True return True
def update_connect_buttons(self, state=None, x=None, force_check=False): def update_connect_buttons(self, state=None, x=None, force_check=False):
""" Updates the connect/disconnect buttons for each network entry. """ Updates the connect/disconnect buttons for each network entry.
If force_check is given, update the buttons even if the If force_check is given, update the buttons even if the
current network state is the same as the previous. current network state is the same as the previous.
""" """
if not DBUS_AVAIL: return if not DBUS_AVAIL:
return
if not state: if not state:
state, x = daemon.GetConnectionStatus() state, x = daemon.GetConnectionStatus()
if self.prev_state != state or force_check: if self.prev_state != state or force_check:
apbssid = wireless.GetApBssid() apbssid = wireless.GetApBssid()
for entry in chain(self.network_list, self.wired_network_box): for entry in chain(self.network_list, self.wired_network_box):
if hasattr(entry, "update_connect_button"): if hasattr(entry, "update_connect_button"):
entry.update_connect_button(state, apbssid) entry.update_connect_button(state, apbssid)
self.prev_state = state self.prev_state = state
def set_status(self, msg): def set_status(self, msg):
""" Sets the status bar message for the GUI. """ """ Sets the status bar message for the GUI. """
self.statusID = self.status_bar.push(1, msg) self.statusID = self.status_bar.push(1, msg)
def dbus_scan_finished(self): def dbus_scan_finished(self):
""" Calls for a non-fresh update of the gui window. """ Calls for a non-fresh update of the gui window.
This method is called after a wireless scan is completed. This method is called after a wireless scan is completed.
""" """
if not DBUS_AVAIL: return if not DBUS_AVAIL:
return
gobject.idle_add(self.refresh_networks, None, False, None) gobject.idle_add(self.refresh_networks, None, False, None)
def dbus_scan_started(self): def dbus_scan_started(self):
""" Called when a wireless scan starts. """ """ Called when a wireless scan starts. """
if not DBUS_AVAIL: return if not DBUS_AVAIL:
return
self.network_list.set_sensitive(False) self.network_list.set_sensitive(False)
def _remove_items_from_vbox(self, vbox): def _remove_items_from_vbox(self, vbox):
""" Remove items fro a VBox. """
for z in vbox: for z in vbox:
vbox.remove(z) vbox.remove(z)
z.destroy() z.destroy()
del z del z
def refresh_clicked(self, widget=None): def refresh_clicked(self, widget=None):
""" Kick off an asynchronous wireless scan. """ """ Kick off an asynchronous wireless scan. """
if not DBUS_AVAIL or self.connecting: return if not DBUS_AVAIL or self.connecting:
return
self.refreshing = True self.refreshing = True
# Remove stuff already in there. # Remove stuff already in there.
@@ -598,7 +667,7 @@ class appGui(object):
wirednet.disconnect_button.connect("clicked", self.disconnect, wirednet.disconnect_button.connect("clicked", self.disconnect,
"wired", 0, wirednet) "wired", 0, wirednet)
wirednet.advanced_button.connect("clicked", wirednet.advanced_button.connect("clicked",
self.edit_advanced, "wired", 0, self.edit_advanced, "wired", 0,
wirednet) wirednet)
state, x = daemon.GetConnectionStatus() state, x = daemon.GetConnectionStatus()
wirednet.update_connect_button(state) wirednet.update_connect_button(state)
@@ -611,13 +680,13 @@ class appGui(object):
def refresh_networks(self, widget=None, fresh=True, hidden=None): def refresh_networks(self, widget=None, fresh=True, hidden=None):
""" Refreshes the network list. """ Refreshes the network list.
If fresh=True, scans for wireless networks and displays the results. If fresh=True, scans for wireless networks and displays the results.
If a ethernet connection is available, or the user has chosen to, If a ethernet connection is available, or the user has chosen to,
displays a Wired Network entry as well. displays a Wired Network entry as well.
If hidden isn't None, will scan for networks after running If hidden isn't None, will scan for networks after running
iwconfig <wireless interface> essid <hidden>. iwconfig <wireless interface> essid <hidden>.
""" """
if fresh: if fresh:
if hidden: if hidden:
@@ -637,7 +706,9 @@ class appGui(object):
skip_never_connect = not daemon.GetShowNeverConnect() skip_never_connect = not daemon.GetShowNeverConnect()
instruct_label.show() instruct_label.show()
for x in xrange(0, num_networks): for x in xrange(0, num_networks):
if skip_never_connect and misc.to_bool(get_wireless_prop(x,'never')): continue if skip_never_connect and \
misc.to_bool(get_wireless_prop(x, 'never')):
continue
if printLine: if printLine:
sep = gtk.HSeparator() sep = gtk.HSeparator()
self.network_list.pack_start(sep, padding=10, fill=False, self.network_list.pack_start(sep, padding=10, fill=False,
@@ -673,17 +744,17 @@ class appGui(object):
entry = networkentry.advanced_dialog entry = networkentry.advanced_dialog
opt_entlist = [] opt_entlist = []
req_entlist = [] req_entlist = []
# First make sure all the Addresses entered are valid. # First make sure all the Addresses entered are valid.
if entry.chkbox_static_ip.get_active(): if entry.chkbox_static_ip.get_active():
req_entlist = [entry.txt_ip, entry.txt_netmask] req_entlist = [entry.txt_ip, entry.txt_netmask]
opt_entlist = [entry.txt_gateway] opt_entlist = [entry.txt_gateway]
if entry.chkbox_static_dns.get_active() and \ if entry.chkbox_static_dns.get_active() and \
not entry.chkbox_global_dns.get_active(): not entry.chkbox_global_dns.get_active():
for ent in [entry.txt_dns_1, entry.txt_dns_2, entry.txt_dns_3]: for ent in [entry.txt_dns_1, entry.txt_dns_2, entry.txt_dns_3]:
opt_entlist.append(ent) opt_entlist.append(ent)
# Required entries. # Required entries.
for lblent in req_entlist: for lblent in req_entlist:
lblent.set_text(lblent.get_text().strip()) lblent.set_text(lblent.get_text().strip())
@@ -691,7 +762,7 @@ class appGui(object):
error(self.window, _('Invalid address in $A entry.'). error(self.window, _('Invalid address in $A entry.').
replace('$A', lblent.label.get_label())) replace('$A', lblent.label.get_label()))
return False return False
# Optional entries, only check for validity if they're entered. # Optional entries, only check for validity if they're entered.
for lblent in opt_entlist: for lblent in opt_entlist:
lblent.set_text(lblent.get_text().strip()) lblent.set_text(lblent.get_text().strip())
@@ -708,17 +779,17 @@ class appGui(object):
elif nettype == "wired": elif nettype == "wired":
if not networkentry.save_wired_settings(): if not networkentry.save_wired_settings():
return False return False
return True return True
def edit_advanced(self, widget, ttype, networkid, networkentry): def edit_advanced(self, widget, ttype, networkid, networkentry):
""" Display the advanced settings dialog. """ Display the advanced settings dialog.
Displays the advanced settings dialog and saves any changes made. Displays the advanced settings dialog and saves any changes made.
If errors occur in the settings, an error message will be displayed If errors occur in the settings, an error message will be displayed
and the user won't be able to save the changes until the errors and the user won't be able to save the changes until the errors
are fixed. are fixed.
""" """
dialog = networkentry.advanced_dialog dialog = networkentry.advanced_dialog
dialog.set_values() dialog.set_values()
@@ -727,13 +798,13 @@ class appGui(object):
if self.run_settings_dialog(dialog, ttype, networkid, networkentry): if self.run_settings_dialog(dialog, ttype, networkid, networkentry):
break break
dialog.hide() dialog.hide()
def run_settings_dialog(self, dialog, nettype, networkid, networkentry): def run_settings_dialog(self, dialog, nettype, networkid, networkentry):
""" Runs the settings dialog. """ Runs the settings dialog.
Runs the settings dialog and returns True if settings are saved Runs the settings dialog and returns True if settings are saved
successfully, and false otherwise. successfully, and false otherwise.
""" """
result = dialog.run() result = dialog.run()
if result == gtk.RESPONSE_ACCEPT: if result == gtk.RESPONSE_ACCEPT:
@@ -742,7 +813,7 @@ class appGui(object):
else: else:
return False return False
return True return True
def check_encryption_valid(self, networkid, entry): def check_encryption_valid(self, networkid, entry):
""" Make sure that encryption settings are properly filled in. """ """ Make sure that encryption settings are properly filled in. """
# Make sure no entries are left blank # Make sure no entries are left blank
@@ -751,18 +822,25 @@ class appGui(object):
for entry_info in encryption_info.itervalues(): for entry_info in encryption_info.itervalues():
if entry_info[0].entry.get_text() == "" and \ if entry_info[0].entry.get_text() == "" and \
entry_info[1] == 'required': entry_info[1] == 'required':
error(self.window, "%s (%s)" % (_('Required encryption information is missing.'), error(
entry_info[0].label.get_label()) self.window,
) "%s (%s)" %
(_('Required encryption information is missing.'),
entry_info[0].label.get_label())
)
return False return False
# Make sure the checkbox is checked when it should be # Make sure the checkbox is checked when it should be
elif not entry.chkbox_encryption.get_active() and \ elif not entry.chkbox_encryption.get_active() and \
wireless.GetWirelessProperty(networkid, "encryption"): wireless.GetWirelessProperty(networkid, "encryption"):
error(self.window, _('This network requires encryption to be enabled.')) error(
self.window,
_('This network requires encryption to be enabled.')
)
return False return False
return True return True
def _wait_for_connect_thread_start(self): def _wait_for_connect_thread_start(self):
""" Wait for the connect thread to start. """
self.wTree.get_object("progressbar").pulse() self.wTree.get_object("progressbar").pulse()
if not self._connect_thread_started: if not self._connect_thread_started:
return True return True
@@ -770,19 +848,22 @@ class appGui(object):
misc.timeout_add(2, self.update_statusbar) misc.timeout_add(2, self.update_statusbar)
self.update_statusbar() self.update_statusbar()
return False return False
def connect(self, widget, nettype, networkid, networkentry): def connect(self, widget, nettype, networkid, networkentry):
""" Initiates the connection process in the daemon. """ """ Initiates the connection process in the daemon. """
def handler(*args): def handler(*args):
self._connect_thread_started = True self._connect_thread_started = True
def setup_interface_for_connection(): def setup_interface_for_connection():
""" Initialize interface for connection. """
cancel_button = self.wTree.get_object("cancel_button") cancel_button = self.wTree.get_object("cancel_button")
cancel_button.set_sensitive(True) cancel_button.set_sensitive(True)
self.all_network_list.set_sensitive(False) self.all_network_list.set_sensitive(False)
if self.statusID: if self.statusID:
gobject.idle_add(self.status_bar.remove_message, 1, self.statusID) gobject.idle_add(
gobject.idle_add(self.set_status, _('Disconnecting active connections...')) self.status_bar.remove_message, 1, self.statusID)
gobject.idle_add(
self.set_status, _('Disconnecting active connections...'))
gobject.idle_add(self.status_area.show_all) gobject.idle_add(self.status_area.show_all)
self.wait_for_events() self.wait_for_events()
self._connect_thread_started = False self._connect_thread_started = False
@@ -798,25 +879,25 @@ class appGui(object):
elif nettype == "wired": elif nettype == "wired":
setup_interface_for_connection() setup_interface_for_connection()
wired.ConnectWired(reply_handler=handler, error_handler=handler) wired.ConnectWired(reply_handler=handler, error_handler=handler)
gobject.source_remove(self.update_cb) gobject.source_remove(self.update_cb)
misc.timeout_add(100, self._wait_for_connect_thread_start, milli=True) misc.timeout_add(100, self._wait_for_connect_thread_start, milli=True)
def disconnect(self, widget, nettype, networkid, networkentry): def disconnect(self, widget, nettype, networkid, networkentry):
""" Disconnects from the given network. """ Disconnects from the given network.
Keyword arguments: Keyword arguments:
widget -- The disconnect button that was pressed. widget -- The disconnect button that was pressed.
event -- unused event -- unused
nettype -- "wired" or "wireless", depending on the network entry type. nettype -- "wired" or "wireless", depending on the network entry type.
networkid -- unused networkid -- unused
networkentry -- The NetworkEntry containing the disconnect button. networkentry -- The NetworkEntry containing the disconnect button.
""" """
def handler(*args): def handler(*args):
gobject.idle_add(self.all_network_list.set_sensitive, True) gobject.idle_add(self.all_network_list.set_sensitive, True)
gobject.idle_add(self.network_list.set_sensitive, True) gobject.idle_add(self.network_list.set_sensitive, True)
widget.hide() widget.hide()
networkentry.connect_button.show() networkentry.connect_button.show()
daemon.SetForcedDisconnect(True) daemon.SetForcedDisconnect(True)
@@ -824,16 +905,16 @@ class appGui(object):
if nettype == "wired": if nettype == "wired":
wired.DisconnectWired(reply_handler=handler, error_handler=handler) wired.DisconnectWired(reply_handler=handler, error_handler=handler)
else: else:
wireless.DisconnectWireless(reply_handler=handler, wireless.DisconnectWireless(reply_handler=handler,
error_handler=handler) error_handler=handler)
def wait_for_events(self, amt=0): def wait_for_events(self, amt=0):
""" Wait for any pending gtk events to finish before moving on. """ Wait for any pending gtk events to finish before moving on.
Keyword arguments: Keyword arguments:
amt -- a number specifying the number of ms to wait before checking amt -- a number specifying the number of ms to wait before checking
for pending events. for pending events.
""" """
time.sleep(amt) time.sleep(amt)
while gtk.events_pending(): while gtk.events_pending():
@@ -843,7 +924,7 @@ class appGui(object):
""" Hide the wicd GUI. """ Hide the wicd GUI.
This method hides the wicd GUI and writes the current window size This method hides the wicd GUI and writes the current window size
to disc for later use. This method normally does NOT actually to disc for later use. This method normally does NOT actually
destroy the GUI, it just hides it. destroy the GUI, it just hides it.
""" """
@@ -864,11 +945,11 @@ class appGui(object):
return True return True
def show_win(self): def show_win(self):
""" Brings the GUI out of the hidden state. """ Brings the GUI out of the hidden state.
Method to show the wicd GUI, alert the daemon that it is open, Method to show the wicd GUI, alert the daemon that it is open,
and refresh the network list. and refresh the network list.
""" """
self.window.present() self.window.present()
self.window.deiconify() self.window.deiconify()

View File

@@ -30,22 +30,27 @@ try:
except ImportError: except ImportError:
print "Importing pynotify failed, notifications disabled." print "Importing pynotify failed, notifications disabled."
HAS_NOTIFY = False HAS_NOTIFY = False
print "Has notifications support", HAS_NOTIFY print "Has notifications support", HAS_NOTIFY
if wpath.no_use_notifications: if wpath.no_use_notifications:
print 'Notifications disabled during setup.py configure' print 'Notifications disabled during setup.py configure'
def can_use_notify(): def can_use_notify():
""" Check whether WICD is allowed to use notifications. """
use_notify = os.path.exists(os.path.join(os.path.expanduser('~/.wicd'), use_notify = os.path.exists(os.path.join(os.path.expanduser('~/.wicd'),
'USE_NOTIFICATIONS') 'USE_NOTIFICATIONS')
) )
return use_notify and HAS_NOTIFY and not wpath.no_use_notifications return use_notify and HAS_NOTIFY and not wpath.no_use_notifications
def error(parent, message, block=True):
def error(parent, message, block=True):
""" Shows an error dialog. """ """ Shows an error dialog. """
def delete_event(dialog, id): def delete_event(dialog, i):
""" Handle dialog destroy. """
dialog.destroy() dialog.destroy()
if can_use_notify() and not block: if can_use_notify() and not block:
notification = pynotify.Notification("ERROR", message, "error") notification = pynotify.Notification("ERROR", message, "error")
notification.show() notification.show()
@@ -59,11 +64,14 @@ def error(parent, message, block=True):
else: else:
dialog.run() dialog.run()
dialog.destroy() dialog.destroy()
def alert(parent, message, block=True):
def alert(parent, message, block=True):
""" Shows an warning dialog. """ """ Shows an warning dialog. """
def delete_event(dialog, id): def delete_event(dialog, i):
""" Handle dialog destroy. """
dialog.destroy() dialog.destroy()
dialog = gtk.MessageDialog(parent, gtk.DIALOG_MODAL, gtk.MESSAGE_WARNING, dialog = gtk.MessageDialog(parent, gtk.DIALOG_MODAL, gtk.MESSAGE_WARNING,
gtk.BUTTONS_OK) gtk.BUTTONS_OK)
dialog.set_markup(message) dialog.set_markup(message)
@@ -74,11 +82,14 @@ def alert(parent, message, block=True):
dialog.run() dialog.run()
dialog.destroy() dialog.destroy()
def string_input(prompt, secondary, textbox_label): def string_input(prompt, secondary, textbox_label):
""" Dialog with a label and an entry. """
# based on a version of a PyGTK text entry from # based on a version of a PyGTK text entry from
# http://ardoris.wordpress.com/2008/07/05/pygtk-text-entry-dialog/ # http://ardoris.wordpress.com/2008/07/05/pygtk-text-entry-dialog/
def dialog_response(entry, dialog, response): def dialog_response(entry, dialog, response):
""" Handle dialog response. """
dialog.response(response) dialog.response(response)
dialog = gtk.MessageDialog( dialog = gtk.MessageDialog(
@@ -103,6 +114,7 @@ def string_input(prompt, secondary, textbox_label):
hbox.pack_start(entry) hbox.pack_start(entry)
# pack the boxes and show the dialog # pack the boxes and show the dialog
# pylint: disable-msg=E1101
dialog.vbox.pack_end(hbox, True, True, 0) dialog.vbox.pack_end(hbox, True, True, 0)
dialog.show_all() dialog.show_all()
@@ -114,19 +126,24 @@ def string_input(prompt, secondary, textbox_label):
dialog.destroy() dialog.destroy()
return None return None
class SmallLabel(gtk.Label): class SmallLabel(gtk.Label):
""" Small GtkLabel. """
def __init__(self, text=''): def __init__(self, text=''):
gtk.Label.__init__(self, text) gtk.Label.__init__(self, text)
self.set_size_request(50, -1) self.set_size_request(50, -1)
class LeftAlignedLabel(gtk.Label): class LeftAlignedLabel(gtk.Label):
"""GtkLabel with text aligned to left. """
def __init__(self, label=None): def __init__(self, label=None):
gtk.Label.__init__(self, label) gtk.Label.__init__(self, label)
self.set_alignment(0.0, 0.5) self.set_alignment(0.0, 0.5)
class LabelEntry(gtk.HBox): class LabelEntry(gtk.HBox):
""" A label on the left with a textbox on the right. """ """ A label on the left with a textbox on the right. """
def __init__(self,text): def __init__(self, text):
gtk.HBox.__init__(self) gtk.HBox.__init__(self)
self.entry = gtk.Entry() self.entry = gtk.Entry()
self.entry.set_size_request(200, -1) self.entry.set_size_request(200, -1)
@@ -143,27 +160,31 @@ class LabelEntry(gtk.HBox):
self.show() self.show()
def set_text(self, text): def set_text(self, text):
""" Set text of the GtkEntry. """
# For compatibility... # For compatibility...
self.entry.set_text(text) self.entry.set_text(text)
def get_text(self): def get_text(self):
""" Get text of the GtkEntry. """
return self.entry.get_text() return self.entry.get_text()
def set_auto_hidden(self, value): def set_auto_hidden(self, value):
""" Set auto-hide of the text of GtkEntry. """
self.entry.set_visibility(False) self.entry.set_visibility(False)
self.auto_hide_text = value self.auto_hide_text = value
def show_characters(self, widget=None, event=None): def show_characters(self, widget=None, event=None):
# When the box has focus, show the characters """ When the box has focus, show the characters. """
if self.auto_hide_text and widget: if self.auto_hide_text and widget:
self.entry.set_visibility(True) self.entry.set_visibility(True)
def set_sensitive(self, value): def set_sensitive(self, value):
""" Set sensitivity of the widget. """
self.entry.set_sensitive(value) self.entry.set_sensitive(value)
self.label.set_sensitive(value) self.label.set_sensitive(value)
def hide_characters(self, widget=None, event=None): def hide_characters(self, widget=None, event=None):
# When the box looses focus, hide them """ When the box looses focus, hide them. """
if self.auto_hide_text and widget: if self.auto_hide_text and widget:
self.entry.set_visibility(False) self.entry.set_visibility(False)
@@ -202,24 +223,30 @@ class ProtectedLabelEntry(gtk.HBox):
self.show() self.show()
def set_entry_text(self, text): def set_entry_text(self, text):
""" Set text of the GtkEntry. """
# For compatibility... # For compatibility...
self.entry.set_text(text) self.entry.set_text(text)
def get_entry_text(self): def get_entry_text(self):
""" Get text of the GtkEntry. """
return self.entry.get_text() return self.entry.get_text()
def set_sensitive(self, value): def set_sensitive(self, value):
""" Set sensitivity of the widget. """
self.entry.set_sensitive(value) self.entry.set_sensitive(value)
self.label.set_sensitive(value) self.label.set_sensitive(value)
self.check.set_sensitive(value) self.check.set_sensitive(value)
def click_handler(self, widget=None, event=None): def click_handler(self, widget=None, event=None):
""" Handle clicks. """
active = self.check.get_active() active = self.check.get_active()
self.entry.set_visibility(active) self.entry.set_visibility(active)
class LabelCombo(gtk.HBox): class LabelCombo(gtk.HBox):
""" A label on the left with a combobox on the right. """ """ A label on the left with a combobox on the right. """
def __init__(self,text):
def __init__(self, text):
gtk.HBox.__init__(self) gtk.HBox.__init__(self)
self.combo = gtk.ComboBox() self.combo = gtk.ComboBox()
self.combo.set_size_request(200, -1) self.combo.set_size_request(200, -1)
@@ -236,20 +263,26 @@ class LabelCombo(gtk.HBox):
self.show() self.show()
def get_active(self): def get_active(self):
""" Return the selected item in the GtkComboBox. """
return self.combo.get_active() return self.combo.get_active()
def set_active(self, index): def set_active(self, index):
""" Set given item in the GtkComboBox. """
self.combo.set_active(index) self.combo.set_active(index)
def get_active_text(self): def get_active_text(self):
""" Return the selected item's text in the GtkComboBox. """
return self.combo.get_active_text() return self.combo.get_active_text()
def get_model(self): def get_model(self):
""" Return the GtkComboBox's model. """
return self.combo.get_model() return self.combo.get_model()
def set_model(self, model=None): def set_model(self, model=None):
""" Set the GtkComboBox's model. """
self.combo.set_model(model) self.combo.set_model(model)
def set_sensitive(self, value): def set_sensitive(self, value):
""" Set sensitivity of the widget. """
self.combo.set_sensitive(value) self.combo.set_sensitive(value)
self.label.set_sensitive(value) self.label.set_sensitive(value)

File diff suppressed because it is too large Load Diff

View File

@@ -26,7 +26,6 @@ handles recieving/sendings the settings from/to the daemon.
import gtk import gtk
import gobject import gobject
#import pango
import os import os
from wicd import misc from wicd import misc
@@ -39,25 +38,75 @@ daemon = None
wireless = None wireless = None
wired = None wired = None
from wicd.translations import language
USER_SETTINGS_DIR = os.path.expanduser('~/.wicd/') USER_SETTINGS_DIR = os.path.expanduser('~/.wicd/')
def setup_dbus(): def setup_dbus():
""" Initialize DBus. """
global daemon, wireless, wired global daemon, wireless, wired
daemon = dbusmanager.get_interface('daemon') daemon = dbusmanager.get_interface('daemon')
wireless = dbusmanager.get_interface('wireless') wireless = dbusmanager.get_interface('wireless')
wired = dbusmanager.get_interface('wired') wired = dbusmanager.get_interface('wired')
class PreferencesDialog(object): class PreferencesDialog(object):
""" Class for handling the wicd preferences dialog window. """ """ Class for handling the wicd preferences dialog window. """
def __init__(self, parent, wTree): def __init__(self, parent, wTree):
setup_dbus() setup_dbus()
self.parent = parent self.parent = parent
self.wTree = wTree self.wTree = wTree
self.ethtoolradio = None
self.miitoolradio = None
self.wpadrivercombo = None
self.wpadrivers = None
self.backends = None
self.backendcombo = None
self.be_descriptions = None
self.preferwiredcheckbox = None
self.useGlobalDNSCheckbox = None
self.displaytypecheckbox = None
self.verifyapcheckbox = None
self.debugmodecheckbox = None
self.wiredcheckbox = None
self.showneverconnectcheckbox = None
self.reconnectcheckbox = None
self.notificationscheckbox = None
self.usedefaultradiobutton = None
self.lastusedradiobutton = None
self.showlistradiobutton = None
self.kdesuradio = None
self.gksudoradio = None
self.sudoautoradio = None
self.ktsussradio = None
self.dhclientradio = None
self.dhcpautoradio = None
self.pumpradio = None
self.udhcpcradio = None
self.dhcpcdradio = None
self.linkautoradio = None
self.routeflushradio = None
self.ipflushradio = None
self.flushautoradio = None
self.dialog = None
self.entryWiredInterface = None
self.entryWirelessInterface = None
self.dns1Entry = None
self.dns2Entry = None
self.dns3Entry = None
self.searchDomEntry = None
self.dnsDomEntry = None
self.prep_settings_diag() self.prep_settings_diag()
self.load_preferences_diag() self.load_preferences_diag()
def _setup_external_app_radios(self, radio_list, get_method, set_method): def _setup_external_app_radios(self, radio_list, get_method, set_method):
""" Generic function for setting up external app radios. """ """ Generic function for setting up external app radios. """
# Disable radios for apps that aren't installed. # Disable radios for apps that aren't installed.
@@ -71,10 +120,10 @@ class PreferencesDialog(object):
# If it isn't, default to Automatic. # If it isn't, default to Automatic.
set_method(misc.AUTO) set_method(misc.AUTO)
radio_list[misc.AUTO].set_active(True) radio_list[misc.AUTO].set_active(True)
def load_preferences_diag(self): def load_preferences_diag(self):
""" Loads data into the preferences Dialog. """ """ Loads data into the preferences Dialog. """
self.wiredcheckbox.set_active(daemon.GetAlwaysShowWiredInterface()) self.wiredcheckbox.set_active(daemon.GetAlwaysShowWiredInterface())
self.reconnectcheckbox.set_active(daemon.GetAutoReconnect()) self.reconnectcheckbox.set_active(daemon.GetAutoReconnect())
self.debugmodecheckbox.set_active(daemon.GetDebugMode()) self.debugmodecheckbox.set_active(daemon.GetDebugMode())
@@ -82,28 +131,30 @@ class PreferencesDialog(object):
self.verifyapcheckbox.set_active(daemon.GetShouldVerifyAp()) self.verifyapcheckbox.set_active(daemon.GetShouldVerifyAp())
self.preferwiredcheckbox.set_active(daemon.GetPreferWiredNetwork()) self.preferwiredcheckbox.set_active(daemon.GetPreferWiredNetwork())
self.showneverconnectcheckbox.set_active(daemon.GetShowNeverConnect()) self.showneverconnectcheckbox.set_active(daemon.GetShowNeverConnect())
dhcp_list = [self.dhcpautoradio, self.dhclientradio, self.dhcpcdradio, dhcp_list = [self.dhcpautoradio, self.dhclientradio, self.dhcpcdradio,
self.pumpradio, self.udhcpcradio] self.pumpradio, self.udhcpcradio]
self._setup_external_app_radios(dhcp_list, daemon.GetDHCPClient, self._setup_external_app_radios(
daemon.SetDHCPClient) dhcp_list, daemon.GetDHCPClient, daemon.SetDHCPClient)
wired_link_list = [self.linkautoradio, self.ethtoolradio, wired_link_list = [self.linkautoradio, self.ethtoolradio,
self.miitoolradio] self.miitoolradio]
self._setup_external_app_radios(wired_link_list, self._setup_external_app_radios(
daemon.GetLinkDetectionTool, wired_link_list,
daemon.SetLinkDetectionTool) daemon.GetLinkDetectionTool,
daemon.SetLinkDetectionTool
)
flush_list = [self.flushautoradio, self.ipflushradio, flush_list = [self.flushautoradio, self.ipflushradio,
self.routeflushradio] self.routeflushradio]
self._setup_external_app_radios(flush_list, daemon.GetFlushTool, self._setup_external_app_radios(
daemon.SetFlushTool) flush_list, daemon.GetFlushTool, daemon.SetFlushTool)
sudo_list = [self.sudoautoradio, self.gksudoradio, self.kdesuradio, sudo_list = [self.sudoautoradio, self.gksudoradio, self.kdesuradio,
self.ktsussradio] self.ktsussradio]
self._setup_external_app_radios(sudo_list, daemon.GetSudoApp, self._setup_external_app_radios(
daemon.SetSudoApp) sudo_list, daemon.GetSudoApp, daemon.SetSudoApp)
auto_conn_meth = daemon.GetWiredAutoConnectMethod() auto_conn_meth = daemon.GetWiredAutoConnectMethod()
if auto_conn_meth == 1: if auto_conn_meth == 1:
self.usedefaultradiobutton.set_active(True) self.usedefaultradiobutton.set_active(True)
@@ -111,7 +162,7 @@ class PreferencesDialog(object):
self.showlistradiobutton.set_active(True) self.showlistradiobutton.set_active(True)
elif auto_conn_meth == 3: elif auto_conn_meth == 3:
self.lastusedradiobutton.set_active(True) self.lastusedradiobutton.set_active(True)
self.entryWirelessInterface.set_text(daemon.GetWirelessInterface()) self.entryWirelessInterface.set_text(daemon.GetWirelessInterface())
self.entryWiredInterface.set_text(daemon.GetWiredInterface()) self.entryWiredInterface.set_text(daemon.GetWiredInterface())
@@ -121,10 +172,14 @@ class PreferencesDialog(object):
except ValueError: except ValueError:
self.wpadrivercombo.set_active(0) self.wpadrivercombo.set_active(0)
self.useGlobalDNSCheckbox.connect("toggled", checkboxTextboxToggle, self.useGlobalDNSCheckbox.connect(
(self.dns1Entry, self.dns2Entry, "toggled",
self.dns3Entry, self.dnsDomEntry, checkboxTextboxToggle,
self.searchDomEntry)) (
self.dns1Entry, self.dns2Entry, self.dns3Entry,
self.dnsDomEntry, self.searchDomEntry
)
)
dns_addresses = daemon.GetGlobalDNSAddresses() dns_addresses = daemon.GetGlobalDNSAddresses()
self.useGlobalDNSCheckbox.set_active(daemon.GetUseGlobalDNS()) self.useGlobalDNSCheckbox.set_active(daemon.GetUseGlobalDNS())
@@ -140,7 +195,7 @@ class PreferencesDialog(object):
self.dns1Entry.set_sensitive(False) self.dns1Entry.set_sensitive(False)
self.dns2Entry.set_sensitive(False) self.dns2Entry.set_sensitive(False)
self.dns3Entry.set_sensitive(False) self.dns3Entry.set_sensitive(False)
cur_backend = daemon.GetSavedBackend() cur_backend = daemon.GetSavedBackend()
try: try:
self.backendcombo.set_active(self.backends.index(cur_backend)) self.backendcombo.set_active(self.backends.index(cur_backend))
@@ -164,24 +219,25 @@ class PreferencesDialog(object):
self.notificationscheckbox.set_active(False) self.notificationscheckbox.set_active(False)
self.notificationscheckbox.hide() self.notificationscheckbox.hide()
self.wTree.get_object('label2').hide() self.wTree.get_object('label2').hide()
self.wTree.get_object("notebook2").set_current_page(0) self.wTree.get_object("notebook2").set_current_page(0)
def run(self): def run(self):
""" Runs the preferences dialog window. """ """ Runs the preferences dialog window. """
return self.dialog.run() return self.dialog.run()
def hide(self): def hide(self):
""" Hides the preferences dialog window. """ """ Hides the preferences dialog window. """
self.dialog.hide() self.dialog.hide()
def destroy(self): def destroy(self):
""" Destroy dialog. """
self.dialog.destroy() self.dialog.destroy()
def show_all(self): def show_all(self):
""" Shows the preferences dialog window. """ """ Shows the preferences dialog window. """
self.dialog.show() self.dialog.show()
def save_results(self): def save_results(self):
""" Pushes the selected settings to the daemon. """ """ Pushes the selected settings to the daemon. """
daemon.SetUseGlobalDNS(self.useGlobalDNSCheckbox.get_active()) daemon.SetUseGlobalDNS(self.useGlobalDNSCheckbox.get_active())
@@ -189,9 +245,13 @@ class PreferencesDialog(object):
for i in [self.dns1Entry, self.dns2Entry, self.dns3Entry, for i in [self.dns1Entry, self.dns2Entry, self.dns3Entry,
self.dnsDomEntry, self.searchDomEntry]: self.dnsDomEntry, self.searchDomEntry]:
i.set_text(i.get_text().strip()) i.set_text(i.get_text().strip())
daemon.SetGlobalDNS(self.dns1Entry.get_text(), self.dns2Entry.get_text(), daemon.SetGlobalDNS(
self.dns3Entry.get_text(), self.dnsDomEntry.get_text(), self.dns1Entry.get_text(),
self.searchDomEntry.get_text()) self.dns2Entry.get_text(),
self.dns3Entry.get_text(),
self.dnsDomEntry.get_text(),
self.searchDomEntry.get_text()
)
daemon.SetWirelessInterface(self.entryWirelessInterface.get_text()) daemon.SetWirelessInterface(self.entryWirelessInterface.get_text())
daemon.SetWiredInterface(self.entryWiredInterface.get_text()) daemon.SetWiredInterface(self.entryWiredInterface.get_text())
daemon.SetWPADriver(self.wpadrivers[self.wpadrivercombo.get_active()]) daemon.SetWPADriver(self.wpadrivers[self.wpadrivercombo.get_active()])
@@ -200,8 +260,10 @@ class PreferencesDialog(object):
daemon.SetDebugMode(self.debugmodecheckbox.get_active()) daemon.SetDebugMode(self.debugmodecheckbox.get_active())
daemon.SetSignalDisplayType(int(self.displaytypecheckbox.get_active())) daemon.SetSignalDisplayType(int(self.displaytypecheckbox.get_active()))
daemon.SetShouldVerifyAp(bool(self.verifyapcheckbox.get_active())) daemon.SetShouldVerifyAp(bool(self.verifyapcheckbox.get_active()))
daemon.SetPreferWiredNetwork(bool(self.preferwiredcheckbox.get_active())) daemon.SetPreferWiredNetwork(
daemon.SetShowNeverConnect(bool(self.showneverconnectcheckbox.get_active())) bool(self.preferwiredcheckbox.get_active()))
daemon.SetShowNeverConnect(
bool(self.showneverconnectcheckbox.get_active()))
if self.showlistradiobutton.get_active(): if self.showlistradiobutton.get_active():
daemon.SetWiredAutoConnectMethod(2) daemon.SetWiredAutoConnectMethod(2)
elif self.lastusedradiobutton.get_active(): elif self.lastusedradiobutton.get_active():
@@ -210,7 +272,7 @@ class PreferencesDialog(object):
daemon.SetWiredAutoConnectMethod(1) daemon.SetWiredAutoConnectMethod(1)
daemon.SetBackend(self.backends[self.backendcombo.get_active()]) daemon.SetBackend(self.backends[self.backendcombo.get_active()])
# External Programs Tab # External Programs Tab
if self.dhcpautoradio.get_active(): if self.dhcpautoradio.get_active():
dhcp_client = misc.AUTO dhcp_client = misc.AUTO
@@ -223,7 +285,7 @@ class PreferencesDialog(object):
else: else:
dhcp_client = misc.UDHCPC dhcp_client = misc.UDHCPC
daemon.SetDHCPClient(dhcp_client) daemon.SetDHCPClient(dhcp_client)
if self.linkautoradio.get_active(): if self.linkautoradio.get_active():
link_tool = misc.AUTO link_tool = misc.AUTO
elif self.ethtoolradio.get_active(): elif self.ethtoolradio.get_active():
@@ -231,7 +293,7 @@ class PreferencesDialog(object):
else: else:
link_tool = misc.MIITOOL link_tool = misc.MIITOOL
daemon.SetLinkDetectionTool(link_tool) daemon.SetLinkDetectionTool(link_tool)
if self.flushautoradio.get_active(): if self.flushautoradio.get_active():
flush_tool = misc.AUTO flush_tool = misc.AUTO
elif self.ipflushradio.get_active(): elif self.ipflushradio.get_active():
@@ -239,7 +301,7 @@ class PreferencesDialog(object):
else: else:
flush_tool = misc.ROUTE flush_tool = misc.ROUTE
daemon.SetFlushTool(flush_tool) daemon.SetFlushTool(flush_tool)
if self.sudoautoradio.get_active(): if self.sudoautoradio.get_active():
sudo_tool = misc.AUTO sudo_tool = misc.AUTO
elif self.gksudoradio.get_active(): elif self.gksudoradio.get_active():
@@ -251,7 +313,7 @@ class PreferencesDialog(object):
daemon.SetSudoApp(sudo_tool) daemon.SetSudoApp(sudo_tool)
[width, height] = self.dialog.get_size() [width, height] = self.dialog.get_size()
not_path = os.path.join(USER_SETTINGS_DIR, 'USE_NOTIFICATIONS') not_path = os.path.join(USER_SETTINGS_DIR, 'USE_NOTIFICATIONS')
if self.notificationscheckbox.get_active(): if self.notificationscheckbox.get_active():
if not os.path.exists(not_path): if not os.path.exists(not_path):
@@ -268,7 +330,7 @@ class PreferencesDialog(object):
def set_label(self, glade_str, label): def set_label(self, glade_str, label):
""" Sets the label for the given widget in wicd.glade. """ """ Sets the label for the given widget in wicd.glade. """
self.wTree.get_object(glade_str).set_label(label) self.wTree.get_object(glade_str).set_label(label)
def prep_settings_diag(self): def prep_settings_diag(self):
""" Set up anything that doesn't have to be persisted later. """ """ Set up anything that doesn't have to be persisted later. """
def build_combobox(lbl): def build_combobox(lbl):
@@ -281,7 +343,7 @@ class PreferencesDialog(object):
combobox.pack_start(cell, True) combobox.pack_start(cell, True)
combobox.add_attribute(cell, 'text', 0) combobox.add_attribute(cell, 'text', 0)
return combobox return combobox
def setup_label(name, lbl=""): def setup_label(name, lbl=""):
""" Sets up a label for the given widget name. """ """ Sets up a label for the given widget name. """
widget = self.wTree.get_object(name) widget = self.wTree.get_object(name)
@@ -290,7 +352,7 @@ class PreferencesDialog(object):
if widget is None: if widget is None:
raise ValueError('widget %s does not exist' % name) raise ValueError('widget %s does not exist' % name)
return widget return widget
# External Programs tab # External Programs tab
# self.wTree.get_object("gen_settings_label").set_label(_('General Settings')) # self.wTree.get_object("gen_settings_label").set_label(_('General Settings'))
# self.wTree.get_object("ext_prog_label").set_label(_('External Programs')) # self.wTree.get_object("ext_prog_label").set_label(_('External Programs'))
@@ -298,14 +360,14 @@ class PreferencesDialog(object):
# self.wTree.get_object("wired_detect_label").set_label(_('Wired Link Detection')) # 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("route_flush_label").set_label(_('Route Table Flushing'))
# self.wTree.get_object("pref_backend_label").set_label(_('Backend') + ":") # self.wTree.get_object("pref_backend_label").set_label(_('Backend') + ":")
# entryWiredAutoMethod = self.wTree.get_object("pref_wired_auto_label") # entryWiredAutoMethod = self.wTree.get_object("pref_wired_auto_label")
# entryWiredAutoMethod.set_label('Wired Autoconnect Setting:') # entryWiredAutoMethod.set_label('Wired Autoconnect Setting:')
# entryWiredAutoMethod.set_alignment(0, 0) # entryWiredAutoMethod.set_alignment(0, 0)
# atrlist = pango.AttrList() # atrlist = pango.AttrList()
# atrlist.insert(pango.AttrWeight(pango.WEIGHT_BOLD, 0, 50)) # atrlist.insert(pango.AttrWeight(pango.WEIGHT_BOLD, 0, 50))
# entryWiredAutoMethod.set_attributes(atrlist) # entryWiredAutoMethod.set_attributes(atrlist)
# self.set_label("pref_dns1_label", "%s 1" % _('DNS server')) # self.set_label("pref_dns1_label", "%s 1" % _('DNS server'))
# self.set_label("pref_dns2_label", "%s 2" % _('DNS server')) # self.set_label("pref_dns2_label", "%s 2" % _('DNS server'))
# self.set_label("pref_dns3_label", "%s 3" % _('DNS server')) # self.set_label("pref_dns3_label", "%s 3" % _('DNS server'))
@@ -313,62 +375,82 @@ class PreferencesDialog(object):
# self.set_label("pref_wifi_label", "%s:" % _('Wireless Interface')) # self.set_label("pref_wifi_label", "%s:" % _('Wireless Interface'))
# self.set_label("pref_wired_label", "%s:" % _('Wired Interface')) # self.set_label("pref_wired_label", "%s:" % _('Wired Interface'))
# self.set_label("pref_driver_label", "%s:" % _('WPA Supplicant Driver')) # self.set_label("pref_driver_label", "%s:" % _('WPA Supplicant Driver'))
self.dialog = self.wTree.get_object("pref_dialog") self.dialog = self.wTree.get_object("pref_dialog")
self.dialog.set_title(_('Preferences')) self.dialog.set_title(_('Preferences'))
if os.path.exists(os.path.join(wpath.images, "wicd.png")): if os.path.exists(os.path.join(wpath.images, "wicd.png")):
self.dialog.set_icon_from_file(os.path.join(wpath.images, "wicd.png")) self.dialog.set_icon_from_file(
os.path.join(wpath.images, "wicd.png"))
width = int(gtk.gdk.screen_width() / 2.4) width = int(gtk.gdk.screen_width() / 2.4)
if width > 450: if width > 450:
width = 450 width = 450
self.dialog.resize(width, int(gtk.gdk.screen_height() / 2)) self.dialog.resize(width, int(gtk.gdk.screen_height() / 2))
self.wiredcheckbox = setup_label("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", self.preferwiredcheckbox = setup_label("pref_prefer_wired_check",
"prefer_wired") "prefer_wired")
self.reconnectcheckbox = setup_label("pref_auto_check", self.reconnectcheckbox = setup_label("pref_auto_check",
_('Automatically reconnect on connection loss')) _('Automatically reconnect on connection loss'))
self.showneverconnectcheckbox = setup_label("pref_show_never_connect_check", self.showneverconnectcheckbox = setup_label(
_('Show never connect networks')) "pref_show_never_connect_check",
_('Show never connect networks')
)
self.debugmodecheckbox = setup_label("pref_debug_check", self.debugmodecheckbox = setup_label("pref_debug_check",
_('Enable debug mode')) _('Enable debug mode'))
self.displaytypecheckbox = setup_label("pref_dbm_check", self.displaytypecheckbox = setup_label(
_('Use dBm to measure signal strength')) "pref_dbm_check",
self.verifyapcheckbox = setup_label("pref_verify_ap_check", _('Use dBm to measure signal strength')
_('Ping static gateways after connecting to verify association')) )
self.usedefaultradiobutton = setup_label("pref_use_def_radio", self.verifyapcheckbox = setup_label(
_('Use default profile on wired autoconnect')) "pref_verify_ap_check",
self.showlistradiobutton = setup_label("pref_prompt_radio", _('Ping static gateways after connecting to verify association')
_('Prompt for profile on wired autoconnect')) )
self.lastusedradiobutton = setup_label("pref_use_last_radio", self.usedefaultradiobutton = setup_label(
_('Use last used profile on wired autoconnect')) "pref_use_def_radio",
_('Use default profile on wired autoconnect')
)
self.showlistradiobutton = setup_label(
"pref_prompt_radio",
_('Prompt for profile on wired autoconnect')
)
self.lastusedradiobutton = setup_label(
"pref_use_last_radio",
_('Use last used profile on wired autoconnect')
)
self.notificationscheckbox = setup_label(
self.notificationscheckbox = setup_label("pref_use_libnotify", "pref_use_libnotify",
_('Display notifications about connection status')) _('Display notifications about connection status')
)
# DHCP Clients # DHCP Clients
self.dhcpautoradio = setup_label("dhcp_auto_radio", _('Automatic (recommended)')) self.dhcpautoradio = setup_label(
"dhcp_auto_radio", _('Automatic (recommended)'))
self.dhclientradio = self.wTree.get_object("dhclient_radio") self.dhclientradio = self.wTree.get_object("dhclient_radio")
self.pumpradio = self.wTree.get_object("pump_radio") self.pumpradio = self.wTree.get_object("pump_radio")
self.dhcpcdradio = self.wTree.get_object("dhcpcd_radio") self.dhcpcdradio = self.wTree.get_object("dhcpcd_radio")
self.udhcpcradio = self.wTree.get_object("udhcpc_radio") self.udhcpcradio = self.wTree.get_object("udhcpc_radio")
# Wired Link Detection Apps # Wired Link Detection Apps
self.linkautoradio = setup_label("link_auto_radio", _('Automatic (recommended)')) self.linkautoradio = setup_label(
"link_auto_radio", _('Automatic (recommended)'))
self.linkautoradio = setup_label("link_auto_radio") self.linkautoradio = setup_label("link_auto_radio")
self.ethtoolradio = setup_label("ethtool_radio") self.ethtoolradio = setup_label("ethtool_radio")
self.miitoolradio = setup_label("miitool_radio") self.miitoolradio = setup_label("miitool_radio")
# Route Flushing Apps # Route Flushing Apps
self.flushautoradio = setup_label("flush_auto_radio", self.flushautoradio = setup_label("flush_auto_radio",
_('Automatic (recommended)')) _('Automatic (recommended)'))
self.ipflushradio = setup_label("ip_flush_radio") self.ipflushradio = setup_label("ip_flush_radio")
self.routeflushradio = setup_label("route_flush_radio") self.routeflushradio = setup_label("route_flush_radio")
# Graphical Sudo Apps # 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.gksudoradio = setup_label("gksudo_radio")
self.kdesuradio = setup_label("kdesu_radio") self.kdesuradio = setup_label("kdesu_radio")
self.ktsussradio = setup_label("ktsuss_radio") self.ktsussradio = setup_label("ktsuss_radio")
@@ -384,7 +466,7 @@ class PreferencesDialog(object):
self.entryWirelessInterface = self.wTree.get_object("pref_wifi_entry") self.entryWirelessInterface = self.wTree.get_object("pref_wifi_entry")
self.entryWiredInterface = self.wTree.get_object("pref_wired_entry") self.entryWiredInterface = self.wTree.get_object("pref_wired_entry")
# Set up global DNS stuff # Set up global DNS stuff
self.useGlobalDNSCheckbox = setup_label("pref_global_check", self.useGlobalDNSCheckbox = setup_label("pref_global_check",
'use_global_dns') 'use_global_dns')
@@ -393,19 +475,19 @@ class PreferencesDialog(object):
self.dns1Entry = self.wTree.get_object("pref_dns1_entry") self.dns1Entry = self.wTree.get_object("pref_dns1_entry")
self.dns2Entry = self.wTree.get_object("pref_dns2_entry") self.dns2Entry = self.wTree.get_object("pref_dns2_entry")
self.dns3Entry = self.wTree.get_object("pref_dns3_entry") self.dns3Entry = self.wTree.get_object("pref_dns3_entry")
self.backendcombo = build_combobox("pref_backend_combobox") self.backendcombo = build_combobox("pref_backend_combobox")
self.backendcombo.connect("changed", self.be_combo_changed) self.backendcombo.connect("changed", self.be_combo_changed)
# Load backend combobox # Load backend combobox
self.backends = daemon.GetBackendList() self.backends = daemon.GetBackendList()
self.be_descriptions = daemon.GetBackendDescriptionDict() self.be_descriptions = daemon.GetBackendDescriptionDict()
for x in self.backends: for x in self.backends:
if x: if x:
if x == 'ioctl': if x == 'ioctl':
x = 'ioctl NOT SUPPORTED' x = 'ioctl NOT SUPPORTED'
self.backendcombo.append_text(x) self.backendcombo.append_text(x)
def be_combo_changed(self, combo): def be_combo_changed(self, combo):
""" Update the description label for the given backend. """ """ Update the description label for the given backend. """
self.backendcombo.set_tooltip_text( self.backendcombo.set_tooltip_text(

View File

@@ -3,7 +3,7 @@
""" wicd - wireless connection daemon frontend implementation """ wicd - wireless connection daemon frontend implementation
This module implements a usermode frontend for wicd. It updates connection This module implements a usermode frontend for wicd. It updates connection
information, provides an (optional) tray icon, and allows for launching of information, provides an (optional) tray icon, and allows for launching of
the wicd GUI and Wired Profile Chooser. the wicd GUI and Wired Profile Chooser.
class TrayIcon() -- Parent class of TrayIconGUI and IconConnectionInfo. class TrayIcon() -- Parent class of TrayIconGUI and IconConnectionInfo.
@@ -11,7 +11,7 @@ class TrayIcon() -- Parent class of TrayIconGUI and IconConnectionInfo.
and updates connection status. and updates connection status.
class TrayIconGUI() -- Child class of TrayIcon which implements the tray. class TrayIconGUI() -- Child class of TrayIcon which implements the tray.
icon itself. Parent class of StatusTrayIconGUI and EggTrayIconGUI. icon itself. Parent class of StatusTrayIconGUI and EggTrayIconGUI.
class StatusTrayIconGUI() -- Implements the tray icon using a class StatusTrayIconGUI() -- Implements the tray icon using a
gtk.StatusIcon. gtk.StatusIcon.
class EggTrayIconGUI() -- Implements the tray icon using egg.trayicon. class EggTrayIconGUI() -- Implements the tray icon using egg.trayicon.
def usage() -- Prints usage information. def usage() -- Prints usage information.
@@ -42,7 +42,6 @@ import gobject
import getopt import getopt
import os import os
import pango import pango
import time
import atexit import atexit
from dbus import DBusException from dbus import DBusException
@@ -74,27 +73,37 @@ if not hasattr(gtk, "StatusIcon"):
import egg.trayicon import egg.trayicon
USE_EGG = True USE_EGG = True
except ImportError: except ImportError:
print 'Unable to load tray icon: Missing both egg.trayicon and gtk.StatusIcon modules.' print 'Unable to load tray icon: Missing both egg.trayicon and ' + \
'gtk.StatusIcon modules.'
ICON_AVAIL = False ICON_AVAIL = False
misc.RenameProcess("wicd-client") misc.RenameProcess("wicd-client")
if __name__ == '__main__': if __name__ == '__main__':
wpath.chdir(__file__) wpath.chdir(__file__)
daemon = wireless = wired = lost_dbus_id = None daemon = wireless = wired = lost_dbus_id = None
DBUS_AVAIL = False DBUS_AVAIL = False
theme = gtk.icon_theme_get_default() theme = gtk.icon_theme_get_default()
theme.append_search_path(wpath.images) theme.append_search_path(wpath.images)
def catchdbus(func): def catchdbus(func):
""" Decorator to catch DBus exceptions. """
def wrapper(*args, **kwargs): def wrapper(*args, **kwargs):
try: try:
return func(*args, **kwargs) return func(*args, **kwargs)
except DBusException, e: except DBusException, e:
if e.get_dbus_name() != None and "DBus.Error.AccessDenied" in e.get_dbus_name(): if e.get_dbus_name() is not None and \
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>")) "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 #raise
raise DBusException(e) raise DBusException(e)
else: else:
@@ -105,9 +114,10 @@ def catchdbus(func):
wrapper.__dict__ = func.__dict__ wrapper.__dict__ = func.__dict__
wrapper.__doc__ = func.__doc__ wrapper.__doc__ = func.__doc__
return wrapper return wrapper
class NetworkMenuItem(gtk.ImageMenuItem): class NetworkMenuItem(gtk.ImageMenuItem):
""" Network menu item. """
def __init__(self, lbl, is_active=False): def __init__(self, lbl, is_active=False):
gtk.ImageMenuItem.__init__(self) gtk.ImageMenuItem.__init__(self)
self.label = gtk.Label(lbl) self.label = gtk.Label(lbl)
@@ -119,13 +129,13 @@ class NetworkMenuItem(gtk.ImageMenuItem):
self.label.set_alignment(0, 0) self.label.set_alignment(0, 0)
self.add(self.label) self.add(self.label)
self.label.show() self.label.show()
class TrayIcon(object): class TrayIcon(object):
""" Base Tray Icon class. """ Base Tray Icon class.
Base Class for implementing a tray icon to display network status. Base Class for implementing a tray icon to display network status.
""" """
def __init__(self, animate, displaytray=True, displayapp=False): def __init__(self, animate, displaytray=True, displayapp=False):
self.cur_sndbytes = -1 self.cur_sndbytes = -1
@@ -145,13 +155,13 @@ class TrayIcon(object):
self.tr.icon_info = self.icon_info self.tr.icon_info = self.icon_info
print 'displaytray %s' % displaytray print 'displaytray %s' % displaytray
self.tr.visible(displaytray) self.tr.visible(displaytray)
def is_embedded(self): def is_embedded(self):
if USE_EGG: if USE_EGG:
raise NotImplementedError() raise NotImplementedError()
else: else:
return self.tr.is_embedded() return self.tr.is_embedded() # pylint: disable-msg=E1103
def get_bandwidth_bytes(self): def get_bandwidth_bytes(self):
""" Gets the amount of byte sent sine the last time I checked """ """ Gets the amount of byte sent sine the last time I checked """
dev_dir = '/sys/class/net/' dev_dir = '/sys/class/net/'
@@ -161,13 +171,15 @@ class TrayIcon(object):
if fldr == iface: if fldr == iface:
dev_dir = dev_dir + fldr + "/statistics/" dev_dir = dev_dir + fldr + "/statistics/"
break break
try: try:
self.cur_rcvbytes = int(open(dev_dir + "rx_bytes", "r").read().strip()) self.cur_rcvbytes = int(
self.cur_sndbytes = int(open(dev_dir + "tx_bytes", "r").read().strip()) open(dev_dir + "rx_bytes", "r").read().strip())
except: self.cur_sndbytes = int(
self.cur_sndbytes = -1 open(dev_dir + "tx_bytes", "r").read().strip())
self.cur_rcvbytes = -1 except (IOError, OSError, ValueError):
self.cur_sndbytes = -1
self.cur_rcvbytes = -1
class TrayConnectionInfo(object): class TrayConnectionInfo(object):
""" Class for updating the tray icon status. """ """ Class for updating the tray icon status. """
@@ -234,8 +246,8 @@ class TrayIcon(object):
if self.should_notify: if self.should_notify:
try: try:
if not self._last_bubble: if not self._last_bubble:
self._last_bubble = pynotify.Notification(title, details, self._last_bubble = pynotify.Notification(
image) title, details, image)
self._last_bubble.show() self._last_bubble.show()
else: else:
self._last_bubble.clear_actions() self._last_bubble.clear_actions()
@@ -258,20 +270,20 @@ class TrayIcon(object):
""" Launch the wired profile chooser. """ """ Launch the wired profile chooser. """
gui.WiredProfileChooser() gui.WiredProfileChooser()
daemon.SetNeedWiredProfileChooser(False) daemon.SetNeedWiredProfileChooser(False)
def set_wired_state(self, info): def set_wired_state(self, info):
""" Sets the icon info for a wired state. """ """ Sets the icon info for a wired state. """
wired_ip = info[0] wired_ip = info[0]
self.network_addr = str(info[0]) self.network_addr = str(info[0])
self.network_type = "wired" self.network_type = "wired"
self.tr.set_from_name('wired') self.tr.set_from_name('wired')
# status_string = _('Connected to wired network (IP: $A)').replace('$A', #status_string = _('Connected to wired network (IP: $A)'). \
#wired_ip) # replace('$A',wired_ip)
# self.tr.set_tooltip(status_string) #self.tr.set_tooltip(status_string)
self._show_notification(_('Wired Network'), self._show_notification(_('Wired Network'),
_('Connection established'), _('Connection established'),
'network-wired') 'network-wired')
self.update_tooltip() self.update_tooltip()
@catchdbus @catchdbus
@@ -289,22 +301,21 @@ class TrayIcon(object):
self.network_str = sig_string self.network_str = sig_string
self.network_br = info[4] self.network_br = info[4]
self.set_signal_image(int(info[2]), lock) self.set_signal_image(int(info[2]), lock)
if wireless.GetWirelessProperty(cur_net_id, "encryption"): if wireless.GetWirelessProperty(cur_net_id, "encryption"):
lock = "-lock" lock = "-lock"
# status_string = (_('Connected to $A at $B (IP: $C)') # status_string = (_('Connected to $A at $B (IP: $C)')
#.replace('$A', self.network) #.replace('$A', self.network)
# .replace('$B', sig_string) # .replace('$B', sig_string)
# .replace('$C', str(wireless_ip))) # .replace('$C', str(wireless_ip)))
#self.tr.set_tooltip(status_string) #self.tr.set_tooltip(status_string)
self.set_signal_image(int(strength), lock) self.set_signal_image(int(strength), lock)
self._show_notification(self.network, self._show_notification(self.network,
_('Connection established'), _('Connection established'),
'network-wireless') 'network-wireless')
self.update_tooltip() self.update_tooltip()
def set_connecting_state(self, info): def set_connecting_state(self, info):
""" Sets the icon info for a connecting state. """ """ Sets the icon info for a connecting state. """
wired = False wired = False
@@ -327,7 +338,6 @@ class TrayIcon(object):
_('Establishing connection...'), _('Establishing connection...'),
'network-wireless') 'network-wireless')
@catchdbus @catchdbus
def set_not_connected_state(self, info=None): def set_not_connected_state(self, info=None):
""" Set the icon info for the not connected state. """ """ Set the icon info for the not connected state. """
@@ -335,7 +345,7 @@ class TrayIcon(object):
if not DBUS_AVAIL: if not DBUS_AVAIL:
status = _('Wicd daemon unreachable') status = _('Wicd daemon unreachable')
elif wireless.GetKillSwitchEnabled(): elif wireless.GetKillSwitchEnabled():
status = (_('Not connected') + " (" + status = (_('Not connected') + " (" +
_('Wireless Kill Switch Enabled') + ")") _('Wireless Kill Switch Enabled') + ")")
else: else:
status = _('Not connected') status = _('Not connected')
@@ -346,17 +356,18 @@ class TrayIcon(object):
@catchdbus @catchdbus
def update_tray_icon(self, state=None, info=None): def update_tray_icon(self, state=None, info=None):
""" Updates the tray icon and current connection status. """ """ Updates the tray icon and current connection status. """
if not DBUS_AVAIL: return False if not DBUS_AVAIL:
return False
if not state or not info: if not state or not info:
[state, info] = daemon.GetConnectionStatus() [state, info] = daemon.GetConnectionStatus()
# should this state change display a notification? # should this state change display a notification?
self.should_notify = (can_use_notify() and self.should_notify = (can_use_notify() and
self.last_state != state) self.last_state != state)
self.last_state = state self.last_state = state
if state == misc.WIRED: if state == misc.WIRED:
self.set_wired_state(info) self.set_wired_state(info)
elif state == misc.WIRELESS: elif state == misc.WIRELESS:
@@ -398,13 +409,13 @@ class TrayIcon(object):
signal_img = "bad-signal" signal_img = "bad-signal"
img_name = ''.join([prefix, signal_img, lock]) img_name = ''.join([prefix, signal_img, lock])
self.tr.set_from_name(img_name) self.tr.set_from_name(img_name)
@catchdbus @catchdbus
def get_bandwidth_activity(self): def get_bandwidth_activity(self):
""" Determines what network activity state we are in. """ """ Determines what network activity state we are in. """
transmitting = False transmitting = False
receiving = False receiving = False
dev_dir = '/sys/class/net/' dev_dir = '/sys/class/net/'
wiface = daemon.GetWirelessInterface() wiface = daemon.GetWirelessInterface()
for fldr in os.listdir(dev_dir): for fldr in os.listdir(dev_dir):
@@ -417,26 +428,26 @@ class TrayIcon(object):
except IOError: except IOError:
sndbytes = None sndbytes = None
rcvbytes = None rcvbytes = None
if not rcvbytes or not sndbytes: if not rcvbytes or not sndbytes:
return 'idle-' return 'idle-'
# Figure out receiving data info. # Figure out receiving data info.
activity = self.is_network_active(self.parent.cur_rcvbytes, activity = self.is_network_active(self.parent.cur_rcvbytes,
self.parent.max_rcv_gain, self.parent.max_rcv_gain,
self.parent.last_rcvbytes) self.parent.last_rcvbytes)
receiving = activity[0] receiving = activity[0]
self.parent.max_rcv_gain = activity[1] self.parent.max_rcv_gain = activity[1]
self.parent.last_rcvbytes = activity[2] self.parent.last_rcvbytes = activity[2]
# Figure out out transmitting data info. # Figure out out transmitting data info.
activity = self.is_network_active(self.parent.cur_sndbytes, activity = self.is_network_active(self.parent.cur_sndbytes,
self.parent.max_snd_gain, self.parent.max_snd_gain,
self.parent.last_sndbytes) self.parent.last_sndbytes)
transmitting = activity[0] transmitting = activity[0]
self.parent.max_snd_gain = activity[1] self.parent.max_snd_gain = activity[1]
self.parent.last_sndbytes = activity[2] self.parent.last_sndbytes = activity[2]
if transmitting and receiving: if transmitting and receiving:
return 'both-' return 'both-'
elif transmitting: elif transmitting:
@@ -445,21 +456,21 @@ class TrayIcon(object):
return 'receiving-' return 'receiving-'
else: else:
return 'idle-' return 'idle-'
def is_network_active(self, bytes, max_gain, last_bytes): def is_network_active(self, bytes, max_gain, last_bytes):
""" Determines if a network is active. """ Determines if a network is active.
Determines if a network is active by looking at the Determines if a network is active by looking at the
number of bytes sent since the previous check. This method number of bytes sent since the previous check. This method
is generic, and can be used to determine activity in both is generic, and can be used to determine activity in both
the sending and receiving directions. the sending and receiving directions.
Returns: Returns:
A tuple containing three elements: A tuple containing three elements:
1) a boolean specifying if the network is active. 1) a boolean specifying if the network is active.
2) an int specifying the maximum gain the network has had. 2) an int specifying the maximum gain the network has had.
3) an int specifying the last recorded number of bytes sent. 3) an int specifying the last recorded number of bytes sent.
""" """
active = False active = False
if last_bytes == -1: if last_bytes == -1:
@@ -467,21 +478,24 @@ class TrayIcon(object):
elif bytes > (last_bytes + float(max_gain / 20.0)): elif bytes > (last_bytes + float(max_gain / 20.0)):
last_bytes = bytes last_bytes = bytes
active = True active = True
gain = bytes - last_bytes gain = bytes - last_bytes
if gain > max_gain: if gain > max_gain:
max_gain = gain max_gain = gain
return (active, max_gain, last_bytes) return (active, max_gain, last_bytes)
class TrayIconGUI(object): class TrayIconGUI(object):
""" Base Tray Icon UI class. """ Base Tray Icon UI class.
Implements methods and variables used by both egg/StatusIcon Implements methods and variables used by both egg/StatusIcon
tray icons. tray icons.
""" """
def __init__(self, parent): def __init__(self, parent):
self.list = []
self.label = None
self.data = None
menu = """ menu = """
<ui> <ui>
<menubar name="Menubar"> <menubar name="Menubar">
@@ -496,13 +510,13 @@ class TrayIcon(object):
</ui> </ui>
""" """
actions = [ actions = [
('Menu', None, 'Menu'), ('Menu', None, 'Menu'),
('Connect', gtk.STOCK_CONNECT, _('Connect')), ('Connect', gtk.STOCK_CONNECT, _('Connect')),
('Info', gtk.STOCK_INFO, _('_Connection Info'), None, ('Info', gtk.STOCK_INFO, _('_Connection Info'), None,
_('Information about the current connection'), _('Information about the current connection'),
self.on_conn_info), self.on_conn_info),
('Quit',gtk.STOCK_QUIT,_('_Quit'),None,_('Quit wicd-tray-icon'), ('Quit', gtk.STOCK_QUIT, _('_Quit'), None,
self.on_quit), _('Quit wicd-tray-icon'), self.on_quit),
] ]
actg = gtk.ActionGroup('Actions') actg = gtk.ActionGroup('Actions')
actg.add_actions(actions) actg.add_actions(actions)
@@ -516,30 +530,34 @@ class TrayIcon(object):
self._is_scanning = False self._is_scanning = False
net_menuitem = self.manager.get_widget("/Menubar/Menu/Connect/") net_menuitem = self.manager.get_widget("/Menubar/Menu/Connect/")
net_menuitem.connect("activate", self.on_net_menu_activate) net_menuitem.connect("activate", self.on_net_menu_activate)
self.parent = parent self.parent = parent
self.time = 2 # Time between updates self.time = 2 # Time between updates
self.cont = 'Stop' self.cont = 'Stop'
self.conn_info_txt = '' self.conn_info_txt = ''
def tray_scan_started(self): def tray_scan_started(self):
""" Callback for when a wireless scan is started. """ """ Callback for when a wireless scan is started. """
if not DBUS_AVAIL: return if not DBUS_AVAIL:
return
self._is_scanning = True self._is_scanning = True
self.init_network_menu() self.init_network_menu()
def tray_scan_ended(self): def tray_scan_ended(self):
""" Callback for when a wireless scan finishes. """ """ Callback for when a wireless scan finishes. """
if not DBUS_AVAIL: return if not DBUS_AVAIL:
return
self._is_scanning = False self._is_scanning = False
self.populate_network_menu() self.populate_network_menu()
def on_activate(self, data=None): def on_activate(self, data=None):
""" Opens the wicd GUI. """ """ Opens the wicd GUI. """
if DBUS_AVAIL: if DBUS_AVAIL:
self.toggle_wicd_gui() self.toggle_wicd_gui()
else: else:
# error(None, _('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 pass
def on_quit(self, widget=None): def on_quit(self, widget=None):
@@ -558,8 +576,13 @@ class TrayIcon(object):
def on_conn_info(self, data=None): def on_conn_info(self, data=None):
""" Opens the Connection Information Dialog """ """ Opens the Connection Information Dialog """
window = gtk.Dialog("Wicd Connection Info", None, 0, (gtk.STOCK_OK, gtk.RESPONSE_CLOSE)) window = gtk.Dialog(
"Wicd Connection Info",
None,
0,
(gtk.STOCK_OK, gtk.RESPONSE_CLOSE)
)
# Create labels # Create labels
self.label = gtk.Label() self.label = gtk.Label()
self.data = gtk.Label() self.data = gtk.Label()
@@ -571,43 +594,43 @@ class TrayIcon(object):
self.list.append(self.label) self.list.append(self.label)
# Setup table # Setup table
table = gtk.Table(1,2) table = gtk.Table(1, 2)
table.set_col_spacings(12) table.set_col_spacings(12)
table.attach(self.label, 0, 1, 0, 1) table.attach(self.label, 0, 1, 0, 1)
table.attach(self.data, 1, 2, 0 ,1) table.attach(self.data, 1, 2, 0, 1)
# Setup Window # Setup Window
content = window.get_content_area() content = window.get_content_area()
content.pack_start(table, True, True, 0) content.pack_start(table, True, True, 0)
content.show_all() content.show_all()
# Start updates # Start updates
self.cont = 'Go' self.cont = 'Go'
gobject.timeout_add(5000, self.update_conn_info_win, self.list) gobject.timeout_add(5000, self.update_conn_info_win, self.list)
self.update_conn_info_win(self.list) self.update_conn_info_win(self.list)
window.run() window.run()
# Destroy window and stop updates # Destroy window and stop updates
window.destroy() window.destroy()
self.cont = 'Stop' self.cont = 'Stop'
def update_conn_info_win(self, list): def update_conn_info_win(self, l):
""" Updates the information in the connection summary window """ """ Updates the information in the connection summary window """
if (self.cont == "Stop"): if (self.cont == "Stop"):
return False return False
[state, info] = daemon.GetConnectionStatus() [state, info] = daemon.GetConnectionStatus()
[rx, tx] = self.get_current_bandwidth() [rx, tx] = self.get_current_bandwidth()
# Choose info for the data # Choose info for the data
if state == misc.WIRED: if state == misc.WIRED:
text = (_('''$A text = (_('''$A
$B KB/s $B KB/s
$C KB/s''') $C KB/s''')
.replace('$A', str(info[0])) #IP .replace('$A', str(info[0])) # IP
.replace('$B', str(rx)) #RX .replace('$B', str(rx)) # RX
.replace('$C', str(tx))) #TX .replace('$C', str(tx))) # TX
elif state == misc.WIRELESS: elif state == misc.WIRELESS:
text = (_('''$A text = (_('''$A
$B $B
@@ -615,10 +638,11 @@ $C
$D $D
$E KB/s $E KB/s
$F KB/s''') $F KB/s''')
.replace('$A', str(info[1])) #SSID .replace('$A', str(info[1])) # SSID
.replace('$B', str(info[4])) #Speed .replace('$B', str(info[4])) # Speed
.replace('$C', str(info[0])) #IP .replace('$C', str(info[0])) # IP
.replace('$D', daemon.FormatSignalForPrinting(str(info[2]))) .replace('$D',
daemon.FormatSignalForPrinting(str(info[2])))
.replace('$E', str(rx)) .replace('$E', str(rx))
.replace('$F', str(tx))) .replace('$F', str(tx)))
else: else:
@@ -643,11 +667,11 @@ TX:'''))
self.list[1].set_text(_('Connecting')) self.list[1].set_text(_('Connecting'))
elif state in (misc.SUSPENDED, misc.NOT_CONNECTED): elif state in (misc.SUSPENDED, misc.NOT_CONNECTED):
self.list[1].set_text(_('Disconnected')) self.list[1].set_text(_('Disconnected'))
return True return True
def get_current_bandwidth(self): def get_current_bandwidth(self):
""" """
Calculates the current bandwidth based on sent/received bytes Calculates the current bandwidth based on sent/received bytes
divided over time. Unit is in KB/s divided over time. Unit is in KB/s
""" """
@@ -660,10 +684,10 @@ TX:'''))
rx_rate = float(rxb / (self.time * 1024)) rx_rate = float(rxb / (self.time * 1024))
tx_rate = float(txb / (self.time * 1024)) tx_rate = float(txb / (self.time * 1024))
return (rx_rate, tx_rate) return (rx_rate, tx_rate)
def _add_item_to_menu(self, net_menu, lbl, type_, n_id, is_connecting, def _add_item_to_menu(self, net_menu, lbl, type_, n_id, is_connecting,
is_active): is_active):
""" Add an item to the network list submenu. """ """ Add an item to the network list submenu. """
def network_selected(widget, net_type, net_id): def network_selected(widget, net_type, net_id):
@@ -672,10 +696,10 @@ TX:'''))
wired.ConnectWired() wired.ConnectWired()
else: else:
wireless.ConnectWireless(net_id) wireless.ConnectWireless(net_id)
item = NetworkMenuItem(lbl, is_active) item = NetworkMenuItem(lbl, is_active)
image = gtk.Image() image = gtk.Image()
if type_ == "__wired__": if type_ == "__wired__":
image.set_from_icon_name("network-wired", 2) image.set_from_icon_name("network-wired", 2)
else: else:
@@ -686,19 +710,19 @@ TX:'''))
net_menu.append(item) net_menu.append(item)
item.show() item.show()
if is_connecting: if is_connecting:
item.set_sensitive(False) item.set_sensitive(False)
del item del item
@catchdbus @catchdbus
def _get_img(self, net_id): def _get_img(self, net_id):
""" Determines which image to use for the wireless entries. """ """ Determines which image to use for the wireless entries. """
def fix_strength(val, default): def fix_strength(val, default):
""" Assigns given strength to a default value if needed. """ """ Assigns given strength to a default value if needed. """
return val and int(val) or default return val and int(val) or default
def get_prop(prop): def get_prop(prop):
return wireless.GetWirelessProperty(net_id, prop) return wireless.GetWirelessProperty(net_id, prop)
strength = fix_strength(get_prop("quality"), -1) strength = fix_strength(get_prop("quality"), -1)
dbm_strength = fix_strength(get_prop('strength'), -100) dbm_strength = fix_strength(get_prop('strength'), -100)
@@ -722,26 +746,27 @@ TX:'''))
else: else:
signal_img = 'signal-25' signal_img = 'signal-25'
return signal_img return signal_img
@catchdbus @catchdbus
def on_net_menu_activate(self, item): def on_net_menu_activate(self, item):
""" Trigger a background scan to populate the network menu. """ Trigger a background scan to populate the network menu.
Called when the network submenu is moused over. We Called when the network submenu is moused over. We
sleep briefly, clear pending gtk events, and if sleep briefly, clear pending gtk events, and if
we're still being moused over we trigger a scan. we're still being moused over we trigger a scan.
This is to prevent scans when the user is just This is to prevent scans when the user is just
mousing past the menu to select another menu item. mousing past the menu to select another menu item.
""" """
def dummy(x=None): pass def dummy(x=None):
pass
if self._is_scanning: if self._is_scanning:
return True return True
self.init_network_menu() self.init_network_menu()
gobject.timeout_add(800, self._trigger_scan_if_needed, item) gobject.timeout_add(800, self._trigger_scan_if_needed, item)
@catchdbus @catchdbus
def _trigger_scan_if_needed(self, item): def _trigger_scan_if_needed(self, item):
""" Trigger a scan if the network menu is being hovered over. """ """ Trigger a scan if the network menu is being hovered over. """
@@ -751,7 +776,7 @@ TX:'''))
return True return True
wireless.Scan(False) wireless.Scan(False)
return False return False
@catchdbus @catchdbus
def populate_network_menu(self, data=None): def populate_network_menu(self, data=None):
""" Populates the network list submenu. """ """ Populates the network list submenu. """
@@ -768,7 +793,7 @@ TX:'''))
is_connecting = daemon.CheckIfConnecting() is_connecting = daemon.CheckIfConnecting()
num_networks = wireless.GetNumberOfNetworks() num_networks = wireless.GetNumberOfNetworks()
[status, info] = daemon.GetConnectionStatus() [status, info] = daemon.GetConnectionStatus()
if daemon.GetAlwaysShowWiredInterface() or \ if daemon.GetAlwaysShowWiredInterface() or \
wired.CheckPluggedIn(): wired.CheckPluggedIn():
if status == misc.WIRED: if status == misc.WIRED:
@@ -780,11 +805,13 @@ TX:'''))
sep = gtk.SeparatorMenuItem() sep = gtk.SeparatorMenuItem()
submenu.append(sep) submenu.append(sep)
sep.show() sep.show()
if num_networks > 0: if num_networks > 0:
skip_never_connect = not daemon.GetShowNeverConnect() skip_never_connect = not daemon.GetShowNeverConnect()
for x in xrange(0, num_networks): for x in xrange(0, num_networks):
if skip_never_connect and misc.to_bool(get_prop(x,"never")): continue if skip_never_connect and \
misc.to_bool(get_prop(x,"never")):
continue
essid = get_prop(x, "essid") essid = get_prop(x, "essid")
if status == misc.WIRELESS and info[1] == essid: if status == misc.WIRELESS and info[1] == essid:
is_active = True is_active = True
@@ -800,7 +827,7 @@ TX:'''))
submenu.reposition() submenu.reposition()
net_menuitem.show() net_menuitem.show()
def init_network_menu(self): def init_network_menu(self):
""" Set the right-click network menu to the scanning state. """ """ Set the right-click network menu to the scanning state. """
net_menuitem = self.manager.get_widget("/Menubar/Menu/Connect/") net_menuitem = self.manager.get_widget("/Menubar/Menu/Connect/")
@@ -812,13 +839,13 @@ TX:'''))
loading_item.show() loading_item.show()
submenu.append(loading_item) submenu.append(loading_item)
net_menuitem.show() net_menuitem.show()
def _clear_menu(self, menu): def _clear_menu(self, menu):
""" Clear the right-click menu. """ """ Clear the right-click menu. """
for item in menu.get_children(): for item in menu.get_children():
menu.remove(item) menu.remove(item)
item.destroy() item.destroy()
def toggle_wicd_gui(self): def toggle_wicd_gui(self):
""" Toggles the wicd GUI. """ """ Toggles the wicd GUI. """
if not self.gui_win: if not self.gui_win:
@@ -828,16 +855,15 @@ TX:'''))
else: else:
self.gui_win.exit() self.gui_win.exit()
return True return True
if USE_EGG: if USE_EGG:
class EggTrayIconGUI(TrayIconGUI): class EggTrayIconGUI(TrayIconGUI):
""" Tray Icon for gtk < 2.10. """ Tray Icon for gtk < 2.10.
Uses the deprecated egg.trayicon module to implement the tray icon. Uses the deprecated egg.trayicon module to implement the tray icon.
Since it relies on a deprecated module, this class is only used Since it relies on a deprecated module, this class is only used
for machines running versions of GTK < 2.10. for machines running versions of GTK < 2.10.
""" """
def __init__(self, parent): def __init__(self, parent):
"""Initializes the tray icon""" """Initializes the tray icon"""
@@ -864,11 +890,15 @@ TX:'''))
def set_from_file(self, val=None): def set_from_file(self, val=None):
""" Calls set_from_file on the gtk.Image for the tray icon. """ """ Calls set_from_file on the gtk.Image for the tray icon. """
self.pic.set_from_file(os.path.join(wpath.images, 'hicolor/22x22/status/%s.png' % val)) self.pic.set_from_file(
os.path.join(
wpath.images, 'hicolor/22x22/status/%s.png' % val
)
)
def set_tooltip(self, val): def set_tooltip(self, val):
""" Set the tooltip for this tray icon. """ Set the tooltip for this tray icon.
Sets the tooltip for the gtk.ToolTips associated with this Sets the tooltip for the gtk.ToolTips associated with this
tray icon. tray icon.
@@ -887,13 +917,12 @@ TX:'''))
else: else:
self.tray.hide_all() self.tray.hide_all()
if hasattr(gtk, "StatusIcon"): if hasattr(gtk, "StatusIcon"):
class StatusTrayIconGUI(gtk.StatusIcon, TrayIconGUI): class StatusTrayIconGUI(gtk.StatusIcon, TrayIconGUI):
""" Class for creating the wicd tray icon on gtk > 2.10. """ Class for creating the wicd tray icon on gtk > 2.10.
Uses gtk.StatusIcon to implement a tray icon. Uses gtk.StatusIcon to implement a tray icon.
""" """
def __init__(self, parent): def __init__(self, parent):
TrayIcon.TrayIconGUI.__init__(self, parent) TrayIcon.TrayIconGUI.__init__(self, parent)
@@ -930,7 +959,7 @@ TX:'''))
def usage(): def usage():
""" Print usage information. """ """ Print usage information. """
print """ print """
wicd %s wicd %s
wireless (and wired) connection daemon front-end. wireless (and wired) connection daemon front-end.
Arguments: Arguments:
@@ -941,23 +970,29 @@ Arguments:
\t-o\t--only-notifications\tDon't display anything except notifications. \t-o\t--only-notifications\tDon't display anything except notifications.
""" % wpath.version """ % wpath.version
def setup_dbus(force=True): def setup_dbus(force=True):
""" Initialize DBus. """
global daemon, wireless, wired, DBUS_AVAIL, lost_dbus_id global daemon, wireless, wired, DBUS_AVAIL, lost_dbus_id
print "Connecting to daemon..." print "Connecting to daemon..."
try: try:
dbusmanager.connect_to_dbus() dbusmanager.connect_to_dbus()
except DBusException: except DBusException:
if force: if force:
print "Can't connect to the daemon, trying to start it automatically..." print "Can't connect to the daemon, trying to start it " + \
"automatically..."
misc.PromptToStartDaemon() misc.PromptToStartDaemon()
try: try:
dbusmanager.connect_to_dbus() dbusmanager.connect_to_dbus()
except DBusException: 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 return False
else: else:
return False return False
if lost_dbus_id: if lost_dbus_id:
gobject.source_remove(lost_dbus_id) gobject.source_remove(lost_dbus_id)
lost_dbus_id = None lost_dbus_id = None
@@ -969,23 +1004,32 @@ def setup_dbus(force=True):
print "Connected." print "Connected."
return True return True
def on_exit(): def on_exit():
""" Handle GUI exit. """
if DBUS_AVAIL: if DBUS_AVAIL:
try: try:
daemon.SetGUIOpen(False) daemon.SetGUIOpen(False)
except DBusException: except DBusException:
pass pass
def handle_no_dbus(): def handle_no_dbus():
""" Called when dbus announces its shutting down. """ """ Called when dbus announces its shutting down. """
global DBUS_AVAIL, lost_dbus_id global DBUS_AVAIL, lost_dbus_id
DBUS_AVAIL = False DBUS_AVAIL = False
gui.handle_no_dbus(from_tray=True) gui.handle_no_dbus(from_tray=True)
print "Wicd daemon is shutting down!" print "Wicd daemon is shutting down!"
lost_dbus_id = misc.timeout_add(5, lambda:error(None, _('The wicd daemon has shut down. The UI will not function properly until it is restarted.'), lost_dbus_id = misc.timeout_add(5,
block=False)) lambda: error(None,
_('The wicd daemon has shut down. The UI will not function '
'properly until it is restarted.'),
block=False
)
)
return False return False
@catchdbus @catchdbus
def main(argv): def main(argv):
""" The main frontend program. """ The main frontend program.
@@ -995,10 +1039,11 @@ def main(argv):
""" """
try: try:
opts, args = getopt.getopt(sys.argv[1:], 'tnhao', ['help', 'no-tray', opts, args = getopt.getopt(
'tray', sys.argv[1:],
'no-animate', 'tnhao',
'only-notifications']) ['help', 'no-tray', 'tray', 'no-animate', 'only-notifications']
)
except getopt.GetoptError: except getopt.GetoptError:
# Print help information and exit # Print help information and exit
usage() usage()
@@ -1024,13 +1069,13 @@ def main(argv):
else: else:
usage() usage()
sys.exit(2) sys.exit(2)
print 'Loading...' print 'Loading...'
setup_dbus() setup_dbus()
atexit.register(on_exit) atexit.register(on_exit)
if display_app and not use_tray or not ICON_AVAIL: if display_app and not use_tray or not ICON_AVAIL:
the_gui = gui.appGui(standalone=True) gui.appGui(standalone=True)
mainloop = gobject.MainLoop() mainloop = gobject.MainLoop()
mainloop.run() mainloop.run()
sys.exit(0) sys.exit(0)
@@ -1043,7 +1088,7 @@ def main(argv):
if DBUS_AVAIL and daemon.GetNeedWiredProfileChooser(): if DBUS_AVAIL and daemon.GetNeedWiredProfileChooser():
daemon.SetNeedWiredProfileChooser(False) daemon.SetNeedWiredProfileChooser(False)
tray_icon.icon_info.wired_profile_chooser() tray_icon.icon_info.wired_profile_chooser()
bus = dbusmanager.get_bus() bus = dbusmanager.get_bus()
bus.add_signal_receiver(tray_icon.icon_info.wired_profile_chooser, bus.add_signal_receiver(tray_icon.icon_info.wired_profile_chooser,
'LaunchChooser', 'org.wicd.daemon') 'LaunchChooser', 'org.wicd.daemon')
@@ -1053,9 +1098,13 @@ def main(argv):
'org.wicd.daemon.wireless') 'org.wicd.daemon.wireless')
bus.add_signal_receiver(tray_icon.tr.tray_scan_started, bus.add_signal_receiver(tray_icon.tr.tray_scan_started,
'SendStartScanSignal', 'org.wicd.daemon.wireless') 'SendStartScanSignal', 'org.wicd.daemon.wireless')
bus.add_signal_receiver(lambda: (handle_no_dbus() or bus.add_signal_receiver(
tray_icon.icon_info.set_not_connected_state()), lambda: (
"DaemonClosing", 'org.wicd.daemon') handle_no_dbus() or tray_icon.icon_info.set_not_connected_state()
),
"DaemonClosing",
'org.wicd.daemon'
)
bus.add_signal_receiver(lambda: setup_dbus(force=False), "DaemonStarting", bus.add_signal_receiver(lambda: setup_dbus(force=False), "DaemonStarting",
"org.wicd.daemon") "org.wicd.daemon")
print 'Done loading.' print 'Done loading.'