prompt.py 16 KB

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