blender-thumbnailer.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. #!/usr/bin/env python3
  2. # ##### BEGIN GPL LICENSE BLOCK #####
  3. #
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU General Public License
  6. # as published by the Free Software Foundation; either version 2
  7. # of the License, or (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software Foundation,
  16. # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  17. #
  18. # ##### END GPL LICENSE BLOCK #####
  19. # <pep8 compliant>
  20. """
  21. Thumbnailer runs with python 2.7 and 3.x.
  22. To run automatically with a file manager such as Nautilus, save this file
  23. in a directory that is listed in PATH environment variable, and create
  24. blender.thumbnailer file in ${HOME}/.local/share/thumbnailers/ directory
  25. with the following contents:
  26. [Thumbnailer Entry]
  27. TryExec=blender-thumbnailer.py
  28. Exec=blender-thumbnailer.py %u %o
  29. MimeType=application/x-blender;
  30. """
  31. import struct
  32. def open_wrapper_get():
  33. """ wrap OS specific read functionality here, fallback to 'open()'
  34. """
  35. class GFileWrapper:
  36. __slots__ = ("mode", "g_file")
  37. def __init__(self, url, mode='r'):
  38. self.mode = mode # used in gzip module
  39. self.g_file = Gio.File.parse_name(url).read(None)
  40. def read(self, size):
  41. return self.g_file.read_bytes(size, None).get_data()
  42. def seek(self, offset, whence=0):
  43. self.g_file.seek(offset, [1, 0, 2][whence], None)
  44. return self.g_file.tell()
  45. def tell(self):
  46. return self.g_file.tell()
  47. def close(self):
  48. self.g_file.close(None)
  49. def open_local_url(url, mode='r'):
  50. o = urlparse(url)
  51. if o.scheme == '':
  52. path = o.path
  53. elif o.scheme == 'file':
  54. path = unquote(o.path)
  55. else:
  56. raise(IOError('URL scheme "%s" needs gi.repository.Gio module' % o.scheme))
  57. return open(path, mode)
  58. try:
  59. from gi.repository import Gio
  60. return GFileWrapper
  61. except ImportError:
  62. try:
  63. # Python 3
  64. from urllib.parse import urlparse, unquote
  65. except ImportError:
  66. # Python 2
  67. from urlparse import urlparse
  68. from urllib import unquote
  69. return open_local_url
  70. def blend_extract_thumb(path):
  71. import os
  72. open_wrapper = open_wrapper_get()
  73. REND = b'REND'
  74. TEST = b'TEST'
  75. blendfile = open_wrapper(path, 'rb')
  76. head = blendfile.read(12)
  77. if head[0:2] == b'\x1f\x8b': # gzip magic
  78. import gzip
  79. blendfile.close()
  80. blendfile = gzip.GzipFile('', 'rb', 0, open_wrapper(path, 'rb'))
  81. head = blendfile.read(12)
  82. if not head.startswith(b'BLENDER'):
  83. blendfile.close()
  84. return None, 0, 0
  85. is_64_bit = (head[7] == b'-'[0])
  86. # true for PPC, false for X86
  87. is_big_endian = (head[8] == b'V'[0])
  88. # blender pre 2.5 had no thumbs
  89. if head[9:11] <= b'24':
  90. return None, 0, 0
  91. sizeof_bhead = 24 if is_64_bit else 20
  92. int_endian = '>i' if is_big_endian else '<i'
  93. int_endian_pair = int_endian + 'i'
  94. while True:
  95. bhead = blendfile.read(sizeof_bhead)
  96. if len(bhead) < sizeof_bhead:
  97. return None, 0, 0
  98. code = bhead[:4]
  99. length = struct.unpack(int_endian, bhead[4:8])[0] # 4 == sizeof(int)
  100. if code == REND:
  101. blendfile.seek(length, os.SEEK_CUR)
  102. else:
  103. break
  104. if code != TEST:
  105. return None, 0, 0
  106. try:
  107. x, y = struct.unpack(int_endian_pair, blendfile.read(8)) # 8 == sizeof(int) * 2
  108. except struct.error:
  109. return None, 0, 0
  110. length -= 8 # sizeof(int) * 2
  111. if length != x * y * 4:
  112. return None, 0, 0
  113. image_buffer = blendfile.read(length)
  114. if len(image_buffer) != length:
  115. return None, 0, 0
  116. return image_buffer, x, y
  117. def write_png(buf, width, height):
  118. import zlib
  119. # reverse the vertical line order and add null bytes at the start
  120. width_byte_4 = width * 4
  121. raw_data = b"".join(b'\x00' + buf[span:span + width_byte_4] for span in range((height - 1) * width * 4, -1, - width_byte_4))
  122. def png_pack(png_tag, data):
  123. chunk_head = png_tag + data
  124. return struct.pack("!I", len(data)) + chunk_head + struct.pack("!I", 0xFFFFFFFF & zlib.crc32(chunk_head))
  125. return b"".join([
  126. b'\x89PNG\r\n\x1a\n',
  127. png_pack(b'IHDR', struct.pack("!2I5B", width, height, 8, 6, 0, 0, 0)),
  128. png_pack(b'IDAT', zlib.compress(raw_data, 9)),
  129. png_pack(b'IEND', b'')])
  130. def main():
  131. import sys
  132. if len(sys.argv) < 3:
  133. print("Expected 2 arguments <input.blend> <output.png>")
  134. else:
  135. file_in = sys.argv[-2]
  136. buf, width, height = blend_extract_thumb(file_in)
  137. if buf:
  138. file_out = sys.argv[-1]
  139. f = open(file_out, "wb")
  140. f.write(write_png(buf, width, height))
  141. f.close()
  142. if __name__ == '__main__':
  143. main()