split_layers.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #!/usr/bin/env python3
  2. from xml.etree import ElementTree as ET
  3. import sys
  4. from pathlib import Path
  5. IN_DIR = Path(__file__).parent
  6. OUT_DIR = IN_DIR / "_autogen"
  7. namespaces = {
  8. "svg": "http://www.w3.org/2000/svg",
  9. "inkscape": "http://www.inkscape.org/namespaces/inkscape",
  10. }
  11. splits = {
  12. "mac.svg": {
  13. "_always": ["Base"],
  14. "01": ["Key"],
  15. "02": ["Key", "Routing table", "Routing table v4"],
  16. "03": ["Key", "Routing table", "Routing table v4", "Routing table - select"],
  17. "04": ["Key", "Yellow router"],
  18. "05": ["Key", "Yellow router", "ARP query", "ARP query v4"],
  19. "06": [
  20. "Key",
  21. "Yellow router",
  22. "ARP query",
  23. "ARP query v4",
  24. "ARP answer",
  25. "ARP answer v4",
  26. ],
  27. "07": ["Key", "Yellow router", "Outbound packet"],
  28. "08": ["Key", "Yellow router", "Outbound packet", "NHonlyMAC"],
  29. "09": ["Key", "Yellow router", "Outbound packet", "NHonlyMAC", "Waitbutthen"],
  30. "10": ["Key v6", "Routing table", "Routing table v6", "Routing table - select"],
  31. "11": [
  32. "Key v6",
  33. "Yellow router",
  34. "ARP query",
  35. "ARP query v6",
  36. "ARP answer",
  37. "ARP answer v6",
  38. ],
  39. "12": ["Key v6", "Yellow router", "Outbound packet"],
  40. }
  41. }
  42. def process_svg(svg_splits, path, out_path):
  43. out_path.mkdir(parents=True, exist_ok=True)
  44. always = svg_splits.get("_always", [])
  45. svg = ET.parse(path.as_posix())
  46. for keyframe in svg_splits:
  47. if keyframe.startswith("_"): # special value -- eg `_always`
  48. continue
  49. layers = always + svg_splits[keyframe]
  50. for layer_node in svg.findall(
  51. ".//svg:g[@inkscape:groupmode='layer']", namespaces=namespaces
  52. ):
  53. layer_node.attrib["style"] = "display:none"
  54. for layer_name in layers:
  55. layer = svg.find(
  56. ".//svg:g[@inkscape:groupmode='layer'][@inkscape:label='{}']".format(
  57. layer_name
  58. ),
  59. namespaces=namespaces,
  60. )
  61. if not layer:
  62. raise Exception("Layer {} not found".format(layer_name))
  63. layer.attrib["style"] = "display:inline"
  64. keyframe_outpath = out_path / "{}.svg".format(keyframe)
  65. svg.write(keyframe_outpath.as_posix(), encoding="utf-8")
  66. print("Written {}".format(keyframe_outpath.as_posix()))
  67. def main():
  68. processlist = []
  69. if len(sys.argv) < 2:
  70. processlist = splits.keys()
  71. else:
  72. processlist = [sys.argv[1]]
  73. for svg_path in processlist:
  74. process_svg(
  75. splits[svg_path], IN_DIR / svg_path, OUT_DIR / (Path(svg_path).stem)
  76. )
  77. if __name__ == "__main__":
  78. main()