treemodel.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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. node.parent = weakref.proxy(parent)
  69. return node
  70. def SearchNodes(self, parent=None, **kwargs):
  71. """Search nodes according to specified attributes."""
  72. nodes = []
  73. parent = parent if parent else self.root
  74. self._searchNodes(node=parent, foundNodes=nodes, **kwargs)
  75. return nodes
  76. def _searchNodes(self, node, foundNodes, **kwargs):
  77. """Helper method for searching nodes."""
  78. if node.match(**kwargs):
  79. foundNodes.append(node)
  80. for child in node.children:
  81. self._searchNodes(node=child, foundNodes=foundNodes, **kwargs)
  82. def GetNodeByIndex(self, index):
  83. """Method used for communication between view (VirtualTree) and model.
  84. :param index: index of node, as defined in VirtualTree doc
  85. (e.g. root ~ [], second node of a first node ~ [0, 1])
  86. """
  87. if len(index) == 0:
  88. return self.root
  89. return self._getNode(self.root, index)
  90. def GetIndexOfNode(self, node):
  91. """Method used for communication between view (VirtualTree) and model."""
  92. index = []
  93. return self._getIndex(node, index)
  94. def _getIndex(self, node, index):
  95. if node.parent:
  96. index.insert(0, node.parent.children.index(node))
  97. return self._getIndex(node.parent, index)
  98. return index
  99. def GetChildrenByIndex(self, index):
  100. """Method used for communication between view (VirtualTree) and model."""
  101. if len(index) == 0:
  102. return self.root.children
  103. node = self._getNode(self.root, index)
  104. return node.children
  105. def _getNode(self, node, index):
  106. if len(index) == 1:
  107. return node.children[index[0]]
  108. else:
  109. return self._getNode(node.children[index[0]], index[1:])
  110. def RemoveNode(self, node):
  111. """Removes node. If node is root, removes root's children, root is kept."""
  112. if node.parent:
  113. node.parent.children.remove(node)
  114. else:
  115. # node is root
  116. del node.children[:]
  117. def SortChildren(self, node):
  118. """Sorts children alphabetically based on label."""
  119. if node.children:
  120. node.children.sort(key=lambda node: node.label)
  121. def __str__(self):
  122. """Print tree."""
  123. text = []
  124. for child in self.root.children:
  125. child.nprint(text)
  126. return "\n".join(text)
  127. class DictNode(object):
  128. """Node which has data in a form of dictionary."""
  129. def __init__(self, label, data=None):
  130. """Create node.
  131. :param label: node label (displayed in GUI)
  132. :param data: data as dictionary or None
  133. """
  134. self.label = label
  135. if data is None:
  136. self.data = dict()
  137. else:
  138. self.data = data
  139. self._children = []
  140. self.parent = None
  141. @property
  142. def children(self):
  143. return self._children
  144. def nprint(self, text, indent=0):
  145. text.append(indent * ' ' + self.label)
  146. if self.data:
  147. for key, value in six.iteritems(self.data):
  148. text.append(
  149. "%(indent)s* %(key)s : %(value)s" %
  150. {'indent': (indent + 2) * ' ', 'key': key, 'value': value})
  151. if self.children:
  152. for child in self.children:
  153. child.nprint(text, indent + 2)
  154. def match(self, key, value):
  155. """Method used for searching according to given parameters.
  156. :param value: dictionary value to be matched
  157. :param key: data dictionary key
  158. """
  159. if key in self.data and self.data[key] == value:
  160. return True
  161. return False
  162. class ModuleNode(DictNode):
  163. """Node representing module."""
  164. def __init__(self, label, data=None):
  165. super(ModuleNode, self).__init__(label=label, data=data)
  166. def match(self, key, value, case_sensitive=False):
  167. """Method used for searching according to command,
  168. keywords or description."""
  169. if not self.data:
  170. return False
  171. if key not in ('command', 'keywords', 'description'):
  172. return False
  173. try:
  174. text = self.data[key]
  175. except KeyError:
  176. return False
  177. if not text:
  178. return False
  179. if case_sensitive:
  180. # start supported but unused, so testing last
  181. return value in text or value == '*'
  182. else:
  183. # this works fully only for English and requires accents
  184. # to be exact match (even Python 3 casefold() does not help)
  185. return value.lower() in text.lower() or value == '*'
  186. def main():
  187. import doctest
  188. doctest.testmod()
  189. if __name__ == '__main__':
  190. main()