prompt.py 19 KB

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