2 # -*- coding: ISO-8859-1 -*-
5 # Copyright (C) 2002-2006 Jörg Lehmann <joergl@users.sourceforge.net>
6 # Copyright (C) 2002-2006 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 """The canvas module provides a PostScript canvas class and related classes
26 A canvas holds a collection of all elements and corresponding attributes to be
33 from __future__
import nested_scopes
38 """Base class for everything which can be inserted into a canvas"""
41 """return bounding box of canvasitem"""
44 def processPS(self
, file, writer
, context
, registry
, bbox
):
45 """process canvasitem by writing the corresponding PS code to file and
46 by updating context, registry as well as bbox
48 - the PS code corresponding to the canvasitem has to be written in the
49 stream file, which provides a write(string) method
50 - writer is the PSwriter used for the output
51 - context is an instance of pswriter.context which is used for keeping
52 track of the graphics state (current linewidth, colorspace and font))
53 - registry is used for tracking resources needed by the canvasitem
54 - bbox has to be updated to include the bounding box of the canvasitem
56 raise NotImplementedError()
58 def processPDF(self
, file, writer
, context
, registry
, bbox
):
59 """process canvasitem by writing the corresponding PDF code to file and
60 by updating context, registry as well as bbox
62 - the PDF code corresponding to the canvasitem has to be written in the
63 stream file, which provides a write(string) method
64 - writer is the PDFwriter used for the output, which contains properties
65 like whether streamcompression is used
66 - context is an instance of pdfwriter.context which is used for keeping
67 track of the graphics state, in particular for the emulation of PS
68 behaviour regarding fill and stroke styles, for keeping track of the
69 currently selected font as well as of text regions.
70 - registry is used for tracking resources needed by the canvasitem
71 - bbox has to be updated to include the bounding box of the canvasitem
73 raise NotImplementedError()
76 import attr
, deco
, deformer
, document
, style
, trafo
, type1font
77 import bbox
as bboxmodule
84 class clip(canvasitem
):
86 """class for use in canvas constructor which clips to a path"""
88 def __init__(self
, path
):
89 """construct a clip instance for a given path"""
93 # as a canvasitem a clipping path has NO influence on the bbox...
94 return bboxmodule
.empty()
97 # ... but for clipping, we nevertheless need the bbox
98 return self
.path
.bbox()
100 def processPS(self
, file, writer
, context
, registry
, bbox
):
101 file.write("newpath\n")
102 self
.path
.outputPS(file, writer
)
105 def processPDF(self
, file, writer
, context
, registry
, bbox
):
106 self
.path
.outputPDF(file, writer
)
111 # general canvas class
114 class _canvas(canvasitem
):
116 """a canvas holds a collection of canvasitems"""
118 def __init__(self
, attrs
=[], texrunner
=None):
120 """construct a canvas
122 The canvas can be modfied by supplying args, which have
123 to be instances of one of the following classes:
124 - trafo.trafo (leading to a global transformation of the canvas)
125 - canvas.clip (clips the canvas)
126 - style.strokestyle, style.fillstyle (sets some global attributes of the canvas)
128 Note that, while the first two properties are fixed for the
129 whole canvas, the last one can be changed via canvas.set().
131 The texrunner instance used for the text method can be specified
132 using the texrunner argument. It defaults to text.defaulttexrunner
137 self
.trafo
= trafo
.trafo()
139 if texrunner
is not None:
140 self
.texrunner
= texrunner
142 # prevent cyclic imports
144 self
.texrunner
= text
.defaulttexrunner
146 attr
.checkattrs(attrs
, [trafo
.trafo_pt
, clip
, style
.strokestyle
, style
.fillstyle
])
147 # We have to reverse the trafos such that the PostScript concat operators
148 # are in the right order. Correspondingly, we below multiply the current self.trafo
150 # Note that while for the stroke and fill styles the order doesn't matter at all,
151 # this is not true for the clip operation.
154 if isinstance(aattr
, trafo
.trafo_pt
):
155 self
.trafo
= self
.trafo
* aattr
156 elif isinstance(aattr
, clip
):
157 if self
.clipbbox
is None:
158 self
.clipbbox
= aattr
.clipbbox().transformed(self
.trafo
)
160 self
.clippbox
*= aattr
.clipbbox().transformed(self
.trafo
)
161 self
.items
.append(aattr
)
164 return len(self
.items
)
166 def __getitem__(self
, i
):
170 """returns bounding box of canvas
172 Note that this bounding box doesn't take into account the linewidths, so
173 is less accurate than the one used when writing the output to a file.
175 obbox
= bboxmodule
.empty()
176 for cmd
in self
.items
:
179 # transform according to our global transformation and
180 # intersect with clipping bounding box (which has already been
181 # transformed in canvas.__init__())
182 obbox
.transform(self
.trafo
)
183 if self
.clipbbox
is not None:
184 obbox
*= self
.clipbbox
187 def processPS(self
, file, writer
, context
, registry
, bbox
):
190 file.write("gsave\n")
191 nbbox
= bboxmodule
.empty()
192 for item
in self
.items
:
193 item
.processPS(file, writer
, context
, registry
, nbbox
)
194 # update bounding bbox
195 nbbox
.transform(self
.trafo
)
196 if self
.clipbbox
is not None:
197 nbbox
*= self
.clipbbox
199 file.write("grestore\n")
201 def processPDF(self
, file, writer
, context
, registry
, bbox
):
204 file.write("q\n") # gsave
205 nbbox
= bboxmodule
.empty()
206 for item
in self
.items
:
207 if isinstance(item
, type1font
.text_pt
):
208 if not context
.textregion
:
210 context
.textregion
= 1
212 if context
.textregion
:
214 context
.textregion
= 0
216 item
.processPDF(file, writer
, context
, registry
, nbbox
)
217 if context
.textregion
:
219 context
.textregion
= 0
221 # update bounding bbox
222 nbbox
.transform(self
.trafo
)
223 if self
.clipbbox
is not None:
224 nbbox
*= self
.clipbbox
226 file.write("Q\n") # grestore
228 def insert(self
, item
, attrs
=None):
229 """insert item in the canvas.
231 If attrs are passed, a canvas containing the item is inserted applying attrs.
237 if not isinstance(item
, canvasitem
):
238 raise RuntimeError("only instances of base.canvasitem can be inserted into a canvas")
243 self
.items
.append(sc
)
245 self
.items
.append(item
)
248 def draw(self
, path
, attrs
):
249 """draw path on canvas using the style given by args
251 The argument attrs consists of PathStyles, which modify
252 the appearance of the path, PathDecos, which add some new
253 visual elements to the path, or trafos, which are applied
254 before drawing the path.
258 attrs
= attr
.mergeattrs(attrs
)
259 attr
.checkattrs(attrs
, [deco
.deco
, deformer
.deformer
, style
.fillstyle
, style
.strokestyle
])
261 for adeformer
in attr
.getattrs(attrs
, [deformer
.deformer
]):
262 path
= adeformer
.deform(path
)
264 styles
= attr
.getattrs(attrs
, [style
.fillstyle
, style
.strokestyle
])
265 dp
= deco
.decoratedpath(path
, styles
=styles
)
267 # add path decorations and modify path accordingly
268 for adeco
in attr
.getattrs(attrs
, [deco
.deco
]):
269 adeco
.decorate(dp
, self
.texrunner
)
273 def stroke(self
, path
, attrs
=[]):
274 """stroke path on canvas using the style given by args
276 The argument attrs consists of PathStyles, which modify
277 the appearance of the path, PathDecos, which add some new
278 visual elements to the path, or trafos, which are applied
279 before drawing the path.
283 self
.draw(path
, [deco
.stroked
]+list(attrs
))
285 def fill(self
, path
, attrs
=[]):
286 """fill path on canvas using the style given by args
288 The argument attrs consists of PathStyles, which modify
289 the appearance of the path, PathDecos, which add some new
290 visual elements to the path, or trafos, which are applied
291 before drawing the path.
295 self
.draw(path
, [deco
.filled
]+list(attrs
))
297 def settexrunner(self
, texrunner
):
298 """sets the texrunner to be used to within the text and text_pt methods"""
300 self
.texrunner
= texrunner
302 def text(self
, x
, y
, atext
, *args
, **kwargs
):
303 """insert a text into the canvas
305 inserts a textbox created by self.texrunner.text into the canvas
307 returns the inserted textbox"""
309 return self
.insert(self
.texrunner
.text(x
, y
, atext
, *args
, **kwargs
))
312 def text_pt(self
, x
, y
, atext
, *args
):
313 """insert a text into the canvas
315 inserts a textbox created by self.texrunner.text_pt into the canvas
317 returns the inserted textbox"""
319 return self
.insert(self
.texrunner
.text_pt(x
, y
, atext
, *args
))
322 # user canvas class which adds a few convenience methods for single page output
325 def _wrappedindocument(method
):
326 def wrappedindocument(self
, file, *args
, **kwargs
):
327 d
= document
.document([document
.page(self
, *args
, **kwargs
)])
328 self
.__name
__ = method
.__name
__
329 self
.__doc
__ = method
.__doc
__
330 return method(d
, file)
331 return wrappedindocument
334 class canvas(_canvas
):
336 """a canvas holds a collection of canvasitems"""
338 writeEPSfile
= _wrappedindocument(document
.document
.writeEPSfile
)
339 writePSfile
= _wrappedindocument(document
.document
.writePSfile
)
340 writePDFfile
= _wrappedindocument(document
.document
.writePDFfile
)
341 writetofile
= _wrappedindocument(document
.document
.writetofile
)
343 def pipeGS(self
, filename
="-", device
=None, resolution
=100,
344 gscommand
="gs", gsoptions
="",
345 textalphabits
=4, graphicsalphabits
=4,
348 if filename
.endswith(".png"):
350 if filename
.endswith(".jpg"):
352 gscommand
+= " -dEPSCrop -dNOPAUSE -dQUIET -dBATCH -r%i -sDEVICE=%s -sOutputFile=%s" % (resolution
, device
, filename
)
354 gscommand
+= " %s" % gsoptions
355 if textalphabits
is not None:
356 gscommand
+= " -dTextAlphaBits=%i" % textalphabits
357 if graphicsalphabits
is not None:
358 gscommand
+= " -dGraphicsAlphaBits=%i" % graphicsalphabits
360 input = os
.popen(gscommand
, "w")
361 self
.writeEPSfile(input, **kwargs
)