query.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. """
  2. @package gui_core.query
  3. @brief wxGUI query dialog
  4. Classes:
  5. - query::QueryDialog
  6. (C) 2013 by the GRASS Development Team
  7. This program is free software under the GNU General Public License
  8. (>=v2). Read the file COPYING that comes with GRASS for details.
  9. @author Anna Kratochvilova <kratochanna gmail.com>
  10. """
  11. import os
  12. import wx
  13. import six
  14. from core.gcmd import DecodeString
  15. from gui_core.treeview import TreeListView
  16. from gui_core.wrap import Button, StaticText, Menu, NewId
  17. from core.treemodel import TreeModel, DictNode
  18. from grass.pydispatch.signal import Signal
  19. class QueryDialog(wx.Dialog):
  20. def __init__(self, parent, data=None):
  21. wx.Dialog.__init__(self, parent, id=wx.ID_ANY,
  22. title=_("Query results"),
  23. size=(420, 400),
  24. style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
  25. # send query output to console
  26. self.redirectOutput = Signal('QueryDialog.redirectOutput')
  27. self.data = data
  28. self.panel = wx.Panel(self, id=wx.ID_ANY)
  29. self.mainSizer = wx.BoxSizer(wx.VERTICAL)
  30. helpText = StaticText(self.panel, wx.ID_ANY, label=_(
  31. "Right click to copy selected values to clipboard."))
  32. helpText.SetForegroundColour(
  33. wx.SystemSettings.GetColour(
  34. wx.SYS_COLOUR_GRAYTEXT))
  35. self.mainSizer.Add(helpText, proportion=0, flag=wx.ALL, border=5)
  36. self._colNames = [_("Feature"), _("Value")]
  37. self._model = QueryTreeBuilder(self.data, column=self._colNames[1])
  38. self.tree = TreeListView(model=self._model, parent=self.panel,
  39. columns=self._colNames,
  40. style=wx.TR_DEFAULT_STYLE | wx.TR_HIDE_ROOT |
  41. wx.TR_FULL_ROW_HIGHLIGHT | wx.TR_MULTIPLE)
  42. self.tree.SetColumnWidth(0, 220)
  43. self.tree.SetColumnWidth(1, 1000)
  44. self.tree.ExpandAll(self._model.root)
  45. self.tree.contextMenu.connect(self.ShowContextMenu)
  46. self.mainSizer.Add(
  47. self.tree,
  48. proportion=1,
  49. flag=wx.EXPAND | wx.ALL,
  50. border=5)
  51. close = Button(self.panel, id=wx.ID_CLOSE)
  52. close.Bind(wx.EVT_BUTTON, lambda event: self.Close())
  53. copy = Button(
  54. self.panel,
  55. id=wx.ID_ANY,
  56. label=_("Copy all to clipboard"))
  57. copy.Bind(wx.EVT_BUTTON, self.Copy)
  58. self.Bind(wx.EVT_CLOSE, self.OnClose)
  59. self.redirect = wx.CheckBox(self.panel, label=_("Redirect to console"))
  60. self.redirect.SetValue(False)
  61. self.redirect.Bind(
  62. wx.EVT_CHECKBOX,
  63. lambda evt: self._onRedirect(
  64. evt.IsChecked()))
  65. hbox = wx.BoxSizer(wx.HORIZONTAL)
  66. hbox.Add(
  67. self.redirect,
  68. proportion=0,
  69. flag=wx.EXPAND | wx.RIGHT,
  70. border=5)
  71. hbox.AddStretchSpacer(1)
  72. hbox.Add(copy, proportion=0, flag=wx.EXPAND | wx.RIGHT, border=5)
  73. hbox.Add(close, proportion=0, flag=wx.EXPAND | wx.ALL, border=0)
  74. self.mainSizer.Add(
  75. hbox,
  76. proportion=0,
  77. flag=wx.EXPAND | wx.ALL,
  78. border=5)
  79. self.panel.SetSizer(self.mainSizer)
  80. self.mainSizer.Fit(self.panel)
  81. # for Windows
  82. self.SendSizeEvent()
  83. def SetData(self, data):
  84. state = self.tree.GetExpansionState()
  85. self.data = data
  86. self._model = QueryTreeBuilder(self.data, column=self._colNames[1])
  87. self.tree.SetModel(self._model)
  88. self.tree.SetExpansionState(state)
  89. if self.redirect.IsChecked():
  90. self.redirectOutput.emit(output=self._textToRedirect())
  91. def Copy(self, event):
  92. text = printResults(self._model, self._colNames[1])
  93. self._copyText(text)
  94. def ShowContextMenu(self, node):
  95. """Show context menu.
  96. Menu for copying distinguishes single and multiple selection.
  97. """
  98. nodes = self.tree.GetSelected()
  99. if not nodes:
  100. return
  101. menu = Menu()
  102. texts = []
  103. if len(nodes) > 1:
  104. values = []
  105. for node in nodes:
  106. values.append(
  107. (node.label, node.data[
  108. self._colNames[1]] if node.data else ''))
  109. col1 = '\n'.join([val[1] for val in values if val[1]])
  110. col2 = '\n'.join([val[0] for val in values if val[0]])
  111. table = '\n'.join([val[0] + ': ' + val[1] for val in values])
  112. texts.append(
  113. (_("Copy from '%s' column") %
  114. self._colNames[1], col1))
  115. texts.append(
  116. (_("Copy from '%s' column") %
  117. self._colNames[0], col2))
  118. texts.append((_("Copy selected lines"), table))
  119. else:
  120. label1 = nodes[0].label
  121. texts.append((_("Copy '%s'" % self._cutLabel(label1)), label1))
  122. if nodes[0].data and nodes[0].data[self._colNames[1]]:
  123. label2 = nodes[0].data[self._colNames[1]]
  124. texts.insert(
  125. 0, (_(
  126. "Copy '%s'" %
  127. self._cutLabel(label2)), label2))
  128. texts.append((_("Copy line"), label1 + ': ' + label2))
  129. ids = []
  130. for text in texts:
  131. id = NewId()
  132. ids.append(id)
  133. self.Bind(
  134. wx.EVT_MENU,
  135. lambda evt,
  136. t=text[1],
  137. id=id: self._copyText(t),
  138. id=id)
  139. menu.Append(id, text[0])
  140. # show the popup menu
  141. self.PopupMenu(menu)
  142. menu.Destroy()
  143. for id in ids:
  144. self.Unbind(wx.EVT_MENU, id=id)
  145. def _onRedirect(self, redirect):
  146. """Emits instructions to redirect query results.
  147. :param redirect: True to start redirecting, False to stop
  148. """
  149. if redirect:
  150. self.redirectOutput.emit(output=_("Query results:"), style='cmd')
  151. self.redirectOutput.emit(output=self._textToRedirect())
  152. else:
  153. self.redirectOutput.emit(output=_(" "), style='cmd')
  154. def _textToRedirect(self):
  155. text = printResults(self._model, self._colNames[1])
  156. text += '\n' + "-" * 50 + '\n'
  157. return text
  158. def _cutLabel(self, label):
  159. limit = 15
  160. if len(label) > limit:
  161. return label[:limit] + '...'
  162. return label
  163. def _copyText(self, text):
  164. """Helper function for copying"""
  165. if wx.TheClipboard.Open():
  166. do = wx.TextDataObject()
  167. do.SetText(text)
  168. wx.TheClipboard.SetData(do)
  169. wx.TheClipboard.Close()
  170. def OnClose(self, event):
  171. if self.redirect.IsChecked():
  172. self._onRedirect(False)
  173. self.Destroy()
  174. event.Skip()
  175. def QueryTreeBuilder(data, column):
  176. """Builds tree model from query results.
  177. :param data: query results as a dictionary
  178. :param column: column name
  179. :return: tree model
  180. """
  181. def addNode(parent, data, model):
  182. for k, v in six.iteritems(data):
  183. if isinstance(v, dict):
  184. node = model.AppendNode(parent=parent, label=k)
  185. addNode(parent=node, data=v, model=model)
  186. else:
  187. if not isinstance(v, six.string_types):
  188. v = str(v)
  189. node = model.AppendNode(parent=parent, label=k,
  190. data={column: v})
  191. model = TreeModel(DictNode)
  192. for part in data:
  193. addNode(parent=model.root, data=part, model=model)
  194. return model
  195. def printResults(model, valueCol):
  196. """Print all results to string.
  197. :param model: results tree model
  198. :param valueCol: column name with value to be printed
  199. """
  200. def printTree(node, textList, valueCol, indent=0):
  201. if node.data.get(valueCol, '') or node.children:
  202. textList.append(
  203. indent * ' ' + node.label + ': ' + node.data.get(valueCol, ''))
  204. for child in node.children:
  205. printTree(
  206. node=child,
  207. textList=textList,
  208. valueCol=valueCol,
  209. indent=indent + 2)
  210. textList = []
  211. for child in model.root.children:
  212. printTree(node=child, textList=textList, valueCol=valueCol)
  213. return '\n'.join(textList)
  214. def PrepareQueryResults(coordinates, result):
  215. """Prepare query results as a Query dialog input.
  216. Adds coordinates, improves vector results tree structure.
  217. """
  218. data = []
  219. data.append({_("east, north"): ", ".join(map(str, coordinates))})
  220. for part in result:
  221. if 'Map' in part:
  222. itemText = part['Map']
  223. if 'Mapset' in part:
  224. itemText += '@' + part['Mapset']
  225. del part['Mapset']
  226. del part['Map']
  227. if part:
  228. data.append({itemText: part})
  229. else:
  230. data.append({itemText: _("Nothing found")})
  231. else:
  232. data.append(part)
  233. return data
  234. def test():
  235. app = wx.App()
  236. from grass.script import vector as gvect
  237. from grass.script import raster as grast
  238. testdata1 = grast.raster_what(
  239. map=('elevation_shade@PERMANENT', 'landclass96'),
  240. coord=[(638509.051416, 224742.348346)],
  241. localized=True)
  242. testdata2 = gvect.vector_what(
  243. map=(
  244. 'firestations', 'bridges'), coord=(
  245. 633177.897487, 221352.921257), distance=10)
  246. testdata = testdata1 + testdata2
  247. data = PrepareQueryResults(
  248. coordinates=(
  249. 638509.051416,
  250. 224742.348346),
  251. result=testdata)
  252. frame = QueryDialog(parent=None, data=data)
  253. frame.ShowModal()
  254. frame.Destroy()
  255. app.MainLoop()
  256. if __name__ == "__main__":
  257. test()