add a layered canvas class
[PyX.git] / pyx / canvas.py
blob20b497af539442cd56c25662737a5bda01af6bb2
1 # -*- encoding: utf-8 -*-
4 # Copyright (C) 2002-2011 Jörg Lehmann <joergl@users.sourceforge.net>
5 # Copyright (C) 2002-2011 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, tempfile
29 import attr, canvasitem, deco, deformer, document, font, pycompat, 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 attrs is None:
93 attrs = []
94 if texrunner is not None:
95 self.texrunner = texrunner
96 else:
97 # prevent cyclic imports
98 import text
99 self.texrunner = text.defaulttexrunner
101 attr.checkattrs(attrs, [trafo.trafo_pt, clip, style.strokestyle, style.fillstyle])
102 # We have to reverse the trafos such that the PostScript concat operators
103 # are in the right order. Correspondingly, we below multiply the current self.trafo
104 # from the right.
105 # Note that while for the stroke and fill styles the order doesn't matter at all,
106 # this is not true for the clip operation.
107 for aattr in attrs[::-1]:
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)
113 else:
114 self.clippbox *= aattr.clipbbox().transformed(self.trafo)
115 self.items.append(aattr)
117 def __len__(self):
118 return len(self.items)
120 def __getitem__(self, i):
121 return self.items[i]
123 def bbox(self):
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:
131 obbox += cmd.bbox()
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
139 return obbox
141 def processPS(self, file, writer, context, registry, bbox):
142 context = context()
143 if self.items:
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
152 bbox += nbbox
153 file.write("grestore\n")
155 def processPDF(self, file, writer, context, registry, bbox):
156 context = context()
157 context.trafo = context.trafo * self.trafo
158 if self.items:
159 file.write("q\n") # gsave
160 nbbox = bboxmodule.empty()
161 for item in self.items:
162 if isinstance(item, style.fillstyle):
163 context.fillstyles.append(item)
164 if not writer.text_as_path:
165 if isinstance(item, font.text_pt):
166 if not context.textregion:
167 file.write("BT\n")
168 context.textregion = 1
169 else:
170 if context.textregion:
171 file.write("ET\n")
172 context.textregion = 0
173 context.selectedfont = None
174 item.processPDF(file, writer, context, registry, nbbox)
175 if context.textregion:
176 file.write("ET\n")
177 context.textregion = 0
178 context.selectedfont = None
179 # update bounding bbox
180 nbbox.transform(self.trafo)
181 if self.clipbbox is not None:
182 nbbox *= self.clipbbox
183 bbox += nbbox
184 file.write("Q\n") # grestore
186 def insert(self, item, attrs=None):
187 """insert item in the canvas.
189 If attrs are passed, a canvas containing the item is inserted applying attrs.
191 returns the item
195 if not isinstance(item, canvasitem.canvasitem):
196 raise RuntimeError("only instances of canvasitem.canvasitem can be inserted into a canvas")
198 if attrs:
199 sc = _canvas(attrs)
200 sc.insert(item)
201 self.items.append(sc)
202 else:
203 self.items.append(item)
204 return item
206 def draw(self, path, attrs):
207 """draw path on canvas using the style given by args
209 The argument attrs consists of PathStyles, which modify
210 the appearance of the path, PathDecos, which add some new
211 visual elements to the path, or trafos, which are applied
212 before drawing the path.
216 attrs = attr.mergeattrs(attrs)
217 attr.checkattrs(attrs, [deco.deco, deformer.deformer, style.fillstyle, style.strokestyle, style.fillrule])
219 for adeformer in attr.getattrs(attrs, [deformer.deformer]):
220 path = adeformer.deform(path)
222 styles = attr.getattrs(attrs, [style.fillstyle, style.strokestyle])
223 fillrule, = attr.getattrs(attrs, [style.fillrule]) or [style.fillrule.nonzero_winding]
224 dp = deco.decoratedpath(path, styles=styles, fillrule=fillrule)
226 # add path decorations and modify path accordingly
227 for adeco in attr.getattrs(attrs, [deco.deco]):
228 adeco.decorate(dp, self.texrunner)
230 self.insert(dp)
232 def stroke(self, path, attrs=[]):
233 """stroke path on canvas using the style given by args
235 The argument attrs consists of PathStyles, which modify
236 the appearance of the path, PathDecos, which add some new
237 visual elements to the path, or trafos, which are applied
238 before drawing the path.
242 self.draw(path, [deco.stroked]+list(attrs))
244 def fill(self, path, attrs=[]):
245 """fill path on canvas using the style given by args
247 The argument attrs consists of PathStyles, which modify
248 the appearance of the path, PathDecos, which add some new
249 visual elements to the path, or trafos, which are applied
250 before drawing the path.
254 self.draw(path, [deco.filled]+list(attrs))
256 def settexrunner(self, texrunner):
257 """sets the texrunner to be used to within the text and text_pt methods"""
259 self.texrunner = texrunner
261 def text(self, x, y, atext, *args, **kwargs):
262 """insert a text into the canvas
264 inserts a textbox created by self.texrunner.text into the canvas
266 returns the inserted textbox"""
268 return self.insert(self.texrunner.text(x, y, atext, *args, **kwargs))
271 def text_pt(self, x, y, atext, *args):
272 """insert a text into the canvas
274 inserts a textbox created by self.texrunner.text_pt into the canvas
276 returns the inserted textbox"""
278 return self.insert(self.texrunner.text_pt(x, y, atext, *args))
281 # user canvas class which adds a few convenience methods for single page output
284 def _wrappedindocument(method):
285 def wrappedindocument(self, file=None, **kwargs):
286 d = document.document([document.page(self, **kwargs)])
287 self.__name__ = method.__name__
288 self.__doc__ = method.__doc__
289 return method(d, file)
290 return wrappedindocument
293 class canvas(_canvas):
295 """a canvas holds a collection of canvasitems"""
297 writeEPSfile = _wrappedindocument(document.document.writeEPSfile)
298 writePSfile = _wrappedindocument(document.document.writePSfile)
299 writePDFfile = _wrappedindocument(document.document.writePDFfile)
300 writetofile = _wrappedindocument(document.document.writetofile)
302 def pipeGS(self, filename="-", device=None, resolution=100,
303 gscommand="gs", gsoptions="",
304 textalphabits=4, graphicsalphabits=4,
305 ciecolor=False, input="eps", **kwargs):
306 if device is None:
307 if filename.endswith(".png"):
308 device = "png16m"
309 if filename.endswith(".jpg"):
310 device = "jpeg"
311 gscommand += " -dEPSCrop -dNOPAUSE -dQUIET -dBATCH -r%i -sDEVICE=%s -sOutputFile=%s" % (resolution, device, filename)
312 if gsoptions:
313 gscommand += " %s" % gsoptions
314 if textalphabits is not None:
315 gscommand += " -dTextAlphaBits=%i" % textalphabits
316 if graphicsalphabits is not None:
317 gscommand += " -dGraphicsAlphaBits=%i" % graphicsalphabits
318 if ciecolor:
319 gscommand += " -dUseCIEColor"
320 if input == "eps":
321 gscommand += " -"
322 pipe = pycompat.popen(gscommand, "wb")
323 self.writeEPSfile(pipe, **kwargs)
324 pipe.close()
325 elif input == "pdf":
326 fd, fname = tempfile.mkstemp()
327 f = os.fdopen(fd, "wb")
328 gscommand += " %s" % fname
329 self.writePDFfile(f, **kwargs)
330 f.close()
331 os.system(gscommand)
332 os.unlink(fname)
333 else:
334 raise RuntimeError("input 'eps' or 'pdf' expected")
337 class layered_canvas(canvas):
339 def __init__(self, **kwargs):
340 canvas.canvas.__init__(self, **kwargs)
341 self._layers = {}
343 def layer(self, name):
344 try:
345 group, layer = name.split(".", 1)
346 except ValueError:
347 if not name in self._layers:
348 self._layers[name] = self.insert(Layer(texrunner=self.texrunner))
349 return self._layers[name]
350 else:
351 if not group in self._layers:
352 self._layers[group] = self.insert(Layer(texrunner=self.texrunner))
353 return self._layers[group].layer(layer)