otTraverse.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. """Methods for traversing trees of otData-driven OpenType tables."""
  2. from collections import deque
  3. from typing import Callable, Deque, Iterable, List, Optional, Tuple
  4. from .otBase import BaseTable
  5. __all__ = [
  6. "bfs_base_table",
  7. "dfs_base_table",
  8. "SubTablePath",
  9. ]
  10. class SubTablePath(Tuple[BaseTable.SubTableEntry, ...]):
  11. def __str__(self) -> str:
  12. path_parts = []
  13. for entry in self:
  14. path_part = entry.name
  15. if entry.index is not None:
  16. path_part += f"[{entry.index}]"
  17. path_parts.append(path_part)
  18. return ".".join(path_parts)
  19. # Given f(current frontier, new entries) add new entries to frontier
  20. AddToFrontierFn = Callable[[Deque[SubTablePath], List[SubTablePath]], None]
  21. def dfs_base_table(
  22. root: BaseTable,
  23. root_accessor: Optional[str] = None,
  24. skip_root: bool = False,
  25. predicate: Optional[Callable[[SubTablePath], bool]] = None,
  26. iter_subtables_fn: Optional[
  27. Callable[[BaseTable], Iterable[BaseTable.SubTableEntry]]
  28. ] = None,
  29. ) -> Iterable[SubTablePath]:
  30. """Depth-first search tree of BaseTables.
  31. Args:
  32. root (BaseTable): the root of the tree.
  33. root_accessor (Optional[str]): attribute name for the root table, if any (mostly
  34. useful for debugging).
  35. skip_root (Optional[bool]): if True, the root itself is not visited, only its
  36. children.
  37. predicate (Optional[Callable[[SubTablePath], bool]]): function to filter out
  38. paths. If True, the path is yielded and its subtables are added to the
  39. queue. If False, the path is skipped and its subtables are not traversed.
  40. iter_subtables_fn (Optional[Callable[[BaseTable], Iterable[BaseTable.SubTableEntry]]]):
  41. function to iterate over subtables of a table. If None, the default
  42. BaseTable.iterSubTables() is used.
  43. Yields:
  44. SubTablePath: tuples of BaseTable.SubTableEntry(name, table, index) namedtuples
  45. for each of the nodes in the tree. The last entry in a path is the current
  46. subtable, whereas preceding ones refer to its parent tables all the way up to
  47. the root.
  48. """
  49. yield from _traverse_ot_data(
  50. root,
  51. root_accessor,
  52. skip_root,
  53. predicate,
  54. lambda frontier, new: frontier.extendleft(reversed(new)),
  55. iter_subtables_fn,
  56. )
  57. def bfs_base_table(
  58. root: BaseTable,
  59. root_accessor: Optional[str] = None,
  60. skip_root: bool = False,
  61. predicate: Optional[Callable[[SubTablePath], bool]] = None,
  62. iter_subtables_fn: Optional[
  63. Callable[[BaseTable], Iterable[BaseTable.SubTableEntry]]
  64. ] = None,
  65. ) -> Iterable[SubTablePath]:
  66. """Breadth-first search tree of BaseTables.
  67. Args:
  68. root
  69. the root of the tree.
  70. root_accessor (Optional[str]): attribute name for the root table, if any (mostly
  71. useful for debugging).
  72. skip_root (Optional[bool]): if True, the root itself is not visited, only its
  73. children.
  74. predicate (Optional[Callable[[SubTablePath], bool]]): function to filter out
  75. paths. If True, the path is yielded and its subtables are added to the
  76. queue. If False, the path is skipped and its subtables are not traversed.
  77. iter_subtables_fn (Optional[Callable[[BaseTable], Iterable[BaseTable.SubTableEntry]]]):
  78. function to iterate over subtables of a table. If None, the default
  79. BaseTable.iterSubTables() is used.
  80. Yields:
  81. SubTablePath: tuples of BaseTable.SubTableEntry(name, table, index) namedtuples
  82. for each of the nodes in the tree. The last entry in a path is the current
  83. subtable, whereas preceding ones refer to its parent tables all the way up to
  84. the root.
  85. """
  86. yield from _traverse_ot_data(
  87. root,
  88. root_accessor,
  89. skip_root,
  90. predicate,
  91. lambda frontier, new: frontier.extend(new),
  92. iter_subtables_fn,
  93. )
  94. def _traverse_ot_data(
  95. root: BaseTable,
  96. root_accessor: Optional[str],
  97. skip_root: bool,
  98. predicate: Optional[Callable[[SubTablePath], bool]],
  99. add_to_frontier_fn: AddToFrontierFn,
  100. iter_subtables_fn: Optional[
  101. Callable[[BaseTable], Iterable[BaseTable.SubTableEntry]]
  102. ] = None,
  103. ) -> Iterable[SubTablePath]:
  104. # no visited because general otData cannot cycle (forward-offset only)
  105. if root_accessor is None:
  106. root_accessor = type(root).__name__
  107. if predicate is None:
  108. def predicate(path):
  109. return True
  110. if iter_subtables_fn is None:
  111. def iter_subtables_fn(table):
  112. return table.iterSubTables()
  113. frontier: Deque[SubTablePath] = deque()
  114. root_entry = BaseTable.SubTableEntry(root_accessor, root)
  115. if not skip_root:
  116. frontier.append((root_entry,))
  117. else:
  118. add_to_frontier_fn(
  119. frontier,
  120. [
  121. (root_entry, subtable_entry)
  122. for subtable_entry in iter_subtables_fn(root)
  123. ],
  124. )
  125. while frontier:
  126. # path is (value, attr_name) tuples. attr_name is attr of parent to get value
  127. path = frontier.popleft()
  128. current = path[-1].value
  129. if not predicate(path):
  130. continue
  131. yield SubTablePath(path)
  132. new_entries = [
  133. path + (subtable_entry,) for subtable_entry in iter_subtables_fn(current)
  134. ]
  135. add_to_frontier_fn(frontier, new_entries)