blender-thumbnailer.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. #!/usr/bin/env python3
  2. ####################################
  3. # #
  4. # COPYRIGHT NOTICE #
  5. # #
  6. # This file is a part of Victori- #
  7. # ous Children Studio Organizer. #
  8. # Or simply VCStudio. Copyright #
  9. # of J.Y.Amihud. But don't be sad #
  10. # because I released the entire #
  11. # project under a GNU GPL license. #
  12. # You may use Version 3 or later. #
  13. # See www.gnu.org/licenses if your #
  14. # copy has no License file. Please #
  15. # note. Ones I used the GPL v2 for #
  16. # it. It's no longer the case. #
  17. # #
  18. ####################################
  19. ####################################
  20. # This code originally was a part #
  21. # of Blender. But I yanked it. And #
  22. # this version is now GPLv3, baby #
  23. ####################################
  24. ####################################
  25. # Changes from the previous origi- #
  26. # nal version include. #
  27. # Changing the GPL license block. #
  28. ####################################
  29. """
  30. Thumbnailer runs with python 2.7 and 3.x.
  31. To run automatically with a file manager such as Nautilus, save this file
  32. in a directory that is listed in PATH environment variable, and create
  33. blender.thumbnailer file in ${HOME}/.local/share/thumbnailers/ directory
  34. with the following contents:
  35. [Thumbnailer Entry]
  36. TryExec=blender-thumbnailer.py
  37. Exec=blender-thumbnailer.py %u %o
  38. MimeType=application/x-blender;
  39. """
  40. import struct
  41. def open_wrapper_get():
  42. """ wrap OS specific read functionality here, fallback to 'open()'
  43. """
  44. class GFileWrapper:
  45. __slots__ = ("mode", "g_file")
  46. def __init__(self, url, mode='r'):
  47. self.mode = mode # used in gzip module
  48. self.g_file = Gio.File.parse_name(url).read(None)
  49. def read(self, size):
  50. return self.g_file.read_bytes(size, None).get_data()
  51. def seek(self, offset, whence=0):
  52. self.g_file.seek(offset, [1, 0, 2][whence], None)
  53. return self.g_file.tell()
  54. def tell(self):
  55. return self.g_file.tell()
  56. def close(self):
  57. self.g_file.close(None)
  58. def open_local_url(url, mode='r'):
  59. o = urlparse(url)
  60. if o.scheme == '':
  61. path = o.path
  62. elif o.scheme == 'file':
  63. path = unquote(o.path)
  64. else:
  65. raise(IOError('URL scheme "%s" needs gi.repository.Gio module' % o.scheme))
  66. return open(path, mode)
  67. try:
  68. from gi.repository import Gio
  69. return GFileWrapper
  70. except ImportError:
  71. try:
  72. # Python 3
  73. from urllib.parse import urlparse, unquote
  74. except ImportError:
  75. # Python 2
  76. from urlparse import urlparse
  77. from urllib import unquote
  78. return open_local_url
  79. def blend_extract_thumb(path):
  80. import os
  81. open_wrapper = open_wrapper_get()
  82. REND = b'REND'
  83. TEST = b'TEST'
  84. blendfile = open_wrapper(path, 'rb')
  85. head = blendfile.read(12)
  86. if head[0:2] == b'\x1f\x8b': # gzip magic
  87. import gzip
  88. blendfile.close()
  89. blendfile = gzip.GzipFile('', 'rb', 0, open_wrapper(path, 'rb'))
  90. head = blendfile.read(12)
  91. if not head.startswith(b'BLENDER'):
  92. blendfile.close()
  93. return None, 0, 0
  94. is_64_bit = (head[7] == b'-'[0])
  95. # true for PPC, false for X86
  96. is_big_endian = (head[8] == b'V'[0])
  97. # blender pre 2.5 had no thumbs
  98. if head[9:11] <= b'24':
  99. return None, 0, 0
  100. sizeof_bhead = 24 if is_64_bit else 20
  101. int_endian = '>i' if is_big_endian else '<i'
  102. int_endian_pair = int_endian + 'i'
  103. while True:
  104. bhead = blendfile.read(sizeof_bhead)
  105. if len(bhead) < sizeof_bhead:
  106. return None, 0, 0
  107. code = bhead[:4]
  108. length = struct.unpack(int_endian, bhead[4:8])[0] # 4 == sizeof(int)
  109. if code == REND:
  110. blendfile.seek(length, os.SEEK_CUR)
  111. else:
  112. break
  113. if code != TEST:
  114. return None, 0, 0
  115. try:
  116. x, y = struct.unpack(int_endian_pair, blendfile.read(8)) # 8 == sizeof(int) * 2
  117. except struct.error:
  118. return None, 0, 0
  119. length -= 8 # sizeof(int) * 2
  120. if length != x * y * 4:
  121. return None, 0, 0
  122. image_buffer = blendfile.read(length)
  123. if len(image_buffer) != length:
  124. return None, 0, 0
  125. return image_buffer, x, y
  126. def write_png(buf, width, height):
  127. import zlib
  128. # reverse the vertical line order and add null bytes at the start
  129. width_byte_4 = width * 4
  130. raw_data = b"".join(b'\x00' + buf[span:span + width_byte_4] for span in range((height - 1) * width * 4, -1, - width_byte_4))
  131. def png_pack(png_tag, data):
  132. chunk_head = png_tag + data
  133. return struct.pack("!I", len(data)) + chunk_head + struct.pack("!I", 0xFFFFFFFF & zlib.crc32(chunk_head))
  134. return b"".join([
  135. b'\x89PNG\r\n\x1a\n',
  136. png_pack(b'IHDR', struct.pack("!2I5B", width, height, 8, 6, 0, 0, 0)),
  137. png_pack(b'IDAT', zlib.compress(raw_data, 9)),
  138. png_pack(b'IEND', b'')])
  139. def main():
  140. import sys
  141. if len(sys.argv) < 3:
  142. print("Expected 2 arguments <input.blend> <output.png>")
  143. else:
  144. file_in = sys.argv[-2]
  145. buf, width, height = blend_extract_thumb(file_in)
  146. if buf:
  147. file_out = sys.argv[-1]
  148. f = open(file_out, "wb")
  149. f.write(write_png(buf, width, height))
  150. f.close()
  151. if __name__ == '__main__':
  152. main()