forked from fikovnik/omnigraffle-export
/
omnigraffle_export.py
273 lines (216 loc) · 8.82 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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
#!/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 appscript import *
class OmniGraffleSchema(object):
""" A class that encapsulates an OmniGraffle schema file"""
# supported formarts
EXPORT_FORMATS = {
"eps": "EPS Format",
"pdf": "Apple PDF pasteboard type",
"png": "PNG",
"svg": "Scalable Vector Graphics XML File Type",
}
# attribute header in PDF document that contains the checksum
PDF_CHECKSUM_ATTRIBUTE = 'OmnigraffleExportChecksum: '
def __init__(self, schemafile, verbose=False):
"""
@param schemafile
@param verbose
"""
schemafile = os.path.abspath(schemafile)
if not os.path.isfile(schemafile) and \
not os.path.isfile(os.path.join(schemafile, "data.plist")):
raise ValueError('File: %s does not exists' % schemafile)
# options
self.verbose = verbose
self.schemafile = os.path.abspath(schemafile)
self.og = app('OmniGraffle Professional 5.app')
self.og.activate()
self.og.current_export_settings.area_type.set(k.all_graphics)
self.doc = self.og.open(self.schemafile)
logging.debug('Opened OmniGraffle file: ' + self.schemafile)
def get_canvas_list(self):
"""
Returns a list of names of all the canvases in the document
"""
return [c.name() for c in self.doc.canvases()]
def export(self, canvasname, filename, format='pdf', force=False):
"""
Exports one canvas named {@code canvasname}
"""
# canvas name
if not canvasname or len(canvasname) == 0:
raise Exception('canvasname is missing')
logging.debug('Exporting canvas: %s ' % canvasname)
# format
if not format or len(format) == 0:
format = 'pdf'
else:
format = format.lower()
if format not in OmniGraffleSchema.EXPORT_FORMATS:
raise Exception('Unknown format: %s' % format)
logging.debug('Exporting into format: %s ' % format)
filename = os.path.abspath(filename)
# suffix
if filename[filename.rfind('.')+1:].lower() != format:
filename = '%s.%s' % (filename, format)
logging.debug('Exporting into: %s ' % filename)
# checksum
chksum = None
if os.path.isfile(filename) and not force:
existing_chksum = checksum(filename) if format != 'pdf' \
else checksum_pdf(filename)
new_chksum = self.compute_canvas_checksum(canvasname)
if existing_chksum == new_chksum and existing_chksum != None:
logging.debug('No exporting - canvas %s not changed' %
canvasname)
return False
else:
chksum = new_chksum
elif format == 'pdf':
chksum = self.compute_canvas_checksum(canvasname)
if self._export_internal(canvasname, filename, format):
if self.verbose:
print "%s" % filename
else:
print >> sys.stderr, 'Failed to export canvas: %s to %s' % \
(canvasname, filename)
# 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 export_all(self, targetdir, fmt='pdf', force=False,
namemap=lambda c, f: '%s.%s' % (c, f) if f else c):
"""
Exports all canvases
"""
for c in self.get_canvas_list():
targetfile = os.path.join(os.path.abspath(targetdir),
namemap(c, fmt))
logging.debug("Exporting `%s' into `%s' as %s" %
(c, targetfile, fmt))
self.export(c, targetfile, fmt, force)
def compute_canvas_checksum(self, canvasname):
tmpfile = tempfile.mkstemp(suffix='.png')[1]
os.unlink(tmpfile)
assert self._export_internal(canvasname, tmpfile, 'png')
try:
chksum = checksum(tmpfile)
return chksum
finally:
os.unlink(tmpfile)
def _export_internal(self, canvasname, filename, format):
# find canvas
canvas = [c for c in self.doc.canvases() if c.name() == canvasname]
if len(canvas) == 1:
canvas = canvas[0]
else:
logging.warn('Canvas %s does not exist in %s' %
(canvasname, self.schemafile))
return False
# export
self.og.windows.first().canvas.set(canvas)
export_format = OmniGraffleSchema.EXPORT_FORMATS[format]
if (export_format == None):
self.doc.save(in_=filename)
else:
self.doc.save(as_=export_format, in_=filename)
logging.debug("Exported `%s' into `%s' as %s" % (canvasname, file,
format))
return True
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
chksum = pdfdoc.documentAttributes()[PDFKit.PDFDocumentSubjectAttribute]
if not chksum.startswith(OmniGraffleSchema.PDF_CHECKSUM_ATTRIBUTE):
return None
else:
return chksum[len(OmniGraffleSchema.PDF_CHECKSUM_ATTRIBUTE):]
def export(source, target, options):
# logging
if options.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
canvasname = options.canvasname
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
format = options.format
if not export_all:
# guess from the suffix
if not format:
format = target[target.rfind('.')+1:]
# 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)
schema = OmniGraffleSchema(source, verbose=options.verbose)
if export_all:
schema.export_all(target, format, force=options.force)
else:
schema.export(canvasname, target, format, options.force)
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('-v', action='store_true', help='verbose', dest='verbose')
parser.add_option('--verbose', action='store_true', help='verbose',
dest='verbose')
parser.add_option('-d', action='store_true', help='debug', dest='debug')
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, options)
if __name__ == '__main__':
main()