remove shebang -- see comment 3 on https://bugzilla.redhat.com/bugzilla/show_bug...
[PyX/mjg.git] / pyx / canvas.py
blob360eea58e2b7a86bcdfdbd82fc803bdfbf0e1b25
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.reverse()
152 for aattr in attrs:
153 if isinstance(aattr, trafo.trafo_pt):
154 self.trafo = self.trafo * aattr
155 elif isinstance(aattr, clip):
156 if self.clipbbox is None:
157 self.clipbbox = aattr.clipbbox().transformed(self.trafo)
158 else:
159 self.clippbox *= aattr.clipbbox().transformed(self.trafo)
160 self.items.append(aattr)
162 def __len__(self):
163 return len(self.items)
165 def __getitem__(self, i):
166 return self.items[i]
168 def bbox(self):
169 """returns bounding box of canvas
171 Note that this bounding box doesn't take into account the linewidths, so
172 is less accurate than the one used when writing the output to a file.
174 obbox = bboxmodule.empty()
175 for cmd in self.items:
176 obbox += cmd.bbox()
178 # transform according to our global transformation and
179 # intersect with clipping bounding box (which has already been
180 # transformed in canvas.__init__())
181 obbox.transform(self.trafo)
182 if self.clipbbox is not None:
183 obbox *= self.clipbbox
184 return obbox
186 def processPS(self, file, writer, context, registry, bbox):
187 context = context()
188 if self.items:
189 file.write("gsave\n")
190 nbbox = bboxmodule.empty()
191 for item in self.items:
192 item.processPS(file, writer, context, registry, nbbox)
193 # update bounding bbox
194 nbbox.transform(self.trafo)
195 if self.clipbbox is not None:
196 nbbox *= self.clipbbox
197 bbox += nbbox
198 file.write("grestore\n")
200 def processPDF(self, file, writer, context, registry, bbox):
201 context = context()
202 if self.items:
203 file.write("q\n") # gsave
204 nbbox = bboxmodule.empty()
205 for item in self.items:
206 if isinstance(item, type1font.text_pt):
207 if not context.textregion:
208 file.write("BT\n")
209 context.textregion = 1
210 else:
211 if context.textregion:
212 file.write("ET\n")
213 context.textregion = 0
214 context.font = None
215 item.processPDF(file, writer, context, registry, nbbox)
216 if context.textregion:
217 file.write("ET\n")
218 context.textregion = 0
219 context.font = None
220 # update bounding bbox
221 nbbox.transform(self.trafo)
222 if self.clipbbox is not None:
223 nbbox *= self.clipbbox
224 bbox += nbbox
225 file.write("Q\n") # grestore
227 def insert(self, item, attrs=None):
228 """insert item in the canvas.
230 If attrs are passed, a canvas containing the item is inserted applying attrs.
232 returns the item
236 if not isinstance(item, canvasitem):
237 raise RuntimeError("only instances of base.canvasitem can be inserted into a canvas")
239 if attrs:
240 sc = _canvas(attrs)
241 sc.insert(item)
242 self.items.append(sc)
243 else:
244 self.items.append(item)
245 return item
247 def draw(self, path, attrs):
248 """draw path on canvas using the style given by args
250 The argument attrs consists of PathStyles, which modify
251 the appearance of the path, PathDecos, which add some new
252 visual elements to the path, or trafos, which are applied
253 before drawing the path.
257 attrs = attr.mergeattrs(attrs)
258 attr.checkattrs(attrs, [deco.deco, deformer.deformer, style.fillstyle, style.strokestyle])
260 for adeformer in attr.getattrs(attrs, [deformer.deformer]):
261 path = adeformer.deform(path)
263 styles = attr.getattrs(attrs, [style.fillstyle, style.strokestyle])
264 dp = deco.decoratedpath(path, styles=styles)
266 # add path decorations and modify path accordingly
267 for adeco in attr.getattrs(attrs, [deco.deco]):
268 adeco.decorate(dp, self.texrunner)
270 self.insert(dp)
272 def stroke(self, path, attrs=[]):
273 """stroke path on canvas using the style given by args
275 The argument attrs consists of PathStyles, which modify
276 the appearance of the path, PathDecos, which add some new
277 visual elements to the path, or trafos, which are applied
278 before drawing the path.
282 self.draw(path, [deco.stroked]+list(attrs))
284 def fill(self, path, attrs=[]):
285 """fill path on canvas using the style given by args
287 The argument attrs consists of PathStyles, which modify
288 the appearance of the path, PathDecos, which add some new
289 visual elements to the path, or trafos, which are applied
290 before drawing the path.
294 self.draw(path, [deco.filled]+list(attrs))
296 def settexrunner(self, texrunner):
297 """sets the texrunner to be used to within the text and text_pt methods"""
299 self.texrunner = texrunner
301 def text(self, x, y, atext, *args, **kwargs):
302 """insert a text into the canvas
304 inserts a textbox created by self.texrunner.text into the canvas
306 returns the inserted textbox"""
308 return self.insert(self.texrunner.text(x, y, atext, *args, **kwargs))
311 def text_pt(self, x, y, atext, *args):
312 """insert a text into the canvas
314 inserts a textbox created by self.texrunner.text_pt into the canvas
316 returns the inserted textbox"""
318 return self.insert(self.texrunner.text_pt(x, y, atext, *args))
321 # user canvas class which adds a few convenience methods for single page output
324 def _wrappedindocument(method):
325 def wrappedindocument(self, file, *args, **kwargs):
326 d = document.document([document.page(self, *args, **kwargs)])
327 self.__name__ = method.__name__
328 self.__doc__ = method.__doc__
329 return method(d, file)
330 return wrappedindocument
333 class canvas(_canvas):
335 """a canvas holds a collection of canvasitems"""
337 writeEPSfile = _wrappedindocument(document.document.writeEPSfile)
338 writePSfile = _wrappedindocument(document.document.writePSfile)
339 writePDFfile = _wrappedindocument(document.document.writePDFfile)
340 writetofile = _wrappedindocument(document.document.writetofile)
342 def pipeGS(self, filename="-", device=None, resolution=100,
343 gscommand="gs", gsoptions="",
344 textalphabits=4, graphicsalphabits=4,
345 **kwargs):
346 if device is None:
347 if filename.endswith(".png"):
348 device = "png16m"
349 if filename.endswith(".jpg"):
350 device = "jpeg"
351 gscommand += " -dEPSCrop -dNOPAUSE -dQUIET -dBATCH -r%i -sDEVICE=%s -sOutputFile=%s" % (resolution, device, filename)
352 if gsoptions:
353 gscommand += " %s" % gsoptions
354 if textalphabits is not None:
355 gscommand += " -dTextAlphaBits=%i" % textalphabits
356 if graphicsalphabits is not None:
357 gscommand += " -dGraphicsAlphaBits=%i" % graphicsalphabits
358 gscommand += " -"
359 input = os.popen(gscommand, "w")
360 self.writeEPSfile(input, **kwargs)