query.py 8.0 KB

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