xcursor_trim.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #!/usr/bin/env python3
  2. """Copy an Xcursor theme, keeping only the images of one nominal size.
  3. Usage: tools/xcursor_trim.py SRC_DIR DST_DIR [SIZE]
  4. Used once to import assets/cursors/adwaita/ from the host's adwaita-cursors
  5. package (/usr/share/icons/Adwaita/cursors). Symlinks (legacy X11 aliases)
  6. are skipped; every regular file is rewritten as a valid Xcursor file that
  7. holds only the SIZE (default 24) image chunks, so the tree does not carry
  8. the 30..96 px images (12 MB for the whole theme, mostly the animated
  9. wait/progress spinners). Comment chunks are dropped.
  10. """
  11. import os
  12. import struct
  13. import sys
  14. XCUR_IMAGE = 0xFFFD0002
  15. def trim(data, size):
  16. magic, hdr, version, ntoc = struct.unpack_from('<4sIII', data, 0)
  17. if magic != b'Xcur':
  18. raise ValueError('not an Xcursor file')
  19. chunks = []
  20. for i in range(ntoc):
  21. typ, sub, pos = struct.unpack_from('<III', data, hdr + i * 12)
  22. if typ != XCUR_IMAGE or sub != size:
  23. continue
  24. chdr, ctyp, csub, cver, w, h, xh, yh, delay = \
  25. struct.unpack_from('<IIIIIIIII', data, pos)
  26. end = pos + chdr + w * h * 4
  27. chunks.append((typ, sub, data[pos:end]))
  28. if not chunks:
  29. raise ValueError('no %d px images' % size)
  30. out = bytearray(struct.pack('<4sIII', b'Xcur', 16, version, len(chunks)))
  31. pos = 16 + 12 * len(chunks)
  32. toc = bytearray()
  33. body = bytearray()
  34. for typ, sub, raw in chunks:
  35. toc += struct.pack('<III', typ, sub, pos + len(body))
  36. body += raw
  37. return bytes(out + toc + body)
  38. def main():
  39. if len(sys.argv) < 3:
  40. sys.exit(__doc__)
  41. src, dst = sys.argv[1], sys.argv[2]
  42. size = int(sys.argv[3]) if len(sys.argv) > 3 else 24
  43. os.makedirs(dst, exist_ok=True)
  44. for name in sorted(os.listdir(src)):
  45. path = os.path.join(src, name)
  46. if os.path.islink(path) or not os.path.isfile(path):
  47. continue
  48. with open(path, 'rb') as f:
  49. data = f.read()
  50. try:
  51. out = trim(data, size)
  52. except ValueError as e:
  53. print('skip %s: %s' % (name, e))
  54. continue
  55. with open(os.path.join(dst, name), 'wb') as f:
  56. f.write(out)
  57. if __name__ == '__main__':
  58. main()