normline_pt.curvature_pt should really return its result -- and changed some docstrings
[PyX/mjg.git] / pyx / pswriter.py
blob02eecd19f7fd5c6df0cd81c7a8f61f78cfe269c1
1 #!/usr/bin/env python
2 # -*- coding: ISO-8859-1 -*-
5 # Copyright (C) 2005 Jörg Lehmann <joergl@users.sourceforge.net>
6 # Copyright (C) 2005 André Wobst <wobsta@users.sourceforge.net>
8 # This file is part of PyX (http://pyx.sourceforge.net/).
10 # PyX is free software; you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 2 of the License, or
13 # (at your option) any later version.
15 # PyX is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
20 # You should have received a copy of the GNU General Public License
21 # along with PyX; if not, write to the Free Software
22 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
24 import copy, time, math
25 import style, version, type1font, unit
27 try:
28 enumerate([])
29 except NameError:
30 # fallback implementation for Python 2.2 and below
31 def enumerate(list):
32 return zip(xrange(len(list)), list)
35 class PSregistry:
37 def __init__(self):
38 # in order to keep a consistent order of the registered resources we
39 # not only store them in a hash but also keep an ordered list (up to a
40 # possible merging of resources, in which case the first instance is
41 # kept)
42 self.resourceshash = {}
43 self.resourceslist = []
45 def add(self, resource):
46 rkey = (resource.type, resource.id)
47 if self.resourceshash.has_key(rkey):
48 self.resourceshash[rkey].merge(resource)
49 else:
50 self.resourceshash[rkey] = resource
51 self.resourceslist.append(resource)
53 def outputPS(self, file, writer):
54 """ write all PostScript code of the prolog resources """
55 for resource in self.resourceslist:
56 resource.outputPS(file, writer, self)
59 # Abstract base class
62 class PSresource:
64 """ a PostScript resource """
66 def __init__(self, type, id):
67 # Every PSresource has to have a type and a unique id.
68 # Resources with the same type and id will be merged
69 # when they are registered in the PSregistry
70 self.type = type
71 self.id = id
73 def merge(self, other):
74 """ merge self with other, which has to be a resource of the same type and with
75 the same id"""
76 pass
78 def outputPS(self, file, writer, registry):
79 raise NotImplementedError("outputPS not implemented for %s" % repr(self))
82 # Different variants of prolog items
85 class PSdefinition(PSresource):
87 """ PostScript function definition included in the prolog """
89 def __init__(self, id, body):
90 self.type = "definition"
91 self.id = id
92 self.body = body
94 def outputPS(self, file, writer, registry):
95 file.write("%%%%BeginRessource: %s\n" % self.id)
96 file.write("%(body)s /%(id)s exch def\n" % self.__dict__)
97 file.write("%%EndRessource\n")
100 class PSfont:
102 def __init__(self, font, chars, registry):
103 if font.filename:
104 registry.add(PSfontfile(font.basefontname,
105 font.filename,
106 font.encoding,
107 chars))
108 if font.encoding:
109 registry.add(_ReEncodeFont)
110 registry.add(PSfontencoding(font.encoding))
111 registry.add(PSfontreencoding(font.name,
112 font.basefontname,
113 font.encoding.name))
116 class PSfontfile(PSresource):
118 """ PostScript font definition included in the prolog """
120 def __init__(self, name, filename, encoding, chars):
121 """ include type 1 font defined by the following parameters
123 - name: name of the PostScript font
124 - filename: name (without path) of file containing the font definition
125 - encfilename: name (without path) of file containing used encoding of font
126 or None (if no encoding file used)
127 - chars: character list to fill usedchars
131 # Note that here we only need the encoding for selecting the used glyphs!
133 self.type = "fontfile"
134 self.id = self.name = name
135 self.filename = filename
136 if encoding is None:
137 self.encodingfilename = None
138 else:
139 self.encodingfilename = encoding.filename
140 self.usedchars = {}
141 for char in chars:
142 self.usedchars[char] = 1
144 def merge(self, other):
145 if self.encodingfilename == other.encodingfilename:
146 self.usedchars.update(other.usedchars)
147 else:
148 self.encodingfilename = None # stripping of font not possible
150 def outputPS(self, file, writer, registry):
151 # XXX: access to the encoding file
152 if self.encodingfilename:
153 encodingfile = type1font.encodingfile(self.encodingfilename, self.encodingfilename)
154 usedglyphs = [encodingfile.decode(char)[1:] for char in self.usedchars.keys()]
156 file.write("%%%%BeginFont: %s\n" % self.name)
157 # file.write("%%Included glyphs: %s\n" % " ".join(usedglyphs))
158 import font.t1font
159 font = font.t1font.T1pfbfont(self.filename)
160 if self.encodingfilename:
161 strippedfont = font.getstrippedfont(usedglyphs)
162 else:
163 strippedfont = font
164 strippedfont.outputPS(file)
165 file.write("\n%%EndFont\n")
168 class PSfontencoding(PSresource):
170 """ PostScript font encoding vector included in the prolog """
172 def __init__(self, encoding):
173 """ include font encoding vector specified by encoding """
175 self.type = "fontencoding"
176 self.id = encoding.name
177 self.encoding = encoding
179 def outputPS(self, file, writer, registry):
180 encodingfile = type1font.encodingfile(self.encoding.name, self.encoding.filename)
181 encodingfile.outputPS(file, writer, registry)
184 class PSfontreencoding(PSresource):
186 """ PostScript font re-encoding directive included in the prolog """
188 def __init__(self, fontname, basefontname, encodingname):
189 """ include font re-encoding directive specified by
191 - fontname: PostScript FontName of the new reencoded font
192 - basefontname: PostScript FontName of the original font
193 - encname: name of the encoding
194 - font: a reference to the font instance (temporarily added for pdf support)
196 Before being able to reencode a font, you have to include the
197 encoding via a fontencoding prolog item with name=encname
201 self.type = "fontreencoding"
202 self.id = self.fontname = fontname
203 self.basefontname = basefontname
204 self.encodingname = encodingname
206 def outputPS(self, file, writer, registry):
207 file.write("%%%%BeginProcSet: %s\n" % self.fontname)
208 file.write("/%s /%s %s ReEncodeFont\n" % (self.basefontname, self.fontname, self.encodingname))
209 file.write("%%EndProcSet\n")
212 _ReEncodeFont = PSdefinition("ReEncodeFont", """{
213 5 dict
214 begin
215 /newencoding exch def
216 /newfontname exch def
217 /basefontname exch def
218 /basefontdict basefontname findfont def
219 /newfontdict basefontdict maxlength dict def
220 basefontdict {
221 exch dup dup /FID ne exch /Encoding ne and
222 { exch newfontdict 3 1 roll put }
223 { pop pop }
224 ifelse
225 } forall
226 newfontdict /FontName newfontname put
227 newfontdict /Encoding newencoding put
228 newfontname newfontdict definefont pop
230 }""")
233 class epswriter:
235 def __init__(self, document, filename):
236 if len(document.pages) != 1:
237 raise ValueError("EPS file can be construced out of a single page document only")
238 page = document.pages[0]
239 canvas = page.canvas
241 if not filename.endswith(".eps"):
242 filename = filename + ".eps"
243 try:
244 file = open(filename, "w")
245 except IOError:
246 raise IOError("cannot open output file")
248 bbox = page.bbox()
249 pagetrafo = page.pagetrafo(bbox)
251 # if a page transformation is necessary, we have to adjust the bounding box
252 # accordingly
253 if pagetrafo is not None:
254 bbox.transform(pagetrafo)
256 file.write("%!PS-Adobe-3.0 EPSF-3.0\n")
257 if bbox:
258 file.write("%%%%BoundingBox: %d %d %d %d\n" % bbox.lowrestuple_pt())
259 file.write("%%%%HiResBoundingBox: %g %g %g %g\n" % bbox.highrestuple_pt())
260 file.write("%%%%Creator: PyX %s\n" % version.version)
261 file.write("%%%%Title: %s\n" % filename)
262 file.write("%%%%CreationDate: %s\n" %
263 time.asctime(time.localtime(time.time())))
264 file.write("%%EndComments\n")
266 file.write("%%BeginProlog\n")
267 registry = PSregistry()
268 canvas.registerPS(registry)
269 registry.outputPS(file, self)
270 file.write("%%EndProlog\n")
272 acontext = context()
273 # apply a possible page transformation
274 if pagetrafo:
275 pagetrafo.outputPS(file, self, acontext)
277 style.linewidth.normal.outputPS(file, self, acontext)
279 # here comes the canvas content
280 canvas.outputPS(file, self, acontext)
282 file.write("showpage\n")
283 file.write("%%Trailer\n")
284 file.write("%%EOF\n")
287 class pswriter:
289 def __init__(self, document, filename, writebbox=0):
290 if not filename.endswith(".ps"):
291 filename = filename + ".ps"
292 try:
293 file = open(filename, "w")
294 except IOError:
295 raise IOError("cannot open output file")
297 # calculated bounding boxes of separate pages and the bounding box of the whole document
298 documentbbox = None
299 for page in document.pages:
300 canvas = page.canvas
301 page._bbox = page.bbox()
302 page._pagetrafo = page.pagetrafo(page._bbox)
303 # if a page transformation is necessary, we have to adjust the bounding box
304 # accordingly
305 if page._pagetrafo:
306 page._transformedbbox = page._bbox.transformed(page._pagetrafo)
307 else:
308 page._transformedbbox = page._bbox
309 if page._transformedbbox:
310 if documentbbox:
311 documentbbox += page._transformedbbox
312 else:
313 documentbbox = page._transformedbbox.enlarge(0) # make a copy
315 file.write("%!PS-Adobe-3.0\n")
316 if documentbbox and writebbox:
317 file.write("%%%%BoundingBox: %d %d %d %d\n" % documentbbox.lowrestuple_pt())
318 file.write("%%%%HiResBoundingBox: %g %g %g %g\n" % documentbbox.highrestuple_pt())
319 file.write("%%%%Creator: PyX %s\n" % version.version)
320 file.write("%%%%Title: %s\n" % filename)
321 file.write("%%%%CreationDate: %s\n" %
322 time.asctime(time.localtime(time.time())))
324 # required paper formats
325 paperformats = {}
326 for page in document.pages:
327 if page.paperformat:
328 paperformats[page.paperformat] = page.paperformat
330 first = 1
331 for paperformat in paperformats.values():
332 if first:
333 file.write("%%DocumentMedia: ")
334 first = 0
335 else:
336 file.write("%%+ ")
337 file.write("%s %d %d 75 white ()\n" % (paperformat.name,
338 unit.topt(paperformat.width),
339 unit.topt(paperformat.height)))
341 # file.write(%%DocumentNeededResources: ") # register not downloaded fonts here
343 file.write("%%%%Pages: %d\n" % len(document.pages))
344 file.write("%%PageOrder: Ascend\n")
345 file.write("%%EndComments\n")
347 # document defaults section
348 #file.write("%%BeginDefaults\n")
349 #file.write("%%EndDefaults\n")
351 # document prolog section
352 file.write("%%BeginProlog\n")
353 registry = PSregistry()
354 for page in document.pages:
355 page.canvas.registerPS(registry)
356 registry.outputPS(file, self)
357 file.write("%%EndProlog\n")
359 # document setup section
360 #file.write("%%BeginSetup\n")
361 #file.write("%%EndSetup\n")
363 # pages section
364 for nr, page in enumerate(document.pages):
365 file.write("%%%%Page: %s %d\n" % (page.pagename is None and str(nr+1) or page.pagename, nr+1))
366 if page.paperformat:
367 file.write("%%%%PageMedia: %s\n" % page.paperformat.name)
368 file.write("%%%%PageOrientation: %s\n" % (page.rotated and "Landscape" or "Portrait"))
369 if page._transformedbbox and writebbox:
370 file.write("%%%%PageBoundingBox: %d %d %d %d\n" % page._transformedbbox.lowrestuple_pt())
372 # page setup section
373 file.write("%%BeginPageSetup\n")
374 file.write("/pgsave save def\n")
376 acontext = context()
377 # apply a possible page transformation
378 if page._pagetrafo is not None:
379 page._pagetrafo.outputPS(file, self, acontext)
381 style.linewidth.normal.outputPS(file, self, acontext)
382 file.write("%%EndPageSetup\n")
384 # here comes the actual content
385 page.canvas.outputPS(file, self, acontext)
386 file.write("pgsave restore\n")
387 file.write("showpage\n")
388 file.write("%%PageTrailer\n")
390 file.write("%%Trailer\n")
391 file.write("%%EOF\n")
393 class context:
395 def __init__(self):
396 self.linewidth_pt = None
397 self.colorspace = None
398 self.font = None
400 def __call__(self, **kwargs):
401 newcontext = copy.copy(self)
402 for key, value in kwargs.items():
403 setattr(newcontext, key, value)
404 return newcontext