1 # -*- coding: ISO-8859-1 -*-
4 # Copyright (C) 2002-2006 Jörg Lehmann <joergl@users.sourceforge.net>
5 # Copyright (C) 2002-2006 André Wobst <wobsta@users.sourceforge.net>
7 # This file is part of PyX (http://pyx.sourceforge.net/).
9 # PyX is free software; you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 2 of the License, or
12 # (at your option) any later version.
14 # PyX is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
19 # You should have received a copy of the GNU General Public License
20 # along with PyX; if not, write to the Free Software
21 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23 """The canvas module provides a PostScript canvas class and related classes
25 A canvas holds a collection of all elements and corresponding attributes to be
32 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
85 class clip(canvasitem
):
87 """class for use in canvas constructor which clips to a path"""
89 def __init__(self
, path
):
90 """construct a clip instance for a given path"""
94 # as a canvasitem a clipping path has NO influence on the bbox...
95 return bboxmodule
.empty()
98 # ... but for clipping, we nevertheless need the bbox
99 return self
.path
.bbox()
101 def processPS(self
, file, writer
, context
, registry
, bbox
):
102 file.write("newpath\n")
103 self
.path
.outputPS(file, writer
)
106 def processPDF(self
, file, writer
, context
, registry
, bbox
):
107 self
.path
.outputPDF(file, writer
)
112 # general canvas class
115 class _canvas(canvasitem
):
117 """a canvas holds a collection of canvasitems"""
119 def __init__(self
, attrs
=[], texrunner
=None):
121 """construct a canvas
123 The canvas can be modfied by supplying args, which have
124 to be instances of one of the following classes:
125 - trafo.trafo (leading to a global transformation of the canvas)
126 - canvas.clip (clips the canvas)
127 - style.strokestyle, style.fillstyle (sets some global attributes of the canvas)
129 Note that, while the first two properties are fixed for the
130 whole canvas, the last one can be changed via canvas.set().
132 The texrunner instance used for the text method can be specified
133 using the texrunner argument. It defaults to text.defaulttexrunner
138 self
.trafo
= trafo
.trafo()
140 if texrunner
is not None:
141 self
.texrunner
= texrunner
143 # prevent cyclic imports
145 self
.texrunner
= text
.defaulttexrunner
147 attr
.checkattrs(attrs
, [trafo
.trafo_pt
, clip
, style
.strokestyle
, style
.fillstyle
])
148 # We have to reverse the trafos such that the PostScript concat operators
149 # are in the right order. Correspondingly, we below multiply the current self.trafo
151 # Note that while for the stroke and fill styles the order doesn't matter at all,
152 # this is not true for the clip operation.
155 if isinstance(aattr
, trafo
.trafo_pt
):
156 self
.trafo
= self
.trafo
* aattr
157 elif isinstance(aattr
, clip
):
158 if self
.clipbbox
is None:
159 self
.clipbbox
= aattr
.clipbbox().transformed(self
.trafo
)
161 self
.clippbox
*= aattr
.clipbbox().transformed(self
.trafo
)
162 self
.items
.append(aattr
)
165 return len(self
.items
)
167 def __getitem__(self
, i
):
171 """returns bounding box of canvas
173 Note that this bounding box doesn't take into account the linewidths, so
174 is less accurate than the one used when writing the output to a file.
176 obbox
= bboxmodule
.empty()
177 for cmd
in self
.items
:
180 # transform according to our global transformation and
181 # intersect with clipping bounding box (which has already been
182 # transformed in canvas.__init__())
183 obbox
.transform(self
.trafo
)
184 if self
.clipbbox
is not None:
185 obbox
*= self
.clipbbox
188 def processPS(self
, file, writer
, context
, registry
, bbox
):
191 file.write("gsave\n")
192 nbbox
= bboxmodule
.empty()
193 for item
in self
.items
:
194 item
.processPS(file, writer
, context
, registry
, nbbox
)
195 # update bounding bbox
196 nbbox
.transform(self
.trafo
)
197 if self
.clipbbox
is not None:
198 nbbox
*= self
.clipbbox
200 file.write("grestore\n")
202 def processPDF(self
, file, writer
, context
, registry
, bbox
):
205 file.write("q\n") # gsave
206 nbbox
= bboxmodule
.empty()
207 for item
in self
.items
:
208 if isinstance(item
, type1font
.text_pt
):
209 if not context
.textregion
:
211 context
.textregion
= 1
213 if context
.textregion
:
215 context
.textregion
= 0
217 item
.processPDF(file, writer
, context
, registry
, nbbox
)
218 if context
.textregion
:
220 context
.textregion
= 0
222 # update bounding bbox
223 nbbox
.transform(self
.trafo
)
224 if self
.clipbbox
is not None:
225 nbbox
*= self
.clipbbox
227 file.write("Q\n") # grestore
229 def insert(self
, item
, attrs
=None):
230 """insert item in the canvas.
232 If attrs are passed, a canvas containing the item is inserted applying attrs.
238 if not isinstance(item
, canvasitem
):
239 raise RuntimeError("only instances of base.canvasitem can be inserted into a canvas")
244 self
.items
.append(sc
)
246 self
.items
.append(item
)
249 def draw(self
, path
, attrs
):
250 """draw path on canvas using the style given by args
252 The argument attrs consists of PathStyles, which modify
253 the appearance of the path, PathDecos, which add some new
254 visual elements to the path, or trafos, which are applied
255 before drawing the path.
259 attrs
= attr
.mergeattrs(attrs
)
260 attr
.checkattrs(attrs
, [deco
.deco
, deformer
.deformer
, style
.fillstyle
, style
.strokestyle
])
262 for adeformer
in attr
.getattrs(attrs
, [deformer
.deformer
]):
263 path
= adeformer
.deform(path
)
265 styles
= attr
.getattrs(attrs
, [style
.fillstyle
, style
.strokestyle
])
266 dp
= deco
.decoratedpath(path
, styles
=styles
)
268 # add path decorations and modify path accordingly
269 for adeco
in attr
.getattrs(attrs
, [deco
.deco
]):
270 adeco
.decorate(dp
, self
.texrunner
)
274 def stroke(self
, path
, attrs
=[]):
275 """stroke path on canvas using the style given by args
277 The argument attrs consists of PathStyles, which modify
278 the appearance of the path, PathDecos, which add some new
279 visual elements to the path, or trafos, which are applied
280 before drawing the path.
284 self
.draw(path
, [deco
.stroked
]+list(attrs
))
286 def fill(self
, path
, attrs
=[]):
287 """fill path on canvas using the style given by args
289 The argument attrs consists of PathStyles, which modify
290 the appearance of the path, PathDecos, which add some new
291 visual elements to the path, or trafos, which are applied
292 before drawing the path.
296 self
.draw(path
, [deco
.filled
]+list(attrs
))
298 def settexrunner(self
, texrunner
):
299 """sets the texrunner to be used to within the text and text_pt methods"""
301 self
.texrunner
= texrunner
303 def text(self
, x
, y
, atext
, *args
, **kwargs
):
304 """insert a text into the canvas
306 inserts a textbox created by self.texrunner.text into the canvas
308 returns the inserted textbox"""
310 return self
.insert(self
.texrunner
.text(x
, y
, atext
, *args
, **kwargs
))
313 def text_pt(self
, x
, y
, atext
, *args
):
314 """insert a text into the canvas
316 inserts a textbox created by self.texrunner.text_pt into the canvas
318 returns the inserted textbox"""
320 return self
.insert(self
.texrunner
.text_pt(x
, y
, atext
, *args
))
323 # user canvas class which adds a few convenience methods for single page output
326 def _wrappedindocument(method
):
327 def wrappedindocument(self
, file, *args
, **kwargs
):
328 d
= document
.document([document
.page(self
, *args
, **kwargs
)])
329 self
.__name
__ = method
.__name
__
330 self
.__doc
__ = method
.__doc
__
331 return method(d
, file)
332 return wrappedindocument
335 class canvas(_canvas
):
337 """a canvas holds a collection of canvasitems"""
339 writeEPSfile
= _wrappedindocument(document
.document
.writeEPSfile
)
340 writePSfile
= _wrappedindocument(document
.document
.writePSfile
)
341 writePDFfile
= _wrappedindocument(document
.document
.writePDFfile
)
342 writetofile
= _wrappedindocument(document
.document
.writetofile
)
344 def pipeGS(self
, filename
="-", device
=None, resolution
=100,
345 gscommand
="gs", gsoptions
="",
346 textalphabits
=4, graphicsalphabits
=4,
349 if filename
.endswith(".png"):
351 if filename
.endswith(".jpg"):
353 gscommand
+= " -dEPSCrop -dNOPAUSE -dQUIET -dBATCH -r%i -sDEVICE=%s -sOutputFile=%s" % (resolution
, device
, filename
)
355 gscommand
+= " %s" % gsoptions
356 if textalphabits
is not None:
357 gscommand
+= " -dTextAlphaBits=%i" % textalphabits
358 if graphicsalphabits
is not None:
359 gscommand
+= " -dGraphicsAlphaBits=%i" % graphicsalphabits
361 input = os
.popen(gscommand
, "w")
362 self
.writeEPSfile(input, **kwargs
)
365 class ref(canvasitem
):
366 """a stupid object insertable into a canvas; it needs to get all the
367 information in the constructor"""
369 def __init__(self
, bbox
, output
, insertcanvas
):
371 self
._output
= output
372 self
._insertcanvas
= insertcanvas
377 def processPS(self
, file, writer
, context
, registry
, bbox
):
378 stringfile
= cStringIO
.StringIO()
379 _canvas
.processPS(self
._insertcanvas
, stringfile
, writer
, context
, registry
, bbox
)
380 canvasproc
= "gsave\nmatrix translate concat\n%sgrestore\n" % stringfile
.getvalue()
382 registry
.add(pswriter
.PSdefinition(self
._insertcanvas
._id
, "{\n" + canvasproc
+ "}"))
383 file.write(self
._output
)
386 def processPDF(self
, file, writer
, context
, registry
, bbox
):
387 raise NotImplementedError("ref canvasitem not implemented for PDF")
389 class translateablecanvas(_canvas
):
390 "a canvas which is efficiently translateable"
392 def __init__(self
, *args
, **kwargs
):
393 _canvas
.__init
__(self
, *args
, **kwargs
)
394 self
._id
= "symbol%d" % id(self
)
396 def translate_pt(self
, x_pt
, y_pt
):
397 """returns an insertable object which stores only the position and
398 a reference to a prolog definition"""
399 return ref(self
.bbox().transformed(trafo
.translate_pt(x_pt
, y_pt
)), "%g %g %s\n" % (x_pt
, y_pt
, self
._id
), self
)