Do not use list as default argument. Although it doesn't matter in this particular...
[PyX/mjg.git] / pyx / canvas.py
blob103c168519a973c23eaa414dbc7c599b3fc2f35c
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
26 displayed. """
28 import os
29 import attr, canvasitem, deco, deformer, document, font, style, trafo
30 import bbox as bboxmodule
34 # clipping class
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"""
43 self.path = path
45 def bbox(self):
46 # as a canvasitem a clipping path has NO influence on the bbox...
47 return bboxmodule.empty()
49 def clipbbox(self):
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)
56 file.write("clip\n")
58 def processPDF(self, file, writer, context, registry, bbox):
59 self.path.outputPDF(file, writer)
60 file.write("W n\n")
64 # general canvas class
67 class _canvas(canvasitem.canvasitem):
69 """a canvas holds a collection of canvasitems"""
71 def __init__(self, attrs=None, texrunner=None):
73 """construct a canvas
75 The canvas can be modfied by supplying a list of attrs, 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
87 """
89 self.items = []
90 self.trafo = trafo.trafo()
91 self.clipbbox = None
92 if texrunner is not None:
93 self.texrunner = texrunner
94 else:
95 # prevent cyclic imports
96 import text
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
102 # from the right.
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.
105 if attrs is not None:
106 for aattr in attrs[::-1]:
107 if isinstance(aattr, trafo.trafo_pt):
108 self.trafo = self.trafo * aattr
109 elif isinstance(aattr, clip):
110 if self.clipbbox is None:
111 self.clipbbox = aattr.clipbbox().transformed(self.trafo)
112 else:
113 self.clippbox *= aattr.clipbbox().transformed(self.trafo)
114 self.items.append(aattr)
116 def __len__(self):
117 return len(self.items)
119 def __getitem__(self, i):
120 return self.items[i]
122 def bbox(self):
123 """returns bounding box of canvas
125 Note that this bounding box doesn't take into account the linewidths, so
126 is less accurate than the one used when writing the output to a file.
128 obbox = bboxmodule.empty()
129 for cmd in self.items:
130 obbox += cmd.bbox()
132 # transform according to our global transformation and
133 # intersect with clipping bounding box (which has already been
134 # transformed in canvas.__init__())
135 obbox.transform(self.trafo)
136 if self.clipbbox is not None:
137 obbox *= self.clipbbox
138 return obbox
140 def processPS(self, file, writer, context, registry, bbox):
141 context = context()
142 if self.items:
143 file.write("gsave\n")
144 nbbox = bboxmodule.empty()
145 for item in self.items:
146 item.processPS(file, writer, context, registry, nbbox)
147 # update bounding bbox
148 nbbox.transform(self.trafo)
149 if self.clipbbox is not None:
150 nbbox *= self.clipbbox
151 bbox += nbbox
152 file.write("grestore\n")
154 def processPDF(self, file, writer, context, registry, bbox):
155 context = context()
156 if self.items:
157 file.write("q\n") # gsave
158 nbbox = bboxmodule.empty()
159 for item in self.items:
160 if isinstance(item, font.text_pt):
161 if not context.textregion:
162 file.write("BT\n")
163 context.textregion = 1
164 else:
165 if context.textregion:
166 file.write("ET\n")
167 context.textregion = 0
168 context.selectedfont = None
169 item.processPDF(file, writer, context, registry, nbbox)
170 if context.textregion:
171 file.write("ET\n")
172 context.textregion = 0
173 context.selectedfont = None
174 # update bounding bbox
175 nbbox.transform(self.trafo)
176 if self.clipbbox is not None:
177 nbbox *= self.clipbbox
178 bbox += nbbox
179 file.write("Q\n") # grestore
181 def insert(self, item, attrs=None):
182 """insert item in the canvas.
184 If attrs are passed, a canvas containing the item is inserted applying attrs.
186 returns the item
190 if not isinstance(item, canvasitem.canvasitem):
191 raise RuntimeError("only instances of canvasitem.canvasitem can be inserted into a canvas")
193 if attrs:
194 sc = _canvas(attrs)
195 sc.insert(item)
196 self.items.append(sc)
197 else:
198 self.items.append(item)
199 return item
201 def draw(self, path, attrs):
202 """draw path on canvas using the style given by args
204 The argument attrs consists of PathStyles, which modify
205 the appearance of the path, PathDecos, which add some new
206 visual elements to the path, or trafos, which are applied
207 before drawing the path.
211 attrs = attr.mergeattrs(attrs)
212 attr.checkattrs(attrs, [deco.deco, deformer.deformer, style.fillstyle, style.strokestyle])
214 for adeformer in attr.getattrs(attrs, [deformer.deformer]):
215 path = adeformer.deform(path)
217 styles = attr.getattrs(attrs, [style.fillstyle, style.strokestyle])
218 dp = deco.decoratedpath(path, styles=styles)
220 # add path decorations and modify path accordingly
221 for adeco in attr.getattrs(attrs, [deco.deco]):
222 adeco.decorate(dp, self.texrunner)
224 self.insert(dp)
226 def stroke(self, path, attrs=[]):
227 """stroke path on canvas using the style given by args
229 The argument attrs consists of PathStyles, which modify
230 the appearance of the path, PathDecos, which add some new
231 visual elements to the path, or trafos, which are applied
232 before drawing the path.
236 self.draw(path, [deco.stroked]+list(attrs))
238 def fill(self, path, attrs=[]):
239 """fill path on canvas using the style given by args
241 The argument attrs consists of PathStyles, which modify
242 the appearance of the path, PathDecos, which add some new
243 visual elements to the path, or trafos, which are applied
244 before drawing the path.
248 self.draw(path, [deco.filled]+list(attrs))
250 def settexrunner(self, texrunner):
251 """sets the texrunner to be used to within the text and text_pt methods"""
253 self.texrunner = texrunner
255 def text(self, x, y, atext, *args, **kwargs):
256 """insert a text into the canvas
258 inserts a textbox created by self.texrunner.text into the canvas
260 returns the inserted textbox"""
262 return self.insert(self.texrunner.text(x, y, atext, *args, **kwargs))
265 def text_pt(self, x, y, atext, *args):
266 """insert a text into the canvas
268 inserts a textbox created by self.texrunner.text_pt into the canvas
270 returns the inserted textbox"""
272 return self.insert(self.texrunner.text_pt(x, y, atext, *args))
275 # user canvas class which adds a few convenience methods for single page output
278 def _wrappedindocument(method):
279 def wrappedindocument(self, file=None, **kwargs):
280 d = document.document([document.page(self, **kwargs)])
281 self.__name__ = method.__name__
282 self.__doc__ = method.__doc__
283 return method(d, file)
284 return wrappedindocument
287 class canvas(_canvas):
289 """a canvas holds a collection of canvasitems"""
291 writeEPSfile = _wrappedindocument(document.document.writeEPSfile)
292 writePSfile = _wrappedindocument(document.document.writePSfile)
293 writePDFfile = _wrappedindocument(document.document.writePDFfile)
294 writetofile = _wrappedindocument(document.document.writetofile)
296 def pipeGS(self, filename="-", device=None, resolution=100,
297 gscommand="gs", gsoptions="",
298 textalphabits=4, graphicsalphabits=4,
299 **kwargs):
300 if device is None:
301 if filename.endswith(".png"):
302 device = "png16m"
303 if filename.endswith(".jpg"):
304 device = "jpeg"
305 gscommand += " -dEPSCrop -dNOPAUSE -dQUIET -dBATCH -r%i -sDEVICE=%s -sOutputFile=%s" % (resolution, device, filename)
306 if gsoptions:
307 gscommand += " %s" % gsoptions
308 if textalphabits is not None:
309 gscommand += " -dTextAlphaBits=%i" % textalphabits
310 if graphicsalphabits is not None:
311 gscommand += " -dGraphicsAlphaBits=%i" % graphicsalphabits
312 gscommand += " -"
313 input = os.popen(gscommand, "w")
314 self.writeEPSfile(input, **kwargs)