forked from fikovnik/omnigraffle-export
-
Notifications
You must be signed in to change notification settings - Fork 0
/
omnigraffle_export.py
182 lines (140 loc) · 5.57 KB
/
omnigraffle_export.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
#!/usr/bin/env python
import os
import sys
import optparse
import logging
import tempfile
import hashlib
from Foundation import NSURL, NSMutableDictionary
from Quartz import PDFKit
from omnigraffle import *
def export(source, target, canvasname=None, format='pdf', debug=False, force=False):
# logging
if debug:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.INFO, format='%(message)s')
# target
target = os.path.abspath(target)
# mode
export_all = os.path.isdir(target)
# determine the canvas
if not export_all:
# guess from filename
if not canvasname:
canvasname = os.path.basename(target)
canvasname = canvasname[:canvasname.rfind('.')]
if not canvasname or len(canvasname) == 0:
print >> sys.stderr, "Without canvas name, the target (-t) "\
"must be a directory"
sys.exit(1)
# determine the format
if not export_all:
# guess from the suffix
if not format:
format = target[target.rfind('.')+1:]
if not format or len(format) == 0:
format = 'pdf'
else:
format = format.lower()
# check source
if not os.access(source, os.R_OK):
print >> sys.stderr, "File: %s could not be opened for reading" % source
sys.exit(1)
og = OmniGraffle()
schema = og.open(source)
if export_all:
namemap=lambda c, f: '%s.%s' % (c, f) if f else c
for c in schema.get_canvas_list():
targetfile = os.path.join(os.path.abspath(target),
namemap(c, format))
logging.debug("Exporting `%s' into `%s' as %s" %
(c, targetfile, format))
export_one(schema, targetfile, c, format, force)
else:
export_one(schema, target, canvasname, format, force)
def export_one(schema, filename, canvasname, format='pdf', force=False):
def _checksum(filepath):
assert os.path.isfile(filepath), '%s is not a file' % filepath
c = hashlib.md5()
with open(filepath, 'rb') as f:
for chunk in iter(lambda: f.read(128), ''):
c.update(chunk)
return c.hexdigest()
def _checksum_pdf(filepath):
assert os.path.isfile(filepath), '%s is not a file' % filepath
url = NSURL.fileURLWithPath_(filepath)
pdfdoc = PDFKit.PDFDocument.alloc().initWithURL_(url)
assert pdfdoc != None
chsum = None
attrs = pdfdoc.documentAttributes()
if PDFKit.PDFDocumentSubjectAttribute in attrs:
chksum = pdfdoc.documentAttributes()[PDFKit.PDFDocumentSubjectAttribute]
else:
return None
if not chksum.startswith(OmniGraffleSchema.PDF_CHECKSUM_ATTRIBUTE):
return None
else:
return chksum[len(OmniGraffleSchema.PDF_CHECKSUM_ATTRIBUTE):]
def _compute_canvas_checksum(canvasname):
tmpfile = tempfile.mkstemp(suffix='.png')[1]
os.unlink(tmpfile)
export_one(schema, tmpfile, canvasname, 'png')
try:
chksum = _checksum(tmpfile)
return chksum
finally:
os.unlink(tmpfile)
# checksum
chksum = None
if os.path.isfile(filename) and not force:
existing_chksum = _checksum(filename) if format != 'pdf' \
else _checksum_pdf(filename)
new_chksum = _compute_canvas_checksum(canvasname)
if existing_chksum == new_chksum and existing_chksum != None:
logging.debug('Not exporting `%s` into `%s` as `%s` - canvas has not been changed' % (canvasname, filename, format))
return False
else:
chksum = new_chksum
elif format == 'pdf':
chksum = _compute_canvas_checksum(canvasname)
try:
schema.export(canvasname, filename, format=format)
except RuntimeError as e:
print >> sys.stderr, e.message
return False
# update checksum
if format == 'pdf':
# save the checksum
url = NSURL.fileURLWithPath_(filename)
pdfdoc = PDFKit.PDFDocument.alloc().initWithURL_(url)
attrs = NSMutableDictionary.alloc().initWithDictionary_(pdfdoc.documentAttributes())
attrs[PDFKit.PDFDocumentSubjectAttribute] = \
'%s%s' % (OmniGraffleSchema.PDF_CHECKSUM_ATTRIBUTE, chksum)
pdfdoc.setDocumentAttributes_(attrs)
pdfdoc.writeToFile_(filename)
return True
def main():
usage = "Usage: %prog [options] <source> <target>"
parser = optparse.OptionParser(usage=usage)
parser.add_option('-c',
help='canvas name. If not given it will be guessed from '
'the target filename unless it is a directory.',
metavar='NAME', dest='canvasname')
parser.add_option('-f',
help='format (one of: pdf, png, svg, eps). Guessed '
'from the target filename suffix unless it is a '
'directory. Defaults to pdf',
metavar='FMT', dest='format')
parser.add_option('--force', action='store_true', help='force the export',
dest='force')
parser.add_option('--debug', action='store_true', help='debug',
dest='debug')
(options, args) = parser.parse_args()
if len(args) != 2:
parser.print_help()
sys.exit(1)
(source, target) = args
export(source, target, canvasname, format, debug, force)
if __name__ == '__main__':
main()