treemodel.py 7.1 KB

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