mirror of
https://github.com/gryf/wicd.git
synced 2025-12-21 13:28:08 +01:00
Fix some issues by pylint
This commit is contained in:
109
cli/wicd-cli.py
109
cli/wicd-cli.py
@@ -1,5 +1,6 @@
|
|||||||
#!/usr/bin/python
|
#!/usr/bin/python
|
||||||
|
|
||||||
|
""" Scriptable command-line interface. """
|
||||||
# This program is free software; you can redistribute it and/or modify
|
# This program is free software; you can redistribute it and/or modify
|
||||||
# it under the terms of the GNU General Public License as published by
|
# it under the terms of the GNU General Public License as published by
|
||||||
# the Free Software Foundation; either version 2 of the License, or
|
# the Free Software Foundation; either version 2 of the License, or
|
||||||
@@ -32,20 +33,30 @@ else:
|
|||||||
|
|
||||||
bus = dbus.SystemBus()
|
bus = dbus.SystemBus()
|
||||||
try:
|
try:
|
||||||
daemon = dbus.Interface(bus.get_object('org.wicd.daemon', '/org/wicd/daemon'),
|
daemon = dbus.Interface(
|
||||||
'org.wicd.daemon')
|
bus.get_object('org.wicd.daemon', '/org/wicd/daemon'),
|
||||||
wireless = dbus.Interface(bus.get_object('org.wicd.daemon', '/org/wicd/daemon/wireless'),
|
'org.wicd.daemon'
|
||||||
'org.wicd.daemon.wireless')
|
)
|
||||||
wired = dbus.Interface(bus.get_object('org.wicd.daemon', '/org/wicd/daemon/wired'),
|
wireless = dbus.Interface(
|
||||||
'org.wicd.daemon.wired')
|
bus.get_object('org.wicd.daemon', '/org/wicd/daemon/wireless'),
|
||||||
config = dbus.Interface(bus.get_object('org.wicd.daemon', '/org/wicd/daemon/config'),
|
'org.wicd.daemon.wireless'
|
||||||
'org.wicd.daemon.config')
|
)
|
||||||
|
wired = dbus.Interface(
|
||||||
|
bus.get_object('org.wicd.daemon', '/org/wicd/daemon/wired'),
|
||||||
|
'org.wicd.daemon.wired'
|
||||||
|
)
|
||||||
|
config = dbus.Interface(
|
||||||
|
bus.get_object('org.wicd.daemon', '/org/wicd/daemon/config'),
|
||||||
|
'org.wicd.daemon.config'
|
||||||
|
)
|
||||||
except dbus.DBusException:
|
except dbus.DBusException:
|
||||||
print 'Error: Could not connect to the daemon. Please make sure it is running.'
|
print 'Error: Could not connect to the daemon. ' + \
|
||||||
|
'Please make sure it is running.'
|
||||||
sys.exit(3)
|
sys.exit(3)
|
||||||
|
|
||||||
if not daemon:
|
if not daemon:
|
||||||
print 'Error connecting to wicd via D-Bus. Please make sure the wicd service is running.'
|
print 'Error connecting to wicd via D-Bus. ' + \
|
||||||
|
'Please make sure the wicd service is running.'
|
||||||
sys.exit(3)
|
sys.exit(3)
|
||||||
|
|
||||||
parser = optparse.OptionParser()
|
parser = optparse.OptionParser()
|
||||||
@@ -61,12 +72,14 @@ parser.add_option('--list-networks', '-l', default=False, action='store_true')
|
|||||||
parser.add_option('--network-details', '-d', default=False, action='store_true')
|
parser.add_option('--network-details', '-d', default=False, action='store_true')
|
||||||
parser.add_option('--disconnect', '-x', default=False, action='store_true')
|
parser.add_option('--disconnect', '-x', default=False, action='store_true')
|
||||||
parser.add_option('--connect', '-c', default=False, action='store_true')
|
parser.add_option('--connect', '-c', default=False, action='store_true')
|
||||||
parser.add_option('--list-encryption-types', '-e', default=False, action='store_true')
|
parser.add_option('--list-encryption-types', '-e', default=False,
|
||||||
|
action='store_true')
|
||||||
# short options for these aren't great.
|
# short options for these aren't great.
|
||||||
parser.add_option('--wireless', '-y', default=False, action='store_true')
|
parser.add_option('--wireless', '-y', default=False, action='store_true')
|
||||||
parser.add_option('--wired', '-z', default=False, action='store_true')
|
parser.add_option('--wired', '-z', default=False, action='store_true')
|
||||||
parser.add_option('--load-profile', '-o', default=False, action='store_true')
|
parser.add_option('--load-profile', '-o', default=False, action='store_true')
|
||||||
parser.add_option('--status', '-i', default=False, action='store_true') # -i(nfo)
|
parser.add_option('--status', '-i', default=False,
|
||||||
|
action='store_true') # -i(nfo)
|
||||||
|
|
||||||
options, arguments = parser.parse_args()
|
options, arguments = parser.parse_args()
|
||||||
|
|
||||||
@@ -114,12 +127,14 @@ if options.status:
|
|||||||
|
|
||||||
# functions
|
# functions
|
||||||
def is_valid_wireless_network_id(network_id):
|
def is_valid_wireless_network_id(network_id):
|
||||||
|
""" Check if it's a valid wireless network. '"""
|
||||||
if not (network_id >= 0 \
|
if not (network_id >= 0 \
|
||||||
and network_id < wireless.GetNumberOfNetworks()):
|
and network_id < wireless.GetNumberOfNetworks()):
|
||||||
print 'Invalid wireless network identifier.'
|
print 'Invalid wireless network identifier.'
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
def is_valid_wired_network_id(network_id):
|
def is_valid_wired_network_id(network_id):
|
||||||
|
""" Check if it's a valid wired network. '"""
|
||||||
num = len(wired.GetWiredProfileList())
|
num = len(wired.GetWiredProfileList())
|
||||||
if not (network_id < num and \
|
if not (network_id < num and \
|
||||||
network_id >= 0):
|
network_id >= 0):
|
||||||
@@ -127,6 +142,7 @@ def is_valid_wired_network_id(network_id):
|
|||||||
sys.exit(4)
|
sys.exit(4)
|
||||||
|
|
||||||
def is_valid_wired_network_profile(profile_name):
|
def is_valid_wired_network_profile(profile_name):
|
||||||
|
""" Check if it's a valid wired network profile. '"""
|
||||||
if not profile_name in wired.GetWiredProfileList():
|
if not profile_name in wired.GetWiredProfileList():
|
||||||
print 'Profile of that name does not exist.'
|
print 'Profile of that name does not exist.'
|
||||||
sys.exit(5)
|
sys.exit(5)
|
||||||
@@ -151,10 +167,10 @@ if options.list_networks:
|
|||||||
wireless.GetWirelessProperty(network_id, 'essid'))
|
wireless.GetWirelessProperty(network_id, 'essid'))
|
||||||
elif options.wired:
|
elif options.wired:
|
||||||
print '#\tProfile name'
|
print '#\tProfile name'
|
||||||
id = 0
|
i = 0
|
||||||
for profile in wired.GetWiredProfileList():
|
for profile in wired.GetWiredProfileList():
|
||||||
print '%s\t%s' % (id, profile)
|
print '%s\t%s' % (i, profile)
|
||||||
id += 1
|
i += 1
|
||||||
op_performed = True
|
op_performed = True
|
||||||
|
|
||||||
if options.network_details:
|
if options.network_details:
|
||||||
@@ -176,10 +192,14 @@ if options.network_details:
|
|||||||
wireless.GetWirelessProperty(network_id, "encryption_method")
|
wireless.GetWirelessProperty(network_id, "encryption_method")
|
||||||
else:
|
else:
|
||||||
print "Encryption: Off"
|
print "Encryption: Off"
|
||||||
print "Quality: %s" % wireless.GetWirelessProperty(network_id, "quality")
|
print "Quality: %s" % \
|
||||||
print "Mode: %s" % wireless.GetWirelessProperty(network_id, "mode")
|
wireless.GetWirelessProperty(network_id, "quality")
|
||||||
print "Channel: %s" % wireless.GetWirelessProperty(network_id, "channel")
|
print "Mode: %s" % \
|
||||||
print "Bit Rates: %s" % wireless.GetWirelessProperty(network_id, "bitrates")
|
wireless.GetWirelessProperty(network_id, "mode")
|
||||||
|
print "Channel: %s" % \
|
||||||
|
wireless.GetWirelessProperty(network_id, "channel")
|
||||||
|
print "Bit Rates: %s" % \
|
||||||
|
wireless.GetWirelessProperty(network_id, "bitrates")
|
||||||
op_performed = True
|
op_performed = True
|
||||||
|
|
||||||
# network properties
|
# network properties
|
||||||
@@ -194,7 +214,8 @@ if options.network_property:
|
|||||||
network_id = wireless.GetCurrentNetworkID(0)
|
network_id = wireless.GetCurrentNetworkID(0)
|
||||||
is_valid_wireless_network_id(network_id)
|
is_valid_wireless_network_id(network_id)
|
||||||
if not options.set_to:
|
if not options.set_to:
|
||||||
print wireless.GetWirelessProperty(network_id, options.network_property)
|
print wireless.GetWirelessProperty(network_id,
|
||||||
|
options.network_property)
|
||||||
else:
|
else:
|
||||||
wireless.SetWirelessProperty(network_id, \
|
wireless.SetWirelessProperty(network_id, \
|
||||||
options.network_property, options.set_to)
|
options.network_property, options.set_to)
|
||||||
@@ -209,11 +230,13 @@ if options.disconnect:
|
|||||||
daemon.Disconnect()
|
daemon.Disconnect()
|
||||||
if options.wireless:
|
if options.wireless:
|
||||||
if wireless.GetCurrentNetworkID(0) > -1:
|
if wireless.GetCurrentNetworkID(0) > -1:
|
||||||
print "Disconnecting from %s on %s" % (wireless.GetCurrentNetwork(0),
|
print "Disconnecting from %s on %s" % \
|
||||||
|
(wireless.GetCurrentNetwork(0),
|
||||||
wireless.DetectWirelessInterface())
|
wireless.DetectWirelessInterface())
|
||||||
elif options.wired:
|
elif options.wired:
|
||||||
if wired.CheckPluggedIn():
|
if wired.CheckPluggedIn():
|
||||||
print "Disconnecting from wired connection on %s" % wired.DetectWiredInterface()
|
print "Disconnecting from wired connection on %s" % \
|
||||||
|
wired.DetectWiredInterface()
|
||||||
op_performed = True
|
op_performed = True
|
||||||
|
|
||||||
if options.connect:
|
if options.connect:
|
||||||
@@ -226,16 +249,17 @@ if options.connect:
|
|||||||
wireless.DetectWirelessInterface())
|
wireless.DetectWirelessInterface())
|
||||||
wireless.ConnectWireless(options.network)
|
wireless.ConnectWireless(options.network)
|
||||||
|
|
||||||
check = lambda: wireless.CheckIfWirelessConnecting()
|
check = wireless.CheckIfWirelessConnecting
|
||||||
status = lambda: wireless.CheckWirelessConnectingStatus()
|
status = wireless.CheckWirelessConnectingStatus
|
||||||
message = lambda: wireless.CheckWirelessConnectingMessage()
|
message = wireless.CheckWirelessConnectingMessage
|
||||||
elif options.wired:
|
elif options.wired:
|
||||||
print "Connecting to wired connection on %s" % wired.DetectWiredInterface()
|
print "Connecting to wired connection on %s" % \
|
||||||
|
wired.DetectWiredInterface()
|
||||||
wired.ConnectWired()
|
wired.ConnectWired()
|
||||||
|
|
||||||
check = lambda: wired.CheckIfWiredConnecting()
|
check = wired.CheckIfWiredConnecting
|
||||||
status = lambda: wired.CheckWiredConnectingStatus()
|
status = wired.CheckWiredConnectingStatus
|
||||||
message = lambda: wired.CheckWiredConnectingMessage()
|
message = wired.CheckWiredConnectingMessage
|
||||||
else:
|
else:
|
||||||
check = lambda: False
|
check = lambda: False
|
||||||
status = lambda: False
|
status = lambda: False
|
||||||
@@ -245,36 +269,37 @@ if options.connect:
|
|||||||
last = None
|
last = None
|
||||||
if check:
|
if check:
|
||||||
while check():
|
while check():
|
||||||
next = status()
|
next_ = status()
|
||||||
if next != last:
|
if next_ != last:
|
||||||
# avoid a race condition where status is updated to "done" after the
|
# avoid a race condition where status is updated to "done" after
|
||||||
# loop check
|
# the loop check
|
||||||
if next == "done":
|
if next_ == "done":
|
||||||
break
|
break
|
||||||
print message()
|
print message()
|
||||||
last = next
|
last = next_
|
||||||
print "done!"
|
print "done!"
|
||||||
op_performed = True
|
op_performed = True
|
||||||
|
|
||||||
# pretty print optional and required properties
|
|
||||||
def str_properties(prop):
|
def str_properties(prop):
|
||||||
|
""" Pretty print optional and required properties. """
|
||||||
if len(prop) == 0:
|
if len(prop) == 0:
|
||||||
return "None"
|
return "None"
|
||||||
else:
|
else:
|
||||||
return ', '.join("%s (%s)" % (x[0], x[1].replace("_", " ")) for x in type['required'])
|
tmp = [(x[0], x[1].replace('_', ' ')) for x in type['required']]
|
||||||
|
return ', '.join("%s (%s)" % (x, y) for x, y in tmp)
|
||||||
|
|
||||||
if options.wireless and options.list_encryption_types:
|
if options.wireless and options.list_encryption_types:
|
||||||
et = misc.LoadEncryptionMethods()
|
et = misc.LoadEncryptionMethods()
|
||||||
# print 'Installed encryption templates:'
|
# print 'Installed encryption templates:'
|
||||||
print '%s\t%-20s\t%s' % ('#', 'Name', 'Description')
|
print '%s\t%-20s\t%s' % ('#', 'Name', 'Description')
|
||||||
id = 0
|
i = 0
|
||||||
for type in et:
|
for t in et:
|
||||||
print '%s\t%-20s\t%s' % (id, type['type'], type['name'])
|
print '%s\t%-20s\t%s' % (i, t['type'], t['name'])
|
||||||
print ' Req: %s' % str_properties(type['required'])
|
print ' Req: %s' % str_properties(t['required'])
|
||||||
print '---'
|
print '---'
|
||||||
# don't print optionals (yet)
|
# don't print optionals (yet)
|
||||||
#print ' Opt: %s' % str_properties(type['optional'])
|
#print ' Opt: %s' % str_properties(type['optional'])
|
||||||
id += 1
|
i += 1
|
||||||
op_performed = True
|
op_performed = True
|
||||||
|
|
||||||
if options.save and options.network > -1:
|
if options.save and options.network > -1:
|
||||||
|
|||||||
@@ -26,26 +26,36 @@ Also recycles a lot of configscript.py, too. :-)
|
|||||||
from wicd import misc
|
from wicd import misc
|
||||||
from wicd.translations import _
|
from wicd.translations import _
|
||||||
import configscript
|
import configscript
|
||||||
from configscript import write_scripts,get_script_info,get_val,none_to_blank,blank_to_none
|
from configscript import write_scripts, get_script_info, get_val
|
||||||
|
from configscript import none_to_blank, blank_to_none
|
||||||
|
|
||||||
import urwid
|
import urwid
|
||||||
import urwid.curses_display
|
import urwid.curses_display
|
||||||
import sys
|
import sys
|
||||||
import os
|
import os
|
||||||
|
|
||||||
|
ui = None
|
||||||
|
frame = None
|
||||||
|
pre_entry = None
|
||||||
|
post_entry = None
|
||||||
|
pre_disconnect_entry = None
|
||||||
|
post_disconnect_entry = None
|
||||||
|
|
||||||
def main(argv):
|
def main(argv):
|
||||||
global ui,frame
|
""" Main function. """
|
||||||
|
global ui, frame
|
||||||
if len(argv) < 2:
|
if len(argv) < 2:
|
||||||
print 'Network id to configure is missing, aborting.'
|
print 'Network id to configure is missing, aborting.'
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
ui = urwid.curses_display.Screen()
|
ui = urwid.curses_display.Screen()
|
||||||
ui.register_palette( [
|
ui.register_palette([
|
||||||
('body','default','default'),
|
('body', 'default', 'default'),
|
||||||
('focus','dark magenta','light gray'),
|
('focus', 'dark magenta', 'light gray'),
|
||||||
('editcp', 'default', 'default', 'standout'),
|
('editcp', 'default', 'default', 'standout'),
|
||||||
('editbx', 'light gray', 'dark blue'),
|
('editbx', 'light gray', 'dark blue'),
|
||||||
('editfc', 'white','dark blue', 'bold')] )
|
('editfc', 'white','dark blue', 'bold'),
|
||||||
|
])
|
||||||
|
|
||||||
network = argv[1]
|
network = argv[1]
|
||||||
network_type = argv[2]
|
network_type = argv[2]
|
||||||
@@ -53,34 +63,44 @@ def main(argv):
|
|||||||
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') + ': ')
|
||||||
|
|
||||||
global pre_entry,post_entry,pre_disconnect_entry,post_disconnect_entry
|
global pre_entry, post_entry, pre_disconnect_entry, post_disconnect_entry
|
||||||
pre_entry = urwid.AttrWrap(urwid.Edit(pre_entry_t,
|
pre_entry = urwid.AttrWrap(urwid.Edit(pre_entry_t,
|
||||||
none_to_blank(script_info.get('pre_entry'))),'editbx','editfc' )
|
none_to_blank(script_info.get('pre_entry'))),
|
||||||
|
'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'))),'editbx','editfc' )
|
none_to_blank(script_info.get('post_entry'))),
|
||||||
|
'editbx','editfc')
|
||||||
|
|
||||||
pre_disconnect_entry = urwid.AttrWrap(urwid.Edit(pre_disconnect_entry_t,
|
pre_disconnect_entry = urwid.AttrWrap(urwid.Edit(pre_disconnect_entry_t,
|
||||||
none_to_blank(script_info.get('pre_disconnect_entry'))),'editbx','editfc' )
|
none_to_blank(script_info.get('pre_disconnect_entry'))),
|
||||||
|
'editbx', 'editfc')
|
||||||
post_disconnect_entry = urwid.AttrWrap(urwid.Edit(post_disconnect_entry_t,
|
post_disconnect_entry = urwid.AttrWrap(urwid.Edit(post_disconnect_entry_t,
|
||||||
none_to_blank(script_info.get('post_disconnect_entry'))),'editbx','editfc' )
|
none_to_blank(script_info.get('post_disconnect_entry'))),
|
||||||
|
'editbx','editfc')
|
||||||
|
|
||||||
# The buttons
|
# The buttons
|
||||||
ok_button = urwid.AttrWrap(urwid.Button(_('OK'),ok_callback),'body','focus')
|
ok_button = urwid.AttrWrap(
|
||||||
cancel_button = urwid.AttrWrap(urwid.Button(_('Cancel'),cancel_callback),'body','focus')
|
urwid.Button(_('OK'), ok_callback),
|
||||||
|
'body','focus'
|
||||||
|
)
|
||||||
|
cancel_button = urwid.AttrWrap(
|
||||||
|
urwid.Button(_('Cancel'), cancel_callback),
|
||||||
|
'body','focus'
|
||||||
|
)
|
||||||
|
|
||||||
button_cols = urwid.Columns([ok_button,cancel_button],dividechars=1)
|
button_cols = urwid.Columns([ok_button, cancel_button], dividechars=1)
|
||||||
|
|
||||||
lbox = urwid.Pile([('fixed',2,urwid.Filler(pre_entry)),
|
lbox = urwid.Pile([('fixed', 2, urwid.Filler(pre_entry)),
|
||||||
#('fixed',urwid.Filler(blank),1),
|
#('fixed', urwid.Filler(blank), 1),
|
||||||
('fixed',2,urwid.Filler(post_entry)),
|
('fixed', 2, urwid.Filler(post_entry)),
|
||||||
('fixed',2,urwid.Filler(pre_disconnect_entry)),
|
('fixed', 2, urwid.Filler(pre_disconnect_entry)),
|
||||||
('fixed',2,urwid.Filler(post_disconnect_entry)),
|
('fixed', 2, urwid.Filler(post_disconnect_entry)),
|
||||||
#blank,blank,blank,blank,blank,
|
#blank, blank, blank, blank, blank,
|
||||||
urwid.Filler(button_cols,'bottom')
|
urwid.Filler(button_cols,'bottom')
|
||||||
])
|
])
|
||||||
frame = urwid.Frame(lbox)
|
frame = urwid.Frame(lbox)
|
||||||
@@ -89,16 +109,18 @@ def main(argv):
|
|||||||
if result == True:
|
if result == True:
|
||||||
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"] = blank_to_none(pre_disconnect_entry.get_edit_text())
|
script_info["pre_disconnect_entry"] = \
|
||||||
script_info["post_disconnect_entry"] = blank_to_none(post_disconnect_entry.get_edit_text())
|
blank_to_none(pre_disconnect_entry.get_edit_text())
|
||||||
|
script_info["post_disconnect_entry"] = \
|
||||||
|
blank_to_none(post_disconnect_entry.get_edit_text())
|
||||||
write_scripts(network, network_type, script_info)
|
write_scripts(network, network_type, script_info)
|
||||||
|
|
||||||
OK_PRESSED = False
|
OK_PRESSED = False
|
||||||
CANCEL_PRESSED = False
|
CANCEL_PRESSED = False
|
||||||
def ok_callback(button_object,user_data=None):
|
def ok_callback(button_object, user_data=None):
|
||||||
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):
|
||||||
global CANCEL_PRESSED
|
global CANCEL_PRESSED
|
||||||
CANCEL_PRESSED = True
|
CANCEL_PRESSED = True
|
||||||
def run():
|
def run():
|
||||||
@@ -119,9 +141,7 @@ def run():
|
|||||||
#Send key to underlying widget:
|
#Send key to underlying widget:
|
||||||
if urwid.is_mouse_event(k):
|
if urwid.is_mouse_event(k):
|
||||||
event, button, col, row = k
|
event, button, col, row = k
|
||||||
frame.mouse_event( dim,
|
frame.mouse_event(dim, event, button, col, row, focus=True)
|
||||||
event, button, col, row,
|
|
||||||
focus=True)
|
|
||||||
else:
|
else:
|
||||||
frame.keypress(dim, k)
|
frame.keypress(dim, k)
|
||||||
# Check if buttons are pressed.
|
# Check if buttons are pressed.
|
||||||
|
|||||||
@@ -27,13 +27,13 @@ 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)"""
|
||||||
# /\
|
# /\
|
||||||
# /!!\
|
# /!!\
|
||||||
# /____\
|
# /____\
|
||||||
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."""
|
||||||
@@ -42,13 +42,12 @@ class SelText(urwid.Text):
|
|||||||
"""Make widget selectable."""
|
"""Make widget selectable."""
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
def keypress(self, size, key):
|
def keypress(self, size, key):
|
||||||
"""Don't handle any keys."""
|
"""Don't handle any keys."""
|
||||||
return key
|
return key
|
||||||
|
|
||||||
# ListBox that can't be selected.
|
|
||||||
class NSelListBox(urwid.ListBox):
|
class NSelListBox(urwid.ListBox):
|
||||||
|
""" Non-selectable ListBox. """
|
||||||
def selectable(self):
|
def selectable(self):
|
||||||
return False
|
return False
|
||||||
|
|
||||||
@@ -64,8 +63,9 @@ class DynWrap(urwid.AttrWrap):
|
|||||||
attrfoc = attributes when in focus, defaults to nothing
|
attrfoc = attributes when in focus, defaults to nothing
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self,w,sensitive=True,attrs=('editbx','editnfc'),focus_attr='editfc'):
|
def __init__(self, w, sensitive=True, attrs=('editbx', 'editnfc'), \
|
||||||
self._attrs=attrs
|
focus_attr='editfc'):
|
||||||
|
self._attrs = attrs
|
||||||
self._sensitive = sensitive
|
self._sensitive = sensitive
|
||||||
|
|
||||||
if sensitive:
|
if sensitive:
|
||||||
@@ -73,48 +73,59 @@ class DynWrap(urwid.AttrWrap):
|
|||||||
else:
|
else:
|
||||||
cur_attr = attrs[1]
|
cur_attr = attrs[1]
|
||||||
|
|
||||||
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. """
|
||||||
return self._sensitive
|
return self._sensitive
|
||||||
def set_sensitive(self,state):
|
def set_sensitive(self, state):
|
||||||
|
""" Setter for sensitive property. """
|
||||||
if state:
|
if state:
|
||||||
self.set_attr(self._attrs[0])
|
self.set_attr(self._attrs[0])
|
||||||
else:
|
else:
|
||||||
self.set_attr(self._attrs[1])
|
self.set_attr(self._attrs[1])
|
||||||
self._sensitive = state
|
self._sensitive = state
|
||||||
property(get_sensitive,set_sensitive)
|
property(get_sensitive, set_sensitive)
|
||||||
|
|
||||||
def get_attrs(self):
|
def get_attrs(self):
|
||||||
|
""" Getter for attrs property. """
|
||||||
return self._attrs
|
return self._attrs
|
||||||
def set_attrs(self,attrs):
|
def set_attrs(self, attrs):
|
||||||
|
""" Setter for attrs property. """
|
||||||
self._attrs = attrs
|
self._attrs = attrs
|
||||||
property(get_attrs,set_attrs)
|
property(get_attrs, set_attrs)
|
||||||
|
|
||||||
def selectable(self):
|
def selectable(self):
|
||||||
return self._sensitive
|
return self._sensitive
|
||||||
|
|
||||||
# Just an Edit Dynwrapped to the most common specifications
|
|
||||||
class DynEdit(DynWrap):
|
class DynEdit(DynWrap):
|
||||||
def __init__(self,caption='',edit_text='',sensitive=True,attrs=('editbx','editnfc'),focus_attr='editfc'):
|
""" Edit DynWrap'ed to the most common specifications. """
|
||||||
caption = ('editcp',caption + ': ')
|
def __init__(self, caption='', edit_text='', sensitive=True,
|
||||||
edit = urwid.Edit(caption,edit_text)
|
attrs=('editbx', 'editnfc'), focus_attr='editfc'):
|
||||||
self.__super.__init__(edit,sensitive,attrs,focus_attr)
|
caption = ('editcp', caption + ': ')
|
||||||
|
edit = urwid.Edit(caption, edit_text)
|
||||||
|
self.__super.__init__(edit, sensitive, attrs, focus_attr)
|
||||||
|
|
||||||
# Just an IntEdit Dynwrapped to the most common specifications
|
|
||||||
class DynIntEdit(DynWrap):
|
class DynIntEdit(DynWrap):
|
||||||
def __init__(self,caption='',edit_text='',sensitive=True,attrs=('editbx','editnfc'),focus_attr='editfc'):
|
""" IntEdit DynWrap'ed to the most common specifications. """
|
||||||
caption = ('editcp',caption + ':')
|
def __init__(self, caption='', edit_text='', sensitive=True,
|
||||||
edit = urwid.IntEdit(caption,edit_text)
|
attrs=('editbx', 'editnfc'), focus_attr='editfc'):
|
||||||
self.__super.__init__(edit,sensitive,attrs,focus_attr)
|
caption = ('editcp', caption + ':')
|
||||||
|
edit = urwid.IntEdit(caption, edit_text)
|
||||||
|
self.__super.__init__(edit, sensitive, attrs, focus_attr)
|
||||||
|
|
||||||
class DynRadioButton(DynWrap):
|
class DynRadioButton(DynWrap):
|
||||||
def __init__(self,group,label,state='first True',on_state_change=None, user_data=None, sensitive=True, attrs=('body','editnfc'),focus_attr='body'):
|
""" RadioButton DynWrap'ed to the most common specifications. """
|
||||||
#caption = ('editcp',caption + ':')
|
def __init__(self, group, label, state='first True', on_state_change=None,
|
||||||
button = urwid.RadioButton(group,label,state,on_state_change,user_data)
|
user_data=None, sensitive=True, attrs=('body', 'editnfc'),
|
||||||
self.__super.__init__(button,sensitive,attrs,focus_attr)
|
focus_attr='body'):
|
||||||
|
#caption = ('editcp', caption + ':')
|
||||||
|
button = urwid.RadioButton(group, label, state, on_state_change,
|
||||||
|
user_data)
|
||||||
|
self.__super.__init__(button, sensitive, attrs, focus_attr)
|
||||||
|
|
||||||
class MaskingEditException(Exception):
|
class MaskingEditException(Exception):
|
||||||
|
""" Custom exception. """
|
||||||
pass
|
pass
|
||||||
|
|
||||||
# Password-style edit
|
# Password-style edit
|
||||||
@@ -131,29 +142,31 @@ class MaskingEdit(urwid.Edit):
|
|||||||
edit_pos = None, layout=None, mask_mode="always",mask_char='*'):
|
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 not supported!')
|
raise MaskingEditException('Masks of more than one character are' +\
|
||||||
|
' not supported!')
|
||||||
self.mask_char = mask_char
|
self.mask_char = mask_char
|
||||||
self.__super.__init__(caption,edit_text,multiline,align,wrap,allow_tab,edit_pos,layout)
|
self.__super.__init__(caption, edit_text, multiline, align, wrap,
|
||||||
|
allow_tab, edit_pos, layout)
|
||||||
|
|
||||||
def get_caption(self):
|
def get_caption(self):
|
||||||
return self.caption
|
return self.caption
|
||||||
def get_mask_mode(self):
|
def get_mask_mode(self):
|
||||||
return self.mask_mode
|
return self.mask_mode
|
||||||
def set_mask_mode(self,mode):
|
def set_mask_mode(self, mode):
|
||||||
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())
|
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 == True):
|
if self.mask_mode == "off" or (self.mask_mode == 'no_focus' and focus):
|
||||||
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.
|
||||||
self._invalidate()
|
self._invalidate()
|
||||||
@@ -163,49 +176,50 @@ class MaskingEdit(urwid.Edit):
|
|||||||
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()
|
||||||
trans = self.get_line_translation( maxcol, (text,attr) )
|
trans = self.get_line_translation(maxcol, (text, attr))
|
||||||
canv = urwid.canvas.apply_text_layout(text, attr, trans, maxcol)
|
canv = urwid.canvas.apply_text_layout(text, attr, trans, maxcol)
|
||||||
|
|
||||||
if focus:
|
if focus:
|
||||||
canv = urwid.CompositeCanvas(canv)
|
canv = urwid.CompositeCanvas(canv)
|
||||||
canv.cursor = self.get_cursor_coords((maxcol,))
|
canv.cursor = self.get_cursor_coords((maxcol, ))
|
||||||
|
|
||||||
return canv
|
return canv
|
||||||
|
|
||||||
# Tabbed interface, mostly for use in the Preferences Dialog
|
|
||||||
class TabColumns(urwid.WidgetWrap):
|
class TabColumns(urwid.WidgetWrap):
|
||||||
"""
|
"""
|
||||||
|
Tabbed interface, mostly for use in the Preferences Dialog
|
||||||
|
|
||||||
titles_dict = dictionary of tab_contents (a SelText) : tab_widget (box)
|
titles_dict = dictionary of tab_contents (a SelText) : tab_widget (box)
|
||||||
attr = normal attributes
|
attr = normal attributes
|
||||||
attrsel = attribute when active
|
attrsel = attribute when active
|
||||||
"""
|
"""
|
||||||
# FIXME Make the bottom_part optional
|
# FIXME Make the bottom_part optional
|
||||||
def __init__(self,tab_str,tab_wid,title,bottom_part=None,attr=('body','focus'),
|
def __init__(self, tab_str, tab_wid, title, bottom_part=None,
|
||||||
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,trash = w.get_text()
|
text, _ = 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'))
|
||||||
|
|
||||||
self.tab_map = dict(zip(tab_str,tab_wid))
|
self.tab_map = dict(zip(tab_str, tab_wid))
|
||||||
self.active_tab = tab_str[0]
|
self.active_tab = tab_str[0]
|
||||||
self.columns = urwid.Columns(column_list,dividechars=1)
|
self.columns = urwid.Columns(column_list, dividechars=1)
|
||||||
#walker = urwid.SimpleListWalker([self.columns,tab_wid[0]])
|
#walker = urwid.SimpleListWalker([self.columns, tab_wid[0]])
|
||||||
#self.listbox = urwid.ListBox(walker)
|
#self.listbox = urwid.ListBox(walker)
|
||||||
self.gen_pile(tab_wid[0],True)
|
self.gen_pile(tab_wid[0], True)
|
||||||
self.frame = urwid.Frame(self.pile)
|
self.frame = urwid.Frame(self.pile)
|
||||||
self.__super.__init__(self.frame)
|
self.__super.__init__(self.frame)
|
||||||
|
|
||||||
# Make the pile in the middle
|
def gen_pile(self, lbox, firstrun=False):
|
||||||
def gen_pile(self,lbox,firstrun=False):
|
""" Make the pile in the middle. """
|
||||||
self.pile = urwid.Pile([
|
self.pile = urwid.Pile([
|
||||||
('fixed',1,urwid.Filler(self.columns,'top')),
|
('fixed', 1, urwid.Filler(self.columns, 'top')),
|
||||||
urwid.Filler(lbox,'top',height=('relative',99)),
|
urwid.Filler(lbox, 'top', height=('relative', 99)),
|
||||||
#('fixed',1,urwid.Filler(self.bottom_part,'bottom'))
|
#('fixed', 1, urwid.Filler(self.bottom_part, 'bottom'))
|
||||||
])
|
])
|
||||||
if not firstrun:
|
if not firstrun:
|
||||||
self.frame.set_body(self.pile)
|
self.frame.set_body(self.pile)
|
||||||
@@ -213,9 +227,11 @@ class TabColumns(urwid.WidgetWrap):
|
|||||||
self._invalidate()
|
self._invalidate()
|
||||||
|
|
||||||
def selectable(self):
|
def selectable(self):
|
||||||
|
""" Return whether the widget is selectable. """
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def keypress(self,size,key):
|
def keypress(self, size, key):
|
||||||
|
""" Handle keypresses. """
|
||||||
# If the key is page up or page down, move focus to the tabs and call
|
# If the key is page up or page down, move focus to the tabs and call
|
||||||
# left or right on the tabs.
|
# left or right on the tabs.
|
||||||
if key == "page up" or key == "page down":
|
if key == "page up" or key == "page down":
|
||||||
@@ -224,10 +240,10 @@ class TabColumns(urwid.WidgetWrap):
|
|||||||
newK = 'left'
|
newK = 'left'
|
||||||
else:
|
else:
|
||||||
newK = 'right'
|
newK = 'right'
|
||||||
self.keypress(size,newK)
|
self.keypress(size, newK)
|
||||||
self._w.get_body().set_focus(1)
|
self._w.get_body().set_focus(1)
|
||||||
else:
|
else:
|
||||||
key = self._w.keypress(size,key)
|
key = self._w.keypress(size, key)
|
||||||
wid = self.pile.get_focus().get_body()
|
wid = self.pile.get_focus().get_body()
|
||||||
if wid == self.columns:
|
if wid == self.columns:
|
||||||
self.active_tab.set_attr('body')
|
self.active_tab.set_attr('body')
|
||||||
@@ -237,12 +253,13 @@ class TabColumns(urwid.WidgetWrap):
|
|||||||
|
|
||||||
return key
|
return key
|
||||||
|
|
||||||
def mouse_event(self,size,event,button,x,y,focus):
|
def mouse_event(self, size, event, button, x, y, focus):
|
||||||
|
""" Handle mouse events. """
|
||||||
wid = self.pile.get_focus().get_body()
|
wid = self.pile.get_focus().get_body()
|
||||||
if wid == self.columns:
|
if wid == self.columns:
|
||||||
self.active_tab.set_attr('body')
|
self.active_tab.set_attr('body')
|
||||||
|
|
||||||
self._w.mouse_event(size,event,button,x,y,focus)
|
self._w.mouse_event(size, event, button, x, y, focus)
|
||||||
if wid == self.columns:
|
if wid == self.columns:
|
||||||
self.active_tab.set_attr('body')
|
self.active_tab.set_attr('body')
|
||||||
self.columns.get_focus().set_attr('tab active')
|
self.columns.get_focus().set_attr('tab active')
|
||||||
@@ -250,8 +267,8 @@ class TabColumns(urwid.WidgetWrap):
|
|||||||
self.gen_pile(self.tab_map[self.active_tab])
|
self.gen_pile(self.tab_map[self.active_tab])
|
||||||
|
|
||||||
|
|
||||||
### Combo box code begins here
|
|
||||||
class ComboBoxException(Exception):
|
class ComboBoxException(Exception):
|
||||||
|
""" Custom exception. """
|
||||||
pass
|
pass
|
||||||
|
|
||||||
# A "combo box" of SelTexts
|
# A "combo box" of SelTexts
|
||||||
@@ -264,10 +281,11 @@ 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"""
|
||||||
def __init__(self,list,body,ui,show_first,pos=(0,0),attr=('body','focus')):
|
def __init__(self, l, body, ui, show_first, pos=(0, 0),
|
||||||
|
attr=('body', 'focus')):
|
||||||
"""
|
"""
|
||||||
body : parent widget
|
body : parent widget
|
||||||
list : stuff to include in the combobox
|
l : stuff to include in the combobox
|
||||||
ui : the screen
|
ui : the screen
|
||||||
show_first: index of the element in the list to pick first
|
show_first: index of the element in the list to pick first
|
||||||
pos : a tuple of (row,col) where to put the list
|
pos : a tuple of (row,col) where to put the list
|
||||||
@@ -275,13 +293,13 @@ class ComboBox(urwid.WidgetWrap):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
#Calculate width and height of the menu widget:
|
#Calculate width and height of the menu widget:
|
||||||
height = len(list)
|
height = len(l)
|
||||||
width = 0
|
width = 0
|
||||||
for entry in list:
|
for entry in l:
|
||||||
if len(entry) > width:
|
if len(entry) > width:
|
||||||
width = len(entry)
|
width = len(entry)
|
||||||
content = [urwid.AttrWrap(SelText(w), attr[0], attr[1])
|
content = [urwid.AttrWrap(SelText(w), attr[0], attr[1])
|
||||||
for w in list]
|
for w in l]
|
||||||
self._listbox = urwid.ListBox(content)
|
self._listbox = urwid.ListBox(content)
|
||||||
self._listbox.set_focus(show_first)
|
self._listbox.set_focus(show_first)
|
||||||
|
|
||||||
@@ -289,8 +307,8 @@ class ComboBox(urwid.WidgetWrap):
|
|||||||
width + 2, ('fixed top', pos[1]), height)
|
width + 2, ('fixed top', pos[1]), height)
|
||||||
self.__super.__init__(overlay)
|
self.__super.__init__(overlay)
|
||||||
|
|
||||||
def show(self,ui,display):
|
def show(self, ui, display):
|
||||||
|
""" Show widget. """
|
||||||
dim = ui.get_cols_rows()
|
dim = ui.get_cols_rows()
|
||||||
keys = True
|
keys = True
|
||||||
|
|
||||||
@@ -306,8 +324,8 @@ class ComboBox(urwid.WidgetWrap):
|
|||||||
if "esc" in keys:
|
if "esc" in keys:
|
||||||
return None
|
return None
|
||||||
if "enter" in keys:
|
if "enter" in keys:
|
||||||
(wid,pos) = self._listbox.get_focus()
|
(wid, pos) = self._listbox.get_focus()
|
||||||
(text,attr) = wid.get_text()
|
(text, attr) = wid.get_text()
|
||||||
return text
|
return text
|
||||||
|
|
||||||
for k in keys:
|
for k in keys:
|
||||||
@@ -316,11 +334,13 @@ class ComboBox(urwid.WidgetWrap):
|
|||||||
|
|
||||||
#def get_size(self):
|
#def get_size(self):
|
||||||
|
|
||||||
def __init__(self,label='',list=[],attrs=('body','editnfc'),focus_attr='focus',use_enter=True,focus=0,callback=None,user_args=None):
|
def __init__(self, label='', l=[], attrs=('body', 'editnfc'),
|
||||||
|
focus_attr='focus', use_enter=True, focus=0, callback=None,
|
||||||
|
user_args=None):
|
||||||
"""
|
"""
|
||||||
label : bit of text that preceeds the combobox. If it is "", then
|
label : bit of text that preceeds the combobox. If it is "", then
|
||||||
ignore it
|
ignore it
|
||||||
list : stuff to include in the combobox
|
l : stuff to include in the combobox
|
||||||
body : parent widget
|
body : parent widget
|
||||||
ui : the screen
|
ui : the screen
|
||||||
row : where this object is to be found onscreen
|
row : where this object is to be found onscreen
|
||||||
@@ -333,15 +353,19 @@ class ComboBox(urwid.WidgetWrap):
|
|||||||
self.label = urwid.Text(label)
|
self.label = urwid.Text(label)
|
||||||
self.attrs = attrs
|
self.attrs = attrs
|
||||||
self.focus_attr = focus_attr
|
self.focus_attr = focus_attr
|
||||||
self.list = list
|
self.list = l
|
||||||
|
|
||||||
str,trash = self.label.get_text()
|
s, _ = self.label.get_text()
|
||||||
|
|
||||||
self.overlay = None
|
self.overlay = None
|
||||||
self.cbox = DynWrap(SelText(self.DOWN_ARROW),attrs=attrs,focus_attr=focus_attr)
|
self.cbox = DynWrap(SelText(self.DOWN_ARROW), attrs=attrs,
|
||||||
|
focus_attr=focus_attr)
|
||||||
# Unicode will kill me sooner or later.
|
# Unicode will kill me sooner or later.
|
||||||
if label != '':
|
if label != '':
|
||||||
w = urwid.Columns([('fixed',len(str),self.label),self.cbox],dividechars=1)
|
w = urwid.Columns(
|
||||||
|
[('fixed', len(s), self.label), self.cbox],
|
||||||
|
dividechars=1
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
w = urwid.Columns([self.cbox])
|
w = urwid.Columns([self.cbox])
|
||||||
self.__super.__init__(w)
|
self.__super.__init__(w)
|
||||||
@@ -361,10 +385,11 @@ class ComboBox(urwid.WidgetWrap):
|
|||||||
self.parent = None
|
self.parent = None
|
||||||
self.ui = None
|
self.ui = None
|
||||||
self.row = None
|
self.row = None
|
||||||
def set_list(self,list):
|
|
||||||
self.list = list
|
|
||||||
|
|
||||||
def set_focus(self,index):
|
def set_list(self, l):
|
||||||
|
self.list = l
|
||||||
|
|
||||||
|
def set_focus(self, index):
|
||||||
if urwid.VERSION < (1, 1, 0):
|
if urwid.VERSION < (1, 1, 0):
|
||||||
self.focus = index
|
self.focus = index
|
||||||
else:
|
else:
|
||||||
@@ -375,33 +400,34 @@ class ComboBox(urwid.WidgetWrap):
|
|||||||
|
|
||||||
# API changed between urwid 0.9.8.4 and 0.9.9
|
# API changed between urwid 0.9.8.4 and 0.9.9
|
||||||
try:
|
try:
|
||||||
self.cbox.set_w(SelText(self.list[index]+self.DOWN_ARROW))
|
self.cbox.set_w(SelText(self.list[index] + self.DOWN_ARROW))
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
self.cbox._w = SelText(self.list[index]+self.DOWN_ARROW)
|
self.cbox._w = SelText(self.list[index] + self.DOWN_ARROW)
|
||||||
if self.overlay:
|
if self.overlay:
|
||||||
self.overlay._listbox.set_focus(index)
|
self.overlay._listbox.set_focus(index)
|
||||||
|
|
||||||
def rebuild_combobox(self):
|
def rebuild_combobox(self):
|
||||||
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):
|
|
||||||
str,trash = self.label.get_text()
|
def build_combobox(self, parent, ui, row):
|
||||||
|
s, _ = 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
|
||||||
|
|
||||||
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)
|
||||||
if str != '':
|
if str != '':
|
||||||
w = urwid.Columns([('fixed',len(str),self.label),self.cbox],
|
w = urwid.Columns([('fixed', len(s), self.label), self.cbox],
|
||||||
dividechars=1)
|
dividechars=1)
|
||||||
self.overlay = self.ComboSpace(self.list,parent,ui,index,
|
self.overlay = self.ComboSpace(self.list, parent, ui, index,
|
||||||
pos=(len(str)+1,row))
|
pos=(len(s) + 1, row))
|
||||||
else:
|
else:
|
||||||
w = urwid.Columns([self.cbox])
|
w = urwid.Columns([self.cbox])
|
||||||
self.overlay = self.ComboSpace(self.list,parent,ui,index,
|
self.overlay = self.ComboSpace(self.list, parent, ui, index,
|
||||||
pos=(0,row))
|
pos=(0, row))
|
||||||
|
|
||||||
self._w = w
|
self._w = w
|
||||||
self._invalidate()
|
self._invalidate()
|
||||||
@@ -410,7 +436,7 @@ class ComboBox(urwid.WidgetWrap):
|
|||||||
self.row = row
|
self.row = row
|
||||||
|
|
||||||
# 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):
|
||||||
activate = key == ' '
|
activate = key == ' '
|
||||||
if self.use_enter:
|
if self.use_enter:
|
||||||
activate = activate or key == 'enter'
|
activate = activate or key == 'enter'
|
||||||
@@ -418,14 +444,14 @@ class ComboBox(urwid.WidgetWrap):
|
|||||||
# 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 == 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 != 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 != 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 self.cbox.selectable()
|
return self.cbox.selectable()
|
||||||
@@ -441,7 +467,7 @@ class ComboBox(urwid.WidgetWrap):
|
|||||||
|
|
||||||
def get_sensitive(self):
|
def get_sensitive(self):
|
||||||
return self.cbox.get_sensitive()
|
return self.cbox.get_sensitive()
|
||||||
def set_sensitive(self,state):
|
def set_sensitive(self, state):
|
||||||
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.
|
||||||
@@ -449,7 +475,7 @@ class DialogExit(Exception):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
class Dialog2(urwid.WidgetWrap):
|
class Dialog2(urwid.WidgetWrap):
|
||||||
def __init__(self, text, height,width, body=None ):
|
def __init__(self, text, height, width, body=None ):
|
||||||
self.width = int(width)
|
self.width = int(width)
|
||||||
if width <= 0:
|
if width <= 0:
|
||||||
self.width = ('relative', 80)
|
self.width = ('relative', 80)
|
||||||
@@ -460,12 +486,14 @@ class Dialog2(urwid.WidgetWrap):
|
|||||||
self.body = body
|
self.body = body
|
||||||
if body is None:
|
if body is None:
|
||||||
# fill space with nothing
|
# fill space with nothing
|
||||||
body = urwid.Filler(urwid.Divider(),'top')
|
body = urwid.Filler(urwid.Divider(), 'top')
|
||||||
|
|
||||||
self.frame = urwid.Frame( body, focus_part='footer')
|
self.frame = urwid.Frame(body, focus_part='footer')
|
||||||
if text is not None:
|
if text is not None:
|
||||||
self.frame.header = urwid.Pile( [urwid.Text(text,align='right'),
|
self.frame.header = urwid.Pile([
|
||||||
urwid.Divider()] )
|
urwid.Text(text, align='right'),
|
||||||
|
urwid.Divider()
|
||||||
|
])
|
||||||
w = self.frame
|
w = self.frame
|
||||||
self.view = w
|
self.view = w
|
||||||
|
|
||||||
@@ -474,29 +502,33 @@ class Dialog2(urwid.WidgetWrap):
|
|||||||
l = []
|
l = []
|
||||||
maxlen = 0
|
maxlen = 0
|
||||||
for name, exitcode in buttons:
|
for name, exitcode in buttons:
|
||||||
b = urwid.Button( name, self.button_press )
|
b = urwid.Button(name, self.button_press)
|
||||||
b.exitcode = exitcode
|
b.exitcode = exitcode
|
||||||
b = urwid.AttrWrap( b, 'body','focus' )
|
b = urwid.AttrWrap(b, 'body', 'focus')
|
||||||
l.append( b )
|
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( [ urwid.Divider(),
|
self.frame.footer = urwid.Pile([
|
||||||
self.buttons ], focus_item = 1)
|
urwid.Divider(),
|
||||||
|
self.buttons
|
||||||
|
], focus_item=1)
|
||||||
|
|
||||||
def button_press(self, button):
|
def button_press(self, button):
|
||||||
raise DialogExit(button.exitcode)
|
raise DialogExit(button.exitcode)
|
||||||
|
|
||||||
def run(self,ui,parent):
|
def run(self, ui, parent):
|
||||||
ui.set_mouse_tracking()
|
ui.set_mouse_tracking()
|
||||||
size = ui.get_cols_rows()
|
size = ui.get_cols_rows()
|
||||||
overlay = urwid.Overlay(urwid.LineBox(self.view),
|
overlay = urwid.Overlay(
|
||||||
|
urwid.LineBox(self.view),
|
||||||
parent, 'center', self.width,
|
parent, 'center', self.width,
|
||||||
'middle', self.height)
|
'middle', self.height
|
||||||
|
)
|
||||||
try:
|
try:
|
||||||
while True:
|
while True:
|
||||||
canvas = overlay.render( size, focus=True )
|
canvas = overlay.render(size, focus=True)
|
||||||
ui.draw_screen( size, canvas )
|
ui.draw_screen(size, canvas)
|
||||||
keys = None
|
keys = None
|
||||||
while not keys:
|
while not keys:
|
||||||
keys = ui.get_input()
|
keys = ui.get_input()
|
||||||
@@ -507,19 +539,18 @@ class Dialog2(urwid.WidgetWrap):
|
|||||||
check_mouse_event = urwid.util.is_mouse_event
|
check_mouse_event = urwid.util.is_mouse_event
|
||||||
if check_mouse_event(k):
|
if check_mouse_event(k):
|
||||||
event, button, col, row = k
|
event, button, col, row = k
|
||||||
overlay.mouse_event( size,
|
overlay.mouse_event(size, event, button, col, row,
|
||||||
event, button, col, row,
|
|
||||||
focus=True)
|
focus=True)
|
||||||
else:
|
else:
|
||||||
if k == 'window resize':
|
if k == 'window resize':
|
||||||
size = ui.get_cols_rows()
|
size = ui.get_cols_rows()
|
||||||
k = self.view.keypress( size, k )
|
k = self.view.keypress(size, k)
|
||||||
if k == 'esc':
|
if k == 'esc':
|
||||||
raise DialogExit(-1)
|
raise DialogExit(-1)
|
||||||
if k:
|
if k:
|
||||||
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):
|
||||||
return exitcode, ""
|
return exitcode, ""
|
||||||
@@ -535,50 +566,50 @@ class TextDialog(Dialog2):
|
|||||||
body = urwid.ListBox(l)
|
body = urwid.ListBox(l)
|
||||||
body = urwid.AttrWrap(body, 'body')
|
body = urwid.AttrWrap(body, 'body')
|
||||||
|
|
||||||
Dialog2.__init__(self, header, height+2, width+2, body)
|
Dialog2.__init__(self, header, height + 2, width + 2, body)
|
||||||
if type(buttons) == list:
|
if type(buttons) == list:
|
||||||
self.add_buttons(buttons)
|
self.add_buttons(buttons)
|
||||||
else:
|
else:
|
||||||
self.add_buttons([buttons])
|
self.add_buttons([buttons])
|
||||||
|
|
||||||
def unhandled_key(self, size, k):
|
def unhandled_key(self, size, k):
|
||||||
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):
|
||||||
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):
|
||||||
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'):
|
||||||
self.frame.set_focus('footer')
|
self.frame.set_focus('footer')
|
||||||
if k == 'enter':
|
if k == 'enter':
|
||||||
# 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):
|
||||||
return exitcode, self.edit.get_edit_text()
|
return exitcode, self.edit.get_edit_text()
|
||||||
|
|
||||||
|
|
||||||
class ClickCols(urwid.WidgetWrap):
|
class ClickCols(urwid.WidgetWrap):
|
||||||
def __init__(self,items,callback=None,args=None):
|
def __init__(self, items, callback=None, args=None):
|
||||||
cols = urwid.Columns(items)
|
cols = urwid.Columns(items)
|
||||||
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):
|
||||||
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])
|
||||||
@@ -589,7 +620,7 @@ class OptCols(urwid.WidgetWrap):
|
|||||||
# 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
|
||||||
def __init__(self,tuples,handler,attrs=('body','infobar'),debug=False):
|
def __init__(self, tuples, handler, attrs=('body', 'infobar'), debug=False):
|
||||||
# Find the longest string. Keys for this bar should be no greater than
|
# Find the longest string. Keys for this bar should be no greater than
|
||||||
# 2 characters long (e.g., -> for left)
|
# 2 characters long (e.g., -> for left)
|
||||||
#maxlen = 6
|
#maxlen = 6
|
||||||
@@ -604,7 +635,7 @@ class OptCols(urwid.WidgetWrap):
|
|||||||
# 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'), \
|
||||||
@@ -618,20 +649,20 @@ class OptCols(urwid.WidgetWrap):
|
|||||||
args = cmd[0]
|
args = cmd[0]
|
||||||
#self.callbacks.append(cmd[2])
|
#self.callbacks.append(cmd[2])
|
||||||
col = ClickCols([
|
col = ClickCols([
|
||||||
('fixed',len(key)+1,urwid.Text((attrs[0],key+':')) ),
|
('fixed', len(key) + 1, urwid.Text((attrs[0], key + ':'))),
|
||||||
urwid.AttrWrap(urwid.Text(cmd[1]),attrs[1])],
|
urwid.AttrWrap(urwid.Text(cmd[1]), attrs[1])],
|
||||||
callback,args)
|
callback, args)
|
||||||
textList.append(col)
|
textList.append(col)
|
||||||
i+=1
|
i += 1
|
||||||
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)
|
||||||
self.__super.__init__(cols)
|
self.__super.__init__(cols)
|
||||||
def debugClick(self,args):
|
def debugClick(self, args):
|
||||||
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):
|
||||||
# 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)
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ dbus_service = '%DBUS_SERVICE%'
|
|||||||
systemd = '%SYSTEMD%'
|
systemd = '%SYSTEMD%'
|
||||||
logrotate = '%LOGROTATE%'
|
logrotate = '%LOGROTATE%'
|
||||||
desktop = '%DESKTOP%'
|
desktop = '%DESKTOP%'
|
||||||
backends= '%BACKENDS%'
|
backends = '%BACKENDS%'
|
||||||
daemon = '%DAEMON%'
|
daemon = '%DAEMON%'
|
||||||
curses = '%CURSES%'
|
curses = '%CURSES%'
|
||||||
gtk = '%GTK%'
|
gtk = '%GTK%'
|
||||||
@@ -88,12 +88,12 @@ no_install_ncurses = %NO_INSTALL_NCURSES%
|
|||||||
no_install_cli = %NO_INSTALL_CLI%
|
no_install_cli = %NO_INSTALL_CLI%
|
||||||
no_use_notifications = %NO_USE_NOTIFICATIONS%
|
no_use_notifications = %NO_USE_NOTIFICATIONS%
|
||||||
|
|
||||||
def chdir(file):
|
def chdir(f):
|
||||||
"""Change directory to the location of the specified file.
|
"""Change directory to the location of the specified file.
|
||||||
|
|
||||||
Keyword arguments:
|
Keyword arguments:
|
||||||
file -- the file to switch to (usually __file__)
|
f -- the file to switch to (usually __file__)
|
||||||
|
|
||||||
"""
|
"""
|
||||||
os.chdir(os.path.dirname(os.path.realpath(file)))
|
os.chdir(os.path.dirname(os.path.realpath(f)))
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
""" WICD core module. """
|
||||||
|
|||||||
@@ -36,14 +36,16 @@ try:
|
|||||||
daemon = dbusmanager.get_interface('daemon')
|
daemon = dbusmanager.get_interface('daemon')
|
||||||
wireless = dbusmanager.get_interface('wireless')
|
wireless = dbusmanager.get_interface('wireless')
|
||||||
except Exception, e:
|
except Exception, e:
|
||||||
print>>sys.stderr, "Exception caught: %s" % str(e)
|
print >> sys.stderr, "Exception caught: %s" % str(e)
|
||||||
print>>sys.stderr, 'Could not connect to daemon.'
|
print >> sys.stderr, 'Could not connect to daemon.'
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
def handler(*args):
|
def handler(*args):
|
||||||
|
""" No-op handler. """
|
||||||
pass
|
pass
|
||||||
def error_handler(*args):
|
def error_handler(*args):
|
||||||
print>>sys.stderr, 'Async error autoconnecting.'
|
""" Error handler. """
|
||||||
|
print >> sys.stderr, 'Async error autoconnecting.'
|
||||||
sys.exit(3)
|
sys.exit(3)
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
@@ -54,6 +56,6 @@ if __name__ == '__main__':
|
|||||||
daemon.AutoConnect(True, reply_handler=handler,
|
daemon.AutoConnect(True, reply_handler=handler,
|
||||||
error_handler=error_handler)
|
error_handler=error_handler)
|
||||||
except Exception, e:
|
except Exception, e:
|
||||||
print>>sys.stderr, "Exception caught: %s" % str(e)
|
print >> sys.stderr, "Exception caught: %s" % str(e)
|
||||||
print>>sys.stderr, 'Error autoconnecting.'
|
print >> sys.stderr, 'Error autoconnecting.'
|
||||||
sys.exit(2)
|
sys.exit(2)
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ import os
|
|||||||
import wicd.wpath as wpath
|
import wicd.wpath as wpath
|
||||||
|
|
||||||
def fail(backend_name, reason):
|
def fail(backend_name, reason):
|
||||||
|
""" Helper to warn the user about failure in loading backend. """
|
||||||
print "Failed to load backend %s: %s" % (backend_name, reason)
|
print "Failed to load backend %s: %s" % (backend_name, reason)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@@ -115,7 +116,8 @@ class BackendManager(object):
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
backend = self._load_backend(backend_name)
|
backend = self._load_backend(backend_name)
|
||||||
if not backend : return None
|
if not backend:
|
||||||
|
return None
|
||||||
|
|
||||||
failed = self._validate_backend(backend, backend_name)
|
failed = self._validate_backend(backend, backend_name)
|
||||||
if failed:
|
if failed:
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
""" Backends module. """
|
||||||
|
|||||||
@@ -155,7 +155,7 @@ class Interface(BaseInterface):
|
|||||||
return socket.inet_ntoa(raw_ip[20:24])
|
return socket.inet_ntoa(raw_ip[20:24])
|
||||||
|
|
||||||
@neediface(False)
|
@neediface(False)
|
||||||
def IsUp(self):
|
def IsUp(self, ifconfig=None):
|
||||||
""" Determines if the interface is up.
|
""" Determines if the interface is up.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
@@ -357,7 +357,8 @@ class WirelessInterface(Interface, BaseWirelessInterface):
|
|||||||
print "Couldn't open ctrl_interface: %s" % e
|
print "Couldn't open ctrl_interface: %s" % e
|
||||||
return None
|
return None
|
||||||
else:
|
else:
|
||||||
print "Couldn't find a wpa_supplicant ctrl_interface for iface %s" % self.iface
|
print "Couldn't find a wpa_supplicant ctrl_interface for iface %s" \
|
||||||
|
% self.iface
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def ValidateAuthentication(self, auth_time):
|
def ValidateAuthentication(self, auth_time):
|
||||||
@@ -402,7 +403,8 @@ class WirelessInterface(Interface, BaseWirelessInterface):
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
if self.verbose:
|
if self.verbose:
|
||||||
print 'wpa_supplicant ctrl_interface status query is %s' % str(status)
|
print 'wpa_supplicant ctrl_interface status query is %s' \
|
||||||
|
% str(status)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
[result] = [l for l in status if l.startswith("wpa_state=")]
|
[result] = [l for l in status if l.startswith("wpa_state=")]
|
||||||
@@ -456,7 +458,8 @@ class WirelessInterface(Interface, BaseWirelessInterface):
|
|||||||
print 'Setting up WEP'
|
print 'Setting up WEP'
|
||||||
cmd = ''.join(['iwconfig ', self.iface, ' key ',
|
cmd = ''.join(['iwconfig ', self.iface, ' key ',
|
||||||
network.get('key')])
|
network.get('key')])
|
||||||
if self.verbose: print cmd
|
if self.verbose:
|
||||||
|
print cmd
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
else:
|
else:
|
||||||
if info[5] == 'SHARED' and info[4] == 'WEP':
|
if info[5] == 'SHARED' and info[4] == 'WEP':
|
||||||
@@ -488,7 +491,8 @@ class WirelessInterface(Interface, BaseWirelessInterface):
|
|||||||
|
|
||||||
for cmd in cmd_list:
|
for cmd in cmd_list:
|
||||||
cmd = 'iwpriv ' + self.iface + ' '
|
cmd = 'iwpriv ' + self.iface + ' '
|
||||||
if self.verbose: print cmd
|
if self.verbose:
|
||||||
|
print cmd
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
|
|
||||||
@neediface("")
|
@neediface("")
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ from wicd.misc import Noneify, to_unicode
|
|||||||
from dbus import Int32
|
from dbus import Int32
|
||||||
|
|
||||||
def sanitize_config_file(path):
|
def sanitize_config_file(path):
|
||||||
|
""" Remove invalid lines from config file. """
|
||||||
conf = open(path)
|
conf = open(path)
|
||||||
newconf = ''
|
newconf = ''
|
||||||
for line in conf:
|
for line in conf:
|
||||||
@@ -56,7 +57,7 @@ class ConfigManager(RawConfigParser):
|
|||||||
sanitize_config_file(path)
|
sanitize_config_file(path)
|
||||||
try:
|
try:
|
||||||
self.read(path)
|
self.read(path)
|
||||||
except ParsingError, e:
|
except ParsingError:
|
||||||
self.write()
|
self.write()
|
||||||
try:
|
try:
|
||||||
self.read(path)
|
self.read(path)
|
||||||
@@ -121,15 +122,18 @@ class ConfigManager(RawConfigParser):
|
|||||||
if default:
|
if default:
|
||||||
if self.debug:
|
if self.debug:
|
||||||
# mask out sensitive information
|
# mask out sensitive information
|
||||||
if option in ['apsk', 'password', 'identity', 'private_key', \
|
if option in ['apsk', 'password', 'identity', \
|
||||||
'private_key_passwd', 'key', 'passphrase']:
|
'private_key', 'private_key_passwd', \
|
||||||
print ''.join(['found ', option, ' in configuration *****'])
|
'key', 'passphrase']:
|
||||||
|
print ''.join(['found ', option, \
|
||||||
|
' in configuration *****'])
|
||||||
else:
|
else:
|
||||||
print ''.join(['found ', option, ' in configuration ',
|
print ''.join(['found ', option, ' in configuration ',
|
||||||
str(ret)])
|
str(ret)])
|
||||||
else:
|
else:
|
||||||
if default != "__None__":
|
if default != "__None__":
|
||||||
print 'did not find %s in configuration, setting default %s' % (option, str(default))
|
print 'did not find %s in configuration, setting default %s' \
|
||||||
|
% (option, str(default))
|
||||||
self.set(section, option, str(default), write=True)
|
self.set(section, option, str(default), write=True)
|
||||||
ret = default
|
ret = default
|
||||||
else:
|
else:
|
||||||
@@ -196,7 +200,8 @@ class ConfigManager(RawConfigParser):
|
|||||||
p = RawConfigParser()
|
p = RawConfigParser()
|
||||||
p.readfp(codecs.open(fname, 'r', 'utf-8'))
|
p.readfp(codecs.open(fname, 'r', 'utf-8'))
|
||||||
for section_name in p.sections():
|
for section_name in p.sections():
|
||||||
# New files override old, so remove first to avoid DuplicateSectionError.
|
# New files override old, so remove first to avoid
|
||||||
|
# DuplicateSectionError.
|
||||||
self.remove_section(section_name)
|
self.remove_section(section_name)
|
||||||
self.add_section(section_name)
|
self.add_section(section_name)
|
||||||
for (name, value) in p.items(section_name):
|
for (name, value) in p.items(section_name):
|
||||||
@@ -206,6 +211,7 @@ class ConfigManager(RawConfigParser):
|
|||||||
|
|
||||||
|
|
||||||
def _copy_section(self, name):
|
def _copy_section(self, name):
|
||||||
|
""" Copy whole section from config file. """
|
||||||
p = ConfigManager("", self.debug, self.mrk_ws)
|
p = ConfigManager("", self.debug, self.mrk_ws)
|
||||||
p.add_section(name)
|
p.add_section(name)
|
||||||
for (iname, value) in self.items(name):
|
for (iname, value) in self.items(name):
|
||||||
@@ -215,7 +221,7 @@ class ConfigManager(RawConfigParser):
|
|||||||
p.remove_option(name, '_filename_')
|
p.remove_option(name, '_filename_')
|
||||||
return p
|
return p
|
||||||
|
|
||||||
def write(self):
|
def write(self, fp):
|
||||||
""" Writes the loaded config file to disk. """
|
""" Writes the loaded config file to disk. """
|
||||||
in_this_file = []
|
in_this_file = []
|
||||||
for sname in sorted(self.sections()):
|
for sname in sorted(self.sections()):
|
||||||
|
|||||||
@@ -33,21 +33,27 @@ else:
|
|||||||
DBUS_MANAGER = None
|
DBUS_MANAGER = None
|
||||||
|
|
||||||
def get_dbus_ifaces():
|
def get_dbus_ifaces():
|
||||||
|
""" Return available DBus interfaces. """
|
||||||
return DBUS_MANAGER.get_dbus_ifaces()
|
return DBUS_MANAGER.get_dbus_ifaces()
|
||||||
|
|
||||||
def get_interface(iface):
|
def get_interface(iface):
|
||||||
|
""" Return specified interface. """
|
||||||
return DBUS_MANAGER.get_interface(iface)
|
return DBUS_MANAGER.get_interface(iface)
|
||||||
|
|
||||||
def get_bus():
|
def get_bus():
|
||||||
|
""" Return the loaded System Bus. """
|
||||||
return DBUS_MANAGER.get_bus()
|
return DBUS_MANAGER.get_bus()
|
||||||
|
|
||||||
def set_mainloop():
|
def set_mainloop(loop):
|
||||||
return DBUS_MANAGER.set_mainloop()
|
""" Set DBus main loop. """
|
||||||
|
return DBUS_MANAGER.set_mainloop(loop)
|
||||||
|
|
||||||
def connect_to_dbus():
|
def connect_to_dbus():
|
||||||
|
""" Connect to DBus. """
|
||||||
return DBUS_MANAGER.connect_to_dbus()
|
return DBUS_MANAGER.connect_to_dbus()
|
||||||
|
|
||||||
def threads_init():
|
def threads_init():
|
||||||
|
""" Init GLib threads. """
|
||||||
dbus.mainloop.glib.threads_init()
|
dbus.mainloop.glib.threads_init()
|
||||||
|
|
||||||
|
|
||||||
@@ -59,12 +65,14 @@ class DBusManager(object):
|
|||||||
|
|
||||||
def get_dbus_ifaces(self):
|
def get_dbus_ifaces(self):
|
||||||
""" Returns a dict of dbus interfaces. """
|
""" Returns a dict of dbus interfaces. """
|
||||||
if not self._dbus_ifaces: connect_to_dbus()
|
if not self._dbus_ifaces:
|
||||||
|
connect_to_dbus()
|
||||||
return self._dbus_ifaces
|
return self._dbus_ifaces
|
||||||
|
|
||||||
def get_interface(self, iface):
|
def get_interface(self, iface):
|
||||||
""" Returns a DBus Interface. """
|
""" Returns a DBus Interface. """
|
||||||
if not self._dbus_ifaces: connect_to_dbus()
|
if not self._dbus_ifaces:
|
||||||
|
connect_to_dbus()
|
||||||
return self._dbus_ifaces[iface]
|
return self._dbus_ifaces[iface]
|
||||||
|
|
||||||
def get_bus(self):
|
def get_bus(self):
|
||||||
@@ -72,6 +80,7 @@ class DBusManager(object):
|
|||||||
return self._bus
|
return self._bus
|
||||||
|
|
||||||
def set_mainloop(self, loop):
|
def set_mainloop(self, loop):
|
||||||
|
""" Set DBus main loop. """
|
||||||
dbus.set_default_main_loop(loop)
|
dbus.set_default_main_loop(loop)
|
||||||
|
|
||||||
def connect_to_dbus(self):
|
def connect_to_dbus(self):
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ import os
|
|||||||
import time
|
import time
|
||||||
|
|
||||||
class SizeError(IOError):
|
class SizeError(IOError):
|
||||||
|
""" Custom error class. """
|
||||||
pass
|
pass
|
||||||
|
|
||||||
class LogFile(file):
|
class LogFile(file):
|
||||||
@@ -48,7 +49,8 @@ class LogFile(file):
|
|||||||
self.written += len(data)
|
self.written += len(data)
|
||||||
|
|
||||||
data = data.decode('utf-8').encode('utf-8')
|
data = data.decode('utf-8').encode('utf-8')
|
||||||
if len(data) <= 0: return
|
if len(data) <= 0:
|
||||||
|
return
|
||||||
if self.eol:
|
if self.eol:
|
||||||
super(LogFile, self).write(self.get_time() + ' :: ')
|
super(LogFile, self).write(self.get_time() + ' :: ')
|
||||||
self.eol = False
|
self.eol = False
|
||||||
@@ -79,6 +81,7 @@ class LogFile(file):
|
|||||||
str(x[4]).rjust(2, '0'), ':', str(x[5]).rjust(2, '0')])
|
str(x[4]).rjust(2, '0'), ':', str(x[5]).rjust(2, '0')])
|
||||||
|
|
||||||
def rotate(self):
|
def rotate(self):
|
||||||
|
""" Rotate logfile. """
|
||||||
return rotate(self)
|
return rotate(self)
|
||||||
|
|
||||||
def note(self, text):
|
def note(self, text):
|
||||||
@@ -108,21 +111,25 @@ class ManagedLog(object):
|
|||||||
self._lf.maxsize, self.maxsave)
|
self._lf.maxsize, self.maxsave)
|
||||||
|
|
||||||
def write(self, data):
|
def write(self, data):
|
||||||
|
""" Write logfile. """
|
||||||
try:
|
try:
|
||||||
self._lf.write(data)
|
self._lf.write(data)
|
||||||
except SizeError:
|
except SizeError:
|
||||||
self._lf = rotate(self._lf, self.maxsave)
|
self._lf = rotate(self._lf, self.maxsave)
|
||||||
|
|
||||||
def note(self, data):
|
def note(self, data):
|
||||||
|
""" Write a note to the logfile. """
|
||||||
try:
|
try:
|
||||||
self._lf.note(data)
|
self._lf.note(data)
|
||||||
except SizeError:
|
except SizeError:
|
||||||
self._lf = rotate(self._lf, self.maxsave)
|
self._lf = rotate(self._lf, self.maxsave)
|
||||||
|
|
||||||
def written(self):
|
def written(self):
|
||||||
|
""" Return whether the logfile was written. """
|
||||||
return self._lf.written
|
return self._lf.written
|
||||||
|
|
||||||
def rotate(self):
|
def rotate(self):
|
||||||
|
""" Rotate logfile. """
|
||||||
self._lf = rotate(self._lf, self.maxsave)
|
self._lf = rotate(self._lf, self.maxsave)
|
||||||
|
|
||||||
# auto-delegate remaining methods (but you should not read or seek an open
|
# auto-delegate remaining methods (but you should not read or seek an open
|
||||||
@@ -133,7 +140,9 @@ class ManagedLog(object):
|
|||||||
|
|
||||||
# useful for logged stdout for daemon processes
|
# useful for logged stdout for daemon processes
|
||||||
class ManagedStdio(ManagedLog):
|
class ManagedStdio(ManagedLog):
|
||||||
|
""" Manage stdout/stderr. """
|
||||||
def write(self, data):
|
def write(self, data):
|
||||||
|
""" Write logfile to disk. """
|
||||||
try:
|
try:
|
||||||
self._lf.write(data)
|
self._lf.write(data)
|
||||||
except SizeError:
|
except SizeError:
|
||||||
@@ -147,6 +156,7 @@ class ManagedStdio(ManagedLog):
|
|||||||
|
|
||||||
|
|
||||||
def rotate(fileobj, maxsave=9):
|
def rotate(fileobj, maxsave=9):
|
||||||
|
""" Rotate fileobj. """
|
||||||
name = fileobj.name
|
name = fileobj.name
|
||||||
mode = fileobj.mode
|
mode = fileobj.mode
|
||||||
maxsize = fileobj.maxsize
|
maxsize = fileobj.maxsize
|
||||||
@@ -157,6 +167,7 @@ def rotate(fileobj, maxsave=9):
|
|||||||
|
|
||||||
# assumes basename logfile is closed.
|
# assumes basename logfile is closed.
|
||||||
def shiftlogs(basename, maxsave):
|
def shiftlogs(basename, maxsave):
|
||||||
|
""" Shift logfiles. """
|
||||||
topname = "%s.%d" % (basename, maxsave)
|
topname = "%s.%d" % (basename, maxsave)
|
||||||
if os.path.isfile(topname):
|
if os.path.isfile(topname):
|
||||||
os.unlink(topname)
|
os.unlink(topname)
|
||||||
@@ -175,9 +186,11 @@ def shiftlogs(basename, maxsave):
|
|||||||
|
|
||||||
|
|
||||||
def open(name, maxsize=360000, maxsave=9):
|
def open(name, maxsize=360000, maxsave=9):
|
||||||
|
""" Open logfile. """
|
||||||
return ManagedLog(name, maxsize, maxsave)
|
return ManagedLog(name, maxsize, maxsave)
|
||||||
|
|
||||||
def writelog(logobj, data):
|
def writelog(logobj, data):
|
||||||
|
""" Write logfile. """
|
||||||
try:
|
try:
|
||||||
logobj.write(data)
|
logobj.write(data)
|
||||||
except SizeError:
|
except SizeError:
|
||||||
|
|||||||
30
wicd/misc.py
30
wicd/misc.py
@@ -84,7 +84,8 @@ _sudo_dict = {
|
|||||||
|
|
||||||
_status_dict = {
|
_status_dict = {
|
||||||
'aborted': _('Connection Cancelled'),
|
'aborted': _('Connection Cancelled'),
|
||||||
'association_failed': _('Connection failed: Could not contact the wireless access point.'),
|
'association_failed': _('Connection failed: Could not contact the ' + \
|
||||||
|
'wireless access point.'),
|
||||||
'bad_pass': _('Connection Failed: Bad password'),
|
'bad_pass': _('Connection Failed: Bad password'),
|
||||||
'configuring_interface': _('Configuring wireless interface...'),
|
'configuring_interface': _('Configuring wireless interface...'),
|
||||||
'dhcp_failed': _('Connection Failed: Unable to Get IP Address'),
|
'dhcp_failed': _('Connection Failed: Unable to Get IP Address'),
|
||||||
@@ -107,6 +108,7 @@ _status_dict = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class WicdError(Exception):
|
class WicdError(Exception):
|
||||||
|
""" Custom Exception type. """
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
@@ -179,7 +181,8 @@ def LaunchAndWait(cmd):
|
|||||||
|
|
||||||
def IsValidIP(ip):
|
def IsValidIP(ip):
|
||||||
""" Make sure an entered IP is valid. """
|
""" Make sure an entered IP is valid. """
|
||||||
if not ip: return False
|
if not ip:
|
||||||
|
return False
|
||||||
|
|
||||||
if not IsValidIPv4(ip):
|
if not IsValidIPv4(ip):
|
||||||
if not IsValidIPv6(ip):
|
if not IsValidIPv6(ip):
|
||||||
@@ -218,9 +221,9 @@ def PromptToStartDaemon():
|
|||||||
os.spawnvpe(os.P_WAIT, sudo_prog, sudo_args, os.environ)
|
os.spawnvpe(os.P_WAIT, sudo_prog, sudo_args, os.environ)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def RunRegex(regex, string):
|
def RunRegex(regex, s):
|
||||||
""" runs a regex search on a string """
|
""" runs a regex search on a string """
|
||||||
m = regex.search(string)
|
m = regex.search(s)
|
||||||
if m:
|
if m:
|
||||||
return m.groups()[0]
|
return m.groups()[0]
|
||||||
else:
|
else:
|
||||||
@@ -271,12 +274,13 @@ def to_bool(var):
|
|||||||
var = bool(var)
|
var = bool(var)
|
||||||
return var
|
return var
|
||||||
|
|
||||||
def Noneify(variable, to_bool=True):
|
def Noneify(variable, convert_to_bool=True):
|
||||||
""" Convert string types to either None or booleans"""
|
""" Convert string types to either None or booleans"""
|
||||||
#set string Nones to real Nones
|
#set string Nones to real Nones
|
||||||
if variable in ("None", "", None):
|
if variable in ("None", "", None):
|
||||||
return None
|
return None
|
||||||
if to_bool:
|
if convert_to_bool:
|
||||||
|
# FIXME: should instead use above to_bool()?
|
||||||
if variable in ("False", "0"):
|
if variable in ("False", "0"):
|
||||||
return False
|
return False
|
||||||
if variable in ("True", "1"):
|
if variable in ("True", "1"):
|
||||||
@@ -415,8 +419,10 @@ def _parse_enc_template(enctype):
|
|||||||
print "Invalid 'optional' line found in template %s" % enctype
|
print "Invalid 'optional' line found in template %s" % enctype
|
||||||
continue
|
continue
|
||||||
elif line.startswith("protected"):
|
elif line.startswith("protected"):
|
||||||
cur_type["protected"] = __parse_field_ent(parse_ent(line, "protected"),
|
cur_type["protected"] = __parse_field_ent(
|
||||||
field_type="protected")
|
parse_ent(line, "protected"),
|
||||||
|
field_type="protected"
|
||||||
|
)
|
||||||
if not cur_type["protected"]:
|
if not cur_type["protected"]:
|
||||||
# An error occured parsing the protected line.
|
# An error occured parsing the protected line.
|
||||||
print "Invalid 'protected' line found in template %s" % enctype
|
print "Invalid 'protected' line found in template %s" % enctype
|
||||||
@@ -530,7 +536,8 @@ def detect_desktop_environment():
|
|||||||
def get_sudo_cmd(msg, prog_num=0):
|
def get_sudo_cmd(msg, prog_num=0):
|
||||||
""" Returns a graphical sudo command for generic use. """
|
""" Returns a graphical sudo command for generic use. """
|
||||||
sudo_prog = choose_sudo_prog(prog_num)
|
sudo_prog = choose_sudo_prog(prog_num)
|
||||||
if not sudo_prog: return None
|
if not sudo_prog:
|
||||||
|
return None
|
||||||
if re.search("(ktsuss|gksu|gksudo)$", sudo_prog):
|
if re.search("(ktsuss|gksu|gksudo)$", sudo_prog):
|
||||||
msg_flag = "-m"
|
msg_flag = "-m"
|
||||||
else:
|
else:
|
||||||
@@ -590,6 +597,8 @@ def stringToNone(text):
|
|||||||
return str(text)
|
return str(text)
|
||||||
|
|
||||||
def checkboxTextboxToggle(checkbox, textboxes):
|
def checkboxTextboxToggle(checkbox, textboxes):
|
||||||
|
""" Manage {de,}activation of textboxes depending on checkboxes. """
|
||||||
|
# FIXME: should be moved to UI-specific files?
|
||||||
for textbox in textboxes:
|
for textbox in textboxes:
|
||||||
textbox.set_sensitive(checkbox.get_active())
|
textbox.set_sensitive(checkbox.get_active())
|
||||||
|
|
||||||
@@ -613,7 +622,8 @@ def timeout_add(time, func, milli=False):
|
|||||||
if hasattr(gobject, "timeout_add_seconds") and not milli:
|
if hasattr(gobject, "timeout_add_seconds") and not milli:
|
||||||
return gobject.timeout_add_seconds(time, func)
|
return gobject.timeout_add_seconds(time, func)
|
||||||
else:
|
else:
|
||||||
if not milli: time = time * 1000
|
if not milli:
|
||||||
|
time = time * 1000
|
||||||
return gobject.timeout_add(time, func)
|
return gobject.timeout_add(time, func)
|
||||||
|
|
||||||
def izip_longest(*args, **kwds):
|
def izip_longest(*args, **kwds):
|
||||||
|
|||||||
@@ -47,6 +47,9 @@ wireless = dbus_dict["wireless"]
|
|||||||
mainloop = None
|
mainloop = None
|
||||||
|
|
||||||
def diewithdbus(func):
|
def diewithdbus(func):
|
||||||
|
"""
|
||||||
|
Decorator catching DBus exceptions, making wicd quit.
|
||||||
|
"""
|
||||||
def wrapper(self, *__args, **__kargs):
|
def wrapper(self, *__args, **__kargs):
|
||||||
try:
|
try:
|
||||||
ret = func(self, *__args, **__kargs)
|
ret = func(self, *__args, **__kargs)
|
||||||
@@ -86,6 +89,7 @@ class ConnectionStatus(object):
|
|||||||
self.trigger_reconnect = False
|
self.trigger_reconnect = False
|
||||||
self.__lost_dbus_count = 0
|
self.__lost_dbus_count = 0
|
||||||
self._to_time = daemon.GetBackendUpdateInterval()
|
self._to_time = daemon.GetBackendUpdateInterval()
|
||||||
|
self.update_callback = None
|
||||||
|
|
||||||
self.add_poll_callback()
|
self.add_poll_callback()
|
||||||
bus = dbusmanager.get_bus()
|
bus = dbusmanager.get_bus()
|
||||||
@@ -310,16 +314,18 @@ class ConnectionStatus(object):
|
|||||||
""" Get the correct signal strength format. """
|
""" Get the correct signal strength format. """
|
||||||
try:
|
try:
|
||||||
if daemon.GetSignalDisplayType() == 0:
|
if daemon.GetSignalDisplayType() == 0:
|
||||||
wifi_signal = int(wireless.GetCurrentSignalStrength(self.iwconfig))
|
signal = wireless.GetCurrentSignalStrength(self.iwconfig)
|
||||||
|
wifi_signal = int(signal)
|
||||||
else:
|
else:
|
||||||
|
signal = wireless.GetCurrentDBMStrength(self.iwconfig)
|
||||||
if always_positive:
|
if always_positive:
|
||||||
# because dBm is negative, add 99 to the signal. This way, if
|
# because dBm is negative, add 99 to the signal. This way,
|
||||||
# the signal drops below -99, wifi_signal will == 0, and
|
# if the signal drops below -99, wifi_signal will == 0, and
|
||||||
# an automatic reconnect will be triggered
|
# an automatic reconnect will be triggered
|
||||||
# this is only used in check_for_wireless_connection
|
# this is only used in check_for_wireless_connection
|
||||||
wifi_signal = 99 + int(wireless.GetCurrentDBMStrength(self.iwconfig))
|
wifi_signal = 99 + int(signal)
|
||||||
else:
|
else:
|
||||||
wifi_signal = int(wireless.GetCurrentDBMStrength(self.iwconfig))
|
wifi_signal = int(signal)
|
||||||
except TypeError:
|
except TypeError:
|
||||||
wifi_signal = 0
|
wifi_signal = 0
|
||||||
|
|
||||||
|
|||||||
@@ -158,25 +158,34 @@ class Controller(object):
|
|||||||
self.driver = None
|
self.driver = None
|
||||||
self.iface = None
|
self.iface = None
|
||||||
|
|
||||||
def get_debug(self): return self._debug
|
def get_debug(self):
|
||||||
|
""" Getter for debug property. """
|
||||||
|
return self._debug
|
||||||
def set_debug(self, value):
|
def set_debug(self, value):
|
||||||
|
""" Setter for debug property. """
|
||||||
self._debug = value
|
self._debug = value
|
||||||
if self.iface:
|
if self.iface:
|
||||||
self.iface.SetDebugMode(value)
|
self.iface.SetDebugMode(value)
|
||||||
debug = property(get_debug, set_debug)
|
debug = property(get_debug, set_debug)
|
||||||
|
|
||||||
def set_dhcp_client(self, value):
|
def set_dhcp_client(self, value):
|
||||||
|
""" Setter for dhcp_client property. """
|
||||||
self._dhcp_client = value
|
self._dhcp_client = value
|
||||||
if self.iface:
|
if self.iface:
|
||||||
self.iface.DHCP_CLIENT = value
|
self.iface.DHCP_CLIENT = value
|
||||||
def get_dhcp_client(self): return self._dhcp_client
|
def get_dhcp_client(self):
|
||||||
|
""" Getter for dhcp_client property. """
|
||||||
|
return self._dhcp_client
|
||||||
dhcp_client = property(get_dhcp_client, set_dhcp_client)
|
dhcp_client = property(get_dhcp_client, set_dhcp_client)
|
||||||
|
|
||||||
def set_flush_tool(self, value):
|
def set_flush_tool(self, value):
|
||||||
|
""" Setter for flush_tool property. """
|
||||||
self._flush_tool = value
|
self._flush_tool = value
|
||||||
if self.iface:
|
if self.iface:
|
||||||
self.iface.flush_tool = value
|
self.iface.flush_tool = value
|
||||||
def get_flush_tool(self): return self._flush_tool
|
def get_flush_tool(self):
|
||||||
|
""" Getter for flush_tool property. """
|
||||||
|
return self._flush_tool
|
||||||
flush_tool = property(get_flush_tool, set_flush_tool)
|
flush_tool = property(get_flush_tool, set_flush_tool)
|
||||||
|
|
||||||
def LoadBackend(self, backend_name):
|
def LoadBackend(self, backend_name):
|
||||||
@@ -337,6 +346,9 @@ class ConnectThread(threading.Thread):
|
|||||||
|
|
||||||
self.SetStatus('interface_down')
|
self.SetStatus('interface_down')
|
||||||
|
|
||||||
|
def _connect(self):
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
def run(self):
|
def run(self):
|
||||||
self.connect_result = "failed"
|
self.connect_result = "failed"
|
||||||
try:
|
try:
|
||||||
@@ -345,12 +357,15 @@ class ConnectThread(threading.Thread):
|
|||||||
self.is_connecting = False
|
self.is_connecting = False
|
||||||
|
|
||||||
def set_should_die(self, val):
|
def set_should_die(self, val):
|
||||||
|
""" Setter for should_die property. """
|
||||||
self.lock.acquire()
|
self.lock.acquire()
|
||||||
try:
|
try:
|
||||||
self._should_die = val
|
self._should_die = val
|
||||||
finally:
|
finally:
|
||||||
self.lock.release()
|
self.lock.release()
|
||||||
def get_should_die(self): return self._should_die
|
def get_should_die(self):
|
||||||
|
""" Getter for should_die property. """
|
||||||
|
return self._should_die
|
||||||
should_die = property(get_should_die, set_should_die)
|
should_die = property(get_should_die, set_should_die)
|
||||||
|
|
||||||
def SetStatus(self, status):
|
def SetStatus(self, status):
|
||||||
@@ -401,6 +416,7 @@ class ConnectThread(threading.Thread):
|
|||||||
|
|
||||||
@abortable
|
@abortable
|
||||||
def run_global_scripts_if_needed(self, script_dir, extra_parameters=()):
|
def run_global_scripts_if_needed(self, script_dir, extra_parameters=()):
|
||||||
|
""" Run global scripts if needed. '"""
|
||||||
misc.ExecuteScripts(script_dir, verbose=self.debug,
|
misc.ExecuteScripts(script_dir, verbose=self.debug,
|
||||||
extra_parameters=extra_parameters)
|
extra_parameters=extra_parameters)
|
||||||
|
|
||||||
@@ -458,7 +474,7 @@ class ConnectThread(threading.Thread):
|
|||||||
hname = os.uname()[1]
|
hname = os.uname()[1]
|
||||||
else:
|
else:
|
||||||
hname = self.network['dhcphostname']
|
hname = self.network['dhcphostname']
|
||||||
print "Running DHCP with hostname",hname
|
print "Running DHCP with hostname", hname
|
||||||
dhcp_status = iface.StartDHCP(hname)
|
dhcp_status = iface.StartDHCP(hname)
|
||||||
if dhcp_status in ['no_dhcp_offers', 'dhcp_failed']:
|
if dhcp_status in ['no_dhcp_offers', 'dhcp_failed']:
|
||||||
if self.connect_result != "aborted":
|
if self.connect_result != "aborted":
|
||||||
@@ -564,22 +580,30 @@ class Wireless(Controller):
|
|||||||
self.should_verify_ap = True
|
self.should_verify_ap = True
|
||||||
|
|
||||||
def set_wireless_iface(self, value):
|
def set_wireless_iface(self, value):
|
||||||
|
""" Setter for wireless_interface property. """
|
||||||
self._wireless_interface = value
|
self._wireless_interface = value
|
||||||
if self.wiface:
|
if self.wiface:
|
||||||
self.wiface.SetInterface(value)
|
self.wiface.SetInterface(value)
|
||||||
def get_wireless_iface(self): return self._wireless_interface
|
def get_wireless_iface(self):
|
||||||
|
""" Getter for wireless_interface property. """
|
||||||
|
return self._wireless_interface
|
||||||
wireless_interface = property(get_wireless_iface, set_wireless_iface)
|
wireless_interface = property(get_wireless_iface, set_wireless_iface)
|
||||||
|
|
||||||
def set_wpa_driver(self, value):
|
def set_wpa_driver(self, value):
|
||||||
|
""" Setter for wpa_driver property. """
|
||||||
self._wpa_driver = value
|
self._wpa_driver = value
|
||||||
if self.wiface:
|
if self.wiface:
|
||||||
self.SetWPADriver(value)
|
self.SetWPADriver(value)
|
||||||
def get_wpa_driver(self): return self._wpa_driver
|
def get_wpa_driver(self):
|
||||||
|
""" Getter for wpa_driver property. """
|
||||||
|
return self._wpa_driver
|
||||||
wpa_driver = property(get_wpa_driver, set_wpa_driver)
|
wpa_driver = property(get_wpa_driver, set_wpa_driver)
|
||||||
|
|
||||||
def set_iface(self, value):
|
def set_iface(self, value):
|
||||||
|
""" Setter for iface property. """
|
||||||
self.wiface = value
|
self.wiface = value
|
||||||
def get_iface(self):
|
def get_iface(self):
|
||||||
|
""" Getter for iface property. """
|
||||||
return self.wiface
|
return self.wiface
|
||||||
iface = property(get_iface, set_iface)
|
iface = property(get_iface, set_iface)
|
||||||
|
|
||||||
@@ -591,8 +615,9 @@ class Wireless(Controller):
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
Controller.LoadBackend(self, backend)
|
Controller.LoadBackend(self, backend)
|
||||||
if self._backend:
|
backend = self._backend
|
||||||
self.wiface = self._backend.WirelessInterface(self.wireless_interface,
|
if backend:
|
||||||
|
self.wiface = backend.WirelessInterface(self.wireless_interface,
|
||||||
self.debug, self.wpa_driver)
|
self.debug, self.wpa_driver)
|
||||||
|
|
||||||
def Scan(self, essid=None):
|
def Scan(self, essid=None):
|
||||||
@@ -606,13 +631,15 @@ class Wireless(Controller):
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
def comp(x, y):
|
def comp(x, y):
|
||||||
|
""" Custom sorting function. """
|
||||||
if 'quality' in x:
|
if 'quality' in x:
|
||||||
key = 'quality'
|
key = 'quality'
|
||||||
else:
|
else:
|
||||||
key = 'strength'
|
key = 'strength'
|
||||||
return cmp(x[key], y[key])
|
return cmp(x[key], y[key])
|
||||||
|
|
||||||
if not self.wiface: return []
|
if not self.wiface:
|
||||||
|
return []
|
||||||
wiface = self.wiface
|
wiface = self.wiface
|
||||||
|
|
||||||
# Prepare the interface for scanning
|
# Prepare the interface for scanning
|
||||||
@@ -639,7 +666,8 @@ class Wireless(Controller):
|
|||||||
network -- network to connect to
|
network -- network to connect to
|
||||||
|
|
||||||
"""
|
"""
|
||||||
if not self.wiface: return False
|
if not self.wiface:
|
||||||
|
return False
|
||||||
|
|
||||||
self.connecting_thread = WirelessConnectThread(network,
|
self.connecting_thread = WirelessConnectThread(network,
|
||||||
self.wireless_interface, self.wpa_driver, self.before_script,
|
self.wireless_interface, self.wpa_driver, self.before_script,
|
||||||
@@ -739,6 +767,7 @@ class Wireless(Controller):
|
|||||||
return BACKEND.GetWpaSupplicantDrivers()
|
return BACKEND.GetWpaSupplicantDrivers()
|
||||||
|
|
||||||
def StopWPA(self):
|
def StopWPA(self):
|
||||||
|
""" Stop wpa_supplicant. """
|
||||||
return self.wiface.StopWPA()
|
return self.wiface.StopWPA()
|
||||||
|
|
||||||
def CreateAdHocNetwork(self, essid, channel, ip, enctype, key,
|
def CreateAdHocNetwork(self, essid, channel, ip, enctype, key,
|
||||||
@@ -821,7 +850,8 @@ class Wireless(Controller):
|
|||||||
"""
|
"""
|
||||||
cmd = 'rfkill list'
|
cmd = 'rfkill list'
|
||||||
rfkill_out = misc.Run(cmd)
|
rfkill_out = misc.Run(cmd)
|
||||||
soft_blocks = filter(lambda x: x.startswith('Soft'), rfkill_out.split('\t'))
|
soft_blocks = filter(lambda x: x.startswith('Soft'),
|
||||||
|
rfkill_out.split('\t'))
|
||||||
for line in map(lambda x: x.strip(), soft_blocks):
|
for line in map(lambda x: x.strip(), soft_blocks):
|
||||||
if line.endswith('yes'):
|
if line.endswith('yes'):
|
||||||
return True
|
return True
|
||||||
@@ -1015,7 +1045,8 @@ class WirelessConnectThread(ConnectThread):
|
|||||||
# cards).
|
# cards).
|
||||||
if self.debug:
|
if self.debug:
|
||||||
print "enctype is %s" % self.network.get('enctype')
|
print "enctype is %s" % self.network.get('enctype')
|
||||||
if self.network.get('key') and 'wpa' in str(self.network.get('enctype')):
|
if self.network.get('key') and \
|
||||||
|
'wpa' in str(self.network.get('enctype')):
|
||||||
self.SetStatus('generating_psk')
|
self.SetStatus('generating_psk')
|
||||||
print 'Generating psk...'
|
print 'Generating psk...'
|
||||||
self.network['psk'] = wiface.GeneratePSK(self.network)
|
self.network['psk'] = wiface.GeneratePSK(self.network)
|
||||||
@@ -1044,23 +1075,31 @@ class Wired(Controller):
|
|||||||
self.liface = None
|
self.liface = None
|
||||||
|
|
||||||
def set_link_detect(self, value):
|
def set_link_detect(self, value):
|
||||||
|
""" Setter for link_detect property. """
|
||||||
self._link_detect = value
|
self._link_detect = value
|
||||||
if self.liface:
|
if self.liface:
|
||||||
self.liface.link_detect = value
|
self.liface.link_detect = value
|
||||||
def get_link_detect(self): return self._link_detect
|
def get_link_detect(self):
|
||||||
|
""" Getter for link_detect property. """
|
||||||
|
return self._link_detect
|
||||||
link_detect = property(get_link_detect, set_link_detect)
|
link_detect = property(get_link_detect, set_link_detect)
|
||||||
|
|
||||||
|
|
||||||
def set_wired_iface(self, value):
|
def set_wired_iface(self, value):
|
||||||
|
""" Setter for wired_interface property. """
|
||||||
self._wired_interface = value
|
self._wired_interface = value
|
||||||
if self.liface:
|
if self.liface:
|
||||||
self.liface.SetInterface(value)
|
self.liface.SetInterface(value)
|
||||||
def get_wired_iface(self): return self._wired_interface
|
def get_wired_iface(self):
|
||||||
|
""" Getter for wired_interface property. """
|
||||||
|
return self._wired_interface
|
||||||
wired_interface = property(get_wired_iface, set_wired_iface)
|
wired_interface = property(get_wired_iface, set_wired_iface)
|
||||||
|
|
||||||
def set_iface(self, value):
|
def set_iface(self, value):
|
||||||
|
""" Setter for iface property. """
|
||||||
self.liface = value
|
self.liface = value
|
||||||
def get_iface(self):
|
def get_iface(self):
|
||||||
|
""" Getter for iface property. """
|
||||||
return self.liface
|
return self.liface
|
||||||
iface = property(get_iface, set_iface)
|
iface = property(get_iface, set_iface)
|
||||||
|
|
||||||
@@ -1087,7 +1126,8 @@ class Wired(Controller):
|
|||||||
network -- network to connect to
|
network -- network to connect to
|
||||||
|
|
||||||
"""
|
"""
|
||||||
if not self.liface: return False
|
if not self.liface:
|
||||||
|
return False
|
||||||
self.connecting_thread = WiredConnectThread(network,
|
self.connecting_thread = WiredConnectThread(network,
|
||||||
self.wired_interface, self.before_script, self.after_script,
|
self.wired_interface, self.before_script, self.after_script,
|
||||||
self.pre_disconnect_script, self.post_disconnect_script,
|
self.pre_disconnect_script, self.post_disconnect_script,
|
||||||
@@ -1103,6 +1143,7 @@ class Wired(Controller):
|
|||||||
self.StopWPA()
|
self.StopWPA()
|
||||||
|
|
||||||
def StopWPA(self):
|
def StopWPA(self):
|
||||||
|
""" Stop wpa_supplicant. """
|
||||||
self.liface.StopWPA()
|
self.liface.StopWPA()
|
||||||
|
|
||||||
def DetectWiredInterface(self):
|
def DetectWiredInterface(self):
|
||||||
|
|||||||
@@ -33,19 +33,17 @@ try:
|
|||||||
proxy_obj = bus.get_object('org.wicd.daemon', '/org/wicd/daemon')
|
proxy_obj = bus.get_object('org.wicd.daemon', '/org/wicd/daemon')
|
||||||
daemon = dbus.Interface(proxy_obj, 'org.wicd.daemon')
|
daemon = dbus.Interface(proxy_obj, 'org.wicd.daemon')
|
||||||
except Exception, e:
|
except Exception, e:
|
||||||
print>>sys.stderr, "Exception caught: %s" % str(e)
|
print >> sys.stderr, "Exception caught: %s" % str(e)
|
||||||
print>>sys.stderr, 'Could not connect to daemon.'
|
print >> sys.stderr, 'Could not connect to daemon.'
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
try:
|
try:
|
||||||
daemon.Disconnect()
|
daemon.Disconnect()
|
||||||
daemon.SetForcedDisconnect(False)
|
daemon.SetForcedDisconnect(False)
|
||||||
daemon.SetSuspend(True)
|
daemon.SetSuspend(True)
|
||||||
except Exception, e:
|
except Exception, e:
|
||||||
print>>sys.stderr, "Exception caught: %s" % str(e)
|
print >> sys.stderr, "Exception caught: %s" % str(e)
|
||||||
print>>sys.stderr, 'Error setting suspend.'
|
print >> sys.stderr, 'Error setting suspend.'
|
||||||
sys.exit(2)
|
sys.exit(2)
|
||||||
|
|
||||||
|
|||||||
@@ -52,8 +52,7 @@ def get_gettext():
|
|||||||
langs += ["en_US"]
|
langs += ["en_US"]
|
||||||
lang = gettext.translation('wicd', local_path, languages=langs,
|
lang = gettext.translation('wicd', local_path, languages=langs,
|
||||||
fallback=True)
|
fallback=True)
|
||||||
_ = lang.ugettext
|
return lang.ugettext
|
||||||
return _
|
|
||||||
|
|
||||||
_ = get_gettext()
|
_ = get_gettext()
|
||||||
|
|
||||||
@@ -67,13 +66,17 @@ language = {}
|
|||||||
# FIXME: these were present in wicd 1.7.0, can't find where they are.
|
# FIXME: these were present in wicd 1.7.0, can't find where they are.
|
||||||
# Leaving here for future reference, they should be removed whenever
|
# Leaving here for future reference, they should be removed whenever
|
||||||
# possible.
|
# possible.
|
||||||
#language['cannot_start_daemon'] = _('''Unable to connect to wicd daemon DBus interface. This typically means there was a problem starting the daemon. Check the wicd log for more information.''')
|
#language['cannot_start_daemon'] = _('Unable to connect to wicd daemon ' + \
|
||||||
#language['backend_alert'] = _('''Changes to your backend won't occur until the daemon is restarted.''')
|
# 'DBus interface. This typically means there was a problem starting ' + \
|
||||||
#language['about_help'] = _('''Stop a network connection in progress''')
|
# 'the daemon. Check the wicd log for more information.')
|
||||||
#language['connect'] = _('''Connect''')
|
#language['backend_alert'] = _('Changes to your backend won't occur until ' + \
|
||||||
|
# 'the daemon is restarted.')
|
||||||
|
#language['about_help'] = _('Stop a network connection in progress')
|
||||||
|
#language['connect'] = _('Connect')
|
||||||
|
|
||||||
# from templates, dict populated with:
|
# from templates, dict populated with:
|
||||||
# grep -R "*" encryption/templates/ | tr " " "\n" | grep "^*" | sed -e "s/*//"| sort -u | tr [A-Z] [a-z]
|
# grep -R "*" encryption/templates/ | tr " " "\n" | grep "^*" | \
|
||||||
|
# sed -e "s/*//" | sort -u | tr [A-Z] [a-z]
|
||||||
language['authentication'] = _('Authentication')
|
language['authentication'] = _('Authentication')
|
||||||
language['domain'] = _('Domain')
|
language['domain'] = _('Domain')
|
||||||
language['identity'] = _('Identity')
|
language['identity'] = _('Identity')
|
||||||
|
|||||||
@@ -71,7 +71,7 @@ wireless_conf = os.path.join(wpath.etc, "wireless-settings.conf")
|
|||||||
wired_conf = os.path.join(wpath.etc, "wired-settings.conf")
|
wired_conf = os.path.join(wpath.etc, "wired-settings.conf")
|
||||||
dhclient_conf = os.path.join(wpath.etc, "dhclient.conf.template")
|
dhclient_conf = os.path.join(wpath.etc, "dhclient.conf.template")
|
||||||
|
|
||||||
class WicdDaemon(dbus.service.Object):
|
class WicdDaemon(dbus.service.Object, object):
|
||||||
""" The main wicd daemon class.
|
""" The main wicd daemon class.
|
||||||
|
|
||||||
This class mostly contains exported DBus methods that are not
|
This class mostly contains exported DBus methods that are not
|
||||||
@@ -107,6 +107,17 @@ class WicdDaemon(dbus.service.Object):
|
|||||||
self.link_detect_tool = 0
|
self.link_detect_tool = 0
|
||||||
self.flush_tool = 0
|
self.flush_tool = 0
|
||||||
self.sudo_app = 0
|
self.sudo_app = 0
|
||||||
|
self.use_global_dns = False
|
||||||
|
self.always_show_wired_interface = True
|
||||||
|
self.wired_connect_mode = 1
|
||||||
|
self.wired_bus.connect_mode = 1
|
||||||
|
self.dns_dom = None
|
||||||
|
self.signal_display_type = 0
|
||||||
|
self.dns1 = None
|
||||||
|
self.dns2 = None
|
||||||
|
self.dns3 = None
|
||||||
|
self.search_dom = None
|
||||||
|
self.auto_reconnect = True
|
||||||
|
|
||||||
# This will speed up the scanning process - if a client doesn't
|
# This will speed up the scanning process - if a client doesn't
|
||||||
# need a fresh scan, just feed them the old one. A fresh scan
|
# need a fresh scan, just feed them the old one. A fresh scan
|
||||||
@@ -126,8 +137,10 @@ class WicdDaemon(dbus.service.Object):
|
|||||||
self.wireless_bus.Scan()
|
self.wireless_bus.Scan()
|
||||||
|
|
||||||
def get_debug_mode(self):
|
def get_debug_mode(self):
|
||||||
|
""" Getter for debug_mode property. """
|
||||||
return self._debug_mode
|
return self._debug_mode
|
||||||
def set_debug_mode(self, mode):
|
def set_debug_mode(self, mode):
|
||||||
|
""" Setter for debug_mode property. """
|
||||||
self._debug_mode = mode
|
self._debug_mode = mode
|
||||||
self.config.debug = mode
|
self.config.debug = mode
|
||||||
debug_mode = property(get_debug_mode, set_debug_mode)
|
debug_mode = property(get_debug_mode, set_debug_mode)
|
||||||
@@ -192,11 +205,13 @@ class WicdDaemon(dbus.service.Object):
|
|||||||
self.dns3 = dns3
|
self.dns3 = dns3
|
||||||
self.wifi.global_dns_3 = dns3
|
self.wifi.global_dns_3 = dns3
|
||||||
self.wired.global_dns_3 = dns3
|
self.wired.global_dns_3 = dns3
|
||||||
self.config.set("Settings", "global_dns_dom", misc.noneToString(dns_dom))
|
self.config.set("Settings", "global_dns_dom",
|
||||||
|
misc.noneToString(dns_dom))
|
||||||
self.dns_dom = dns_dom
|
self.dns_dom = dns_dom
|
||||||
self.wifi.dns_dom = dns_dom
|
self.wifi.dns_dom = dns_dom
|
||||||
self.wired.dns_dom = dns_dom
|
self.wired.dns_dom = dns_dom
|
||||||
self.config.set("Settings", "global_search_dom", misc.noneToString(search_dom))
|
self.config.set("Settings", "global_search_dom",
|
||||||
|
misc.noneToString(search_dom))
|
||||||
self.search_dom = search_dom
|
self.search_dom = search_dom
|
||||||
self.wifi.global_search_dom = search_dom
|
self.wifi.global_search_dom = search_dom
|
||||||
self.wired.global_search_dom = search_dom
|
self.wired.global_search_dom = search_dom
|
||||||
@@ -211,7 +226,8 @@ class WicdDaemon(dbus.service.Object):
|
|||||||
print "setting backend to %s" % backend
|
print "setting backend to %s" % backend
|
||||||
backends = networking.BACKEND_MGR.get_available_backends()
|
backends = networking.BACKEND_MGR.get_available_backends()
|
||||||
if backend not in backends:
|
if backend not in backends:
|
||||||
print "backend %s not available, trying to fallback to another" % backend
|
print "backend %s not available, trying to fallback to another" \
|
||||||
|
% backend
|
||||||
try:
|
try:
|
||||||
backend = backends[0]
|
backend = backends[0]
|
||||||
except IndexError:
|
except IndexError:
|
||||||
@@ -310,18 +326,18 @@ class WicdDaemon(dbus.service.Object):
|
|||||||
self.wired.Disconnect()
|
self.wired.Disconnect()
|
||||||
|
|
||||||
@dbus.service.method('org.wicd.daemon')
|
@dbus.service.method('org.wicd.daemon')
|
||||||
def FormatSignalForPrinting(self, signal):
|
def FormatSignalForPrinting(self, sign):
|
||||||
""" Returns the suffix to display after the signal strength number. """
|
""" Returns the suffix to display after the signal strength number. """
|
||||||
if self.GetSignalDisplayType() == 1:
|
if self.GetSignalDisplayType() == 1:
|
||||||
return '%s dBm' % signal
|
return '%s dBm' % sign
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
if int(signal) == 101:
|
if int(sign) == 101:
|
||||||
return '??%'
|
return '??%'
|
||||||
else:
|
else:
|
||||||
return '%s%%' % signal
|
return '%s%%' % sign
|
||||||
except ValueError:
|
except ValueError:
|
||||||
return '%s%%' % signal
|
return '%s%%' % sign
|
||||||
|
|
||||||
@dbus.service.method('org.wicd.daemon')
|
@dbus.service.method('org.wicd.daemon')
|
||||||
def SetSuspend(self, val):
|
def SetSuspend(self, val):
|
||||||
@@ -463,7 +479,8 @@ class WicdDaemon(dbus.service.Object):
|
|||||||
started.
|
started.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
if self.debug_mode and value: print "Forced disconnect on"
|
if self.debug_mode and value:
|
||||||
|
print "Forced disconnect on"
|
||||||
self.forced_disconnect = bool(value)
|
self.forced_disconnect = bool(value)
|
||||||
|
|
||||||
@dbus.service.method('org.wicd.daemon')
|
@dbus.service.method('org.wicd.daemon')
|
||||||
@@ -578,7 +595,8 @@ class WicdDaemon(dbus.service.Object):
|
|||||||
@dbus.service.method('org.wicd.daemon')
|
@dbus.service.method('org.wicd.daemon')
|
||||||
def SetShowNeverConnect(self, value):
|
def SetShowNeverConnect(self, value):
|
||||||
""" Sets the how_never_connect state. """
|
""" Sets the how_never_connect state. """
|
||||||
self.config.set("Settings", "show_never_connect", bool(value), write=True)
|
self.config.set("Settings", "show_never_connect", bool(value),
|
||||||
|
write=True)
|
||||||
self.show_never_connect = bool(value)
|
self.show_never_connect = bool(value)
|
||||||
|
|
||||||
@dbus.service.method('org.wicd.daemon')
|
@dbus.service.method('org.wicd.daemon')
|
||||||
@@ -746,7 +764,7 @@ class WicdDaemon(dbus.service.Object):
|
|||||||
try:
|
try:
|
||||||
gobject.timeout_add_seconds(3, self._monitor_wired_autoconnect,
|
gobject.timeout_add_seconds(3, self._monitor_wired_autoconnect,
|
||||||
fresh)
|
fresh)
|
||||||
except:
|
except AttributeError:
|
||||||
gobject.timeout_add(3000, self._monitor_wired_autoconnect, fresh)
|
gobject.timeout_add(3000, self._monitor_wired_autoconnect, fresh)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@@ -772,28 +790,36 @@ class WicdDaemon(dbus.service.Object):
|
|||||||
|
|
||||||
@dbus.service.method("org.wicd.daemon")
|
@dbus.service.method("org.wicd.daemon")
|
||||||
def ConnectResultsAvailable(self):
|
def ConnectResultsAvailable(self):
|
||||||
if ((self.wired.connecting_thread and self.wired.connecting_thread.connect_result) or
|
""" Return whether connection results are available. """
|
||||||
(self.wifi.connecting_thread and self.wifi.connecting_thread.connect_result)):
|
wired_thread = self.wired.connecting_thread
|
||||||
|
wifi_thread = self.wifi.connecting_thread
|
||||||
|
if ((wired_thread and wired_thread.connect_result) or
|
||||||
|
(wifi_thread and wifi_thread.connect_result)):
|
||||||
return True
|
return True
|
||||||
else:
|
else:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
@dbus.service.method("org.wicd.daemon")
|
@dbus.service.method("org.wicd.daemon")
|
||||||
def SendConnectResultsIfAvail(self):
|
def SendConnectResultsIfAvail(self):
|
||||||
|
""" Send connection results if they're available. '"""
|
||||||
if self.ConnectResultsAvailable():
|
if self.ConnectResultsAvailable():
|
||||||
self.SendConnectResult()
|
self.SendConnectResult()
|
||||||
|
|
||||||
@dbus.service.method("org.wicd.daemon")
|
@dbus.service.method("org.wicd.daemon")
|
||||||
def SendConnectResult(self):
|
def SendConnectResult(self):
|
||||||
if self.wired.connecting_thread and self.wired.connecting_thread.connect_result:
|
""" Send connection result. """
|
||||||
self.ConnectResultsSent(self.wired.connecting_thread.connect_result)
|
wired_thread = self.wired.connecting_thread
|
||||||
self.wired.connecting_thread.connect_result = ""
|
wifi_thread = self.wifi.connecting_thread
|
||||||
elif self.wifi.connecting_thread and self.wifi.connecting_thread.connect_result:
|
if wired_thread and wired_thread.connect_result:
|
||||||
self.ConnectResultsSent(self.wifi.connecting_thread.connect_result)
|
self.ConnectResultsSent(wired_thread.connect_result)
|
||||||
self.wifi.connecting_thread.connect_result = ""
|
wired_thread.connect_result = ""
|
||||||
|
elif wifi_thread and wifi_thread.connect_result:
|
||||||
|
self.ConnectResultsSent(wifi_thread.connect_result)
|
||||||
|
wifi_thread.connect_result = ""
|
||||||
|
|
||||||
@dbus.service.signal(dbus_interface="org.wicd.daemon",signature='s')
|
@dbus.service.signal(dbus_interface="org.wicd.daemon",signature='s')
|
||||||
def ConnectResultsSent(self, result):
|
def ConnectResultsSent(self, result):
|
||||||
|
""" Signal emit when connection results are sent. """
|
||||||
print "Sending connection attempt result %s" % result
|
print "Sending connection attempt result %s" % result
|
||||||
|
|
||||||
@dbus.service.method("org.wicd.daemon")
|
@dbus.service.method("org.wicd.daemon")
|
||||||
@@ -853,15 +879,18 @@ class WicdDaemon(dbus.service.Object):
|
|||||||
|
|
||||||
# Load network interfaces.
|
# Load network interfaces.
|
||||||
iface = self.wireless_bus.DetectWirelessInterface()
|
iface = self.wireless_bus.DetectWirelessInterface()
|
||||||
if not iface: iface = 'wlan0'
|
if not iface:
|
||||||
|
iface = 'wlan0'
|
||||||
self.SetWirelessInterface(app_conf.get("Settings", "wireless_interface",
|
self.SetWirelessInterface(app_conf.get("Settings", "wireless_interface",
|
||||||
default=iface))
|
default=iface))
|
||||||
iface = self.wired_bus.DetectWiredInterface()
|
iface = self.wired_bus.DetectWiredInterface()
|
||||||
if not iface: iface = 'eth0'
|
if not iface:
|
||||||
|
iface = 'eth0'
|
||||||
self.SetWiredInterface(app_conf.get("Settings", "wired_interface",
|
self.SetWiredInterface(app_conf.get("Settings", "wired_interface",
|
||||||
default=iface))
|
default=iface))
|
||||||
|
|
||||||
self.SetWPADriver(app_conf.get("Settings", "wpa_driver", default="wext"))
|
self.SetWPADriver(app_conf.get("Settings", "wpa_driver",
|
||||||
|
default="wext"))
|
||||||
self.SetAlwaysShowWiredInterface(app_conf.get("Settings",
|
self.SetAlwaysShowWiredInterface(app_conf.get("Settings",
|
||||||
"always_show_wired_interface",
|
"always_show_wired_interface",
|
||||||
default=False))
|
default=False))
|
||||||
@@ -871,7 +900,8 @@ class WicdDaemon(dbus.service.Object):
|
|||||||
dns2 = app_conf.get("Settings", "global_dns_2", default='None')
|
dns2 = app_conf.get("Settings", "global_dns_2", default='None')
|
||||||
dns3 = app_conf.get("Settings", "global_dns_3", default='None')
|
dns3 = app_conf.get("Settings", "global_dns_3", default='None')
|
||||||
dns_dom = app_conf.get("Settings", "global_dns_dom", default='None')
|
dns_dom = app_conf.get("Settings", "global_dns_dom", default='None')
|
||||||
search_dom = app_conf.get("Settings", "global_search_dom", default='None')
|
search_dom = app_conf.get("Settings", "global_search_dom",
|
||||||
|
default='None')
|
||||||
self.SetGlobalDNS(dns1, dns2, dns3, dns_dom, search_dom)
|
self.SetGlobalDNS(dns1, dns2, dns3, dns_dom, search_dom)
|
||||||
self.SetAutoReconnect(app_conf.get("Settings", "auto_reconnect",
|
self.SetAutoReconnect(app_conf.get("Settings", "auto_reconnect",
|
||||||
default=True))
|
default=True))
|
||||||
@@ -933,7 +963,7 @@ class WicdDaemon(dbus.service.Object):
|
|||||||
###### Wireless Daemon #######
|
###### Wireless Daemon #######
|
||||||
##############################
|
##############################
|
||||||
|
|
||||||
class WirelessDaemon(dbus.service.Object):
|
class WirelessDaemon(dbus.service.Object, object):
|
||||||
""" DBus interface for wireless connection operations. """
|
""" DBus interface for wireless connection operations. """
|
||||||
def __init__(self, bus_name, daemon, wifi=None, debug=False):
|
def __init__(self, bus_name, daemon, wifi=None, debug=False):
|
||||||
""" Intitialize the wireless DBus interface. """
|
""" Intitialize the wireless DBus interface. """
|
||||||
@@ -948,8 +978,10 @@ class WirelessDaemon(dbus.service.Object):
|
|||||||
self.config = ConfigManager(wireless_conf, debug=debug)
|
self.config = ConfigManager(wireless_conf, debug=debug)
|
||||||
|
|
||||||
def get_debug_mode(self):
|
def get_debug_mode(self):
|
||||||
|
""" Getter for the debug_mode property. """
|
||||||
return self._debug_mode
|
return self._debug_mode
|
||||||
def set_debug_mode(self, mode):
|
def set_debug_mode(self, mode):
|
||||||
|
""" Setter for the debug_mode property. """
|
||||||
self._debug_mode = mode
|
self._debug_mode = mode
|
||||||
self.config.debug = mode
|
self.config.debug = mode
|
||||||
debug_mode = property(get_debug_mode, set_debug_mode)
|
debug_mode = property(get_debug_mode, set_debug_mode)
|
||||||
@@ -1068,10 +1100,10 @@ class WirelessDaemon(dbus.service.Object):
|
|||||||
return self.wifi.GetRfKillStatus()
|
return self.wifi.GetRfKillStatus()
|
||||||
|
|
||||||
@dbus.service.method('org.wicd.daemon.wireless')
|
@dbus.service.method('org.wicd.daemon.wireless')
|
||||||
def GetWirelessProperty(self, networkid, property):
|
def GetWirelessProperty(self, networkid, prop):
|
||||||
""" Retrieves wireless property from the network specified """
|
""" Retrieves wireless property from the network specified """
|
||||||
try:
|
try:
|
||||||
value = self.LastScan[networkid].get(property)
|
value = self.LastScan[networkid].get(prop)
|
||||||
except IndexError:
|
except IndexError:
|
||||||
return ""
|
return ""
|
||||||
value = misc.to_unicode(value)
|
value = misc.to_unicode(value)
|
||||||
@@ -1088,7 +1120,8 @@ class WirelessDaemon(dbus.service.Object):
|
|||||||
return False
|
return False
|
||||||
# whitelist some props that need different handling
|
# whitelist some props that need different handling
|
||||||
if prop in ('key_index', ):
|
if prop in ('key_index', ):
|
||||||
self.LastScan[netid][prop] = misc.to_unicode(misc.Noneify(value, False))
|
self.LastScan[netid][prop] = \
|
||||||
|
misc.to_unicode(misc.Noneify(value, False))
|
||||||
else:
|
else:
|
||||||
self.LastScan[netid][prop] = misc.to_unicode(misc.Noneify(value))
|
self.LastScan[netid][prop] = misc.to_unicode(misc.Noneify(value))
|
||||||
|
|
||||||
@@ -1161,27 +1194,28 @@ class WirelessDaemon(dbus.service.Object):
|
|||||||
return result
|
return result
|
||||||
|
|
||||||
@dbus.service.method('org.wicd.daemon.wireless')
|
@dbus.service.method('org.wicd.daemon.wireless')
|
||||||
def ConnectWireless(self, id):
|
def ConnectWireless(self, nid):
|
||||||
""" Connects the the wireless network specified by i"""
|
""" Connects the the wireless network specified by i"""
|
||||||
self.SaveWirelessNetworkProfile(id)
|
self.SaveWirelessNetworkProfile(nid)
|
||||||
# Will returned instantly, that way we don't hold up dbus.
|
# Will returned instantly, that way we don't hold up dbus.
|
||||||
# CheckIfWirelessConnecting can be used to test if the connection
|
# CheckIfWirelessConnecting can be used to test if the connection
|
||||||
# is done.
|
# is done.
|
||||||
self.wifi.before_script = self.GetWirelessProperty(id, 'beforescript')
|
self.wifi.before_script = self.GetWirelessProperty(nid, 'beforescript')
|
||||||
self.wifi.after_script = self.GetWirelessProperty(id, 'afterscript')
|
self.wifi.after_script = self.GetWirelessProperty(nid, 'afterscript')
|
||||||
self.wifi.pre_disconnect_script = self.GetWirelessProperty(id,
|
self.wifi.pre_disconnect_script = self.GetWirelessProperty(nid,
|
||||||
'predisconnectscript')
|
'predisconnectscript')
|
||||||
self.wifi.post_disconnect_script = self.GetWirelessProperty(id,
|
self.wifi.post_disconnect_script = self.GetWirelessProperty(nid,
|
||||||
'postdisconnectscript')
|
'postdisconnectscript')
|
||||||
self.wifi.bitrate = self.GetWirelessProperty(id, 'bitrate')
|
self.wifi.bitrate = self.GetWirelessProperty(nid, 'bitrate')
|
||||||
self.wifi.allow_lower_bitrates = self.GetWirelessProperty(id,
|
self.wifi.allow_lower_bitrates = self.GetWirelessProperty(nid,
|
||||||
'allow_lower_bitrates')
|
'allow_lower_bitrates')
|
||||||
print 'Connecting to wireless network ' + str(self.LastScan[id]['essid'])
|
print 'Connecting to wireless network ' + \
|
||||||
|
str(self.LastScan[nid]['essid'])
|
||||||
# disconnect to make sure that scripts are run
|
# disconnect to make sure that scripts are run
|
||||||
self.wifi.Disconnect()
|
self.wifi.Disconnect()
|
||||||
self.daemon.wired_bus.wired.Disconnect()
|
self.daemon.wired_bus.wired.Disconnect()
|
||||||
self.daemon.SetForcedDisconnect(False)
|
self.daemon.SetForcedDisconnect(False)
|
||||||
conthread = self.wifi.Connect(self.LastScan[id], debug=self.debug_mode)
|
self.wifi.Connect(self.LastScan[nid], debug=self.debug_mode)
|
||||||
self.daemon.UpdateState()
|
self.daemon.UpdateState()
|
||||||
|
|
||||||
@dbus.service.method('org.wicd.daemon.wireless')
|
@dbus.service.method('org.wicd.daemon.wireless')
|
||||||
@@ -1217,9 +1251,9 @@ class WirelessDaemon(dbus.service.Object):
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
@dbus.service.method('org.wicd.daemon.wireless')
|
@dbus.service.method('org.wicd.daemon.wireless')
|
||||||
def ReadWirelessNetworkProfile(self, id):
|
def ReadWirelessNetworkProfile(self, nid):
|
||||||
""" Reads in wireless profile as the active network """
|
""" Reads in wireless profile as the active network """
|
||||||
cur_network = self.LastScan[id]
|
cur_network = self.LastScan[nid]
|
||||||
essid_key = "essid:%s" % cur_network["essid"]
|
essid_key = "essid:%s" % cur_network["essid"]
|
||||||
bssid_key = cur_network["bssid"]
|
bssid_key = cur_network["bssid"]
|
||||||
|
|
||||||
@@ -1247,13 +1281,13 @@ class WirelessDaemon(dbus.service.Object):
|
|||||||
cur_network['essid'] = stored_essid
|
cur_network['essid'] = stored_essid
|
||||||
|
|
||||||
@dbus.service.method('org.wicd.daemon.wireless')
|
@dbus.service.method('org.wicd.daemon.wireless')
|
||||||
def SaveWirelessNetworkProfile(self, id):
|
def SaveWirelessNetworkProfile(self, nid):
|
||||||
""" Writes a wireless profile to disk. """
|
""" Writes a wireless profile to disk. """
|
||||||
def write_script_ent(prof, script):
|
def write_script_ent(prof, script):
|
||||||
if not self.config.has_option(prof, script):
|
if not self.config.has_option(prof, script):
|
||||||
self.config.set(prof, script, None)
|
self.config.set(prof, script, None)
|
||||||
|
|
||||||
cur_network = self.LastScan[id]
|
cur_network = self.LastScan[nid]
|
||||||
bssid_key = cur_network["bssid"]
|
bssid_key = cur_network["bssid"]
|
||||||
essid_key = "essid:%s" % cur_network["essid"]
|
essid_key = "essid:%s" % cur_network["essid"]
|
||||||
|
|
||||||
@@ -1287,7 +1321,7 @@ class WirelessDaemon(dbus.service.Object):
|
|||||||
self.config.write()
|
self.config.write()
|
||||||
|
|
||||||
@dbus.service.method('org.wicd.daemon.wireless')
|
@dbus.service.method('org.wicd.daemon.wireless')
|
||||||
def SaveWirelessNetworkProperty(self, id, option):
|
def SaveWirelessNetworkProperty(self, nid, option):
|
||||||
""" Writes a particular wireless property to disk. """
|
""" Writes a particular wireless property to disk. """
|
||||||
option = misc.sanitize_config(option)
|
option = misc.sanitize_config(option)
|
||||||
if option.endswith("script"):
|
if option.endswith("script"):
|
||||||
@@ -1295,7 +1329,7 @@ class WirelessDaemon(dbus.service.Object):
|
|||||||
'the daemon.'
|
'the daemon.'
|
||||||
return
|
return
|
||||||
config = self.config
|
config = self.config
|
||||||
cur_network = self.LastScan[id]
|
cur_network = self.LastScan[nid]
|
||||||
essid_key = "essid:" + cur_network["essid"]
|
essid_key = "essid:" + cur_network["essid"]
|
||||||
|
|
||||||
config.set(cur_network["bssid"], option, str(cur_network[option]))
|
config.set(cur_network["bssid"], option, str(cur_network[option]))
|
||||||
@@ -1347,12 +1381,14 @@ class WirelessDaemon(dbus.service.Object):
|
|||||||
self.config.remove_section(section)
|
self.config.remove_section(section)
|
||||||
self.config.write()
|
self.config.write()
|
||||||
|
|
||||||
@dbus.service.signal(dbus_interface='org.wicd.daemon.wireless', signature='')
|
@dbus.service.signal(dbus_interface='org.wicd.daemon.wireless', \
|
||||||
|
signature='')
|
||||||
def SendStartScanSignal(self):
|
def SendStartScanSignal(self):
|
||||||
""" Emits a signal announcing a scan has started. """
|
""" Emits a signal announcing a scan has started. """
|
||||||
self._scanning = True
|
self._scanning = True
|
||||||
|
|
||||||
@dbus.service.signal(dbus_interface='org.wicd.daemon.wireless', signature='')
|
@dbus.service.signal(dbus_interface='org.wicd.daemon.wireless', \
|
||||||
|
signature='')
|
||||||
def SendEndScanSignal(self):
|
def SendEndScanSignal(self):
|
||||||
""" Emits a signal announcing a scan has finished. """
|
""" Emits a signal announcing a scan has finished. """
|
||||||
self._scanning = False
|
self._scanning = False
|
||||||
@@ -1372,11 +1408,10 @@ class WirelessDaemon(dbus.service.Object):
|
|||||||
if self.debug_mode:
|
if self.debug_mode:
|
||||||
print network["essid"] + ' has profile'
|
print network["essid"] + ' has profile'
|
||||||
if bool(network.get('automatic')):
|
if bool(network.get('automatic')):
|
||||||
try:
|
|
||||||
if network.get('never'):
|
if network.get('never'):
|
||||||
print network["essid"],'marked never connect'
|
print network["essid"],'marked never connect'
|
||||||
continue
|
continue
|
||||||
except:
|
else:
|
||||||
print network["essid"],'has no never connect value'
|
print network["essid"],'has no never connect value'
|
||||||
print 'trying to automatically connect to...' + \
|
print 'trying to automatically connect to...' + \
|
||||||
network["essid"]
|
network["essid"]
|
||||||
@@ -1389,7 +1424,7 @@ class WirelessDaemon(dbus.service.Object):
|
|||||||
###### Wired Daemon #######
|
###### Wired Daemon #######
|
||||||
###########################
|
###########################
|
||||||
|
|
||||||
class WiredDaemon(dbus.service.Object):
|
class WiredDaemon(dbus.service.Object, object):
|
||||||
""" DBus interface for wired connection operations. """
|
""" DBus interface for wired connection operations. """
|
||||||
def __init__(self, bus_name, daemon, wired=None, debug=False):
|
def __init__(self, bus_name, daemon, wired=None, debug=False):
|
||||||
""" Intitialize the wireless DBus interface. """
|
""" Intitialize the wireless DBus interface. """
|
||||||
@@ -1403,8 +1438,10 @@ class WiredDaemon(dbus.service.Object):
|
|||||||
self.config = ConfigManager(wired_conf, debug=debug)
|
self.config = ConfigManager(wired_conf, debug=debug)
|
||||||
|
|
||||||
def get_debug_mode(self):
|
def get_debug_mode(self):
|
||||||
|
""" Getter for debug_mode property. """
|
||||||
return self._debug_mode
|
return self._debug_mode
|
||||||
def set_debug_mode(self, mode):
|
def set_debug_mode(self, mode):
|
||||||
|
""" Setter for debug_mode property. """
|
||||||
self._debug_mode = mode
|
self._debug_mode = mode
|
||||||
self.config.debug = mode
|
self.config.debug = mode
|
||||||
debug_mode = property(get_debug_mode, set_debug_mode)
|
debug_mode = property(get_debug_mode, set_debug_mode)
|
||||||
@@ -1465,10 +1502,10 @@ class WiredDaemon(dbus.service.Object):
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
@dbus.service.method('org.wicd.daemon.wired')
|
@dbus.service.method('org.wicd.daemon.wired')
|
||||||
def GetWiredProperty(self, property):
|
def GetWiredProperty(self, prop):
|
||||||
""" Returns the requested wired property. """
|
""" Returns the requested wired property. """
|
||||||
if self.WiredNetwork:
|
if self.WiredNetwork:
|
||||||
value = self.WiredNetwork.get(property)
|
value = self.WiredNetwork.get(prop)
|
||||||
return value
|
return value
|
||||||
else:
|
else:
|
||||||
print 'GetWiredProperty: WiredNetwork does not exist'
|
print 'GetWiredProperty: WiredNetwork does not exist'
|
||||||
@@ -1516,8 +1553,10 @@ class WiredDaemon(dbus.service.Object):
|
|||||||
""" Connects to a wired network. """
|
""" Connects to a wired network. """
|
||||||
self.wired.before_script = self.GetWiredProperty("beforescript")
|
self.wired.before_script = self.GetWiredProperty("beforescript")
|
||||||
self.wired.after_script = self.GetWiredProperty("afterscript")
|
self.wired.after_script = self.GetWiredProperty("afterscript")
|
||||||
self.wired.pre_disconnect_script = self.GetWiredProperty("predisconnectscript")
|
self.wired.pre_disconnect_script = \
|
||||||
self.wired.post_disconnect_script = self.GetWiredProperty("postdisconnectscript")
|
self.GetWiredProperty("predisconnectscript")
|
||||||
|
self.wired.post_disconnect_script = \
|
||||||
|
self.GetWiredProperty("postdisconnectscript")
|
||||||
self.daemon.wireless_bus.wifi.Disconnect()
|
self.daemon.wireless_bus.wifi.Disconnect()
|
||||||
# make sure disconnect scripts are run
|
# make sure disconnect scripts are run
|
||||||
self.wired.Disconnect()
|
self.wired.Disconnect()
|
||||||
@@ -1543,7 +1582,7 @@ class WiredDaemon(dbus.service.Object):
|
|||||||
"postdisconnectscript", "encryption_enabled"]:
|
"postdisconnectscript", "encryption_enabled"]:
|
||||||
self.config.set(profilename, option, None)
|
self.config.set(profilename, option, None)
|
||||||
self.config.set(profilename, "default", default)
|
self.config.set(profilename, "default", default)
|
||||||
self.config.set(profilename,"dhcphostname",os.uname()[1])
|
self.config.set(profilename, "dhcphostname", os.uname()[1])
|
||||||
self.config.write()
|
self.config.write()
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@@ -1628,7 +1667,8 @@ class WiredDaemon(dbus.service.Object):
|
|||||||
profile[x] = misc.Noneify(self.config.get(profilename, x))
|
profile[x] = misc.Noneify(self.config.get(profilename, x))
|
||||||
profile['use_global_dns'] = bool(profile.get('use_global_dns'))
|
profile['use_global_dns'] = bool(profile.get('use_global_dns'))
|
||||||
profile['use_static_dns'] = bool(profile.get('use_static_dns'))
|
profile['use_static_dns'] = bool(profile.get('use_static_dns'))
|
||||||
profile['encryption_enabled'] = bool(profile.get('encryption_enabled'))
|
profile['encryption_enabled'] = \
|
||||||
|
bool(profile.get('encryption_enabled'))
|
||||||
profile['profilename'] = profilename
|
profile['profilename'] = profilename
|
||||||
self.WiredNetwork = profile
|
self.WiredNetwork = profile
|
||||||
self._cur_wired_prof_name = profilename
|
self._cur_wired_prof_name = profilename
|
||||||
@@ -1657,6 +1697,7 @@ class WiredDaemon(dbus.service.Object):
|
|||||||
return wnettools.GetWiredInterfaces()
|
return wnettools.GetWiredInterfaces()
|
||||||
|
|
||||||
def usage():
|
def usage():
|
||||||
|
""" Print help screen. """
|
||||||
print """
|
print """
|
||||||
wicd %s
|
wicd %s
|
||||||
wireless (and wired) connection daemon.
|
wireless (and wired) connection daemon.
|
||||||
@@ -1765,8 +1806,8 @@ def main(argv):
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
opts, args = getopt.getopt(sys.argv[1:], 'fenoahk',
|
opts, args = getopt.getopt(sys.argv[1:], 'fenoahk',
|
||||||
['help', 'no-daemon', 'no-poll', 'no-stderr', 'no-stdout',
|
['help', 'no-daemon', 'no-poll', 'no-stderr',
|
||||||
'no-autoconnect', 'kill'])
|
'no-stdout', 'no-autoconnect', 'kill'])
|
||||||
except getopt.GetoptError:
|
except getopt.GetoptError:
|
||||||
# Print help information and exit
|
# Print help information and exit
|
||||||
usage()
|
usage()
|
||||||
@@ -1793,7 +1834,7 @@ def main(argv):
|
|||||||
if kill:
|
if kill:
|
||||||
try:
|
try:
|
||||||
f = open(wpath.pidfile)
|
f = open(wpath.pidfile)
|
||||||
except:
|
except IOError:
|
||||||
#print >> sys.stderr, "No wicd instance active, aborting."
|
#print >> sys.stderr, "No wicd instance active, aborting."
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
@@ -1817,7 +1858,7 @@ def main(argv):
|
|||||||
dbus_ifaces['daemon'].Disconnect()
|
dbus_ifaces['daemon'].Disconnect()
|
||||||
pid = int(f.readline())
|
pid = int(f.readline())
|
||||||
f.close()
|
f.close()
|
||||||
os.kill(pid,signal.SIGTERM)
|
os.kill(pid, signal.SIGTERM)
|
||||||
|
|
||||||
# quit, this should be the only option specified
|
# quit, this should be the only option specified
|
||||||
sys.exit(0)
|
sys.exit(0)
|
||||||
@@ -1830,7 +1871,8 @@ def main(argv):
|
|||||||
if not os.path.exists(wpath.networks):
|
if not os.path.exists(wpath.networks):
|
||||||
os.makedirs(wpath.networks)
|
os.makedirs(wpath.networks)
|
||||||
|
|
||||||
if do_daemonize: daemonize()
|
if do_daemonize:
|
||||||
|
daemonize()
|
||||||
|
|
||||||
if redirect_stderr or redirect_stdout:
|
if redirect_stderr or redirect_stdout:
|
||||||
logpath = os.path.join(wpath.log, 'wicd.log')
|
logpath = os.path.join(wpath.log, 'wicd.log')
|
||||||
@@ -1840,8 +1882,8 @@ def main(argv):
|
|||||||
output = ManagedStdio(logpath)
|
output = ManagedStdio(logpath)
|
||||||
if os.path.exists(logpath):
|
if os.path.exists(logpath):
|
||||||
try:
|
try:
|
||||||
os.chmod(logpath, int(wpath.log_perms,8))
|
os.chmod(logpath, int(wpath.log_perms, 8))
|
||||||
except:
|
except OSError:
|
||||||
print 'unable to chmod log file to %s' % wpath.log_perms
|
print 'unable to chmod log file to %s' % wpath.log_perms
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -1849,11 +1891,13 @@ def main(argv):
|
|||||||
import grp
|
import grp
|
||||||
group = grp.getgrnam(wpath.log_group)
|
group = grp.getgrnam(wpath.log_group)
|
||||||
os.chown(logpath, 0, group[2])
|
os.chown(logpath, 0, group[2])
|
||||||
except:
|
except OSError:
|
||||||
print 'unable to chown log file to %s' % group[2]
|
print 'unable to chown log file to %s' % group[2]
|
||||||
|
|
||||||
if redirect_stdout: sys.stdout = output
|
if redirect_stdout:
|
||||||
if redirect_stderr: sys.stderr = output
|
sys.stdout = output
|
||||||
|
if redirect_stderr:
|
||||||
|
sys.stderr = output
|
||||||
|
|
||||||
print '---------------------------'
|
print '---------------------------'
|
||||||
print 'wicd initializing...'
|
print 'wicd initializing...'
|
||||||
|
|||||||
@@ -49,7 +49,8 @@ essid_pattern = re.compile('.*ESSID:"?(.*?)".*\n', _re_mode)
|
|||||||
ap_mac_pattern = re.compile('.*Address: (.*?)\n', _re_mode)
|
ap_mac_pattern = re.compile('.*Address: (.*?)\n', _re_mode)
|
||||||
channel_pattern = re.compile('.*Channel:?=? ?(\d+)', _re_mode)
|
channel_pattern = re.compile('.*Channel:?=? ?(\d+)', _re_mode)
|
||||||
strength_pattern = re.compile('.*Quality:?=? ?(\d+)\s*/?\s*(\d*)', _re_mode)
|
strength_pattern = re.compile('.*Quality:?=? ?(\d+)\s*/?\s*(\d*)', _re_mode)
|
||||||
altstrength_pattern = re.compile('.*Signal level:?=? ?(\d+)\s*/?\s*(\d*)', _re_mode)
|
altstrength_pattern = re.compile('.*Signal level:?=? ?(\d+)\s*/?\s*(\d*)',
|
||||||
|
_re_mode)
|
||||||
signaldbm_pattern = re.compile('.*Signal level:?=? ?(-\d\d*)', _re_mode)
|
signaldbm_pattern = re.compile('.*Signal level:?=? ?(-\d\d*)', _re_mode)
|
||||||
bitrates_pattern = re.compile('([\d\.]+)\s+\S+/s', _re_mode)
|
bitrates_pattern = re.compile('([\d\.]+)\s+\S+/s', _re_mode)
|
||||||
mode_pattern = re.compile('.*Mode:([A-Za-z-]*?)\n', _re_mode)
|
mode_pattern = re.compile('.*Mode:([A-Za-z-]*?)\n', _re_mode)
|
||||||
@@ -61,12 +62,15 @@ wpa2_pattern = re.compile('(WPA2)', _re_mode)
|
|||||||
|
|
||||||
#iwconfig-only regular expressions.
|
#iwconfig-only regular expressions.
|
||||||
ip_up = re.compile(r'flags=[0.9]*<([^>]*)>', re.S)
|
ip_up = re.compile(r'flags=[0.9]*<([^>]*)>', re.S)
|
||||||
ip_pattern = re.compile(r'inet [Aa]d?dr[^.]*:([^.]*\.[^.]*\.[^.]*\.[0-9]*)', re.S)
|
ip_pattern = re.compile(r'inet [Aa]d?dr[^.]*:([^.]*\.[^.]*\.[^.]*\.[0-9]*)',
|
||||||
|
re.S)
|
||||||
ip_pattern1 = re.compile(r'inet ([^.]*\.[^.]*\.[^.]*\.[0-9]*)', re.S)
|
ip_pattern1 = re.compile(r'inet ([^.]*\.[^.]*\.[^.]*\.[0-9]*)', re.S)
|
||||||
bssid_pattern = re.compile('.*[(Access Point)|(Cell)]: (([0-9A-Z]{2}:){5}[0-9A-Z]{2})', _re_mode)
|
bssid_pattern = re.compile('.*[(Access Point)|(Cell)]: ' + \
|
||||||
|
'(([0-9A-Z]{2}:){5}[0-9A-Z]{2})', _re_mode)
|
||||||
bitrate_pattern = re.compile('.*Bit Rate[=:](.*?/s)', _re_mode)
|
bitrate_pattern = re.compile('.*Bit Rate[=:](.*?/s)', _re_mode)
|
||||||
opmode_pattern = re.compile('.*Mode:(.*?) ', _re_mode)
|
opmode_pattern = re.compile('.*Mode:(.*?) ', _re_mode)
|
||||||
authmethods_pattern = re.compile('.*Authentication capabilities :\n(.*?)Current', _re_mode)
|
authmethods_pattern = re.compile('.*Authentication capabilities ' + \
|
||||||
|
':\n(.*?)Current', _re_mode)
|
||||||
|
|
||||||
# Regular expressions for wpa_cli output
|
# Regular expressions for wpa_cli output
|
||||||
auth_pattern = re.compile('.*wpa_state=(.*?)\n', _re_mode)
|
auth_pattern = re.compile('.*wpa_state=(.*?)\n', _re_mode)
|
||||||
@@ -79,12 +83,14 @@ blacklist_norm = ";`$!*|><&\\"
|
|||||||
blank_trans = maketrans("", "")
|
blank_trans = maketrans("", "")
|
||||||
|
|
||||||
def _sanitize_string(string):
|
def _sanitize_string(string):
|
||||||
|
""" Sanitize string. """
|
||||||
if string:
|
if string:
|
||||||
return translate(str(string), blank_trans, blacklist_norm)
|
return translate(str(string), blank_trans, blacklist_norm)
|
||||||
else:
|
else:
|
||||||
return string
|
return string
|
||||||
|
|
||||||
def _sanitize_string_strict(string):
|
def _sanitize_string_strict(string):
|
||||||
|
""" Sanitize string in a stricter way. """
|
||||||
if string:
|
if string:
|
||||||
return translate(str(string), blank_trans, blacklist_strict)
|
return translate(str(string), blank_trans, blacklist_strict)
|
||||||
else:
|
else:
|
||||||
@@ -140,7 +146,8 @@ def isWireless(devname):
|
|||||||
in the future, if wireless.h is fully replaced.
|
in the future, if wireless.h is fully replaced.
|
||||||
"""
|
"""
|
||||||
we = None
|
we = None
|
||||||
for t in [socket.AF_INET, socket.AF_INET6, socket.AF_IPX, socket.AF_AX25, socket.AF_APPLETALK]:
|
for t in [socket.AF_INET, socket.AF_INET6, socket.AF_IPX, socket.AF_AX25,
|
||||||
|
socket.AF_APPLETALK]:
|
||||||
sk = socket.socket(t, socket.SOCK_DGRAM)
|
sk = socket.socket(t, socket.SOCK_DGRAM)
|
||||||
if sk is None:
|
if sk is None:
|
||||||
continue
|
continue
|
||||||
@@ -149,7 +156,7 @@ def isWireless(devname):
|
|||||||
#define SIOCGIWNAME 0x8b01 in linux/wireless.h
|
#define SIOCGIWNAME 0x8b01 in linux/wireless.h
|
||||||
# "used to verify the presence of wireless extensions"
|
# "used to verify the presence of wireless extensions"
|
||||||
we = fcntl.ioctl(skfd, 0x8b01, devname)
|
we = fcntl.ioctl(skfd, 0x8b01, devname)
|
||||||
except:
|
except IOError:
|
||||||
pass
|
pass
|
||||||
sk.close()
|
sk.close()
|
||||||
return we is not None
|
return we is not None
|
||||||
@@ -184,7 +191,7 @@ def GetWpaSupplicantDrivers():
|
|||||||
output = misc.Run(["wpa_supplicant", "-h"])
|
output = misc.Run(["wpa_supplicant", "-h"])
|
||||||
try:
|
try:
|
||||||
output = output.split("drivers:")[1].split("options:")[0].strip()
|
output = output.split("drivers:")[1].split("options:")[0].strip()
|
||||||
except:
|
except KeyError:
|
||||||
print "Warning: Couldn't get list of valid wpa_supplicant drivers"
|
print "Warning: Couldn't get list of valid wpa_supplicant drivers"
|
||||||
return [""]
|
return [""]
|
||||||
patt = re.compile("(\S+)\s+=.*")
|
patt = re.compile("(\S+)\s+=.*")
|
||||||
@@ -237,6 +244,23 @@ class BaseInterface(object):
|
|||||||
self.link_detect = None
|
self.link_detect = None
|
||||||
self.dhcp_object = None
|
self.dhcp_object = None
|
||||||
|
|
||||||
|
self.ethtool_cmd = None
|
||||||
|
self.miitool_cmd = None
|
||||||
|
self.ip_cmd = None
|
||||||
|
self.route_cmd = None
|
||||||
|
self.wpa_cli_cmd = None
|
||||||
|
self.resolvconf_cmd = None
|
||||||
|
|
||||||
|
self.dhclient_cmd = None
|
||||||
|
self.dhclient_needs_verbose = False
|
||||||
|
self.udhcpc_cmd = None
|
||||||
|
self.dhcpcd_cmd = None
|
||||||
|
self.pump_cmd = None
|
||||||
|
|
||||||
|
self.kdesu_cmd = None
|
||||||
|
self.gksudo_cmd = None
|
||||||
|
self.ktsuss_cmd = None
|
||||||
|
|
||||||
def SetDebugMode(self, value):
|
def SetDebugMode(self, value):
|
||||||
""" If True, verbose output is enabled. """
|
""" If True, verbose output is enabled. """
|
||||||
self.verbose = value
|
self.verbose = value
|
||||||
@@ -363,7 +387,8 @@ class BaseInterface(object):
|
|||||||
"hostname" : hostname,
|
"hostname" : hostname,
|
||||||
'dhclientconf' : dhclient_conf_path }
|
'dhclientconf' : dhclient_conf_path }
|
||||||
elif flavor == "release":
|
elif flavor == "release":
|
||||||
return client_dict[client_name]['release'] % {"cmd":cmd, "iface":self.iface}
|
return client_dict[client_name]['release'] % \
|
||||||
|
{"cmd": cmd, "iface": self.iface}
|
||||||
else:
|
else:
|
||||||
return client_dict[client_name]['id']
|
return client_dict[client_name]['id']
|
||||||
|
|
||||||
@@ -429,6 +454,7 @@ class BaseInterface(object):
|
|||||||
self.route_cmd = self._find_program_path("route")
|
self.route_cmd = self._find_program_path("route")
|
||||||
|
|
||||||
def CheckSudoApplications(self):
|
def CheckSudoApplications(self):
|
||||||
|
""" Check for available root-gaining 'sudo' applications. """
|
||||||
self.gksudo_cmd = self._find_program_path("gksudo")
|
self.gksudo_cmd = self._find_program_path("gksudo")
|
||||||
self.kdesu_cmd = self._find_program_path("kdesu")
|
self.kdesu_cmd = self._find_program_path("kdesu")
|
||||||
self.ktsuss_cmd = self._find_program_path("ktsuss")
|
self.ktsuss_cmd = self._find_program_path("ktsuss")
|
||||||
@@ -442,7 +468,8 @@ class BaseInterface(object):
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
cmd = 'ifconfig ' + self.iface + ' up'
|
cmd = 'ifconfig ' + self.iface + ' up'
|
||||||
if self.verbose: print cmd
|
if self.verbose:
|
||||||
|
print cmd
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@@ -455,7 +482,8 @@ class BaseInterface(object):
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
cmd = 'ifconfig ' + self.iface + ' down'
|
cmd = 'ifconfig ' + self.iface + ' down'
|
||||||
if self.verbose: print cmd
|
if self.verbose:
|
||||||
|
print cmd
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@@ -464,7 +492,8 @@ class BaseInterface(object):
|
|||||||
def GetIfconfig(self):
|
def GetIfconfig(self):
|
||||||
""" Runs ifconfig and returns the output. """
|
""" Runs ifconfig and returns the output. """
|
||||||
cmd = "ifconfig %s" % self.iface
|
cmd = "ifconfig %s" % self.iface
|
||||||
if self.verbose: print cmd
|
if self.verbose:
|
||||||
|
print cmd
|
||||||
return misc.Run(cmd)
|
return misc.Run(cmd)
|
||||||
|
|
||||||
@neediface("")
|
@neediface("")
|
||||||
@@ -491,7 +520,8 @@ class BaseInterface(object):
|
|||||||
cmd = ''.join([cmd, 'netmask ', netmask, ' '])
|
cmd = ''.join([cmd, 'netmask ', netmask, ' '])
|
||||||
if broadcast:
|
if broadcast:
|
||||||
cmd = ''.join([cmd, 'broadcast ', broadcast, ' '])
|
cmd = ''.join([cmd, 'broadcast ', broadcast, ' '])
|
||||||
if self.verbose: print cmd
|
if self.verbose:
|
||||||
|
print cmd
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
|
|
||||||
def _parse_dhclient(self, pipe):
|
def _parse_dhclient(self, pipe):
|
||||||
@@ -624,7 +654,8 @@ class BaseInterface(object):
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
cmd = self._get_dhcp_command('connect', hostname)
|
cmd = self._get_dhcp_command('connect', hostname)
|
||||||
if self.verbose: print cmd
|
if self.verbose:
|
||||||
|
print cmd
|
||||||
self.dhcp_object = misc.Run(cmd, include_stderr=True, return_obj=True)
|
self.dhcp_object = misc.Run(cmd, include_stderr=True, return_obj=True)
|
||||||
pipe = self.dhcp_object.stdout
|
pipe = self.dhcp_object.stdout
|
||||||
client_dict = { misc.DHCLIENT : self._parse_dhclient,
|
client_dict = { misc.DHCLIENT : self._parse_dhclient,
|
||||||
@@ -646,7 +677,8 @@ class BaseInterface(object):
|
|||||||
def ReleaseDHCP(self):
|
def ReleaseDHCP(self):
|
||||||
""" Release the DHCP lease for this interface. """
|
""" Release the DHCP lease for this interface. """
|
||||||
cmd = self._get_dhcp_command("release")
|
cmd = self._get_dhcp_command("release")
|
||||||
if self.verbose: print cmd
|
if self.verbose:
|
||||||
|
print cmd
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
|
|
||||||
@neediface(False)
|
@neediface(False)
|
||||||
@@ -659,7 +691,8 @@ class BaseInterface(object):
|
|||||||
else:
|
else:
|
||||||
print "No route manipulation command available!"
|
print "No route manipulation command available!"
|
||||||
return
|
return
|
||||||
if self.verbose: print cmd
|
if self.verbose:
|
||||||
|
print cmd
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
|
|
||||||
@neediface(False)
|
@neediface(False)
|
||||||
@@ -671,7 +704,8 @@ class BaseInterface(object):
|
|||||||
"""
|
"""
|
||||||
if self.resolvconf_cmd:
|
if self.resolvconf_cmd:
|
||||||
cmd = [self.resolvconf_cmd, '-d', self.iface + '.wicd']
|
cmd = [self.resolvconf_cmd, '-d', self.iface + '.wicd']
|
||||||
if self.verbose: print cmd
|
if self.verbose:
|
||||||
|
print cmd
|
||||||
p = misc.Run(cmd, include_stderr=True, return_obj=True)
|
p = misc.Run(cmd, include_stderr=True, return_obj=True)
|
||||||
p.communicate()
|
p.communicate()
|
||||||
|
|
||||||
@@ -711,7 +745,8 @@ class BaseInterface(object):
|
|||||||
|
|
||||||
if self.resolvconf_cmd:
|
if self.resolvconf_cmd:
|
||||||
cmd = [self.resolvconf_cmd, '-a', self.iface + '.wicd']
|
cmd = [self.resolvconf_cmd, '-a', self.iface + '.wicd']
|
||||||
if self.verbose: print cmd
|
if self.verbose:
|
||||||
|
print cmd
|
||||||
p = misc.Run(cmd, include_stderr=True, return_obj=True)
|
p = misc.Run(cmd, include_stderr=True, return_obj=True)
|
||||||
p.communicate(input=resolv_params)
|
p.communicate(input=resolv_params)
|
||||||
else:
|
else:
|
||||||
@@ -730,7 +765,8 @@ class BaseInterface(object):
|
|||||||
print "No flush command available!"
|
print "No flush command available!"
|
||||||
cmds = []
|
cmds = []
|
||||||
for cmd in cmds:
|
for cmd in cmds:
|
||||||
if self.verbose: print cmd
|
if self.verbose:
|
||||||
|
print cmd
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
|
|
||||||
@neediface(False)
|
@neediface(False)
|
||||||
@@ -745,7 +781,8 @@ class BaseInterface(object):
|
|||||||
print 'WARNING: Invalid gateway found. Aborting!'
|
print 'WARNING: Invalid gateway found. Aborting!'
|
||||||
return False
|
return False
|
||||||
cmd = 'route add default gw %s dev %s' % (gw, self.iface)
|
cmd = 'route add default gw %s dev %s' % (gw, self.iface)
|
||||||
if self.verbose: print cmd
|
if self.verbose:
|
||||||
|
print cmd
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
|
|
||||||
@neediface("")
|
@neediface("")
|
||||||
@@ -763,7 +800,8 @@ class BaseInterface(object):
|
|||||||
# check multiple ifconfig output styles
|
# check multiple ifconfig output styles
|
||||||
for pat in [ip_pattern, ip_pattern1]:
|
for pat in [ip_pattern, ip_pattern1]:
|
||||||
m = misc.RunRegex(pat, output)
|
m = misc.RunRegex(pat, output)
|
||||||
if m: return m
|
if m:
|
||||||
|
return m
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@neediface(False)
|
@neediface(False)
|
||||||
@@ -784,7 +822,8 @@ class BaseInterface(object):
|
|||||||
# timeout, while the above will wait (-w) 3 seconds at
|
# timeout, while the above will wait (-w) 3 seconds at
|
||||||
# most.
|
# most.
|
||||||
cmd = "ping -q -c 1 %s" % gateway
|
cmd = "ping -q -c 1 %s" % gateway
|
||||||
if self.verbose: print cmd
|
if self.verbose:
|
||||||
|
print cmd
|
||||||
return misc.LaunchAndWait(cmd)
|
return misc.LaunchAndWait(cmd)
|
||||||
|
|
||||||
@neediface(False)
|
@neediface(False)
|
||||||
@@ -799,7 +838,8 @@ class BaseInterface(object):
|
|||||||
try:
|
try:
|
||||||
flags = open(flags_file, "r").read().strip()
|
flags = open(flags_file, "r").read().strip()
|
||||||
except IOError:
|
except IOError:
|
||||||
print "Could not open %s, using ifconfig to determine status" % flags_file
|
print "Could not open %s, using ifconfig to determine status" \
|
||||||
|
% flags_file
|
||||||
return self._slow_is_up(ifconfig)
|
return self._slow_is_up(ifconfig)
|
||||||
return bool(int(flags, 16) & 1)
|
return bool(int(flags, 16) & 1)
|
||||||
|
|
||||||
@@ -807,7 +847,8 @@ class BaseInterface(object):
|
|||||||
def StopWPA(self):
|
def StopWPA(self):
|
||||||
""" Terminates wpa using wpa_cli"""
|
""" Terminates wpa using wpa_cli"""
|
||||||
cmd = 'wpa_cli -i %s terminate' % self.iface
|
cmd = 'wpa_cli -i %s terminate' % self.iface
|
||||||
if self.verbose: print cmd
|
if self.verbose:
|
||||||
|
print cmd
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
|
|
||||||
|
|
||||||
@@ -866,7 +907,8 @@ class BaseWiredInterface(BaseInterface):
|
|||||||
while True:
|
while True:
|
||||||
tries += 1
|
tries += 1
|
||||||
time.sleep(2)
|
time.sleep(2)
|
||||||
if self.IsUp() or tries > MAX_TRIES: break
|
if self.IsUp() or tries > MAX_TRIES:
|
||||||
|
break
|
||||||
|
|
||||||
if os.path.exists(carrier_path):
|
if os.path.exists(carrier_path):
|
||||||
carrier = open(carrier_path, 'r')
|
carrier = open(carrier_path, 'r')
|
||||||
@@ -878,7 +920,8 @@ class BaseWiredInterface(BaseInterface):
|
|||||||
elif link == 0:
|
elif link == 0:
|
||||||
return False
|
return False
|
||||||
except (IOError, ValueError, TypeError):
|
except (IOError, ValueError, TypeError):
|
||||||
print 'Error checking link using /sys/class/net/%s/carrier' % self.iface
|
print 'Error checking link using /sys/class/net/%s/carrier' \
|
||||||
|
% self.iface
|
||||||
|
|
||||||
if self.ethtool_cmd and self.link_detect in [misc.ETHTOOL, misc.AUTO]:
|
if self.ethtool_cmd and self.link_detect in [misc.ETHTOOL, misc.AUTO]:
|
||||||
return self._eth_get_plugged_in()
|
return self._eth_get_plugged_in()
|
||||||
@@ -901,10 +944,13 @@ class BaseWiredInterface(BaseInterface):
|
|||||||
print 'Wired Interface is down, putting it up'
|
print 'Wired Interface is down, putting it up'
|
||||||
self.Up()
|
self.Up()
|
||||||
time.sleep(6)
|
time.sleep(6)
|
||||||
if self.verbose: print cmd
|
if self.verbose:
|
||||||
|
print cmd
|
||||||
tool_data = misc.Run(cmd, include_stderr=True)
|
tool_data = misc.Run(cmd, include_stderr=True)
|
||||||
if misc.RunRegex(re.compile('(Link detected: yes)', re.I | re.M | re.S),
|
if misc.RunRegex(
|
||||||
tool_data):
|
re.compile('(Link detected: yes)', re.I | re.M | re.S),
|
||||||
|
tool_data
|
||||||
|
):
|
||||||
return True
|
return True
|
||||||
else:
|
else:
|
||||||
return False
|
return False
|
||||||
@@ -917,14 +963,16 @@ class BaseWiredInterface(BaseInterface):
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
cmd = "%s %s" % (self.miitool_cmd, self.iface)
|
cmd = "%s %s" % (self.miitool_cmd, self.iface)
|
||||||
if self.verbose: print cmd
|
if self.verbose:
|
||||||
|
print cmd
|
||||||
tool_data = misc.Run(cmd, include_stderr=True)
|
tool_data = misc.Run(cmd, include_stderr=True)
|
||||||
if misc.RunRegex(re.compile('(Invalid argument)', re.I | re.M | re.S),
|
if misc.RunRegex(re.compile('(Invalid argument)', re.I | re.M | re.S),
|
||||||
tool_data) is not None:
|
tool_data) is not None:
|
||||||
print 'Wired Interface is down, putting it up'
|
print 'Wired Interface is down, putting it up'
|
||||||
self.Up()
|
self.Up()
|
||||||
time.sleep(4)
|
time.sleep(4)
|
||||||
if self.verbose: print cmd
|
if self.verbose:
|
||||||
|
print cmd
|
||||||
tool_data = misc.Run(cmd, include_stderr=True)
|
tool_data = misc.Run(cmd, include_stderr=True)
|
||||||
|
|
||||||
if misc.RunRegex(re.compile('(link ok)', re.I | re.M | re.S),
|
if misc.RunRegex(re.compile('(link ok)', re.I | re.M | re.S),
|
||||||
@@ -934,11 +982,13 @@ class BaseWiredInterface(BaseInterface):
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
def Authenticate(self, network):
|
def Authenticate(self, network):
|
||||||
|
""" Authenticate with wpa_supplicant. """
|
||||||
misc.ParseEncryption(network)
|
misc.ParseEncryption(network)
|
||||||
cmd = ['wpa_supplicant', '-B', '-i', self.iface, '-c',
|
cmd = ['wpa_supplicant', '-B', '-i', self.iface, '-c',
|
||||||
os.path.join(wpath.networks, 'wired'),
|
os.path.join(wpath.networks, 'wired'),
|
||||||
'-Dwired']
|
'-Dwired']
|
||||||
if self.verbose: print cmd
|
if self.verbose:
|
||||||
|
print cmd
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
|
|
||||||
class BaseWirelessInterface(BaseInterface):
|
class BaseWirelessInterface(BaseInterface):
|
||||||
@@ -968,7 +1018,8 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
cmd = ['iwconfig', self.iface, 'essid', '--', str(essid)]
|
cmd = ['iwconfig', self.iface, 'essid', '--', str(essid)]
|
||||||
if self.verbose: print str(cmd)
|
if self.verbose:
|
||||||
|
print str(cmd)
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
|
|
||||||
@neediface(False)
|
@neediface(False)
|
||||||
@@ -994,7 +1045,8 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
def GetIwconfig(self):
|
def GetIwconfig(self):
|
||||||
""" Returns the output of iwconfig for this interface. """
|
""" Returns the output of iwconfig for this interface. """
|
||||||
cmd = "iwconfig " + self.iface
|
cmd = "iwconfig " + self.iface
|
||||||
if self.verbose: print cmd
|
if self.verbose:
|
||||||
|
print cmd
|
||||||
return misc.Run(cmd)
|
return misc.Run(cmd)
|
||||||
|
|
||||||
def _FreqToChannel(self, freq):
|
def _FreqToChannel(self, freq):
|
||||||
@@ -1019,7 +1071,7 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
try:
|
try:
|
||||||
ret = freq_dict[freq]
|
ret = freq_dict[freq]
|
||||||
except KeyError:
|
except KeyError:
|
||||||
print "Couldn't determine channel number for frequency: " + str(freq)
|
print "Couldn't determine channel number for frequency:", str(freq)
|
||||||
|
|
||||||
return ret
|
return ret
|
||||||
|
|
||||||
@@ -1040,7 +1092,7 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
for x in lines:
|
for x in lines:
|
||||||
ap = {}
|
ap = {}
|
||||||
info = x.split(" ")
|
info = x.split(" ")
|
||||||
info = filter(None, [x.strip() for x in info])
|
info = [x.strip() for x in info if x.strip()]
|
||||||
if len(info) < 5:
|
if len(info) < 5:
|
||||||
continue
|
continue
|
||||||
if re.match(patt, info[2].upper()):
|
if re.match(patt, info[2].upper()):
|
||||||
@@ -1066,7 +1118,7 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
ap['enctype'] = info[4 + offset]
|
ap['enctype'] = info[4 + offset]
|
||||||
elif info[5 + offset] == 'WPA2-PSK':
|
elif info[5 + offset] == 'WPA2-PSK':
|
||||||
ap['encryption_method'] = 'WPA2'
|
ap['encryption_method'] = 'WPA2'
|
||||||
ap['authmode'] ="WPA2PSK"
|
ap['authmode'] = "WPA2PSK"
|
||||||
ap['keyname'] = "WPA2PSK"
|
ap['keyname'] = "WPA2PSK"
|
||||||
ap['enctype'] = info[4 + offset]
|
ap['enctype'] = info[4 + offset]
|
||||||
elif info[4 + offset] == "NONE":
|
elif info[4 + offset] == "NONE":
|
||||||
@@ -1075,7 +1127,8 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
print "Unknown AuthMode, can't assign encryption_method!"
|
print "Unknown AuthMode, can't assign encryption_method!"
|
||||||
ap['encryption_method'] = 'Unknown'
|
ap['encryption_method'] = 'Unknown'
|
||||||
aps[bssid] = ap
|
aps[bssid] = ap
|
||||||
if self.verbose: print str(aps)
|
if self.verbose:
|
||||||
|
print str(aps)
|
||||||
return aps
|
return aps
|
||||||
|
|
||||||
def _ParseRalinkAccessPoint(self, ap, ralink_info, cell):
|
def _ParseRalinkAccessPoint(self, ap, ralink_info, cell):
|
||||||
@@ -1090,7 +1143,6 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
Updated array containing info about the current access point
|
Updated array containing info about the current access point
|
||||||
|
|
||||||
"""
|
"""
|
||||||
wep_pattern = re.compile('.*Encryption key:(.*?)\n', re.I | re.M | re.S)
|
|
||||||
if ralink_info.has_key(ap['bssid']):
|
if ralink_info.has_key(ap['bssid']):
|
||||||
info = ralink_info[ap['bssid']]
|
info = ralink_info[ap['bssid']]
|
||||||
for key in info.keys():
|
for key in info.keys():
|
||||||
@@ -1115,7 +1167,8 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
if mode.lower() == 'master':
|
if mode.lower() == 'master':
|
||||||
mode = 'managed'
|
mode = 'managed'
|
||||||
cmd = 'iwconfig %s mode %s' % (self.iface, mode)
|
cmd = 'iwconfig %s mode %s' % (self.iface, mode)
|
||||||
if self.verbose: print cmd
|
if self.verbose:
|
||||||
|
print cmd
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
|
|
||||||
@neediface(False)
|
@neediface(False)
|
||||||
@@ -1131,7 +1184,8 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
cmd = 'iwconfig %s channel %s' % (self.iface, str(channel))
|
cmd = 'iwconfig %s channel %s' % (self.iface, str(channel))
|
||||||
if self.verbose: print cmd
|
if self.verbose:
|
||||||
|
print cmd
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
|
|
||||||
@neediface(False)
|
@neediface(False)
|
||||||
@@ -1143,7 +1197,8 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
cmd = 'iwconfig %s key %s' % (self.iface, key)
|
cmd = 'iwconfig %s key %s' % (self.iface, key)
|
||||||
if self.verbose: print cmd
|
if self.verbose:
|
||||||
|
print cmd
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
|
|
||||||
@neediface(False)
|
@neediface(False)
|
||||||
@@ -1176,11 +1231,13 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
base = "iwconfig %s" % self.iface
|
base = "iwconfig %s" % self.iface
|
||||||
if channel and str(channel).isdigit():
|
if channel and str(channel).isdigit():
|
||||||
cmd = "%s channel %s" % (base, str(channel))
|
cmd = "%s channel %s" % (base, str(channel))
|
||||||
if self.verbose: print cmd
|
if self.verbose:
|
||||||
|
print cmd
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
if bssid:
|
if bssid:
|
||||||
cmd = "%s ap %s" % (base, bssid)
|
cmd = "%s ap %s" % (base, bssid)
|
||||||
if self.verbose: print cmd
|
if self.verbose:
|
||||||
|
print cmd
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
|
|
||||||
def GeneratePSK(self, network):
|
def GeneratePSK(self, network):
|
||||||
@@ -1191,11 +1248,13 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
wpa_pass_path = misc.find_path('wpa_passphrase')
|
wpa_pass_path = misc.find_path('wpa_passphrase')
|
||||||
if not wpa_pass_path: return None
|
if not wpa_pass_path:
|
||||||
|
return None
|
||||||
key_pattern = re.compile('network={.*?\spsk=(.*?)\n}.*',
|
key_pattern = re.compile('network={.*?\spsk=(.*?)\n}.*',
|
||||||
re.I | re.M | re.S)
|
re.I | re.M | re.S)
|
||||||
cmd = [wpa_pass_path, str(network['essid']), str(network['key'])]
|
cmd = [wpa_pass_path, str(network['essid']), str(network['key'])]
|
||||||
if self.verbose: print cmd
|
if self.verbose:
|
||||||
|
print cmd
|
||||||
return misc.RunRegex(key_pattern, misc.Run(cmd))
|
return misc.RunRegex(key_pattern, misc.Run(cmd))
|
||||||
|
|
||||||
@neediface(False)
|
@neediface(False)
|
||||||
@@ -1218,7 +1277,8 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
os.path.join(wpath.networks,
|
os.path.join(wpath.networks,
|
||||||
network['bssid'].replace(':', '').lower()),
|
network['bssid'].replace(':', '').lower()),
|
||||||
driver]
|
driver]
|
||||||
if self.verbose: print cmd
|
if self.verbose:
|
||||||
|
print cmd
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
|
|
||||||
def _AuthenticateRalinkLegacy(self, network):
|
def _AuthenticateRalinkLegacy(self, network):
|
||||||
@@ -1243,7 +1303,8 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
print 'Setting up WEP'
|
print 'Setting up WEP'
|
||||||
cmd = ''.join(['iwconfig ', self.iface, ' key ',
|
cmd = ''.join(['iwconfig ', self.iface, ' key ',
|
||||||
network.get('key')])
|
network.get('key')])
|
||||||
if self.verbose: print cmd
|
if self.verbose:
|
||||||
|
print cmd
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
else:
|
else:
|
||||||
cmd_list = []
|
cmd_list = []
|
||||||
@@ -1251,13 +1312,14 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
cmd_list.append('AuthMode=' + info['authmode'])
|
cmd_list.append('AuthMode=' + info['authmode'])
|
||||||
cmd_list.append('EncrypType=' + info['enctype'])
|
cmd_list.append('EncrypType=' + info['enctype'])
|
||||||
cmd_list.append('SSID="%s"' % network['essid'])
|
cmd_list.append('SSID="%s"' % network['essid'])
|
||||||
cmd_list.append('%s="%s"' % (network['keyname'], network['key']))
|
cmd_list.append('%(keyname)s="%(key)s"' % network)
|
||||||
if info['nettype'] == 'SHARED' and info['enctype'] == 'WEP':
|
if info['nettype'] == 'SHARED' and info['enctype'] == 'WEP':
|
||||||
cmd_list.append('DefaultKeyID=1')
|
cmd_list.append('DefaultKeyID=1')
|
||||||
|
|
||||||
for cmd in cmd_list:
|
for cmd in cmd_list:
|
||||||
cmd = ['iwpriv', self.iface, 'set', cmd]
|
cmd = ['iwpriv', self.iface, 'set', cmd]
|
||||||
if self.verbose: print ' '.join(cmd)
|
if self.verbose:
|
||||||
|
print ' '.join(cmd)
|
||||||
misc.Run(cmd)
|
misc.Run(cmd)
|
||||||
|
|
||||||
@neediface([])
|
@neediface([])
|
||||||
@@ -1269,7 +1331,8 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
cmd = 'iwlist ' + self.iface + ' scan'
|
cmd = 'iwlist ' + self.iface + ' scan'
|
||||||
if self.verbose: print cmd
|
if self.verbose:
|
||||||
|
print cmd
|
||||||
results = misc.Run(cmd)
|
results = misc.Run(cmd)
|
||||||
# Split the networks apart, using Cell as our split point
|
# Split the networks apart, using Cell as our split point
|
||||||
# this way we can look at only one network at a time.
|
# this way we can look at only one network at a time.
|
||||||
@@ -1501,7 +1564,8 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
""" Get the available authentication methods for the interface. """
|
""" Get the available authentication methods for the interface. """
|
||||||
if not iwlistauth:
|
if not iwlistauth:
|
||||||
cmd = 'iwlist ' + self.iface + ' auth'
|
cmd = 'iwlist ' + self.iface + ' auth'
|
||||||
if self.verbose: print cmd
|
if self.verbose:
|
||||||
|
print cmd
|
||||||
output = misc.Run(cmd)
|
output = misc.Run(cmd)
|
||||||
else:
|
else:
|
||||||
output = iwlistauth
|
output = iwlistauth
|
||||||
@@ -1515,13 +1579,14 @@ class BaseWirelessInterface(BaseInterface):
|
|||||||
""" Get the available bitrates the wifi card can use. """
|
""" Get the available bitrates the wifi card can use. """
|
||||||
|
|
||||||
cmd = 'iwlist ' + self.iface + ' rate'
|
cmd = 'iwlist ' + self.iface + ' rate'
|
||||||
if self.verbose: print cmd
|
if self.verbose:
|
||||||
|
print cmd
|
||||||
rates = misc.Run(cmd)
|
rates = misc.Run(cmd)
|
||||||
|
|
||||||
# process the output
|
# process the output
|
||||||
rates = rates.split('\n')
|
rates = rates.split('\n')
|
||||||
rates = filter(None, map(lambda x: x.strip().split(' ')[0], rates))
|
rates = [x.strip().split(' ')[0] for x in rates]
|
||||||
rates = filter(lambda x: x[0].isdigit(), rates)
|
rates = [x for x in rates if x[0].isdigit()]
|
||||||
return dbus.Array(rates, signature='v')
|
return dbus.Array(rates, signature='v')
|
||||||
|
|
||||||
def _get_link_quality(self, output):
|
def _get_link_quality(self, output):
|
||||||
|
|||||||
Reference in New Issue
Block a user