[GRASS-SVN] r53879 - in grass/trunk/gui/wxpython: . core gui_core

svn_grass at osgeo.org svn_grass at osgeo.org
Sun Nov 18 02:14:44 PST 2012


Author: wenzeslaus
Date: 2012-11-18 02:14:43 -0800 (Sun, 18 Nov 2012)
New Revision: 53879

Added:
   grass/trunk/gui/wxpython/core/modulesdata.py
Modified:
   grass/trunk/gui/wxpython/gui_core/ghelp.py
   grass/trunk/gui/wxpython/gui_core/goutput.py
   grass/trunk/gui/wxpython/gui_core/menu.py
   grass/trunk/gui/wxpython/gui_core/prompt.py
   grass/trunk/gui/wxpython/wxpythonlib.dox
Log:
wxGUI/gprompt: module info moved from GPrompt (co-author: annakrat)

Added: grass/trunk/gui/wxpython/core/modulesdata.py
===================================================================
--- grass/trunk/gui/wxpython/core/modulesdata.py	                        (rev 0)
+++ grass/trunk/gui/wxpython/core/modulesdata.py	2012-11-18 10:14:43 UTC (rev 53879)
@@ -0,0 +1,185 @@
+"""!
+ at package core.modulesdata
+
+ at brief Provides information about available modules
+
+Classes:
+ - modules::modulesdata
+
+(C) 2009-2012 by the GRASS Development Team
+
+This program is free software under the GNU General Public License
+(>=v2). Read the file COPYING that comes with GRASS for details.
+
+ at author Martin Landa <landa.martin gmail.com>
+ at author Vaclav Petras <wenzeslaus gmail.com>
+ at author Anna Kratochvilova <kratochanna gmail.com>
+"""
+
+import sys
+import os
+
+if __name__ == '__main__':
+    sys.path.append(os.path.join(os.environ['GISBASE'], "etc", "gui", "wxpython"))
+
+from core import globalvar
+from lmgr.menudata import ManagerData
+
+
+class ModulesData(object):
+    """!Holds information about modules.
+
+    @todo add doctest
+    """
+    def __init__(self, modulesDesc = None):
+
+        if modulesDesc is not None:
+            self.moduleDesc = modulesDesc
+        else:
+            self.moduleDesc = ManagerData().GetModules()
+
+        self.moduleList = self._getListOfModules()
+
+    def GetCommandDesc(self, cmd):
+        """!Gets the description for a given module (command).
+
+        If the given module is not available, an empty string is returned.
+        
+        \code
+        print data.GetCommandDesc('r.info')
+        Outputs basic information about a raster map.
+        \endcode
+        """
+        if cmd in self.moduleDesc:
+            return self.moduleDesc[cmd]['desc']
+
+        return ''
+
+    def GetCommandItems(self):
+        """!Gets list of available modules (commands).
+
+        The list contains available module names.
+
+        \code
+        print data.GetCommandItems()[0:4]
+        ['d.barscale', 'd.colorlist', 'd.colortable', 'd.correlate']
+        \endcode
+        """
+        items = list()
+
+        mList = self.moduleList
+
+        prefixes = mList.keys()
+        prefixes.sort()
+
+        for prefix in prefixes:
+            for command in mList[prefix]:
+                name = prefix + '.' + command
+                if name not in items:
+                    items.append(name)
+
+        items.sort()
+
+        return items
+
+    def _getListOfModules(self):
+        """!Gets list of modules as a dictionary optimized for autocomplete.
+
+        \code
+        print data._getListOfModules()['r'][0:4]
+        print data._getListOfModules()['r.li'][0:4]
+        r: ['basins.fill', 'bitpattern', 'blend', 'buffer']
+        r.li: ['cwed', 'dominance', 'edgedensity', 'mpa']
+        \endcode
+        """
+        result = dict()
+        for module in globalvar.grassCmd:
+            try:
+                group, name = module.split('.', 1)
+            except ValueError:
+                continue  # TODO
+
+            if group not in result:
+                result[group] = list()
+            result[group].append(name)
+
+            # for better auto-completion:
+            # not only result['r']={...,'colors.out',...}
+            # but also result['r.colors']={'out',...}
+            for i in range(len(name.split('.')) - 1):
+                group = '.'.join([group, name.split('.', 1)[0]])
+                name = name.split('.', 1)[1]
+                if group not in result:
+                    result[group] = list()
+                result[group].append(name)
+
+        # sort list of names
+        for group in result.keys():
+            result[group].sort()
+
+        return result
+
+    def FindModules(self, text, findIn):
+        """!Finds modules according to given text.
+
+        @param text string to search
+        @param findIn where to search for text
+        (allowed values are 'description', 'keywords' and 'command')
+        """
+        modules = dict()
+        iFound = 0
+        for module, data in self.moduleDesc.iteritems():
+            found = False
+            if findIn == 'description':
+                if text in data['desc']:
+                    found = True
+            elif findIn == 'keywords':
+                if text in ','.join(data['keywords']):
+                    found = True
+            elif findIn == 'command':
+                if module[:len(text)] == text:
+                    found = True
+            else:
+                raise ValueError("Parameter findIn is not valid")
+
+            if found:
+                try:
+                    group, name = module.split('.')
+                except ValueError:
+                    continue # TODO                
+                iFound += 1
+                if group not in modules:
+                    modules[group] = list()
+                modules[group].append(name)
+        return modules, iFound
+
+    def SetFilter(self, data = None):
+        """!Sets filter modules
+
+        If @p data is not specified, module dictionary is derived
+        from an internal data structures.
+        
+        @todo Document this method.
+
+        @param data data dict
+        """
+        if data:
+            self.moduleList = data
+        else:
+            self.moduleList = self._getListOfModules()
+
+
+def test():
+    data = ModulesData()
+    module = 'r.info'
+    print '%s:' % module, data.GetCommandDesc(module)
+    print '[0:5]:', data.GetCommandItems()[0:5]
+
+    modules = data._getListOfModules()  # pylint: disable=W0212
+    print 'r:', modules['r'][0:4]
+    print 'r.li:', modules['r.li'][0:4]
+    
+
+
+if __name__ == '__main__':
+    test()
\ No newline at end of file


Property changes on: grass/trunk/gui/wxpython/core/modulesdata.py
___________________________________________________________________
Added: svn:mime-type
   + text/x-python
Added: svn:eol-style
   + native

Modified: grass/trunk/gui/wxpython/gui_core/ghelp.py
===================================================================
--- grass/trunk/gui/wxpython/gui_core/ghelp.py	2012-11-18 09:38:23 UTC (rev 53878)
+++ grass/trunk/gui/wxpython/gui_core/ghelp.py	2012-11-18 10:14:43 UTC (rev 53879)
@@ -44,11 +44,12 @@
 
 class SearchModuleWindow(wx.Panel):
     """!Search module window (used in MenuTreeWindow)"""
-    def __init__(self, parent, id = wx.ID_ANY, cmdPrompt = None,
+    def __init__(self, parent, modulesData, id = wx.ID_ANY, cmdPrompt = None,
                  showChoice = True, showTip = False, **kwargs):
         self.showTip    = showTip
         self.showChoice = showChoice
         self.cmdPrompt  = cmdPrompt
+        self.modulesData = modulesData
         
         wx.Panel.__init__(self, parent = parent, id = id, **kwargs)
         
@@ -59,10 +60,11 @@
         self.box = wx.StaticBox(parent = self, id = wx.ID_ANY,
                                 label = " %s " % _("Find module - (press Enter for next match)"))
         
-        self.searchBy = wx.Choice(parent = self, id = wx.ID_ANY,
-                                  choices = [_('description'),
-                                             _('keywords'),
-                                             _('command')])
+        self.searchBy = wx.Choice(parent = self, id = wx.ID_ANY)
+        items = [_('description'), _('keywords'), _('command')]
+        datas = ['description', 'keywords', 'command']
+        for item, data in zip(items, datas):
+            self.searchBy.Append(item = item, clientData = data)
         self.searchBy.SetSelection(0)
         
         self.search = wx.SearchCtrl(parent = self, id = wx.ID_ANY,
@@ -77,7 +79,7 @@
         if self.showChoice:
             self.searchChoice = wx.Choice(parent = self, id = wx.ID_ANY)
             if self.cmdPrompt:
-                self.searchChoice.SetItems(self.cmdPrompt.GetCommandItems())
+                self.searchChoice.SetItems(self.modulesData.GetCommandItems())
             self.searchChoice.Bind(wx.EVT_CHOICE, self.OnSelectModule)
         
         self._layout()
@@ -134,45 +136,21 @@
         
         text = event.GetEventObject().GetValue()
         if not text:
-            self.cmdPrompt.SetFilter(None)
-            mList = self.cmdPrompt.GetCommandItems()
+            self.modulesData.SetFilter()
+            mList = self.modulesData.GetCommandItems()
             self.searchChoice.SetItems(mList)
             if self.showTip:
                 self.searchTip.SetLabel(_("%d modules found") % len(mList))
             event.Skip()
             return
-        
-        modules = dict()
-        iFound = 0
-        for module, data in self.cmdPrompt.moduleDesc.iteritems():
-            found = False
-            sel = self.searchBy.GetSelection()
-            if sel == 0: # -> description
-                if text in data['desc']:
-                    found = True
-            elif sel == 1: # keywords
-                if text in ','.join(data['keywords']):
-                    found = True
-            else: # command
-                if module[:len(text)] == text:
-                    found = True
-            
-            if found:
-                iFound += 1
-                try:
-                    group, name = module.split('.')
-                except ValueError:
-                    continue # TODO
-                
-                if group not in modules:
-                    modules[group] = list()
-                modules[group].append(name)
-                
-        self.cmdPrompt.SetFilter(modules)
-        self.searchChoice.SetItems(self.cmdPrompt.GetCommandItems())
+
+        findIn = self.searchBy.GetClientData(self.searchBy.GetSelection())
+        modules, nFound = self.modulesData.FindModules(text = text, findIn = findIn)
+        self.modulesData.SetFilter(modules)
+        self.searchChoice.SetItems(self.modulesData.GetCommandItems())
         self.searchChoice.SetSelection(0)
         if self.showTip:
-            self.searchTip.SetLabel(_("%d modules match") % iFound)
+            self.searchTip.SetLabel(_("%d modules match") % nFound)
         
         event.Skip()
         
@@ -188,7 +166,7 @@
             self.cmdPrompt.SetCurrentPos(pos)
             self.cmdPrompt.SetFocus()
         
-        desc = self.cmdPrompt.GetCommandDesc(cmd)
+        desc = self.modulesData.GetCommandDesc(cmd)
         if self.showTip:
             self.searchTip.SetLabel(desc)
         

Modified: grass/trunk/gui/wxpython/gui_core/goutput.py
===================================================================
--- grass/trunk/gui/wxpython/gui_core/goutput.py	2012-11-18 09:38:23 UTC (rev 53878)
+++ grass/trunk/gui/wxpython/gui_core/goutput.py	2012-11-18 10:14:43 UTC (rev 53879)
@@ -44,6 +44,7 @@
 from core.debug      import Debug
 from core.settings   import UserSettings, GetDisplayVectSettings
 from gui_core.ghelp  import SearchModuleWindow
+from core.modulesdata import ModulesData
 
 wxCmdOutput,   EVT_CMD_OUTPUT   = NewEvent()
 wxCmdProgress, EVT_CMD_PROGRESS = NewEvent()
@@ -251,10 +252,13 @@
         self.Bind(EVT_CMD_DONE,    self.OnCmdDone)
         self.Bind(EVT_CMD_PREPARE, self.OnCmdPrepare)
 
+        # information about available modules
+        modulesData = ModulesData()
+
         # search & command prompt
         # move to the if below
         # search depends on cmd prompt
-        self.cmdPrompt = GPromptSTC(parent = self)
+        self.cmdPrompt = GPromptSTC(parent = self, modulesData = modulesData)
         if not self._gcstyle & GC_PROMPT:
             self.cmdPrompt.Hide()
 
@@ -266,7 +270,7 @@
                                                  label = self.infoCollapseLabelExp,
                                                  style = wx.CP_DEFAULT_STYLE |
                                                  wx.CP_NO_TLW_RESIZE | wx.EXPAND)
-            self.MakeSearchPaneContent(self.searchPane.GetPane())
+            self.MakeSearchPaneContent(self.searchPane.GetPane(), modulesData)
             self.searchPane.Collapse(True)
             self.Bind(wx.EVT_COLLAPSIBLEPANE_CHANGED, self.OnSearchPaneChanged, self.searchPane) 
             self.search.Bind(wx.EVT_TEXT,             self.OnUpdateStatusBar)
@@ -387,11 +391,13 @@
         self.SetAutoLayout(True)
         self.Layout()
 
-    def MakeSearchPaneContent(self, pane):
+    def MakeSearchPaneContent(self, pane, modulesData):
         """!Create search pane"""
         border = wx.BoxSizer(wx.VERTICAL)
         
-        self.search = SearchModuleWindow(parent = pane, cmdPrompt = self.cmdPrompt)
+        self.search = SearchModuleWindow(parent = pane,
+                                         cmdPrompt = self.cmdPrompt,
+                                         modulesData = modulesData)
         
         border.Add(item = self.search, proportion = 0,
                    flag = wx.EXPAND | wx.ALL, border = 1)

Modified: grass/trunk/gui/wxpython/gui_core/menu.py
===================================================================
--- grass/trunk/gui/wxpython/gui_core/menu.py	2012-11-18 09:38:23 UTC (rev 53878)
+++ grass/trunk/gui/wxpython/gui_core/menu.py	2012-11-18 10:14:43 UTC (rev 53879)
@@ -134,11 +134,14 @@
         self.dataBox = wx.StaticBox(parent = self, id = wx.ID_ANY,
                                     label = " %s " % _("Menu tree (double-click or Ctrl-Enter to run command)"))
         # tree
-        self.tree = MenuTree(parent = self, data = ManagerData())
+        menuData = ManagerData()
+        self.tree = MenuTree(parent = self, data = menuData)
         self.tree.Load()
 
         # search widget
-        self.search = SearchModuleWindow(parent = self, showChoice = False)
+        self.search = SearchModuleWindow(parent = self,
+                                         modulesData = menuData.GetModules(),
+                                         showChoice = False)
         
         # buttons
         self.btnRun   = wx.Button(self, id = wx.ID_OK, label = _("&Run"))

Modified: grass/trunk/gui/wxpython/gui_core/prompt.py
===================================================================
--- grass/trunk/gui/wxpython/gui_core/prompt.py	2012-11-18 09:38:23 UTC (rev 53878)
+++ grass/trunk/gui/wxpython/gui_core/prompt.py	2012-11-18 10:14:43 UTC (rev 53879)
@@ -470,7 +470,7 @@
 
     See subclass GPromptPopUp and GPromptSTC.
     """
-    def __init__(self, parent):
+    def __init__(self, parent, modulesData):
         self.parent = parent                 # GConsole
         self.panel  = self.parent.GetPanel()
         
@@ -478,19 +478,13 @@
             self.standAlone = True
         else:
             self.standAlone = False
+
+        # probably only subclasses need this
+        self.modulesData = modulesData
+
+        self.mapList    = self._getListOfMaps()
+        self.mapsetList = utils.ListOfMapsets()
         
-        # dictionary of modules (description, keywords, ...)
-        if not self.standAlone:
-            if self.parent.parent.GetName() == 'Modeler':
-                self.moduleDesc = ManagerData().GetModules()
-            else:
-                self.moduleDesc = parent.parent.menubar.GetData().GetModules()
-            self.moduleList = self._getListOfModules()
-            self.mapList    = self._getListOfMaps()
-            self.mapsetList = utils.ListOfMapsets()
-        else:
-            self.moduleDesc = self.moduleList = self.mapList = None
-        
         # auto complete items
         self.autoCompList   = list()
         self.autoCompFilter = None
@@ -524,66 +518,6 @@
         
         return hist
 
-    def GetCommandDesc(self, cmd):
-        """!Get description for given command"""
-        if cmd in self.moduleDesc:
-            return self.moduleDesc[cmd]['desc']
-        
-        return ''
-    
-    def GetCommandItems(self):
-        """!Get list of available commands"""
-        items = list()
-        
-        if self.autoCompFilter is not None:
-            mList = self.autoCompFilter
-        else:
-            mList = self.moduleList
-            
-        if not mList:
-            return items
-        
-        prefixes = mList.keys()
-        prefixes.sort()
-        
-        for prefix in prefixes:
-            for command in mList[prefix]:
-                name = prefix + '.' + command
-                if name not in items:
-                    items.append(name)
-                
-        items.sort()
-        
-        return items
-    
-    def _getListOfModules(self):
-        """!Get list of modules"""
-        result = dict()
-        for module in globalvar.grassCmd:
-            try:
-                group, name = module.split('.',1)
-            except ValueError:
-                continue # TODO
-            
-            if group not in result:
-                result[group] = list()
-            result[group].append(name)
-            
-            # for better auto-completion: 
-            # not only result['r']={...,'colors.out',...}, but also result['r.colors']={'out',...}
-            for i in range(len(name.split('.'))-1):
-                group = '.'.join([group,name.split('.',1)[0]])
-                name = name.split('.',1)[1]
-                if group not in result:
-                    result[group] = list()
-                result[group].append(name)
-      
-        # sort list of names
-        for group in result.keys():
-            result[group].sort()
-        
-        return result
-    
     def _getListOfMaps(self):
         """!Get list of maps"""
         result = dict()
@@ -653,10 +587,8 @@
         @param module True to filter modules, otherwise data
         """
         if module:
-            if data:
-                self.moduleList = data
-            else:
-                self.moduleList = self._getListOfModules()
+            # TODO: remove this and module param
+            raise NotImplementedError("Replace by call to common ModulesData object (SetFilter with module=True)")
         else:
             if data:
                 self.dataList = data
@@ -712,8 +644,8 @@
         
 class GPromptSTC(GPrompt, wx.stc.StyledTextCtrl):
     """!Styled wxGUI prompt with autocomplete and calltips"""    
-    def __init__(self, parent, id = wx.ID_ANY, margin = False):
-        GPrompt.__init__(self, parent)
+    def __init__(self, parent, modulesData, id = wx.ID_ANY, margin = False):
+        GPrompt.__init__(self, parent, modulesData)
         wx.stc.StyledTextCtrl.__init__(self, self.panel, id)
         
         #
@@ -770,7 +702,7 @@
         if self.toComplete['entity'] == 'command':
             item = self.toComplete['cmd'].rpartition('.')[0] + '.' + self.autoCompList[event.GetIndex()] 
             try:
-                desc = self.moduleDesc[item]['desc']        
+                desc = self.modulesData.GetCommandDesc(item)
             except KeyError:
                 desc = '' 
             self.ShowStatusText(desc)
@@ -951,7 +883,7 @@
             self.toComplete = self.EntityToComplete()
             try:
                 if self.toComplete['entity'] == 'command': 
-                    self.autoCompList = self.moduleList[entry.strip()]
+                    self.autoCompList = self.modulesData.GetCommandItems(entry.strip())
             except (KeyError, TypeError):
                 return
             self.ShowList()

Modified: grass/trunk/gui/wxpython/wxpythonlib.dox
===================================================================
--- grass/trunk/gui/wxpython/wxpythonlib.dox	2012-11-18 09:38:23 UTC (rev 53878)
+++ grass/trunk/gui/wxpython/wxpythonlib.dox	2012-11-18 10:14:43 UTC (rev 53879)
@@ -68,6 +68,8 @@
  - gcmd::CommandThread
 - core::menudata
  - menudata::MenuData
+- core::modulesdata
+ - modulesdata::ModulesData
 - core::render
  - render::Layer
  - render::Layer



More information about the grass-commit mailing list