1#!/usr/bin/env python
2
3# Copyright 2016 Google Inc.
4#
5# Use of this source code is governed by a BSD-style license that can be
6# found in the LICENSE file.
7
8# Experimental Skia Multi-Picture Doc parser.
9
10from __future__ import print_function
11
12import fileinput
13import sys
14import struct
15
16if len(sys.argv) < 2:
17  sys.stderr.write('Usage:\n\tpython %s MSKP_FILE [OUTPUT_SKP]\n\n'
18                   % sys.argv[0])
19  exit(1)
20
21mskp_src = sys.argv[1]
22src = open(mskp_src, 'rb')
23
24magic_constant = b'Skia Multi-Picture Doc\n\n'
25magic = src.read(len(magic_constant))
26if magic != magic_constant:
27  sys.stderr.write('Not a mskp file: "%s"\n' % mskp_src)
28  exit(2)
29
30version, page_count = struct.unpack('II', src.read(8))[:2]
31print('MSKP version: ', version)
32print('page count: ', page_count)
33if version > 2 or version < 1:
34  #TODO(halcanary): Remove support for version 1.
35  sys.stderr.write('unsupported mskp version\n')
36  exit(3)
37offsets = []
38for page in range(page_count):
39  print('page %3d\t' % page, end='')
40  if version == 1:
41    offset, size_x, size_y =struct.unpack('Qff', src.read(16))
42    print('offset = %-7d\t' % offset, end='')
43    offsets.append(offset)
44  elif version == 2:
45    size_x, size_y =struct.unpack('ff', src.read(8))
46  print('size = (%r,%r)' % (size_x, size_y))
47
48if len(sys.argv) >= 3:
49  with open(sys.argv[2], 'wb') as o:
50    if version == 2 or len(offsets) < 2:
51      while True:
52        file_buffer = src.read(8192)
53        if 0 == len(file_buffer):
54          break
55        o.write(file_buffer)
56    else:
57      o.write(src.read(offsets[1] - offsets[0]))
58