prompt.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. """!
  2. @package prompt.py
  3. @brief GRASS prompt
  4. Classes:
  5. - GPrompt
  6. - PromptListCtrl
  7. - TextCtrlAutoComplete
  8. @todo: fix TextCtrlAutoComplete to work also on Macs (missing
  9. wx.PopupWindow())
  10. (C) 2009 by the GRASS Development Team
  11. This program is free software under the GNU General Public
  12. License (>=v2). Read the file COPYING that comes with GRASS
  13. for details.
  14. @author Martin Landa <landa.martin gmail.com>
  15. """
  16. import sys
  17. import shlex
  18. import wx
  19. import wx.lib.mixins.listctrl as listmix
  20. from grass.script import core as grass
  21. import globalvar
  22. import utils
  23. import menuform
  24. import menudata
  25. class GPrompt:
  26. """!Interactive GRASS prompt"""
  27. def __init__(self, parent):
  28. self.parent = parent # GMFrame
  29. # dictionary of modules (description, keywords, ...)
  30. self.modules = self.parent.menudata.GetModules()
  31. self.panel, self.input = self.__create()
  32. def __create(self):
  33. """!Create widget"""
  34. cmdprompt = wx.Panel(self.parent)
  35. #
  36. # search
  37. #
  38. searchTxt = wx.StaticText(parent = cmdprompt, id = wx.ID_ANY,
  39. label = _("Search:"))
  40. self.searchBy = wx.Choice(parent = cmdprompt, id = wx.ID_ANY,
  41. choices = [_("description"),
  42. _("keywords")])
  43. self.search = wx.TextCtrl(parent = cmdprompt, id = wx.ID_ANY,
  44. value = "", size = (-1, 25))
  45. label = wx.Button(parent = cmdprompt, id = wx.ID_ANY,
  46. label = _("Cmd >"), size = (-1, 25))
  47. label.SetToolTipString(_("Click for erasing command prompt"))
  48. ### todo: fix TextCtrlAutoComplete to work also on Macs
  49. ### reason: missing wx.PopupWindow()
  50. try:
  51. cmdinput = TextCtrlAutoComplete(parent = cmdprompt, id = wx.ID_ANY,
  52. value = "",
  53. style = wx.TE_LINEWRAP | wx.TE_PROCESS_ENTER,
  54. size = (-1, 25))
  55. except NotImplementedError:
  56. # wx.PopupWindow may be not available in wxMac
  57. # see http://trac.wxwidgets.org/ticket/9377
  58. cmdinput = wx.TextCtrl(parent = cmdprompt, id = wx.ID_ANY,
  59. value = "",
  60. style=wx.TE_LINEWRAP | wx.TE_PROCESS_ENTER,
  61. size = (-1, 25))
  62. self.searchBy.Enable(False)
  63. self.search.Enable(False)
  64. cmdinput.SetFont(wx.Font(10, wx.FONTFAMILY_MODERN, wx.NORMAL, wx.NORMAL, 0, ''))
  65. wx.CallAfter(cmdinput.SetInsertionPoint, 0)
  66. # bidnings
  67. label.Bind(wx.EVT_BUTTON, self.OnCmdErase)
  68. cmdinput.Bind(wx.EVT_TEXT_ENTER, self.OnRunCmd)
  69. cmdinput.Bind(wx.EVT_TEXT, self.OnUpdateStatusBar)
  70. self.search.Bind(wx.EVT_TEXT, self.OnSearchModule)
  71. # layout
  72. sizer = wx.GridBagSizer(hgap=5, vgap=5)
  73. sizer.AddGrowableCol(2)
  74. sizer.Add(item = searchTxt,
  75. flag = wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL,
  76. pos = (0, 0))
  77. sizer.Add(item = self.searchBy,
  78. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER,
  79. pos = (0, 1))
  80. sizer.Add(item = self.search,
  81. flag = wx.EXPAND | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER,
  82. border = 5,
  83. pos = (0, 2))
  84. sizer.Add(item = label,
  85. flag = wx.LEFT | wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER,
  86. border = 5,
  87. pos = (1, 0))
  88. sizer.Add(item = cmdinput,
  89. flag = wx.EXPAND | wx.RIGHT,
  90. border = 5,
  91. pos = (1, 1), span = (1, 2))
  92. cmdprompt.SetSizer(sizer)
  93. sizer.Fit(cmdprompt)
  94. cmdprompt.Layout()
  95. return cmdprompt, cmdinput
  96. def GetPanel(self):
  97. """!Get main widget panel"""
  98. return self.panel
  99. def GetInput(self):
  100. """!Get main prompt widget"""
  101. return self.input
  102. def OnCmdErase(self, event):
  103. """!Erase command prompt"""
  104. self.input.SetValue('')
  105. def OnRunCmd(self, event):
  106. """!Run command"""
  107. cmdString = event.GetString()
  108. if self.parent.GetName() != "LayerManager":
  109. return
  110. if cmdString[:2] == 'd.' and not self.parent.curr_page:
  111. self.parent.NewDisplay(show=True)
  112. cmd = shlex.split(str(cmdString))
  113. if len(cmd) > 1:
  114. self.parent.goutput.RunCmd(cmd, switchPage = True)
  115. else:
  116. self.parent.goutput.RunCmd(cmd, switchPage = False)
  117. self.OnUpdateStatusBar(None)
  118. def OnUpdateStatusBar(self, event):
  119. """!Update Layer Manager status bar"""
  120. if self.parent.GetName() != "LayerManager":
  121. return
  122. if event is None:
  123. self.parent.statusbar.SetStatusText("")
  124. else:
  125. self.parent.statusbar.SetStatusText(_("Type GRASS command and run by pressing ENTER"))
  126. event.Skip()
  127. def OnSearchModule(self, event):
  128. """!Search module by metadata"""
  129. text = event.GetString()
  130. if not text:
  131. self.input.SetChoices(globalvar.grassCmd['all'])
  132. return
  133. modules = []
  134. for module, data in self.modules.iteritems():
  135. if text in data['desc']:
  136. modules.append(module)
  137. self.parent.statusbar.SetStatusText(_("%d modules found") % len(modules))
  138. self.input.SetChoices(modules)
  139. class PromptListCtrl(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin):
  140. def __init__(self, parent, id = wx.ID_ANY, pos = wx.DefaultPosition,
  141. size = wx.DefaultSize, style = 0):
  142. wx.ListCtrl.__init__(self, parent, id, pos, size, style)
  143. listmix.ListCtrlAutoWidthMixin.__init__(self)
  144. class TextCtrlAutoComplete(wx.TextCtrl, listmix.ColumnSorterMixin):
  145. def __init__ (self, parent, id = wx.ID_ANY, choices = [], **kwargs):
  146. """!Constructor works just like wx.TextCtrl except you can pass in a
  147. list of choices. You can also change the choice list at any time
  148. by calling setChoices.
  149. Inspired by http://wiki.wxpython.org/TextCtrlAutoComplete
  150. """
  151. if kwargs.has_key('style'):
  152. kwargs['style'] = wx.TE_PROCESS_ENTER | kwargs['style']
  153. else:
  154. kwargs['style'] = wx.TE_PROCESS_ENTER
  155. wx.TextCtrl.__init__(self, parent, id, **kwargs)
  156. # some variables
  157. self._choices = choices
  158. self._hideOnNoMatch = True
  159. self._module = None # currently selected module
  160. self._choiceType = None # type of choice (module, params, flags, raster, vector ...)
  161. self._screenheight = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_Y)
  162. # sort variable needed by listmix
  163. self.itemDataMap = dict()
  164. # widgets
  165. try:
  166. self.dropdown = wx.PopupWindow(self)
  167. except NotImplementedError:
  168. self.Destroy()
  169. raise NotImplementedError
  170. # create the list and bind the events
  171. self.dropdownlistbox = PromptListCtrl(parent = self.dropdown,
  172. style = wx.LC_REPORT | wx.LC_SINGLE_SEL | \
  173. wx.LC_SORT_ASCENDING | wx.LC_NO_HEADER,
  174. pos = wx.Point(0, 0))
  175. listmix.ColumnSorterMixin.__init__(self, 1)
  176. # set choices (list of GRASS modules)
  177. self._choicesCmd = globalvar.grassCmd['all']
  178. self._choicesMap = dict()
  179. for type in ('raster', 'vector'):
  180. self._choicesMap[type] = grass.list_strings(type = type[:4])
  181. # first search for GRASS module
  182. self.SetChoices(self._choicesCmd)
  183. # bindings...
  184. self.Bind(wx.EVT_KILL_FOCUS, self.OnControlChanged, self)
  185. self.Bind(wx.EVT_TEXT, self.OnEnteredText, self)
  186. self.Bind(wx.EVT_KEY_DOWN , self.OnKeyDown, self)
  187. # if need drop down on left click
  188. self.dropdown.Bind(wx.EVT_LISTBOX , self.OnListItemSelected, self.dropdownlistbox)
  189. self.dropdownlistbox.Bind(wx.EVT_LEFT_DOWN, self.OnListClick)
  190. self.dropdownlistbox.Bind(wx.EVT_LEFT_DCLICK, self.OnListDClick)
  191. self.dropdownlistbox.Bind(wx.EVT_LIST_COL_CLICK, self.OnListColClick)
  192. def _updateDataList(self, choices):
  193. """!Update data list"""
  194. # delete, if need, all the previous data
  195. if self.dropdownlistbox.GetColumnCount() != 0:
  196. self.dropdownlistbox.DeleteAllColumns()
  197. self.dropdownlistbox.DeleteAllItems()
  198. # and update the dict
  199. if choices:
  200. for numVal, data in enumerate(choices):
  201. self.itemDataMap[numVal] = data
  202. else:
  203. numVal = 0
  204. self.SetColumnCount(numVal)
  205. def _setListSize(self):
  206. """!Set list size"""
  207. choices = self._choices
  208. longest = 0
  209. for choice in choices:
  210. longest = max(len(choice), longest)
  211. longest += 3
  212. itemcount = min(len( choices ), 7) + 2
  213. charheight = self.dropdownlistbox.GetCharHeight()
  214. charwidth = self.dropdownlistbox.GetCharWidth()
  215. self.popupsize = wx.Size(charwidth*longest, charheight*itemcount)
  216. self.dropdownlistbox.SetSize(self.popupsize)
  217. self.dropdown.SetClientSize(self.popupsize)
  218. def _showDropDown(self, show = True):
  219. """!Either display the drop down list (show = True) or hide it
  220. (show = False).
  221. """
  222. if show:
  223. size = self.dropdown.GetSize()
  224. width, height = self.GetSizeTuple()
  225. x, y = self.ClientToScreenXY(0, height)
  226. if size.GetWidth() != width:
  227. size.SetWidth(width)
  228. self.dropdown.SetSize(size)
  229. self.dropdownlistbox.SetSize(self.dropdown.GetClientSize())
  230. if (y + size.GetHeight()) < self._screenheight:
  231. self.dropdown.SetPosition(wx.Point(x, y))
  232. else:
  233. self.dropdown.SetPosition(wx.Point(x, y - height - size.GetHeight()))
  234. self.dropdown.Show(show)
  235. def _listItemVisible(self):
  236. """!Moves the selected item to the top of the list ensuring it is
  237. always visible.
  238. """
  239. toSel = self.dropdownlistbox.GetFirstSelected()
  240. if toSel == -1:
  241. return
  242. self.dropdownlistbox.EnsureVisible(toSel)
  243. def _setValueFromSelected(self):
  244. """!Sets the wx.TextCtrl value from the selected wx.ListCtrl item.
  245. Will do nothing if no item is selected in the wx.ListCtrl.
  246. """
  247. sel = self.dropdownlistbox.GetFirstSelected()
  248. if sel > -1:
  249. if self._colFetch != -1:
  250. col = self._colFetch
  251. else:
  252. col = self._colSearch
  253. itemtext = self.dropdownlistbox.GetItem(sel, col).GetText()
  254. cmd = shlex.split(str(self.GetValue()))
  255. if len(cmd) > 1:
  256. # -> append text (skip last item)
  257. if self._choiceType == 'param':
  258. self.SetValue(' '.join(cmd[:-1]) + ' ' + itemtext + '=')
  259. optType = self._module.get_param(itemtext)['prompt']
  260. if optType in ('raster', 'vector'):
  261. # -> raster/vector map
  262. self.SetChoices(self._choicesMap[optType], optType)
  263. elif self._choiceType == 'flag':
  264. if len(itemtext) > 1:
  265. prefix = '--'
  266. else:
  267. prefix = '-'
  268. self.SetValue(' '.join(cmd[:-1]) + ' ' + prefix + itemtext)
  269. elif self._choiceType in ('raster', 'vector'):
  270. self.SetValue(' '.join(cmd[:-1]) + ' ' + cmd[-1].split('=', 1)[0] + '=' + itemtext)
  271. else:
  272. # -> reset text
  273. self.SetValue(itemtext + ' ')
  274. self.SetInsertionPointEnd()
  275. self._showDropDown(False)
  276. def GetListCtrl(self):
  277. """!Method required by listmix.ColumnSorterMixin"""
  278. return self.dropdownlistbox
  279. def SetChoices(self, choices, type = 'module'):
  280. """!Sets the choices available in the popup wx.ListBox.
  281. The items will be sorted case insensitively.
  282. """
  283. self._choices = choices
  284. self._choiceType = type
  285. self.dropdownlistbox.SetWindowStyleFlag(wx.LC_REPORT | wx.LC_SINGLE_SEL | \
  286. wx.LC_SORT_ASCENDING | wx.LC_NO_HEADER)
  287. if not isinstance(choices, list):
  288. self._choices = [ x for x in choices ]
  289. if self._choiceType not in ('raster', 'vector'):
  290. # do not sort raster/vector maps
  291. utils.ListSortLower(self._choices)
  292. self._updateDataList(self._choices)
  293. self.dropdownlistbox.InsertColumn(0, "")
  294. for num, colVal in enumerate(self._choices):
  295. index = self.dropdownlistbox.InsertImageStringItem(sys.maxint, colVal, -1)
  296. self.dropdownlistbox.SetStringItem(index, 0, colVal)
  297. self.dropdownlistbox.SetItemData(index, num)
  298. self._setListSize()
  299. # there is only one choice for both search and fetch if setting a single column:
  300. self._colSearch = 0
  301. self._colFetch = -1
  302. def OnListClick(self, evt):
  303. """!Left mouse button pressed"""
  304. toSel, flag = self.dropdownlistbox.HitTest( evt.GetPosition() )
  305. #no values on poition, return
  306. if toSel == -1: return
  307. self.dropdownlistbox.Select(toSel)
  308. def OnListDClick(self, evt):
  309. """!Mouse button double click"""
  310. self._setValueFromSelected()
  311. def OnListColClick(self, evt):
  312. """!Left mouse button pressed on column"""
  313. col = evt.GetColumn()
  314. # reverse the sort
  315. if col == self._colSearch:
  316. self._ascending = not self._ascending
  317. self.SortListItems( evt.GetColumn(), ascending=self._ascending )
  318. self._colSearch = evt.GetColumn()
  319. evt.Skip()
  320. def OnListItemSelected(self, event):
  321. """!Item selected"""
  322. self._setValueFromSelected()
  323. event.Skip()
  324. def OnEnteredText(self, event):
  325. """!Text entered"""
  326. text = event.GetString()
  327. if not text:
  328. # control is empty; hide dropdown if shown:
  329. if self.dropdown.IsShown():
  330. self._showDropDown(False)
  331. event.Skip()
  332. return
  333. cmd = shlex.split(str(text))
  334. pattern = str(text)
  335. if len(cmd) > 1:
  336. # search for module's options
  337. if cmd[0] in self._choicesCmd and not self._module:
  338. self._module = menuform.GUI().ParseInterface(cmd = cmd)
  339. if self._module:
  340. if len(cmd[-1].split('=', 1)) == 1:
  341. # new option
  342. if cmd[-1][0] == '-':
  343. # -> flags
  344. self.SetChoices(self._module.get_list_flags(), type = 'flag')
  345. pattern = cmd[-1].lstrip('-')
  346. else:
  347. # -> options
  348. self.SetChoices(self._module.get_list_params(), type = 'param')
  349. pattern = cmd[-1]
  350. else:
  351. # value
  352. pattern = cmd[-1].split('=', 1)[1]
  353. else:
  354. # search for GRASS modules
  355. if self._module:
  356. # -> switch back to GRASS modules list
  357. self.SetChoices(self._choicesCmd)
  358. self._module = None
  359. self._choiceType = None
  360. found = False
  361. choices = self._choices
  362. for numCh, choice in enumerate(choices):
  363. if choice.lower().startswith(pattern):
  364. found = True
  365. if found:
  366. self._showDropDown(True)
  367. item = self.dropdownlistbox.GetItem(numCh)
  368. toSel = item.GetId()
  369. self.dropdownlistbox.Select(toSel)
  370. break
  371. if not found:
  372. self.dropdownlistbox.Select(self.dropdownlistbox.GetFirstSelected(), False)
  373. if self._hideOnNoMatch:
  374. self._showDropDown(False)
  375. if self._module and cmd[-1][-2] == '=':
  376. optType = self._module.get_param(cmd[-1][:-2])['prompt']
  377. if optType in ('raster', 'vector'):
  378. # -> raster/vector map
  379. self.SetChoices(self._choicesMap[optType], optType)
  380. self._listItemVisible()
  381. event.Skip()
  382. def OnKeyDown (self, event):
  383. """
  384. Do some work when the user press on the keys: up and down:
  385. move the cursor left and right: move the search
  386. """
  387. skip = True
  388. sel = self.dropdownlistbox.GetFirstSelected()
  389. visible = self.dropdown.IsShown()
  390. KC = event.GetKeyCode()
  391. if KC == wx.WXK_DOWN:
  392. if sel < (self.dropdownlistbox.GetItemCount() - 1):
  393. self.dropdownlistbox.Select(sel + 1)
  394. self._listItemVisible()
  395. self._showDropDown()
  396. skip = False
  397. elif KC == wx.WXK_UP:
  398. if sel > 0:
  399. self.dropdownlistbox.Select(sel - 1)
  400. self._listItemVisible()
  401. self._showDropDown ()
  402. skip = False
  403. if visible:
  404. if event.GetKeyCode() == wx.WXK_RETURN:
  405. self._setValueFromSelected()
  406. skip = False
  407. if event.GetKeyCode() == wx.WXK_ESCAPE:
  408. self._showDropDown(False)
  409. skip = False
  410. if skip:
  411. event.Skip()
  412. def OnControlChanged(self, event):
  413. """!Control changed"""
  414. if self.IsShown():
  415. self._showDropDown(False)
  416. event.Skip()