query.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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 sys
  13. import wx
  14. if __name__ == '__main__':
  15. gui_wx_path = os.path.join(os.getenv('GISBASE'), 'etc', 'gui', 'wxpython')
  16. if gui_wx_path not in sys.path:
  17. sys.path.append(gui_wx_path)
  18. from core.utils import _
  19. from gui_core.treeview import TreeListView
  20. from core.treemodel import TreeModel, DictNode
  21. class QueryDialog(wx.Dialog):
  22. def __init__(self, parent, data = None):
  23. wx.Dialog.__init__(self, parent, id = wx.ID_ANY,
  24. title = _("Query results"),
  25. size = (420, 400),
  26. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
  27. self.data = data
  28. self.panel = wx.Panel(self, id = wx.ID_ANY)
  29. self.mainSizer = wx.BoxSizer(wx.VERTICAL)
  30. helpText = wx.StaticText(self.panel, wx.ID_ANY,
  31. label=_("Right click to copy selected values to clipboard."))
  32. helpText.SetForegroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_GRAYTEXT))
  33. self.mainSizer.Add(item=helpText, proportion=0, flag=wx.ALL, border=5)
  34. self._colNames = [_("Feature"), _("Value")]
  35. self._model = QueryTreeBuilder(self.data, column=self._colNames[1])
  36. self.tree = TreeListView(model=self._model, parent=self.panel,
  37. columns=self._colNames,
  38. style=wx.TR_DEFAULT_STYLE |
  39. wx.TR_FULL_ROW_HIGHLIGHT | wx.TR_MULTIPLE)
  40. self.tree.SetColumnWidth(0, 220)
  41. self.tree.SetColumnWidth(1, 400)
  42. self.tree.ExpandAll(self._model.root)
  43. self.tree.contextMenu.connect(self.ShowContextMenu)
  44. self.mainSizer.Add(item = self.tree, proportion = 1, flag = wx.EXPAND | wx.ALL, border = 5)
  45. close = wx.Button(self.panel, id = wx.ID_CLOSE)
  46. close.Bind(wx.EVT_BUTTON, lambda event: self.Close())
  47. copy = wx.Button(self.panel, id = wx.ID_ANY, label = _("Copy all to clipboard"))
  48. copy.Bind(wx.EVT_BUTTON, self.Copy)
  49. self.Bind(wx.EVT_CLOSE, self.OnClose)
  50. hbox = wx.BoxSizer(wx.HORIZONTAL)
  51. hbox.AddStretchSpacer(1)
  52. hbox.Add(item = copy, proportion = 0, flag = wx.EXPAND | wx.RIGHT, border = 5)
  53. hbox.Add(item = close, proportion = 0, flag = wx.EXPAND | wx.ALL, border = 0)
  54. self.mainSizer.Add(item = hbox, proportion = 0, flag = wx.EXPAND | wx.ALL, border = 5)
  55. self.panel.SetSizer(self.mainSizer)
  56. self.mainSizer.Fit(self.panel)
  57. # for Windows
  58. self.SendSizeEvent()
  59. def SetData(self, data):
  60. state = self.tree.GetExpansionState()
  61. self.data = data
  62. self._model = QueryTreeBuilder(self.data, column=self._colNames[1])
  63. self.tree.SetModel(self._model)
  64. self.tree.SetExpansionState(state)
  65. def Copy(self, event):
  66. text = printResults(self._model, self._colNames[1])
  67. self._copyText(text)
  68. def ShowContextMenu(self, node):
  69. """!Show context menu.
  70. Menu for copying distinguishes single and multiple selection.
  71. """
  72. nodes = self.tree.GetSelected()
  73. if not nodes:
  74. return
  75. menu = wx.Menu()
  76. texts = []
  77. if len(nodes) > 1:
  78. values = []
  79. for node in nodes:
  80. values.append((node.label, node.data[self._colNames[1]] if node.data else ''))
  81. col1 = '\n'.join([val[1] for val in values if val[1]])
  82. col2 = '\n'.join([val[0] for val in values if val[0]])
  83. table = '\n'.join([val[0] + ': ' + val[1] for val in values])
  84. texts.append((_("Copy from '%s' column") % self._colNames[1], col1))
  85. texts.append((_("Copy from '%s' column") % self._colNames[0], col2))
  86. texts.append((_("Copy selected lines"), table))
  87. else:
  88. label1 = nodes[0].label
  89. texts.append((_("Copy '%s'" % self._cutLabel(label1)), label1))
  90. if nodes[0].data and nodes[0].data[self._colNames[1]]:
  91. label2 = nodes[0].data[self._colNames[1]]
  92. texts.insert(0, (_("Copy '%s'" % self._cutLabel(label2)), label2))
  93. texts.append((_("Copy line"), label1 + ': ' + label2))
  94. ids = []
  95. for text in texts:
  96. id = wx.NewId()
  97. ids.append(id)
  98. self.Bind(wx.EVT_MENU, lambda evt, t=text[1], id=id: self._copyText(t), id=id)
  99. menu.Append(id, text[0])
  100. # show the popup menu
  101. self.PopupMenu(menu)
  102. menu.Destroy()
  103. for id in ids:
  104. self.Unbind(wx.EVT_MENU, id=id)
  105. def _cutLabel(self, label):
  106. limit = 15
  107. if len(label) > limit:
  108. return label[:limit] + '...'
  109. return label
  110. def _copyText(self, text):
  111. """!Helper function for copying"""
  112. if wx.TheClipboard.Open():
  113. do = wx.TextDataObject()
  114. do.SetText(text)
  115. wx.TheClipboard.SetData(do)
  116. wx.TheClipboard.Close()
  117. def OnClose(self, event):
  118. self.Destroy()
  119. event.Skip()
  120. def QueryTreeBuilder(data, column):
  121. """!Builds tree model from query results.
  122. @param data query results as a dictionary
  123. @param column column name
  124. @returns tree model
  125. """
  126. def addNode(parent, data, model):
  127. for k, v in data.iteritems():
  128. if isinstance(v, dict):
  129. node = model.AppendNode(parent=parent, label=k)
  130. addNode(parent=node, data=v, model=model)
  131. else:
  132. node = model.AppendNode(parent=parent, label=k,
  133. data={column: str(v)})
  134. model = TreeModel(DictNode)
  135. for part in data:
  136. addNode(parent=model.root, data=part, model=model)
  137. return model
  138. def printResults(model, valueCol):
  139. """!Print all results to string.
  140. @param model results tree model
  141. @param valueCol column name with value to be printed
  142. """
  143. def printTree(node, textList, valueCol, indent=0):
  144. textList.append(indent*' ' + node.label + ': ' + node.data.get(valueCol, ''))
  145. for child in node.children:
  146. printTree(node=child, textList=textList, valueCol=valueCol, indent=indent + 2)
  147. textList=[]
  148. for child in model.root.children:
  149. printTree(node=child, textList=textList, valueCol=valueCol)
  150. return '\n'.join(textList)
  151. def PrepareQueryResults(coordinates, result):
  152. """!Prepare query results as a Query dialog input.
  153. Adds coordinates, improves vector results tree structure.
  154. """
  155. data = []
  156. data.append({_("east"): coordinates[0]})
  157. data.append({_("north"): coordinates[1]})
  158. for part in result:
  159. if 'Map' in part:
  160. itemText = part['Map']
  161. if 'Mapset' in part:
  162. itemText += '@' + part['Mapset']
  163. del part['Mapset']
  164. del part['Map']
  165. if part:
  166. data.append({itemText: part})
  167. else:
  168. data.append({itemText: _("Nothing found")})
  169. else:
  170. data.append(part)
  171. return data
  172. def test():
  173. app = wx.PySimpleApp()
  174. from grass.script import vector as gvect
  175. from grass.script import raster as grast
  176. testdata1 = grast.raster_what(map = ('elevation_shade@PERMANENT','landclass96'),
  177. coord = [(638509.051416,224742.348346)])
  178. testdata2 = gvect.vector_what(map=('firestations','bridges'),
  179. coord=(633177.897487,221352.921257), distance=10)
  180. testdata = testdata1 + testdata2
  181. data = PrepareQueryResults(coordinates = (638509.051416,224742.348346), result = testdata)
  182. frame = QueryDialog(parent = None, data = data)
  183. frame.ShowModal()
  184. frame.Destroy()
  185. app.MainLoop()
  186. if __name__ == "__main__":
  187. test()