prompt.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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 self.searchBy.GetSelection() == 0: # -> description
  136. ref = data['desc']
  137. else: # -> keywords
  138. ref = ','.join(data['keywords'])
  139. if text in ref:
  140. modules.append(module)
  141. self.parent.statusbar.SetStatusText(_("%d modules found") % len(modules))
  142. self.input.SetChoices(modules)
  143. class PromptListCtrl(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin):
  144. def __init__(self, parent, id = wx.ID_ANY, pos = wx.DefaultPosition,
  145. size = wx.DefaultSize, style = 0):
  146. wx.ListCtrl.__init__(self, parent, id, pos, size, style)
  147. listmix.ListCtrlAutoWidthMixin.__init__(self)
  148. class TextCtrlAutoComplete(wx.TextCtrl, listmix.ColumnSorterMixin):
  149. def __init__ (self, parent, id = wx.ID_ANY, choices = [], **kwargs):
  150. """!Constructor works just like wx.TextCtrl except you can pass in a
  151. list of choices. You can also change the choice list at any time
  152. by calling setChoices.
  153. Inspired by http://wiki.wxpython.org/TextCtrlAutoComplete
  154. """
  155. if kwargs.has_key('style'):
  156. kwargs['style'] = wx.TE_PROCESS_ENTER | kwargs['style']
  157. else:
  158. kwargs['style'] = wx.TE_PROCESS_ENTER
  159. wx.TextCtrl.__init__(self, parent, id, **kwargs)
  160. # some variables
  161. self._choices = choices
  162. self._hideOnNoMatch = True
  163. self._module = None # currently selected module
  164. self._choiceType = None # type of choice (module, params, flags, raster, vector ...)
  165. self._screenheight = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_Y)
  166. # sort variable needed by listmix
  167. self.itemDataMap = dict()
  168. # widgets
  169. try:
  170. self.dropdown = wx.PopupWindow(self)
  171. except NotImplementedError:
  172. self.Destroy()
  173. raise NotImplementedError
  174. # create the list and bind the events
  175. self.dropdownlistbox = PromptListCtrl(parent = self.dropdown,
  176. style = wx.LC_REPORT | wx.LC_SINGLE_SEL | \
  177. wx.LC_SORT_ASCENDING | wx.LC_NO_HEADER,
  178. pos = wx.Point(0, 0))
  179. listmix.ColumnSorterMixin.__init__(self, 1)
  180. # set choices (list of GRASS modules)
  181. self._choicesCmd = globalvar.grassCmd['all']
  182. self._choicesMap = dict()
  183. for type in ('raster', 'vector'):
  184. self._choicesMap[type] = grass.list_strings(type = type[:4])
  185. # first search for GRASS module
  186. self.SetChoices(self._choicesCmd)
  187. # bindings...
  188. self.Bind(wx.EVT_KILL_FOCUS, self.OnControlChanged, self)
  189. self.Bind(wx.EVT_TEXT, self.OnEnteredText, self)
  190. self.Bind(wx.EVT_KEY_DOWN , self.OnKeyDown, self)
  191. # if need drop down on left click
  192. self.dropdown.Bind(wx.EVT_LISTBOX , self.OnListItemSelected, self.dropdownlistbox)
  193. self.dropdownlistbox.Bind(wx.EVT_LEFT_DOWN, self.OnListClick)
  194. self.dropdownlistbox.Bind(wx.EVT_LEFT_DCLICK, self.OnListDClick)
  195. self.dropdownlistbox.Bind(wx.EVT_LIST_COL_CLICK, self.OnListColClick)
  196. def _updateDataList(self, choices):
  197. """!Update data list"""
  198. # delete, if need, all the previous data
  199. if self.dropdownlistbox.GetColumnCount() != 0:
  200. self.dropdownlistbox.DeleteAllColumns()
  201. self.dropdownlistbox.DeleteAllItems()
  202. # and update the dict
  203. if choices:
  204. for numVal, data in enumerate(choices):
  205. self.itemDataMap[numVal] = data
  206. else:
  207. numVal = 0
  208. self.SetColumnCount(numVal)
  209. def _setListSize(self):
  210. """!Set list size"""
  211. choices = self._choices
  212. longest = 0
  213. for choice in choices:
  214. longest = max(len(choice), longest)
  215. longest += 3
  216. itemcount = min(len( choices ), 7) + 2
  217. charheight = self.dropdownlistbox.GetCharHeight()
  218. charwidth = self.dropdownlistbox.GetCharWidth()
  219. self.popupsize = wx.Size(charwidth*longest, charheight*itemcount)
  220. self.dropdownlistbox.SetSize(self.popupsize)
  221. self.dropdown.SetClientSize(self.popupsize)
  222. def _showDropDown(self, show = True):
  223. """!Either display the drop down list (show = True) or hide it
  224. (show = False).
  225. """
  226. if show:
  227. size = self.dropdown.GetSize()
  228. width, height = self.GetSizeTuple()
  229. x, y = self.ClientToScreenXY(0, height)
  230. if size.GetWidth() != width:
  231. size.SetWidth(width)
  232. self.dropdown.SetSize(size)
  233. self.dropdownlistbox.SetSize(self.dropdown.GetClientSize())
  234. if (y + size.GetHeight()) < self._screenheight:
  235. self.dropdown.SetPosition(wx.Point(x, y))
  236. else:
  237. self.dropdown.SetPosition(wx.Point(x, y - height - size.GetHeight()))
  238. self.dropdown.Show(show)
  239. def _listItemVisible(self):
  240. """!Moves the selected item to the top of the list ensuring it is
  241. always visible.
  242. """
  243. toSel = self.dropdownlistbox.GetFirstSelected()
  244. if toSel == -1:
  245. return
  246. self.dropdownlistbox.EnsureVisible(toSel)
  247. def _setValueFromSelected(self):
  248. """!Sets the wx.TextCtrl value from the selected wx.ListCtrl item.
  249. Will do nothing if no item is selected in the wx.ListCtrl.
  250. """
  251. sel = self.dropdownlistbox.GetFirstSelected()
  252. if sel > -1:
  253. if self._colFetch != -1:
  254. col = self._colFetch
  255. else:
  256. col = self._colSearch
  257. itemtext = self.dropdownlistbox.GetItem(sel, col).GetText()
  258. cmd = shlex.split(str(self.GetValue()))
  259. if len(cmd) > 1:
  260. # -> append text (skip last item)
  261. if self._choiceType == 'param':
  262. self.SetValue(' '.join(cmd[:-1]) + ' ' + itemtext + '=')
  263. optType = self._module.get_param(itemtext)['prompt']
  264. if optType in ('raster', 'vector'):
  265. # -> raster/vector map
  266. self.SetChoices(self._choicesMap[optType], optType)
  267. elif self._choiceType == 'flag':
  268. if len(itemtext) > 1:
  269. prefix = '--'
  270. else:
  271. prefix = '-'
  272. self.SetValue(' '.join(cmd[:-1]) + ' ' + prefix + itemtext)
  273. elif self._choiceType in ('raster', 'vector'):
  274. self.SetValue(' '.join(cmd[:-1]) + ' ' + cmd[-1].split('=', 1)[0] + '=' + itemtext)
  275. else:
  276. # -> reset text
  277. self.SetValue(itemtext + ' ')
  278. self.SetInsertionPointEnd()
  279. self._showDropDown(False)
  280. def GetListCtrl(self):
  281. """!Method required by listmix.ColumnSorterMixin"""
  282. return self.dropdownlistbox
  283. def SetChoices(self, choices, type = 'module'):
  284. """!Sets the choices available in the popup wx.ListBox.
  285. The items will be sorted case insensitively.
  286. """
  287. self._choices = choices
  288. self._choiceType = type
  289. self.dropdownlistbox.SetWindowStyleFlag(wx.LC_REPORT | wx.LC_SINGLE_SEL | \
  290. wx.LC_SORT_ASCENDING | wx.LC_NO_HEADER)
  291. if not isinstance(choices, list):
  292. self._choices = [ x for x in choices ]
  293. if self._choiceType not in ('raster', 'vector'):
  294. # do not sort raster/vector maps
  295. utils.ListSortLower(self._choices)
  296. self._updateDataList(self._choices)
  297. self.dropdownlistbox.InsertColumn(0, "")
  298. for num, colVal in enumerate(self._choices):
  299. index = self.dropdownlistbox.InsertImageStringItem(sys.maxint, colVal, -1)
  300. self.dropdownlistbox.SetStringItem(index, 0, colVal)
  301. self.dropdownlistbox.SetItemData(index, num)
  302. self._setListSize()
  303. # there is only one choice for both search and fetch if setting a single column:
  304. self._colSearch = 0
  305. self._colFetch = -1
  306. def OnListClick(self, evt):
  307. """!Left mouse button pressed"""
  308. toSel, flag = self.dropdownlistbox.HitTest( evt.GetPosition() )
  309. #no values on poition, return
  310. if toSel == -1: return
  311. self.dropdownlistbox.Select(toSel)
  312. def OnListDClick(self, evt):
  313. """!Mouse button double click"""
  314. self._setValueFromSelected()
  315. def OnListColClick(self, evt):
  316. """!Left mouse button pressed on column"""
  317. col = evt.GetColumn()
  318. # reverse the sort
  319. if col == self._colSearch:
  320. self._ascending = not self._ascending
  321. self.SortListItems( evt.GetColumn(), ascending=self._ascending )
  322. self._colSearch = evt.GetColumn()
  323. evt.Skip()
  324. def OnListItemSelected(self, event):
  325. """!Item selected"""
  326. self._setValueFromSelected()
  327. event.Skip()
  328. def OnEnteredText(self, event):
  329. """!Text entered"""
  330. text = event.GetString()
  331. if not text:
  332. # control is empty; hide dropdown if shown:
  333. if self.dropdown.IsShown():
  334. self._showDropDown(False)
  335. event.Skip()
  336. return
  337. cmd = shlex.split(str(text))
  338. pattern = str(text)
  339. if len(cmd) > 1:
  340. # search for module's options
  341. if cmd[0] in self._choicesCmd and not self._module:
  342. self._module = menuform.GUI().ParseInterface(cmd = cmd)
  343. if self._module:
  344. if len(cmd[-1].split('=', 1)) == 1:
  345. # new option
  346. if cmd[-1][0] == '-':
  347. # -> flags
  348. self.SetChoices(self._module.get_list_flags(), type = 'flag')
  349. pattern = cmd[-1].lstrip('-')
  350. else:
  351. # -> options
  352. self.SetChoices(self._module.get_list_params(), type = 'param')
  353. pattern = cmd[-1]
  354. else:
  355. # value
  356. pattern = cmd[-1].split('=', 1)[1]
  357. else:
  358. # search for GRASS modules
  359. if self._module:
  360. # -> switch back to GRASS modules list
  361. self.SetChoices(self._choicesCmd)
  362. self._module = None
  363. self._choiceType = None
  364. found = False
  365. choices = self._choices
  366. for numCh, choice in enumerate(choices):
  367. if choice.lower().startswith(pattern):
  368. found = True
  369. if found:
  370. self._showDropDown(True)
  371. item = self.dropdownlistbox.GetItem(numCh)
  372. toSel = item.GetId()
  373. self.dropdownlistbox.Select(toSel)
  374. break
  375. if not found:
  376. self.dropdownlistbox.Select(self.dropdownlistbox.GetFirstSelected(), False)
  377. if self._hideOnNoMatch:
  378. self._showDropDown(False)
  379. if self._module and cmd[-1][-2] == '=':
  380. optType = self._module.get_param(cmd[-1][:-2])['prompt']
  381. if optType in ('raster', 'vector'):
  382. # -> raster/vector map
  383. self.SetChoices(self._choicesMap[optType], optType)
  384. self._listItemVisible()
  385. event.Skip()
  386. def OnKeyDown (self, event):
  387. """
  388. Do some work when the user press on the keys: up and down:
  389. move the cursor left and right: move the search
  390. """
  391. skip = True
  392. sel = self.dropdownlistbox.GetFirstSelected()
  393. visible = self.dropdown.IsShown()
  394. KC = event.GetKeyCode()
  395. if KC == wx.WXK_DOWN:
  396. if sel < (self.dropdownlistbox.GetItemCount() - 1):
  397. self.dropdownlistbox.Select(sel + 1)
  398. self._listItemVisible()
  399. self._showDropDown()
  400. skip = False
  401. elif KC == wx.WXK_UP:
  402. if sel > 0:
  403. self.dropdownlistbox.Select(sel - 1)
  404. self._listItemVisible()
  405. self._showDropDown ()
  406. skip = False
  407. if visible:
  408. if event.GetKeyCode() == wx.WXK_RETURN:
  409. self._setValueFromSelected()
  410. skip = False
  411. if event.GetKeyCode() == wx.WXK_ESCAPE:
  412. self._showDropDown(False)
  413. skip = False
  414. if skip:
  415. event.Skip()
  416. def OnControlChanged(self, event):
  417. """!Control changed"""
  418. if self.IsShown():
  419. self._showDropDown(False)
  420. event.Skip()