treemodel.py 7.4 KB

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