prompt.py 19 KB

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