set indent to four spaces.

This commit is contained in:
Ferdi Franceschini
2014-07-05 20:16:09 +10:00
parent 30791324ac
commit a0465541b3

View File

@ -1,5 +1,5 @@
#!/usr/bin/env python #!/usr/bin/env python
# vim: tabstop=8 softtabstop=2 shiftwidth=2 nocin si et ft=python # vim: tabstop=8 softtabstop=4 shiftwidth=4 nocin si et ft=python
# View Screen has 3 parts # View Screen has 3 parts
# (Instrument Configuration), (Configuration Options), (Option Implementation) # (Instrument Configuration), (Configuration Options), (Option Implementation)
@ -30,277 +30,277 @@ import copy
from collections import defaultdict from collections import defaultdict
Palette = [ Palette = [
('body', 'dark cyan', '', 'standout'), ('body', 'dark cyan', '', 'standout'),
('focus', 'dark red', '', 'standout'), ('focus', 'dark red', '', 'standout'),
('head', 'light red', 'black'), ('head', 'light red', 'black'),
] ]
class RadioButtonListWalker(urwid.SimpleListWalker): class RadioButtonListWalker(urwid.SimpleListWalker):
def __init__(self, item_states, on_state_change=None, user_data=None): def __init__(self, item_states, on_state_change=None, user_data=None):
radio_grp = [] radio_grp = []
mapped_rb_list = [] mapped_rb_list = []
self.button_dict = {} self.button_dict = {}
for item,stateval in item_states: for item,stateval in item_states:
rb = urwid.RadioButton(radio_grp, item, state=stateval, on_state_change=on_state_change, user_data=user_data) rb = urwid.RadioButton(radio_grp, item, state=stateval, on_state_change=on_state_change, user_data=user_data)
self.button_dict[item] = rb self.button_dict[item] = rb
mapped_rb = urwid.AttrMap(rb, 'body', 'focus') mapped_rb = urwid.AttrMap(rb, 'body', 'focus')
mapped_rb_list.append(mapped_rb) mapped_rb_list.append(mapped_rb)
super(RadioButtonListWalker, self).__init__(mapped_rb_list) super(RadioButtonListWalker, self).__init__(mapped_rb_list)
return return
class CheckBoxListWalker(urwid.SimpleListWalker): class CheckBoxListWalker(urwid.SimpleListWalker):
def __init__(self, item_states, on_state_change = None, user_data = None): def __init__(self, item_states, on_state_change = None, user_data = None):
mapped_cb_list = [] mapped_cb_list = []
self.button_dict = {} self.button_dict = {}
for item,stateval in item_states: for item,stateval in item_states:
cb = urwid.CheckBox(item, state = stateval, on_state_change = on_state_change, user_data = user_data) cb = urwid.CheckBox(item, state = stateval, on_state_change = on_state_change, user_data = user_data)
self.button_dict[item] = cb self.button_dict[item] = cb
mapped_cb = urwid.AttrMap(cb, 'body', 'focus') mapped_cb = urwid.AttrMap(cb, 'body', 'focus')
mapped_cb_list.append(mapped_cb) mapped_cb_list.append(mapped_cb)
super(CheckBoxListWalker, self).__init__(mapped_cb_list) super(CheckBoxListWalker, self).__init__(mapped_cb_list)
return return
class OptionListWalker(CheckBoxListWalker): class OptionListWalker(CheckBoxListWalker):
def __init__(self, opt_dict, statechange_cb): def __init__(self, opt_dict, statechange_cb):
urwid.register_signal(OptionListWalker, ['focus_change']) urwid.register_signal(OptionListWalker, ['focus_change'])
item_states = [(i,d['enabled']) for i,d in opt_dict.iteritems()] item_states = [(i,d['enabled']) for i,d in opt_dict.iteritems()]
item_states.sort() item_states.sort()
super(OptionListWalker, self).__init__(item_states, statechange_cb) super(OptionListWalker, self).__init__(item_states, statechange_cb)
return return
def set_focus(self, pos): def set_focus(self, pos):
dbg.msg(0, 'OptionListWalker:set_focus({0}) -> emit focus_change'.format(pos)) dbg.msg(0, 'OptionListWalker:set_focus({0}) -> emit focus_change'.format(pos))
urwid.emit_signal(self, 'focus_change', pos) urwid.emit_signal(self, 'focus_change', pos)
return super(OptionListWalker, self).set_focus(pos) return super(OptionListWalker, self).set_focus(pos)
# ClosedListBox implements a ListBox which prevents selection outside of the # ClosedListBox implements a ListBox which prevents selection outside of the
# list using the 'up' or 'down' keys # list using the 'up' or 'down' keys
class ClosedListBox(urwid.ListBox): class ClosedListBox(urwid.ListBox):
def keypress(self, size, key): def keypress(self, size, key):
"""Prevents navigating outside of a ClosedListBox with the up and down arrow keys""" """Prevents navigating outside of a ClosedListBox with the up and down arrow keys"""
pos = self.get_focus()[1] pos = self.get_focus()[1]
ll = len(self.body) ll = len(self.body)
if (pos <= 0 and key == 'up') or (pos >= ll-1 and key == 'down'): if (pos <= 0 and key == 'up') or (pos >= ll-1 and key == 'down'):
return return
else: else:
return super(ClosedListBox, self).keypress(size, key) return super(ClosedListBox, self).keypress(size, key)
# List of Checkboxes # List of Checkboxes
class OptionListBox(ClosedListBox): class OptionListBox(ClosedListBox):
def __init__(self, listwalker): def __init__(self, listwalker):
super(OptionListBox, self).__init__(listwalker) super(OptionListBox, self).__init__(listwalker)
return return
# List of RadioButtons # List of RadioButtons
class ImpListBox(ClosedListBox): class ImpListBox(ClosedListBox):
def __init__(self, listwalker): def __init__(self, listwalker):
super(ImpListBox, self).__init__(listwalker) super(ImpListBox, self).__init__(listwalker)
return return
def use_listwalker(self, liswalker): def use_listwalker(self, liswalker):
self.body.contents[:] = liswalker self.body.contents[:] = liswalker
return return
class InstConfigData: class InstConfigData:
msg_index = 4 msg_index = 4
# configuration_dict: dict of instrument configurations as defined below, # configuration_dict: dict of instrument configurations as defined below,
# {configname: {'enabled':T/F, 'cascade_list':[(option, dflt_imp)]} } # {configname: {'enabled':T/F, 'cascade_list':[(option, dflt_imp)]} }
configuration_dict = defaultdict(dict) configuration_dict = defaultdict(dict)
# imp_dict: dict of implementations indexed by optype, # imp_dict: dict of implementations indexed by optype,
# {optype: [impname] } # {optype: [impname] }
imp_dict = defaultdict(list) imp_dict = defaultdict(list)
# opt_dict: dict of configuration options as defined below, # opt_dict: dict of configuration options as defined below,
# {optname:{'enabled': T/F/Always, 'imptype':optype, 'selected_imp':dflt}} # {optname:{'enabled': T/F/Always, 'imptype':optype, 'selected_imp':dflt}}
opt_dict = defaultdict(dict) opt_dict = defaultdict(dict)
# imp2opt_dict: Maps each implementation to an option or None, # imp2opt_dict: Maps each implementation to an option or None,
# {imp: opt/None} # {imp: opt/None}
imp2opt_dict = {} imp2opt_dict = {}
# optypelist: list of (opt, optype) tuples # optypelist: list of (opt, optype) tuples
# [(opt, optype)] # [(opt, optype)]
optypelist = [] optypelist = []
def __get_configurations(self): def __get_configurations(self):
for s in self.file_parser.sections(): for s in self.file_parser.sections():
cascade_list = [] cascade_list = []
if self.file_parser.has_option(s, 'cascade'): if self.file_parser.has_option(s, 'cascade'):
enabled = self.file_parser.get(s, 'enabled') enabled = self.file_parser.get(s, 'enabled')
for cascade_str in self.file_parser.get(s,'cascade').split(','): for cascade_str in self.file_parser.get(s,'cascade').split(','):
cascade_list.append(tuple(cascade_str.split(':'))) cascade_list.append(tuple(cascade_str.split(':')))
if enabled.lower() in ['true','always']: if enabled.lower() in ['true','always']:
stateval = True stateval = True
else: else:
stateval = False stateval = False
self.configuration_dict[s]['enabled'] = stateval self.configuration_dict[s]['enabled'] = stateval
self.configuration_dict[s]['cascade_list'] = cascade_list self.configuration_dict[s]['cascade_list'] = cascade_list
def __get_options(self): def __get_options(self):
for s in self.file_parser.sections(): for s in self.file_parser.sections():
if self.file_parser.has_option(s, 'implementation'): if self.file_parser.has_option(s, 'implementation'):
selected_imp = self.file_parser.get(s, 'implementation') selected_imp = self.file_parser.get(s, 'implementation')
imptype = self.file_parser.get(s, 'optype') imptype = self.file_parser.get(s, 'optype')
enabled = self.file_parser.get(s, 'enabled').lower() enabled = self.file_parser.get(s, 'enabled').lower()
if enabled == 'always': if enabled == 'always':
stateval = True stateval = True
permanent = True permanent = True
elif enabled == 'true': elif enabled == 'true':
stateval = True stateval = True
permanent = False permanent = False
else: else:
stateval = False stateval = False
permanent = False permanent = False
if self.file_parser.has_option(s, 'id'): if self.file_parser.has_option(s, 'id'):
id = self.file_parser.get(s, 'id') id = self.file_parser.get(s, 'id')
self.opt_dict[s]['id'] = id self.opt_dict[s]['id'] = id
self.opt_dict[s]['enabled'] = stateval self.opt_dict[s]['enabled'] = stateval
self.opt_dict[s]['permanent'] = permanent self.opt_dict[s]['permanent'] = permanent
self.opt_dict[s]['imptype'] = imptype self.opt_dict[s]['imptype'] = imptype
if selected_imp in self.imp2opt_dict: if selected_imp in self.imp2opt_dict:
self.opt_dict[s]['selected_imp'] = 'none' self.opt_dict[s]['selected_imp'] = 'none'
else: else:
self.opt_dict[s]['selected_imp'] = selected_imp self.opt_dict[s]['selected_imp'] = selected_imp
if selected_imp != 'none': if selected_imp != 'none':
print 'Add imp2opt_dict[{0}] = {1}'.format(selected_imp,s) print 'Add imp2opt_dict[{0}] = {1}'.format(selected_imp,s)
self.imp2opt_dict[selected_imp] = s self.imp2opt_dict[selected_imp] = s
def __get_implementations(self): def __get_implementations(self):
for s in self.file_parser.sections(): for s in self.file_parser.sections():
if self.file_parser.has_option(s, 'imptype'): if self.file_parser.has_option(s, 'imptype'):
key = self.file_parser.get(s, 'imptype') key = self.file_parser.get(s, 'imptype')
if 'none' not in self.imp_dict[key]: if 'none' not in self.imp_dict[key]:
self.imp_dict[key].append('none') self.imp_dict[key].append('none')
self.imp_dict[key].append(s) self.imp_dict[key].append(s)
if s not in self.imp2opt_dict: if s not in self.imp2opt_dict:
print 'Add imp2opt_dict[{0}] = none'.format(s) print 'Add imp2opt_dict[{0}] = none'.format(s)
self.imp2opt_dict[s] = 'none' self.imp2opt_dict[s] = 'none'
def read_config_file(self, config_filename): def read_config_file(self, config_filename):
self.config_filename = config_filename self.config_filename = config_filename
self.file_parser = ConfigParser.SafeConfigParser() self.file_parser = ConfigParser.SafeConfigParser()
self.file_parser.read(config_filename) self.file_parser.read(config_filename)
self.__get_options() self.__get_options()
self.__get_implementations() self.__get_implementations()
self.__get_configurations() self.__get_configurations()
for opt,dict in self.opt_dict.iteritems(): for opt,dict in self.opt_dict.iteritems():
self.optypelist.append((opt, dict['imptype'])) self.optypelist.append((opt, dict['imptype']))
def backup_files(self): def backup_files(self):
for idx in range(8, 0, -1): for idx in range(8, 0, -1):
if os.path.exists(self.config_filename + "." + str(idx)): if os.path.exists(self.config_filename + "." + str(idx)):
os.rename(self.config_filename + "." + str(idx), os.rename(self.config_filename + "." + str(idx),
self.config_filename + "." + str(idx + 1)) self.config_filename + "." + str(idx + 1))
if os.path.exists(self.config_filename): if os.path.exists(self.config_filename):
shutil.copy(self.config_filename, self.config_filename + ".1") shutil.copy(self.config_filename, self.config_filename + ".1")
def write_config_file(self): def write_config_file(self):
for item,dict in self.opt_dict.iteritems(): for item,dict in self.opt_dict.iteritems():
if 'permanent' in dict and dict['permanent'] == True: if 'permanent' in dict and dict['permanent'] == True:
enabled = 'Always' enabled = 'Always'
else: else:
enabled = dict['enabled'].__str__() enabled = dict['enabled'].__str__()
self.file_parser.set(item, 'enabled', enabled) self.file_parser.set(item, 'enabled', enabled)
self.file_parser.set(item, 'implementation', dict['selected_imp']) self.file_parser.set(item, 'implementation', dict['selected_imp'])
self.file_parser.set(item, 'optype', dict['imptype']) self.file_parser.set(item, 'optype', dict['imptype'])
for item,dict in self.configuration_dict.iteritems(): for item,dict in self.configuration_dict.iteritems():
enabled = dict['enabled'].__str__() enabled = dict['enabled'].__str__()
self.file_parser.set(item, 'enabled', enabled) self.file_parser.set(item, 'enabled', enabled)
for imp,opt in self.imp2opt_dict.iteritems(): for imp,opt in self.imp2opt_dict.iteritems():
if imp != 'none' and opt != 'none' and 'id' in self.opt_dict[opt]: if imp != 'none' and opt != 'none' and 'id' in self.opt_dict[opt]:
self.file_parser.set(imp, 'id', self.opt_dict[opt]['id']) self.file_parser.set(imp, 'id', self.opt_dict[opt]['id'])
with open(self.config_filename,'w') as cfile: with open(self.config_filename,'w') as cfile:
for section in sorted(self.file_parser.sections()): for section in sorted(self.file_parser.sections()):
cfile.write("[%s]\n" % section) cfile.write("[%s]\n" % section)
for option in sorted(self.file_parser.options(section)): for option in sorted(self.file_parser.options(section)):
cfile.write("%s = %s\n" % (option, self.file_parser.get(section, option))) cfile.write("%s = %s\n" % (option, self.file_parser.get(section, option)))
cfile.write("\n") cfile.write("\n")
def set_imp(self, opt, new_imp): def set_imp(self, opt, new_imp):
old_imp =self.opt_dict[opt]['selected_imp'] old_imp =self.opt_dict[opt]['selected_imp']
self.imp2opt_dict[old_imp] = 'none' self.imp2opt_dict[old_imp] = 'none'
self.opt_dict[opt]['selected_imp'] = new_imp self.opt_dict[opt]['selected_imp'] = new_imp
self.imp2opt_dict[new_imp] = opt self.imp2opt_dict[new_imp] = opt
def get_optypelist (self): def get_optypelist (self):
return self.optypelist return self.optypelist
def iter_implementations(self, opt): def iter_implementations(self, opt):
dict = self.opt_dict[opt] dict = self.opt_dict[opt]
for imp in self.imp_dict[dict['imptype']]: for imp in self.imp_dict[dict['imptype']]:
yield imp yield imp
def cf_statechange(self, cfg_id, new_state, udat=None): def cf_statechange(self, cfg_id, new_state, udat=None):
self.configuration_dict[cfg_id]['enabled'] = new_state self.configuration_dict[cfg_id]['enabled'] = new_state
def opt_statechange(self, opt, new_state, udat=None): def opt_statechange(self, opt, new_state, udat=None):
dbg.msg(3, 'InstConfigData:opt_statechange({0},{1},{2})'.format(opt, new_state, udat)) dbg.msg(3, 'InstConfigData:opt_statechange({0},{1},{2})'.format(opt, new_state, udat))
self.opt_dict[opt]['enabled'] = new_state self.opt_dict[opt]['enabled'] = new_state
def imp_statechange(self, selected_imp, new_state, opt): def imp_statechange(self, selected_imp, new_state, opt):
dbg.msg(self.msg_index, 'InstConfigData:imp_statechange({0},{1},{2})'.format(selected_imp, new_state, opt)) dbg.msg(self.msg_index, 'InstConfigData:imp_statechange({0},{1},{2})'.format(selected_imp, new_state, opt))
self.msg_index = (self.msg_index - 3) % 2 + 4 self.msg_index = (self.msg_index - 3) % 2 + 4
if new_state == True: if new_state == True:
self.opt_dict[opt]['selected_imp'] = selected_imp self.opt_dict[opt]['selected_imp'] = selected_imp
class InstConfigView(urwid.Pile): class InstConfigView(urwid.Pile):
def __init__(self, cf_dat, cf_man, dbmsg): def __init__(self, cf_dat, cf_man, dbmsg):
self.cf_dat = cf_dat self.cf_dat = cf_dat
self.cf_man = cf_man self.cf_man = cf_man
option_ListBoxes = [ option_ListBoxes = [
self.cf_man.config_lb, self.cf_man.config_lb,
self.cf_man.opt_lb, self.cf_man.opt_lb,
self.cf_man.imp_lb, self.cf_man.imp_lb,
dbmsg] dbmsg]
super(InstConfigView, self).__init__(option_ListBoxes) super(InstConfigView, self).__init__(option_ListBoxes)
return return
def keyinput(self, key): def keyinput(self, key):
if key == 'meta q': if key == 'meta q':
raise urwid.ExitMainLoop() raise urwid.ExitMainLoop()
elif key == 'w': elif key == 'w':
self.cf_dat.backup_files() self.cf_dat.backup_files()
self.cf_dat.write_config_file() self.cf_dat.write_config_file()
elif key in ['right', 'tab']: elif key in ['right', 'tab']:
if self.get_focus() == self.cf_man.config_lb: if self.get_focus() == self.cf_man.config_lb:
self.set_focus(self.cf_man.opt_lb) self.set_focus(self.cf_man.opt_lb)
elif self.get_focus() == self.cf_man.opt_lb: elif self.get_focus() == self.cf_man.opt_lb:
self.set_focus(self.cf_man.imp_lb) self.set_focus(self.cf_man.imp_lb)
else: else:
self.set_focus(self.cf_man.config_lb) self.set_focus(self.cf_man.config_lb)
elif key in ['left', 'shift tab']: elif key in ['left', 'shift tab']:
if self.get_focus() == self.cf_man.config_lb: if self.get_focus() == self.cf_man.config_lb:
self.set_focus(self.cf_man.imp_lb) self.set_focus(self.cf_man.imp_lb)
elif self.get_focus() == self.cf_man.opt_lb: elif self.get_focus() == self.cf_man.opt_lb:
self.set_focus(self.cf_man.config_lb) self.set_focus(self.cf_man.config_lb)
else: else:
self.set_focus(self.cf_man.opt_lb) self.set_focus(self.cf_man.opt_lb)
# Contains OptionListWalker dict indexed by option # Contains OptionListWalker dict indexed by option
@ -309,164 +309,164 @@ class InstConfigView(urwid.Pile):
# Tracks selected implementation for each option # Tracks selected implementation for each option
# and sets selection on ImpListBox # and sets selection on ImpListBox
class InstConfigManager: class InstConfigManager:
cf_msg_index = 8 cf_msg_index = 8
imp_lw_dict = {} imp_lw_dict = {}
def __init__(self, cf_dat): def __init__(self, cf_dat):
self.cf_dat = cf_dat self.cf_dat = cf_dat
urwid.register_signal(InstConfigManager, ['focus_change']) urwid.register_signal(InstConfigManager, ['focus_change'])
self.opt_optype_list = self.cf_dat.get_optypelist() self.opt_optype_list = self.cf_dat.get_optypelist()
self.opt_optype_list.sort() self.opt_optype_list.sort()
firstopt = self.opt_optype_list[0][0] firstopt = self.opt_optype_list[0][0]
self.imp_lw = self.__gen_imp_listwalker(firstopt) self.imp_lw = self.__gen_imp_listwalker(firstopt)
self.opt_lw = OptionListWalker(cf_dat.opt_dict, self.opt_statechange) self.opt_lw = OptionListWalker(cf_dat.opt_dict, self.opt_statechange)
for label, button in self.opt_lw.button_dict.iteritems(): for label, button in self.opt_lw.button_dict.iteritems():
button.set_label('{0}:{1}'.format(label, self.cf_dat.opt_dict[label]['selected_imp'])) button.set_label('{0}:{1}'.format(label, self.cf_dat.opt_dict[label]['selected_imp']))
self.imp_lb = ImpListBox(self.imp_lw) self.imp_lb = ImpListBox(self.imp_lw)
urwid.connect_signal(self.opt_lw, 'focus_change', self.update_imp_lb) urwid.connect_signal(self.opt_lw, 'focus_change', self.update_imp_lb)
item_states = [(i,d['enabled']) for i,d in cf_dat.configuration_dict.iteritems()] item_states = [(i,d['enabled']) for i,d in cf_dat.configuration_dict.iteritems()]
item_states.sort() item_states.sort()
self.cfg_lw = RadioButtonListWalker(item_states, on_state_change = self.cf_statechange) self.cfg_lw = RadioButtonListWalker(item_states, on_state_change = self.cf_statechange)
self.config_lb = OptionListBox(self.cfg_lw) self.config_lb = OptionListBox(self.cfg_lw)
self.opt_lb = OptionListBox(self.opt_lw) self.opt_lb = OptionListBox(self.opt_lw)
self.opt_lb.set_focus(0) self.opt_lb.set_focus(0)
return return
def __imp_unavailable(self, imp): def __imp_unavailable(self, imp):
if imp == 'none': if imp == 'none':
return False return False
ckopt = self.cf_dat.imp2opt_dict[imp] ckopt = self.cf_dat.imp2opt_dict[imp]
if ckopt == 'none': if ckopt == 'none':
return False return False
elif self.cf_dat.opt_dict[ckopt]['enabled']: elif self.cf_dat.opt_dict[ckopt]['enabled']:
return True return True
else: else:
return False return False
def __gen_imp_listwalker(self, opt): def __gen_imp_listwalker(self, opt):
imp_items = [] imp_items = []
for imp in self.cf_dat.iter_implementations(opt): for imp in self.cf_dat.iter_implementations(opt):
if self.__imp_unavailable(imp): if self.__imp_unavailable(imp):
continue continue
if imp == self.cf_dat.opt_dict[opt]['selected_imp']: if imp == self.cf_dat.opt_dict[opt]['selected_imp']:
imp_items.append((imp, True)) imp_items.append((imp, True))
else: else:
imp_items.append((imp, False)) imp_items.append((imp, False))
imp_items = imp_items[:1] + sorted(imp_items[1:]) imp_items = imp_items[:1] + sorted(imp_items[1:])
rb_lw = RadioButtonListWalker(imp_items, on_state_change=self.imp_statechange, user_data=opt) rb_lw = RadioButtonListWalker(imp_items, on_state_change=self.imp_statechange, user_data=opt)
return rb_lw return rb_lw
def cf_statechange(self, button, new_state, udat=None): def cf_statechange(self, button, new_state, udat=None):
cfg_id = button.get_label() cfg_id = button.get_label()
self.cf_dat.cf_statechange(cfg_id, new_state, udat) self.cf_dat.cf_statechange(cfg_id, new_state, udat)
cascade = self.cf_dat.configuration_dict[cfg_id]['cascade_list'] cascade = self.cf_dat.configuration_dict[cfg_id]['cascade_list']
if new_state == True: if new_state == True:
for opt in self.cf_dat.opt_dict.keys(): for opt in self.cf_dat.opt_dict.keys():
self.opt_lw.button_dict[opt].set_state(False) self.opt_lw.button_dict[opt].set_state(False)
for opt,imp in cascade: for opt,imp in cascade:
self.cf_dat.set_imp(opt, imp) self.cf_dat.set_imp(opt, imp)
self.opt_lw.button_dict[opt].set_state(True) self.opt_lw.button_dict[opt].set_state(True)
imp_lw = self.__gen_imp_listwalker(opt) imp_lw = self.__gen_imp_listwalker(opt)
for opt in self.cf_dat.opt_dict.keys(): for opt in self.cf_dat.opt_dict.keys():
if self.cf_dat.opt_dict[opt]['permanent'] == True: if self.cf_dat.opt_dict[opt]['permanent'] == True:
self.opt_lw.button_dict[opt].set_state(True) self.opt_lw.button_dict[opt].set_state(True)
dbg.msg(self.cf_msg_index, 'InstConfigManager:cf_statechange({0},{1},{2}), cascade = {3}'.format(cfg_id, new_state, udat, cascade)) dbg.msg(self.cf_msg_index, 'InstConfigManager:cf_statechange({0},{1},{2}), cascade = {3}'.format(cfg_id, new_state, udat, cascade))
self.cf_msg_index = (self.cf_msg_index - 7) % 2 + 8 self.cf_msg_index = (self.cf_msg_index - 7) % 2 + 8
return return
def opt_statechange(self, button, new_state, udat=None): def opt_statechange(self, button, new_state, udat=None):
opt = button.get_label().split(':')[0] opt = button.get_label().split(':')[0]
imp = self.cf_dat.opt_dict[opt]['selected_imp'] imp = self.cf_dat.opt_dict[opt]['selected_imp']
if new_state == True: if new_state == True:
if self.__imp_unavailable(imp): if self.__imp_unavailable(imp):
self.cf_dat.opt_dict[opt]['selected_imp'] = 'none' self.cf_dat.opt_dict[opt]['selected_imp'] = 'none'
imp_none_button = self.imp_lw.button_dict['none'] imp_none_button = self.imp_lw.button_dict['none']
imp_none_button.set_state(True) imp_none_button.set_state(True)
opt_button = self.opt_lw.button_dict[opt] opt_button = self.opt_lw.button_dict[opt]
opt_button.set_label('{0}:none'.format(opt)) opt_button.set_label('{0}:none'.format(opt))
else: else:
opt_button = self.opt_lw.button_dict[opt] opt_button = self.opt_lw.button_dict[opt]
opt_button.set_label('{0}:{1}'.format(opt,imp)) opt_button.set_label('{0}:{1}'.format(opt,imp))
self.cf_dat.set_imp(opt, imp) self.cf_dat.set_imp(opt, imp)
self.cf_dat.opt_statechange(opt, new_state, udat) self.cf_dat.opt_statechange(opt, new_state, udat)
def imp_statechange(self, button, new_state, opt): def imp_statechange(self, button, new_state, opt):
if new_state == True: if new_state == True:
imp = button.get_label() imp = button.get_label()
self.cf_dat.set_imp(opt, imp) self.cf_dat.set_imp(opt, imp)
opt_button = self.opt_lw.button_dict[opt] opt_button = self.opt_lw.button_dict[opt]
opt_button.set_label('{0}:{1}'.format(opt, imp)) opt_button.set_label('{0}:{1}'.format(opt, imp))
self.cf_dat.imp_statechange(imp, new_state, opt) self.cf_dat.imp_statechange(imp, new_state, opt)
return return
def update_imp_lb(self, pos): def update_imp_lb(self, pos):
optname = self.opt_optype_list[pos][0] optname = self.opt_optype_list[pos][0]
optype = self.opt_optype_list[pos][1] optype = self.opt_optype_list[pos][1]
mstr = 'InstConfigManager:update_imp_lb({0}) -> select {1}'.format(pos, optype) mstr = 'InstConfigManager:update_imp_lb({0}) -> select {1}'.format(pos, optype)
dbg.msg(1, mstr) dbg.msg(1, mstr)
self.imp_lw = self.__gen_imp_listwalker(optname) self.imp_lw = self.__gen_imp_listwalker(optname)
self.imp_lb.use_listwalker(self.imp_lw) self.imp_lb.use_listwalker(self.imp_lw)
return return
import pdb import pdb
class DEBUG: class DEBUG:
msgTextDict = {} msgTextDict = {}
msglist = [] msglist = []
msg_ids = [ 'm0', 'm1', 'm2', 'm3', 'm4', 'm5', 'm6', 'm7', 'm8', 'm9' ] msg_ids = [ 'm0', 'm1', 'm2', 'm3', 'm4', 'm5', 'm6', 'm7', 'm8', 'm9' ]
def __init__(self, enabled=False): def __init__(self, enabled=False):
self.enabled = enabled self.enabled = enabled
if enabled: if enabled:
for msgID in self.msg_ids: for msgID in self.msg_ids:
msgText = urwid.Text(u'Space for message {0}'.format(msgID)) msgText = urwid.Text(u'Space for message {0}'.format(msgID))
self.msgTextDict[msgID] = msgText self.msgTextDict[msgID] = msgText
self.msglist.append(urwid.AttrMap(msgText, 'body', 'focus')) self.msglist.append(urwid.AttrMap(msgText, 'body', 'focus'))
mlw = urwid.SimpleListWalker(self.msglist) mlw = urwid.SimpleListWalker(self.msglist)
self.mlb = urwid.ListBox(mlw) self.mlb = urwid.ListBox(mlw)
def msg(self, index, msg): def msg(self, index, msg):
if self.enabled: if self.enabled:
mid = self.msg_ids[index] mid = self.msg_ids[index]
self.msgTextDict[mid].set_text(msg) self.msgTextDict[mid].set_text(msg)
dbg = DEBUG(enabled=True) dbg = DEBUG(enabled=True)
def main(config_ini): def main(config_ini):
global cf_dat, cf_man, cf_viewer global cf_dat, cf_man, cf_viewer
# Make configuration data # Make configuration data
cf_dat = InstConfigData() cf_dat = InstConfigData()
cf_dat.read_config_file(config_ini) cf_dat.read_config_file(config_ini)
# Make configuration editor # Make configuration editor
cf_man = InstConfigManager(cf_dat) cf_man = InstConfigManager(cf_dat)
# Make configuration viewer # Make configuration viewer
cf_viewer = InstConfigView(cf_dat, cf_man, dbg.mlb) cf_viewer = InstConfigView(cf_dat, cf_man, dbg.mlb)
urwid.MainLoop(cf_viewer, Palette, unhandled_input=cf_viewer.keyinput).run() urwid.MainLoop(cf_viewer, Palette, unhandled_input=cf_viewer.keyinput).run()
return return
if '__main__' == __name__: if '__main__' == __name__:
default_ini = "/usr/local/sics/sics_config.ini" default_ini = "/usr/local/sics/sics_config.ini"
parser = argparse.ArgumentParser(description = """ parser = argparse.ArgumentParser(description = """
Edit a configuration (*.ini) file using python urwid widget library. Edit a configuration (*.ini) file using python urwid widget library.
Options can be enabled or disabled with mouse or spacebar. Options can be enabled or disabled with mouse or spacebar.
Navigate with arrow keys. Navigate with arrow keys.
Press W to save. Press W to save.
Press Alt-Q to quit. Press Alt-Q to quit.
The default configuration filename is %s. The default configuration filename is %s.
""" % default_ini) """ % default_ini)
parser.add_argument("-v", "--verbose", action="store_true", help="give more info in the footer") parser.add_argument("-v", "--verbose", action="store_true", help="give more info in the footer")
parser.add_argument("path", nargs="?", default = default_ini, help="name of file to edit [%s]" % default_ini) parser.add_argument("path", nargs="?", default = default_ini, help="name of file to edit [%s]" % default_ini)
args = parser.parse_args() args = parser.parse_args()
default_ini = os.path.abspath(args.path) default_ini = os.path.abspath(args.path)
main(default_ini) main(default_ini)