menu.py 9.5 KB

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