Ignore:
Timestamp:
Sep 29, 2014 2:31:04 PM (7 years ago)
Author:
toby
Message:

logging refactored, and much cleaner\!

File:
1 edited

Legend:

Unmodified
Added
Removed
  • branch/logging/GSASIIgrid.py

    r1497 r1509  
    160160#### GSAS-II class definitions
    161161################################################################################       
    162 
     162class G2TreeCtrl(wx.TreeCtrl):
     163    '''Create a wrapper around the standard TreeCtrl so we can "wrap"
     164    various events.
     165   
     166    This logs when a tree item is selected (in :meth:`onSelectionChanged`)
     167
     168    This also wraps lists and dicts pulled out of the tree to track where
     169    they were retrieved from.
     170    '''
     171    def __init__(self,parent=None,*args,**kwargs):
     172        super(self.__class__,self).__init__(parent=parent,*args,**kwargs)
     173        log.LogInfo['G2frame'] = self.G2frame = parent.GetParent()
     174        self.root = self.AddRoot('Loaded Data: ')
     175        self.SelectionChanged = None
     176        log.LogInfo['Tree'] = self
     177
     178    def _getTreeItemsList(self,item):
     179        '''Get the full tree hierarchy from a reference to a tree item.
     180        Note that this effectively hard-codes phase and histogram names in the
     181        returned list. We may want to make these names relative in the future.
     182        '''
     183        textlist = [self.GetItemText(item)]
     184        parent = self.GetItemParent(item)
     185        while parent:
     186            if parent == self.root: break
     187            textlist.insert(0,self.GetItemText(parent))
     188            parent = self.GetItemParent(parent)
     189        return textlist
     190
     191    def onSelectionChanged(self,event):
     192        '''Log each press on a tree item here.
     193        '''
     194        if self.SelectionChanged:
     195            textlist = self._getTreeItemsList(event.GetItem())
     196            if log.LogInfo['Logging'] and event.GetItem() != self.root:
     197                textlist[0] = self.GetRelativeHistNum(textlist[0])
     198                if textlist[0] == "Phases" and len(textlist) > 1:
     199                    textlist[1] = self.GetRelativePhaseNum(textlist[1])
     200                log.G2logList.append(log.TreeLogEntry(textlist))
     201            self.SelectionChanged(event)
     202
     203    def Bind(self,eventtype,handler,*args,**kwargs):
     204        '''Override the Bind() function so that page change events can be trapped
     205        '''
     206        if eventtype == wx.EVT_TREE_SEL_CHANGED:
     207            self.SelectionChanged = handler
     208            wx.TreeCtrl.Bind(self,eventtype,self.onSelectionChanged)
     209            return
     210        wx.TreeCtrl.Bind(self,eventtype,handler,*args,**kwargs)
     211
     212    def GetItemPyData(self,*args,**kwargs):
     213        '''Override the standard method to wrap the contents
     214        so that the source can be tracked
     215        '''
     216        data = super(self.__class__,self).GetItemPyData(*args,**kwargs)
     217        textlist = self._getTreeItemsList(args[0])
     218        if type(data) is dict:
     219            return log.dictLogged(data,textlist)
     220        if type(data) is list:
     221            return log.listLogged(data,textlist)
     222        if type(data) is tuple: #N.B. tuples get converted to lists
     223            return log.listLogged(list(data),textlist)
     224        return data
     225
     226    def GetRelativeHistNum(self,histname):
     227        '''Returns list with a histogram type and a relative number for that
     228        histogram, or the original string if not a histogram
     229        '''
     230        histtype = histname.split()[0]
     231        if histtype != histtype.upper(): # histograms (only) have a keyword all in caps
     232            return histname
     233        item, cookie = self.GetFirstChild(self.root)
     234        i = 0
     235        while item:
     236            itemtext = self.GetItemText(item)
     237            if itemtext == histname:
     238                return histtype,i
     239            elif itemtext.split()[0] == histtype:
     240                i += 1
     241            item, cookie = self.GetNextChild(self.root, cookie)
     242        else:
     243            raise Exception("Histogram not found: "+histname)
     244
     245    def ConvertRelativeHistNum(self,histtype,histnum):
     246        '''Converts a histogram type and relative histogram number to a
     247        histogram name in the current project
     248        '''
     249        item, cookie = self.GetFirstChild(self.root)
     250        i = 0
     251        while item:
     252            itemtext = self.GetItemText(item)
     253            if itemtext.split()[0] == histtype:
     254                if i == histnum: return itemtext
     255                i += 1
     256            item, cookie = self.GetNextChild(self.root, cookie)
     257        else:
     258            raise Exception("Histogram #'+str(histnum)+' of type "+histtype+' not found')
     259       
     260    def GetRelativePhaseNum(self,phasename):
     261        '''Returns a phase number if the string matches a phase name
     262        or else returns the original string
     263        '''
     264        item, cookie = self.GetFirstChild(self.root)
     265        while item:
     266            itemtext = self.GetItemText(item)
     267            if itemtext == "Phases":
     268                parent = item
     269                item, cookie = self.GetFirstChild(parent)
     270                i = 0
     271                while item:
     272                    itemtext = self.GetItemText(item)
     273                    if itemtext == phasename:
     274                        return i
     275                    item, cookie = self.GetNextChild(parent, cookie)
     276                    i += 1
     277                else:
     278                    return phasename # not a phase name
     279            item, cookie = self.GetNextChild(self.root, cookie)
     280        else:
     281            raise Exception("No phases found ")
     282
     283    def ConvertRelativePhaseNum(self,phasenum):
     284        '''Converts relative phase number to a phase name in
     285        the current project
     286        '''
     287        item, cookie = self.GetFirstChild(self.root)
     288        while item:
     289            itemtext = self.GetItemText(item)
     290            if itemtext == "Phases":
     291                parent = item
     292                item, cookie = self.GetFirstChild(parent)
     293                i = 0
     294                while item:
     295                    if i == phasenum:
     296                        return self.GetItemText(item)
     297                    item, cookie = self.GetNextChild(parent, cookie)
     298                    i += 1
     299                else:
     300                    raise Exception("Phase "+str(phasenum)+" not found")
     301            item, cookie = self.GetNextChild(self.root, cookie)
     302        else:
     303            raise Exception("No phases found ")
     304#===========================================================================
     305class G2LoggedButton(wx.Button):
     306    '''A version of wx.Button that creates logging events. Bindings are saved
     307    in the object, and are looked up rather than directly set with a bind.
     308    An index to these buttons is saved as log.ButtonBindingLookup
     309    '''
     310    def __init__(self,parent,id,label,locationcode,handler,*args,**kwargs):
     311        super(self.__class__,self).__init__(parent,id,label,*args,**kwargs)
     312        self.label = label
     313        self.handler = handler
     314        self.locationcode = locationcode
     315        key = locationcode + '+' + label # hash code to find button
     316        self.Bind(wx.EVT_BUTTON,self.onPress)
     317        log.ButtonBindingLookup[key] = self
     318    def onPress(self,event):
     319        'create log event and call handler'
     320        G2logList.append(log.ButtonLogEntry(self.locationcode,self.label))
     321        self.handler(event)
     322
     323#===========================================================================
    163324class ValidatedTxtCtrl(wx.TextCtrl):
    164325    '''Create a TextCtrl widget that uses a validator to prevent the
     
    26702831        For other platforms, either wrap calls that will be logged
    26712832        or call the default wx.Frame Bind() to bind to the menu item directly.
     2833
     2834        Note that bindings can be made to objects by Id or by direct reference to the
     2835        object. As a convention, when bindings are to objects, they are not logged
     2836        but when bindings are by Id, they are logged.
    26722837        '''
    26732838        if sys.platform == "darwin": # mac
     
    39754140        print event
    39764141        treekeylist = [u'Phases', u'CuCr2O4']
    3977         log.SimTreeEvent(treekeylist)
    3978         log.SimTabPress('Phase Data for CuCr2O4','Atoms')
    3979     btn = wx.Button(G2frame.dataDisplay, wx.ID_ANY,"test")
    3980     btn.Bind(wx.EVT_BUTTON, TestButton)
     4142        #log.SimTreeEvent(treekeylist)
     4143        #log.SimTabPress('Phase Data for CuCr2O4','Atoms')
     4144    btn = G2LoggedButton(G2frame.dataDisplay, wx.ID_ANY,"test",
     4145                         locationcode='Controls',handler=TestButton)
     4146    #btn = wx.Button(G2frame.dataDisplay, wx.ID_ANY,"test")
     4147    #btn.Bind(wx.EVT_BUTTON, TestButton)
    39814148    mainSizer.Add(btn,0,wx.ALL,10)
    39824149   
Note: See TracChangeset for help on using the changeset viewer.