query.py 7.9 KB

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