treemodel.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. """
  2. @package core.treemodel
  3. @brief tree structure model (used for menu, search tree)
  4. Classes:
  5. - treemodel::TreeModel
  6. - treemodel::DictNode
  7. - treemodel::ModuleNode
  8. (C) 2013 by the GRASS Development Team
  9. This program is free software under the GNU General Public License
  10. (>=v2). Read the file COPYING that comes with GRASS for details.
  11. @author Anna Petrasova <kratochanna gmail.com>
  12. """
  13. import six
  14. class TreeModel(object):
  15. """Class represents a tree structure with hidden root.
  16. TreeModel is used together with TreeView class to display results in GUI.
  17. The functionality is not complete, only needed methods are implemented.
  18. If needed, the functionality can be extended.
  19. >>> tree = TreeModel(DictNode)
  20. >>> root = tree.root
  21. >>> n1 = tree.AppendNode(parent=root, label='node1')
  22. >>> n2 = tree.AppendNode(parent=root, label='node2')
  23. >>> n11 = tree.AppendNode(parent=n1, label='node11', data={'xxx': 1})
  24. >>> n111 = tree.AppendNode(parent=n11, label='node111', data={'xxx': 4})
  25. >>> n12 = tree.AppendNode(parent=n1, label='node12', data={'xxx': 2})
  26. >>> n21 = tree.AppendNode(parent=n2, label='node21', data={'xxx': 1})
  27. >>> [node.label for node in tree.SearchNodes(key='xxx', value=1)]
  28. ['node11', 'node21']
  29. >>> [node.label for node in tree.SearchNodes(key='xxx', value=5)]
  30. []
  31. >>> tree.GetIndexOfNode(n111)
  32. [0, 0, 0]
  33. >>> tree.GetNodeByIndex((0,1)).label
  34. 'node12'
  35. >>> print tree
  36. node1
  37. node11
  38. * xxx : 1
  39. node111
  40. * xxx : 4
  41. node12
  42. * xxx : 2
  43. node2
  44. node21
  45. * xxx : 1
  46. """
  47. def __init__(self, nodeClass):
  48. """Constructor creates root node.
  49. :param nodeClass: class which is used for creating nodes
  50. """
  51. self._root = nodeClass('root')
  52. self.nodeClass = nodeClass
  53. @property
  54. def root(self):
  55. return self._root
  56. def AppendNode(self, parent, label, data=None):
  57. """Create node and append it to parent node.
  58. :param parent: parent node of the new node
  59. :param label: node label
  60. :param data: optional node data
  61. :return: new node
  62. """
  63. node = self.nodeClass(label=label, data=data)
  64. parent.children.append(node)
  65. node.parent = parent
  66. return node
  67. def SearchNodes(self, parent=None, **kwargs):
  68. """Search nodes according to specified attributes."""
  69. nodes = []
  70. parent = parent if parent else self.root
  71. self._searchNodes(node=parent, foundNodes=nodes, **kwargs)
  72. return nodes
  73. def _searchNodes(self, node, foundNodes, **kwargs):
  74. """Helper method for searching nodes."""
  75. if node.match(**kwargs):
  76. foundNodes.append(node)
  77. for child in node.children:
  78. self._searchNodes(node=child, foundNodes=foundNodes, **kwargs)
  79. def GetNodeByIndex(self, index):
  80. """Method used for communication between view (VirtualTree) and model.
  81. :param index: index of node, as defined in VirtualTree doc
  82. (e.g. root ~ [], second node of a first node ~ [0, 1])
  83. """
  84. if len(index) == 0:
  85. return self.root
  86. return self._getNode(self.root, index)
  87. def GetIndexOfNode(self, node):
  88. """Method used for communication between view (VirtualTree) and model."""
  89. index = []
  90. return self._getIndex(node, index)
  91. def _getIndex(self, node, index):
  92. if node.parent:
  93. index.insert(0, node.parent.children.index(node))
  94. return self._getIndex(node.parent, index)
  95. return index
  96. def GetChildrenByIndex(self, index):
  97. """Method used for communication between view (VirtualTree) and model."""
  98. if len(index) == 0:
  99. return self.root.children
  100. node = self._getNode(self.root, index)
  101. return node.children
  102. def _getNode(self, node, index):
  103. if len(index) == 1:
  104. return node.children[index[0]]
  105. else:
  106. return self._getNode(node.children[index[0]], index[1:])
  107. def RemoveNode(self, node):
  108. """Removes node."""
  109. if node.parent:
  110. node.parent.children.remove(node)
  111. else:
  112. # node is root
  113. for n in node.children:
  114. node.children.remove(n)
  115. def SortChildren(self, node):
  116. """Sorts children alphabetically based on label."""
  117. if node.children:
  118. node.children.sort(key=lambda node: node.label)
  119. def __str__(self):
  120. """Print tree."""
  121. text = []
  122. for child in self.root.children:
  123. child.nprint(text)
  124. return "\n".join(text)
  125. class DictNode(object):
  126. """Node which has data in a form of dictionary."""
  127. def __init__(self, label, data=None):
  128. """Create node.
  129. :param label: node label (displayed in GUI)
  130. :param data: data as dictionary or None
  131. """
  132. self.label = label
  133. if data is None:
  134. self.data = dict()
  135. else:
  136. self.data = data
  137. self._children = []
  138. self.parent = None
  139. @property
  140. def children(self):
  141. return self._children
  142. def nprint(self, text, indent=0):
  143. text.append(indent * ' ' + self.label)
  144. if self.data:
  145. for key, value in six.iteritems(self.data):
  146. text.append(
  147. "%(indent)s* %(key)s : %(value)s" %
  148. {'indent': (indent + 2) * ' ', 'key': key, 'value': value})
  149. if self.children:
  150. for child in self.children:
  151. child.nprint(text, indent + 2)
  152. def match(self, key, value):
  153. """Method used for searching according to given parameters.
  154. :param value: dictionary value to be matched
  155. :param key: data dictionary key
  156. """
  157. if key in self.data and self.data[key] == value:
  158. return True
  159. return False
  160. class ModuleNode(DictNode):
  161. """Node representing module."""
  162. def __init__(self, label, data=None):
  163. super(ModuleNode, self).__init__(label=label, data=data)
  164. def match(self, key, value, case_sensitive=False):
  165. """Method used for searching according to command,
  166. keywords or description."""
  167. if not self.data:
  168. return False
  169. if key not in ('command', 'keywords', 'description'):
  170. return False
  171. try:
  172. text = self.data[key]
  173. except KeyError:
  174. return False
  175. if not text:
  176. return False
  177. if case_sensitive:
  178. # start supported but unused, so testing last
  179. return value in text or value == '*'
  180. else:
  181. # this works fully only for English and requires accents
  182. # to be exact match (even Python 3 casefold() does not help)
  183. return value.lower() in text.lower() or value == '*'
  184. def main():
  185. import doctest
  186. doctest.testmod()
  187. if __name__ == '__main__':
  188. main()