Skip to content

Commit

Permalink
ListBoxes.getChecked():
Browse files Browse the repository at this point in the history
Under #190.

Eliminate FindWindowById() boilerplate wx code.
I also  renamed local vars in ListBoxes.init for readability.

Mopy/bash/basher/__init__.py
replaced a `with ListBoxes` with `ListBoxes.Display` - not sure why I
hadn't

 # This is the 2nd commit message:

belt: FindWindowById(wx.ID_FORWARD) calls encapsulated
  • Loading branch information
Utumno committed Apr 29, 2015
1 parent f93246e commit 46599bb
Show file tree
Hide file tree
Showing 5 changed files with 85 additions and 93 deletions.
81 changes: 47 additions & 34 deletions Mopy/bash/balt.py
Original file line number Diff line number Diff line change
Expand Up @@ -2275,13 +2275,7 @@ def _promptDelete(self, items, dialogTitle, order):
_(u'Delete these items? This operation cannot be '
u'undone.'), [message]) as dialog:
if not dialog.askOkModal(): return []
id_ = dialog.ids[message[0]]
checks = dialog.FindWindowById(id_)
checked = []
if checks:
for i, mod in enumerate(items):
if checks.IsChecked(i): checked.append(mod)
return checked
return dialog.getChecked(message[0], items)

def _postDeleteRefresh(self, deleted): self.RefreshUI()

Expand Down Expand Up @@ -2702,8 +2696,8 @@ class ListBoxes(Dialog):
"""A window with 1 or more lists."""

def __init__(self, parent, title, message, lists, liststyle='check',
style=0, bOk=_(u'OK'), bCancel=_(u'Cancel'), Cancel=True,
resize=False):
style=0, bOk=_(u'OK'), bCancel=_(u'Cancel'), canCancel=True,
resize=False): # NB: message param is unused (since day 1)
"""lists is in this format:
if liststyle == 'check' or 'list'
[title,tooltip,item1,item2,itemn],
Expand All @@ -2721,38 +2715,38 @@ def __init__(self, parent, title, message, lists, liststyle='check',
self.SetIcons(Resources.bashBlue)
minWidth = self.GetTextExtent(title)[0]*1.2+64
sizer = wx.FlexGridSizer(len(lists)+1,1)
self.ids = {}
self._ids = {}
labels = {wx.ID_CANCEL: bCancel, wx.ID_OK: bOk}
self.SetSize(wxSize(self.GetTextExtent(title)[0]*1.2+64,-1))
for i,group in enumerate(lists):
title = group[0]
title = group[0] # also serves as key in self._ids dict
tip = group[1]
try: items = [x.s for x in group[2:]]
except: items = [x for x in group[2:]]
if len(items) == 0: continue
try: strings = [x.s for x in group[2:]]
except AttributeError: strings = [x for x in group[2:]]
if len(strings) == 0: continue
subsizer = hsbSizer((self, wx.ID_ANY, title))
if liststyle == 'check':
checks = listBox(self, choices=items, isSingle=True,
isHScroll=True, kind='checklist')
checks.Bind(wx.EVT_KEY_UP,self.OnKeyUp)
checks.Bind(wx.EVT_CONTEXT_MENU,self.OnContext)
for i in xrange(len(items)):
checks.Check(i,True)
checksCtrl = listBox(self, choices=strings, isSingle=True,
isHScroll=True, kind='checklist')
checksCtrl.Bind(wx.EVT_KEY_UP,self.OnKeyUp)
checksCtrl.Bind(wx.EVT_CONTEXT_MENU,self.OnContext)
# check all - for range and set see wx._controls.CheckListBox
checksCtrl.SetChecked(set(range(len(strings))))
elif liststyle == 'list':
checks = listBox(self, choices=items, isHScroll=True)
checksCtrl = listBox(self, choices=strings, isHScroll=True)
else:
checks = wx.TreeCtrl(self, size=(150, 200),
style=wx.TR_DEFAULT_STYLE |
wx.TR_FULL_ROW_HIGHLIGHT |
wx.TR_HIDE_ROOT)
root = checks.AddRoot(title)
for item in group[2]:
child = checks.AppendItem(root,item.s)
for subitem in group[2][item]:
sub = checks.AppendItem(child,subitem.s)
self.ids[title] = checks.GetId()
checks.SetToolTip(tooltip(tip))
subsizer.Add(checks,1,wx.EXPAND|wx.ALL,2)
checksCtrl = wx.TreeCtrl(self, size=(150, 200),
style=wx.TR_DEFAULT_STYLE |
wx.TR_FULL_ROW_HIGHLIGHT |
wx.TR_HIDE_ROOT)
root = checksCtrl.AddRoot(title)
for item, subitems in group[2].iteritems():
child = checksCtrl.AppendItem(root,item.s)
for subitem in subitems:
checksCtrl.AppendItem(child,subitem.s)
self._ids[title] = checksCtrl.GetId()
checksCtrl.SetToolTip(tooltip(tip))
subsizer.Add(checksCtrl,1,wx.EXPAND|wx.ALL,2)
sizer.Add(subsizer,0,wx.EXPAND|wx.ALL,5)
sizer.AddGrowableRow(i)
okButton = OkButton(self, label=labels[wx.ID_OK], default=True)
Expand All @@ -2765,7 +2759,7 @@ def __init__(self, parent, title, message, lists, liststyle='check',
but = button(self,id=id,label=label)
but.Bind(wx.EVT_BUTTON,self.OnClick)
buttonSizer.Add(but,0,wx.ALIGN_RIGHT|wx.LEFT,2)
if Cancel:
if canCancel:
buttonSizer.Add(CancelButton(self, label=labels[wx.ID_CANCEL]),0,wx.ALIGN_RIGHT|wx.LEFT,2)
sizer.Add(buttonSizer,1,wx.EXPAND|wx.BOTTOM|wx.LEFT|wx.RIGHT,5)
sizer.AddGrowableCol(0)
Expand Down Expand Up @@ -2800,3 +2794,22 @@ def OnClick(self,event):
event.Skip()

def askOkModal(self): return self.ShowModal() != wx.ID_CANCEL

def getChecked(self, key, items, checked=True):
"""Return a sublist of 'items' containing (un)checked items.
The control only displays the string names of items, that is why items
needs to be passed in. If items is empty it will return an empty list.
:param key: a key for the private _ids dictionary
:param items: the items that correspond to the _ids[key] checksCtrl
:param checked: keep checked items if True (default) else unchecked
:rtype : list
:return: the items in 'items' for (un)checked checkboxes in _ids[key]
"""
if not items: return []
select = []
checkList = self.FindWindowById(self._ids[key])
if checkList:
for i, mod in enumerate(items):
if checkList.IsChecked(i) ^ (not checked): select.append(mod)
return select
12 changes: 5 additions & 7 deletions Mopy/bash/basher/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4030,7 +4030,7 @@ def RefreshData(self, event=None):
message.extend(sorted(bosh.modInfos.mtimesReset))
ListBoxes.Display(self, _(u'Modified Dates Reset'), _(
u'Modified dates have been reset for some mod files.'),
[message], liststyle='list',Cancel=False)
[message], liststyle='list', canCancel=False)
del bosh.modInfos.mtimesReset[:]
popMods = 'ALL'
#--Check savegames directory...
Expand Down Expand Up @@ -4147,7 +4147,7 @@ def _corruptedWarns(self):
ListBoxes.Display(
self, _(u'Warning: Corrupt/Unrecognized Files'),
_(u'Some files have corrupted headers or TES4 header versions:'),
message, liststyle='list', Cancel=False)
message, liststyle='list', canCancel=False)

def _corruptedGameIni(self):
#--Corrupt Oblivion.ini
Expand All @@ -4167,11 +4167,9 @@ def _y2038Resets(self): # CRUFT python 2.5
u"2038. Accordingly, the dates for the following files have "
u"been reset to an earlier date: ")]
message.extend(sorted(bolt.Path.mtimeResets))
with ListBoxes(self, _(u'Warning: Dates Reset'), _(
u'Modified dates have been reset to an earlier date for '
u'these files'), [message], liststyle='list',
Cancel=False) as dialog:
dialog.ShowModal()
ListBoxes.Display(self, _(u'Warning: Dates Reset'), _(
u'Modified dates have been reset to an earlier date for these '
u'files'), [message], liststyle='list', canCancel=False)
del bolt.Path.mtimeResets[:]

def _obmmWarn(self):
Expand Down
15 changes: 4 additions & 11 deletions Mopy/bash/basher/installers_links.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,17 +154,10 @@ def Execute(self,event):
dialog.Destroy()
return
include = set()
for (lst,key) in [(newFiles,newFilesKey),
(changedFiles,changedFilesKey),
(touchedFiles,touchedFilesKey),
]:
if lst:
id_ = dialog.ids[key]
checks = dialog.FindWindowById(id_)
if checks:
for i,file_ in enumerate(lst):
if checks.IsChecked(i):
include.add(file_)
for (lst, key) in [(newFiles, newFilesKey),
(changedFiles, changedFilesKey),
(touchedFiles, touchedFilesKey), ]:
include |= set(dialog.getChecked(key, lst))
dialog.Destroy()
# Create Project
if not include:
Expand Down
50 changes: 17 additions & 33 deletions Mopy/bash/basher/mod_links.py
Original file line number Diff line number Diff line change
Expand Up @@ -881,18 +881,11 @@ def _Execute(self):
u" the patch."), checklists, bCancel=_(u'Skip'))
if dialog.askOkModal():
deselect = set()
for (list_,key) in [(unfiltered,unfilteredKey),
(merge,mergeKey),
(noMerge,noMergeKey),
(deactivate,deactivateKey),
]:
if list_:
id_ = dialog.ids[key]
checks = dialog.FindWindowById(id_)
if checks:
for i,mod in enumerate(list_):
if checks.IsChecked(i):
deselect.add(mod)
for (lst, key) in [(unfiltered, unfilteredKey),
(merge, mergeKey),
(noMerge, noMergeKey),
(deactivate, deactivateKey), ]:
deselect |= set(dialog.getChecked(key, lst))
if deselect:
with balt.BusyCursor():
for mod in deselect:
Expand Down Expand Up @@ -2721,32 +2714,23 @@ def Execute(self,event):
Current.load()
oldMasters = modFile.TES4.masters
cleaned = modFile.CleanMasters()

if cleaned:
newMasters = modFile.TES4.masters
removed = [GPath(x) for x in oldMasters if x not in newMasters]
removeKey = _(u'Masters')
group = [removeKey,
_(u'These master files are not referenced within the mod, and can safely be removed.'),
]
group = [removeKey, _(
u'These master files are not referenced within the mod, '
u'and can safely be removed.'), ]
group.extend(removed)
checklists = [group]
dialog = ListBoxes(Link.Frame,_(u'Remove these masters?'),
_(u'The following master files can be safely removed.'),
checklists)
if not dialog.askOkModal():
dialog.Destroy()
return
id_ = dialog.ids[removeKey]
checks = dialog.FindWindowById(id_)
if checks:
for i,mod in enumerate(removed):
if not checks.IsChecked(i):
newMasters.append(mod)

modFile.TES4.masters = newMasters
modFile.save()
dialog.Destroy()
deprint(u'to remove:', removed)
with ListBoxes(Link.Frame, _(u'Remove these masters?'), _(
u'The following master files can be safely removed.'),
checklists) as dialog:
if not dialog.askOkModal(): return
newMasters.extend(
dialog.getChecked(removeKey, removed, checked=False))
modFile.TES4.masters = newMasters
modFile.save()
deprint(u'to remove:', removed)
else:
self._showOk(_(u'No Masters to clean.'), _(u'Clean Masters'))
20 changes: 12 additions & 8 deletions Mopy/bash/belt.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,10 +196,14 @@ def Run(self):
# a couple simple things here
#-------------------------------------------------------------
class PageInstaller(wiz.PyWizardPage):

def __init__(self, parent):
wiz.PyWizardPage.__init__(self, parent)
self.parent = parent
parent.FindWindowById(wx.ID_FORWARD).Enable(True)
self._enableForward(True)

def _enableForward(self, enable):
self.parent.FindWindowById(wx.ID_FORWARD).Enable(enable)

def GetNext(self): return self.parent.dummy
def GetPrev(self):
Expand All @@ -222,7 +226,7 @@ def __init__(self, parent, title, errorMsg):
PageInstaller.__init__(self, parent)

#Disable the "Finish"/"Next" button
self.parent.FindWindowById(wx.ID_FORWARD).Enable(False)
self._enableForward(False)

#Layout stuff
sizerMain = wx.FlexGridSizer(2, 1, 5, 5)
Expand Down Expand Up @@ -277,7 +281,7 @@ def __init__(self, parent, bMany, title, desc, listItems, listDescs, listImages,
else:
self.listOptions = balt.listBox(self, choices=listItems,
isHScroll=True)
self.parent.FindWindowById(wx.ID_FORWARD).Enable(False)
self._enableForward(False)
for index, default in enumerate(defaultMap):
if default:
self.listOptions.Select(index)
Expand Down Expand Up @@ -313,7 +317,7 @@ def OnDoubleClick(self, event):
pass

def Selection(self, index):
self.parent.FindWindowById(wx.ID_FORWARD).Enable(True)
self._enableForward(True)
self.index = index
self.textItem.SetValue(self.descs[index])
# Don't want the bitmap to resize until we call self.Layout()
Expand Down Expand Up @@ -478,15 +482,15 @@ def __init__(self, parent, subsList, espmsList, espmRenames, bAuto, notes, inied
checkSizer.Add(checkSubSizer,0,wx.EXPAND)
sizerMain.Add(checkSizer,0,wx.TOP|wx.RIGHT|wx.EXPAND,5)

self.parent.FindWindowById(wx.ID_FORWARD).Enable(bAuto)
self._enableForward(bAuto)
self.parent.finishing = True

sizerMain.SetSizeHints(self)
self.SetSizer(sizerMain)
self.Layout()

def OnCheckApply(self, event):
self.parent.FindWindowById(wx.ID_FORWARD).Enable(self.checkApply.IsChecked())
self._enableForward(self.checkApply.IsChecked())

def OnCheckInstall(self, event):
self.parent.ret.Install = self.checkInstall.IsChecked()
Expand Down Expand Up @@ -590,7 +594,7 @@ def __init__(self, parent, bGameOk, gameHave, gameNeed, bSEOk, seHave,
sizerCheck = wx.FlexGridSizer(1, 2, 5, 5)
self.checkOk = balt.checkBox(self, _(u'Install anyway.'),
onCheck=self.OnCheck)
self.parent.FindWindowById(wx.ID_FORWARD).Enable(False)
self._enableForward(False)
sizerCheck.AddStretchSpacer()
sizerCheck.Add(self.checkOk)
sizerCheck.AddGrowableRow(0)
Expand All @@ -604,7 +608,7 @@ def __init__(self, parent, bGameOk, gameHave, gameNeed, bSEOk, seHave,
self.Layout()

def OnCheck(self, event):
self.parent.FindWindowById(wx.ID_FORWARD).Enable(self.checkOk.IsChecked())
self._enableForward(self.checkOk.IsChecked())
# END PageVersions -----------------------------------------------

# WryeParser -----------------------------------------------------
Expand Down

0 comments on commit 46599bb

Please sign in to comment.