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
29 import attr
, canvasitem
, deco
, deformer
, document
, font
, style
, trafo
30 import bbox
as bboxmodule
37 class clip(canvasitem
.canvasitem
):
39 """class for use in canvas constructor which clips to a path"""
41 def __init__(self
, path
):
42 """construct a clip instance for a given path"""
46 # as a canvasitem a clipping path has NO influence on the bbox...
47 return bboxmodule
.empty()
50 # ... but for clipping, we nevertheless need the bbox
51 return self
.path
.bbox()
53 def processPS(self
, file, writer
, context
, registry
, bbox
):
54 file.write("newpath\n")
55 self
.path
.outputPS(file, writer
)
58 def processPDF(self
, file, writer
, context
, registry
, bbox
):
59 self
.path
.outputPDF(file, writer
)
64 # general canvas class
67 class _canvas(canvasitem
.canvasitem
):
69 """a canvas holds a collection of canvasitems"""
71 def __init__(self
, attrs
=[], texrunner
=None):
75 The canvas can be modfied by supplying args, which have
76 to be instances of one of the following classes:
77 - trafo.trafo (leading to a global transformation of the canvas)
78 - canvas.clip (clips the canvas)
79 - style.strokestyle, style.fillstyle (sets some global attributes of the canvas)
81 Note that, while the first two properties are fixed for the
82 whole canvas, the last one can be changed via canvas.set().
84 The texrunner instance used for the text method can be specified
85 using the texrunner argument. It defaults to text.defaulttexrunner
90 self
.trafo
= trafo
.trafo()
92 if texrunner
is not None:
93 self
.texrunner
= texrunner
95 # prevent cyclic imports
97 self
.texrunner
= text
.defaulttexrunner
99 attr
.checkattrs(attrs
, [trafo
.trafo_pt
, clip
, style
.strokestyle
, style
.fillstyle
])
100 # We have to reverse the trafos such that the PostScript concat operators
101 # are in the right order. Correspondingly, we below multiply the current self.trafo
103 # Note that while for the stroke and fill styles the order doesn't matter at all,
104 # this is not true for the clip operation.
108 if isinstance(aattr
, trafo
.trafo_pt
):
109 self
.trafo
= self
.trafo
* aattr
110 elif isinstance(aattr
, clip
):
111 if self
.clipbbox
is None:
112 self
.clipbbox
= aattr
.clipbbox().transformed(self
.trafo
)
114 self
.clippbox
*= aattr
.clipbbox().transformed(self
.trafo
)
115 self
.items
.append(aattr
)
118 return len(self
.items
)
120 def __getitem__(self
, i
):
124 """returns bounding box of canvas
126 Note that this bounding box doesn't take into account the linewidths, so
127 is less accurate than the one used when writing the output to a file.
129 obbox
= bboxmodule
.empty()
130 for cmd
in self
.items
:
133 # transform according to our global transformation and
134 # intersect with clipping bounding box (which has already been
135 # transformed in canvas.__init__())
136 obbox
.transform(self
.trafo
)
137 if self
.clipbbox
is not None:
138 obbox
*= self
.clipbbox
141 def processPS(self
, file, writer
, context
, registry
, bbox
):
144 file.write("gsave\n")
145 nbbox
= bboxmodule
.empty()
146 for item
in self
.items
:
147 item
.processPS(file, writer
, context
, registry
, nbbox
)
148 # update bounding bbox
149 nbbox
.transform(self
.trafo
)
150 if self
.clipbbox
is not None:
151 nbbox
*= self
.clipbbox
153 file.write("grestore\n")
155 def processPDF(self
, file, writer
, context
, registry
, bbox
):
158 file.write("q\n") # gsave
159 nbbox
= bboxmodule
.empty()
160 for item
in self
.items
:
161 if isinstance(item
, font
.text_pt
):
162 if not context
.textregion
:
164 context
.textregion
= 1
166 if context
.textregion
:
168 context
.textregion
= 0
170 item
.processPDF(file, writer
, context
, registry
, nbbox
)
171 if context
.textregion
:
173 context
.textregion
= 0
175 # update bounding bbox
176 nbbox
.transform(self
.trafo
)
177 if self
.clipbbox
is not None:
178 nbbox
*= self
.clipbbox
180 file.write("Q\n") # grestore
182 def insert(self
, item
, attrs
=None):
183 """insert item in the canvas.
185 If attrs are passed, a canvas containing the item is inserted applying attrs.
191 if not isinstance(item
, canvasitem
.canvasitem
):
192 raise RuntimeError("only instances of canvasitem.canvasitem can be inserted into a canvas")
197 self
.items
.append(sc
)
199 self
.items
.append(item
)
202 def draw(self
, path
, attrs
):
203 """draw path on canvas using the style given by args
205 The argument attrs consists of PathStyles, which modify
206 the appearance of the path, PathDecos, which add some new
207 visual elements to the path, or trafos, which are applied
208 before drawing the path.
212 attrs
= attr
.mergeattrs(attrs
)
213 attr
.checkattrs(attrs
, [deco
.deco
, deformer
.deformer
, style
.fillstyle
, style
.strokestyle
])
215 for adeformer
in attr
.getattrs(attrs
, [deformer
.deformer
]):
216 path
= adeformer
.deform(path
)
218 styles
= attr
.getattrs(attrs
, [style
.fillstyle
, style
.strokestyle
])
219 dp
= deco
.decoratedpath(path
, styles
=styles
)
221 # add path decorations and modify path accordingly
222 for adeco
in attr
.getattrs(attrs
, [deco
.deco
]):
223 adeco
.decorate(dp
, self
.texrunner
)
227 def stroke(self
, path
, attrs
=[]):
228 """stroke path on canvas using the style given by args
230 The argument attrs consists of PathStyles, which modify
231 the appearance of the path, PathDecos, which add some new
232 visual elements to the path, or trafos, which are applied
233 before drawing the path.
237 self
.draw(path
, [deco
.stroked
]+list(attrs
))
239 def fill(self
, path
, attrs
=[]):
240 """fill path on canvas using the style given by args
242 The argument attrs consists of PathStyles, which modify
243 the appearance of the path, PathDecos, which add some new
244 visual elements to the path, or trafos, which are applied
245 before drawing the path.
249 self
.draw(path
, [deco
.filled
]+list(attrs
))
251 def settexrunner(self
, texrunner
):
252 """sets the texrunner to be used to within the text and text_pt methods"""
254 self
.texrunner
= texrunner
256 def text(self
, x
, y
, atext
, *args
, **kwargs
):
257 """insert a text into the canvas
259 inserts a textbox created by self.texrunner.text into the canvas
261 returns the inserted textbox"""
263 return self
.insert(self
.texrunner
.text(x
, y
, atext
, *args
, **kwargs
))
266 def text_pt(self
, x
, y
, atext
, *args
):
267 """insert a text into the canvas
269 inserts a textbox created by self.texrunner.text_pt into the canvas
271 returns the inserted textbox"""
273 return self
.insert(self
.texrunner
.text_pt(x
, y
, atext
, *args
))
276 # user canvas class which adds a few convenience methods for single page output
279 def _wrappedindocument(method
):
280 def wrappedindocument(self
, file=None, **kwargs
):
281 d
= document
.document([document
.page(self
, **kwargs
)])
282 self
.__name
__ = method
.__name
__
283 self
.__doc
__ = method
.__doc
__
284 return method(d
, file)
285 return wrappedindocument
288 class canvas(_canvas
):
290 """a canvas holds a collection of canvasitems"""
292 writeEPSfile
= _wrappedindocument(document
.document
.writeEPSfile
)
293 writePSfile
= _wrappedindocument(document
.document
.writePSfile
)
294 writePDFfile
= _wrappedindocument(document
.document
.writePDFfile
)
295 writetofile
= _wrappedindocument(document
.document
.writetofile
)
297 def pipeGS(self
, filename
="-", device
=None, resolution
=100,
298 gscommand
="gs", gsoptions
="",
299 textalphabits
=4, graphicsalphabits
=4,
302 if filename
.endswith(".png"):
304 if filename
.endswith(".jpg"):
306 gscommand
+= " -dEPSCrop -dNOPAUSE -dQUIET -dBATCH -r%i -sDEVICE=%s -sOutputFile=%s" % (resolution
, device
, filename
)
308 gscommand
+= " %s" % gsoptions
309 if textalphabits
is not None:
310 gscommand
+= " -dTextAlphaBits=%i" % textalphabits
311 if graphicsalphabits
is not None:
312 gscommand
+= " -dGraphicsAlphaBits=%i" % graphicsalphabits
314 input = os
.popen(gscommand
, "w")
315 self
.writeEPSfile(input, **kwargs
)