3d function plots
[PyX/mjg.git] / pyx / canvas.py
blob6110af17ef69bba1df5b03f71e84438b44864630
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. """
29 # canvas item
32 from __future__ import nested_scopes
33 import os
35 class canvasitem:
37 """Base class for everything which can be inserted into a canvas"""
39 def bbox(self):
40 """return bounding box of canvasitem"""
41 pass
43 def processPS(self, file, writer, context, registry, bbox):
44 """process canvasitem by writing the corresponding PS code to file and
45 by updating context, registry as well as bbox
47 - the PS code corresponding to the canvasitem has to be written in the
48 stream file, which provides a write(string) method
49 - writer is the PSwriter used for the output
50 - context is an instance of pswriter.context which is used for keeping
51 track of the graphics state (current linewidth, colorspace and font))
52 - registry is used for tracking resources needed by the canvasitem
53 - bbox has to be updated to include the bounding box of the canvasitem
54 """
55 raise NotImplementedError()
57 def processPDF(self, file, writer, context, registry, bbox):
58 """process canvasitem by writing the corresponding PDF code to file and
59 by updating context, registry as well as bbox
61 - the PDF code corresponding to the canvasitem has to be written in the
62 stream file, which provides a write(string) method
63 - writer is the PDFwriter used for the output, which contains properties
64 like whether streamcompression is used
65 - context is an instance of pdfwriter.context which is used for keeping
66 track of the graphics state, in particular for the emulation of PS
67 behaviour regarding fill and stroke styles, for keeping track of the
68 currently selected font as well as of text regions.
69 - registry is used for tracking resources needed by the canvasitem
70 - bbox has to be updated to include the bounding box of the canvasitem
71 """
72 raise NotImplementedError()
75 import attr, deco, deformer, document, style, trafo, type1font
76 import bbox as bboxmodule
80 # clipping class
83 class clip(canvasitem):
85 """class for use in canvas constructor which clips to a path"""
87 def __init__(self, path):
88 """construct a clip instance for a given path"""
89 self.path = path
91 def bbox(self):
92 # as a canvasitem a clipping path has NO influence on the bbox...
93 return bboxmodule.empty()
95 def clipbbox(self):
96 # ... but for clipping, we nevertheless need the bbox
97 return self.path.bbox()
99 def processPS(self, file, writer, context, registry, bbox):
100 file.write("newpath\n")
101 self.path.outputPS(file, writer)
102 file.write("clip\n")
104 def processPDF(self, file, writer, context, registry, bbox):
105 self.path.outputPDF(file, writer)
106 file.write("W n\n")
110 # general canvas class
113 class _canvas(canvasitem):
115 """a canvas holds a collection of canvasitems"""
117 def __init__(self, attrs=[], texrunner=None):
119 """construct a canvas
121 The canvas can be modfied by supplying args, which have
122 to be instances of one of the following classes:
123 - trafo.trafo (leading to a global transformation of the canvas)
124 - canvas.clip (clips the canvas)
125 - style.strokestyle, style.fillstyle (sets some global attributes of the canvas)
127 Note that, while the first two properties are fixed for the
128 whole canvas, the last one can be changed via canvas.set().
130 The texrunner instance used for the text method can be specified
131 using the texrunner argument. It defaults to text.defaulttexrunner
135 self.items = []
136 self.trafo = trafo.trafo()
137 self.clipbbox = None
138 if texrunner is not None:
139 self.texrunner = texrunner
140 else:
141 # prevent cyclic imports
142 import text
143 self.texrunner = text.defaulttexrunner
145 attr.checkattrs(attrs, [trafo.trafo_pt, clip, style.strokestyle, style.fillstyle])
146 # We have to reverse the trafos such that the PostScript concat operators
147 # are in the right order. Correspondingly, we below multiply the current self.trafo
148 # from the right.
149 # Note that while for the stroke and fill styles the order doesn't matter at all,
150 # this is not true for the clip operation.
151 attrs = attrs[:]
152 attrs.reverse()
153 for aattr in attrs:
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)
159 else:
160 self.clippbox *= aattr.clipbbox().transformed(self.trafo)
161 self.items.append(aattr)
163 def __len__(self):
164 return len(self.items)
166 def __getitem__(self, i):
167 return self.items[i]
169 def bbox(self):
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:
177 obbox += cmd.bbox()
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
185 return obbox
187 def processPS(self, file, writer, context, registry, bbox):
188 context = context()
189 if self.items:
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
198 bbox += nbbox
199 file.write("grestore\n")
201 def processPDF(self, file, writer, context, registry, bbox):
202 context = context()
203 if self.items:
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:
209 file.write("BT\n")
210 context.textregion = 1
211 else:
212 if context.textregion:
213 file.write("ET\n")
214 context.textregion = 0
215 context.font = None
216 item.processPDF(file, writer, context, registry, nbbox)
217 if context.textregion:
218 file.write("ET\n")
219 context.textregion = 0
220 context.font = None
221 # update bounding bbox
222 nbbox.transform(self.trafo)
223 if self.clipbbox is not None:
224 nbbox *= self.clipbbox
225 bbox += nbbox
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.
233 returns the item
237 if not isinstance(item, canvasitem):
238 raise RuntimeError("only instances of base.canvasitem can be inserted into a canvas")
240 if attrs:
241 sc = _canvas(attrs)
242 sc.insert(item)
243 self.items.append(sc)
244 else:
245 self.items.append(item)
246 return 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)
271 self.insert(dp)
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,
346 **kwargs):
347 if device is None:
348 if filename.endswith(".png"):
349 device = "png16m"
350 if filename.endswith(".jpg"):
351 device = "jpeg"
352 gscommand += " -dEPSCrop -dNOPAUSE -dQUIET -dBATCH -r%i -sDEVICE=%s -sOutputFile=%s" % (resolution, device, filename)
353 if gsoptions:
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
359 gscommand += " -"
360 input = os.popen(gscommand, "w")
361 self.writeEPSfile(input, **kwargs)