menu.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. """
  2. @package gui_core.menu
  3. @brief Menu classes for wxGUI
  4. Classes:
  5. - menu::Menu
  6. - menu::SearchModuleWindow
  7. (C) 2010-2013 by the GRASS Development Team
  8. This program is free software under the GNU General Public License
  9. (>=v2). Read the file COPYING that comes with GRASS for details.
  10. @author Martin Landa <landa.martin gmail.com>
  11. @author Pawel Netzel (menu customization)
  12. @author Milena Nowotarska (menu customization)
  13. @author Robert Szczepanek (menu customization)
  14. @author Vaclav Petras <wenzeslaus gmail.com> (menu customization)
  15. """
  16. import re
  17. import wx
  18. from core import globalvar
  19. from core import utils
  20. from core.gcmd import EncodeString
  21. from core.utils import _
  22. from gui_core.widgets import SearchModuleWidget
  23. from gui_core.treeview import CTreeView
  24. from gui_core.wrap import Button
  25. from gui_core.wrap import Menu as MenuWidget
  26. from icons.icon import MetaIcon
  27. from grass.pydispatch.signal import Signal
  28. class Menu(wx.MenuBar):
  29. def __init__(self, parent, model):
  30. """Creates menubar"""
  31. wx.MenuBar.__init__(self)
  32. self.parent = parent
  33. self.model = model
  34. self.menucmd = dict()
  35. self.bmpsize = (16, 16)
  36. for child in self.model.root.children:
  37. self.Append(self._createMenu(child), child.label)
  38. def _createMenu(self, node):
  39. """Creates menu"""
  40. menu = MenuWidget()
  41. for child in node.children:
  42. if child.children:
  43. label = child.label
  44. subMenu = self._createMenu(child)
  45. menu.AppendMenu(wx.ID_ANY, label, subMenu)
  46. else:
  47. data = child.data.copy()
  48. data.pop('label')
  49. self._createMenuItem(menu, label=child.label, **data)
  50. self.parent.Bind(wx.EVT_MENU_HIGHLIGHT_ALL, self.OnMenuHighlight)
  51. return menu
  52. def _createMenuItem(
  53. self, menu, label, description, handler, command, keywords,
  54. shortcut='', icon='', wxId=wx.ID_ANY, kind=wx.ITEM_NORMAL):
  55. """Creates menu items
  56. There are three menu styles (menu item text styles).
  57. 1 -- label only, 2 -- label and cmd name, 3 -- cmd name only
  58. """
  59. if not label:
  60. menu.AppendSeparator()
  61. return
  62. if command:
  63. helpString = command + ' -- ' + description
  64. else:
  65. helpString = description
  66. if shortcut:
  67. label += '\t' + shortcut
  68. menuItem = wx.MenuItem(menu, wxId, label, helpString, kind)
  69. if icon:
  70. menuItem.SetBitmap(MetaIcon(img=icon).GetBitmap(self.bmpsize))
  71. menu.AppendItem(menuItem)
  72. self.menucmd[menuItem.GetId()] = command
  73. if command:
  74. try:
  75. cmd = utils.split(str(command))
  76. except UnicodeError:
  77. cmd = utils.split(EncodeString((command)))
  78. # disable only grass commands which are not present (e.g.
  79. # r.in.lidar)
  80. if cmd and cmd[0] not in globalvar.grassCmd and \
  81. re.match('[rvdipmgt][3bs]?\.([a-z0-9\.])+', cmd[0]):
  82. menuItem.Enable(False)
  83. rhandler = eval('self.parent.' + handler)
  84. self.parent.Bind(wx.EVT_MENU, rhandler, menuItem)
  85. def GetData(self):
  86. """Get menu data"""
  87. return self.model
  88. def GetCmd(self):
  89. """Get dictionary of commands (key is id)
  90. :return: dictionary of commands
  91. """
  92. return self.menucmd
  93. def OnMenuHighlight(self, event):
  94. """
  95. Default menu help handler
  96. """
  97. # Show how to get menu item info from this event handler
  98. id = event.GetMenuId()
  99. item = self.FindItemById(id)
  100. if item:
  101. text = item.GetText()
  102. help = item.GetHelp()
  103. # but in this case just call Skip so the default is done
  104. event.Skip()
  105. class SearchModuleWindow(wx.Panel):
  106. """Menu tree and search widget for searching modules.
  107. Signal:
  108. showNotification - attribute 'message'
  109. """
  110. def __init__(self, parent, handlerObj, giface, model, id=wx.ID_ANY,
  111. **kwargs):
  112. self.parent = parent
  113. self._handlerObj = handlerObj
  114. self._giface = giface
  115. self.showNotification = Signal('SearchModuleWindow.showNotification')
  116. wx.Panel.__init__(self, parent=parent, id=id, **kwargs)
  117. # tree
  118. self._tree = CTreeView(model=model, parent=self)
  119. self._tree.SetToolTipString(
  120. _("Double-click or Ctrl-Enter to run selected module"))
  121. # self._dataBox = wx.StaticBox(parent = self, id = wx.ID_ANY,
  122. # label = " %s " % _("Module tree"))
  123. # search widget
  124. self._search = SearchModuleWidget(parent=self,
  125. model=model,
  126. showChoice=False)
  127. self._search.showSearchResult.connect(
  128. lambda result: self._tree.Select(result))
  129. self._search.showNotification.connect(self.showNotification)
  130. self._helpText = wx.StaticText(
  131. parent=self, id=wx.ID_ANY,
  132. label="Press Enter for next match, Ctrl+Enter to run command")
  133. self._helpText.SetForegroundColour(
  134. wx.SystemSettings.GetColour(
  135. wx.SYS_COLOUR_GRAYTEXT))
  136. # buttons
  137. self._btnRun = Button(self, id=wx.ID_OK, label=_("&Run"))
  138. self._btnRun.SetToolTip(_("Run selected module from the tree"))
  139. self._btnHelp = Button(self, id=wx.ID_ANY, label=_("H&elp"))
  140. self._btnHelp.SetToolTip(
  141. _("Show manual for selected module from the tree"))
  142. self._btnAdvancedSearch = Button(self, id=wx.ID_ANY,
  143. label=_("Adva&nced search..."))
  144. self._btnAdvancedSearch.SetToolTip(
  145. _("Do advanced search using %s module") % 'g.search.module')
  146. # bindings
  147. self._btnRun.Bind(wx.EVT_BUTTON, lambda evt: self.Run())
  148. self._btnHelp.Bind(wx.EVT_BUTTON, lambda evt: self.Help())
  149. self._btnAdvancedSearch.Bind(wx.EVT_BUTTON,
  150. lambda evt: self.AdvancedSearch())
  151. self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
  152. self._tree.selectionChanged.connect(self.OnItemSelected)
  153. self._tree.itemActivated.connect(lambda node: self.Run(node))
  154. self._layout()
  155. self._search.SetFocus()
  156. def _layout(self):
  157. """Do dialog layout"""
  158. sizer = wx.BoxSizer(wx.VERTICAL)
  159. # body
  160. dataSizer = wx.BoxSizer(wx.HORIZONTAL)
  161. dataSizer.Add(self._tree, proportion=1,
  162. flag=wx.EXPAND)
  163. # buttons
  164. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  165. btnSizer.Add(self._btnAdvancedSearch, proportion=0)
  166. btnSizer.AddStretchSpacer()
  167. btnSizer.Add(self._btnHelp, proportion=0)
  168. btnSizer.Add(self._btnRun, proportion=0)
  169. sizer.Add(dataSizer, proportion=1,
  170. flag=wx.EXPAND | wx.ALL, border=5)
  171. sizer.Add(self._search, proportion=0,
  172. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)
  173. sizer.Add(item=btnSizer, proportion=0,
  174. flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)
  175. sizer.Add(self._helpText,
  176. proportion=0, flag=wx.EXPAND | wx.LEFT, border=5)
  177. sizer.Fit(self)
  178. sizer.SetSizeHints(self)
  179. self.SetSizer(sizer)
  180. self.Fit()
  181. self.SetAutoLayout(True)
  182. self.Layout()
  183. def _GetSelectedNode(self):
  184. selection = self._tree.GetSelected()
  185. if not selection:
  186. return None
  187. return selection[0]
  188. def Run(self, node=None):
  189. """Run selected command.
  190. :param node: a tree node associated with the module or other item
  191. """
  192. if not node:
  193. node = self._GetSelectedNode()
  194. # nothing selected
  195. if not node:
  196. return
  197. data = node.data
  198. # non-leaf nodes
  199. if not data:
  200. return
  201. # extract name of the handler and create a new call
  202. handler = 'self._handlerObj.' + data['handler'].lstrip('self.')
  203. if data['command']:
  204. eval(handler)(event=None, cmd=data['command'].split())
  205. else:
  206. eval(handler)(event=None)
  207. def Help(self, node=None):
  208. """Show documentation for a module"""
  209. if not node:
  210. node = self._GetSelectedNode()
  211. # nothing selected
  212. if not node:
  213. return
  214. data = node.data
  215. # non-leaf nodes
  216. if not data:
  217. return
  218. if not data['command']:
  219. # showing nothing for non-modules
  220. return
  221. # strip parameters from command if present
  222. name = data['command'].split()[0]
  223. self._giface.Help(name)
  224. self.showNotification.emit(
  225. message=_("Documentation for %s is now open in the web browser")
  226. % name)
  227. def AdvancedSearch(self):
  228. """Show advanced search window"""
  229. self._handlerObj.RunMenuCmd(cmd=['g.search.modules'])
  230. def OnKeyUp(self, event):
  231. """Key or key combination pressed"""
  232. if event.ControlDown() and \
  233. event.GetKeyCode() in (wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER):
  234. self.Run()
  235. def OnItemSelected(self, node):
  236. """Item selected"""
  237. data = node.data
  238. if not data or 'command' not in data:
  239. return
  240. if data['command']:
  241. label = data['command']
  242. if data['description']:
  243. label += ' -- ' + data['description']
  244. else:
  245. label = data['description']
  246. self.showNotification.emit(message=label)