get rid of comparison with None
[PyX.git] / document.py
blob200755b1c9d06682b146aa8be2fa9c96166983e4
1 # -*- encoding: utf-8 -*-
4 # Copyright (C) 2005-2011 Jörg Lehmann <joergl@users.sourceforge.net>
5 # Copyright (C) 2005-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 import sys, warnings
24 from . import bbox, pswriter, pdfwriter, writer, trafo, style, unit
27 class paperformat:
29 def __init__(self, width, height, name=None):
30 self.width = width
31 self.height = height
32 self.name = name
34 paperformat.A5 = paperformat(148.5 * unit.t_mm, 210 * unit.t_mm, "A5")
35 paperformat.A4 = paperformat(210 * unit.t_mm, 297 * unit.t_mm, "A4")
36 paperformat.A3 = paperformat(297 * unit.t_mm, 420 * unit.t_mm, "A3")
37 paperformat.A2 = paperformat(420 * unit.t_mm, 594 * unit.t_mm, "A2")
38 paperformat.A1 = paperformat(594 * unit.t_mm, 840 * unit.t_mm, "A1")
39 paperformat.A0 = paperformat(840 * unit.t_mm, 1188 * unit.t_mm, "A0")
40 paperformat.A0b = paperformat(910 * unit.t_mm, 1370 * unit.t_mm, None) # dedicated to our friends in Augsburg
41 paperformat.Letter = paperformat(8.5 * unit.t_inch, 11 * unit.t_inch, "Letter")
42 paperformat.Legal = paperformat(8.5 * unit.t_inch, 14 * unit.t_inch, "Legal")
44 def _paperformatfromstring(name):
45 return getattr(paperformat, name.capitalize())
48 class page:
50 def __init__(self, canvas, pagename=None, paperformat=None, rotated=0, centered=1, fittosize=0,
51 margin=1*unit.t_cm, bboxenlarge=1*unit.t_pt, bbox=None):
52 self.canvas = canvas
53 self.pagename = pagename
54 # support for deprecated string specification of paper formats
55 try:
56 paperformat + ""
57 except:
58 self.paperformat = paperformat
59 else:
60 self.paperformat = _paperformatfromstring(paperformat)
61 warnings.warn("specification of paperformat by string is deprecated, use document.paperformat.%s instead" % paperformat.capitalize(), DeprecationWarning)
63 self.rotated = rotated
64 self.centered = centered
65 self.fittosize = fittosize
66 self.margin = margin
67 self.bboxenlarge = bboxenlarge
68 self.pagebbox = bbox
70 def _process(self, processMethod, contentfile, writer, context, registry, bbox):
71 # usually, it is the bbox of the canvas enlarged by self.bboxenlarge, but
72 # it might be a different bbox as specified in the page constructor
73 assert not bbox
74 if self.pagebbox:
75 bbox.set(self.pagebbox)
76 else:
77 bbox.set(self.canvas.bbox()) # this bbox is not accurate
78 bbox.enlarge(self.bboxenlarge)
80 # check whether we expect a page trafo and use a temporary canvas to insert the
81 # page canvas
82 if self.paperformat and (self.rotated or self.centered or self.fittosize) and bbox:
83 # calculate the pagetrafo
84 paperwidth, paperheight = self.paperformat.width, self.paperformat.height
86 # center (optionally rotated) output on page
87 if self.rotated:
88 pagetrafo = trafo.rotate(90).translated(paperwidth, 0)
89 if self.centered or self.fittosize:
90 if not self.fittosize and (bbox.height() > paperwidth or bbox.width() > paperheight):
91 warnings.warn("content exceeds the papersize")
92 pagetrafo = pagetrafo.translated(-0.5*(paperwidth - bbox.height()) + bbox.bottom(),
93 0.5*(paperheight - bbox.width()) - bbox.left())
94 else:
95 if not self.fittosize and (bbox.width() > paperwidth or bbox.height() > paperheight):
96 warnings.warn("content exceeds the papersize")
97 pagetrafo = trafo.translate(0.5*(paperwidth - bbox.width()) - bbox.left(),
98 0.5*(paperheight - bbox.height()) - bbox.bottom())
100 if self.fittosize:
102 if 2*self.margin > paperwidth or 2*self.margin > paperheight:
103 raise ValueError("Margins too broad for selected paperformat. Aborting.")
105 paperwidth -= 2 * self.margin
106 paperheight -= 2 * self.margin
108 # scale output to pagesize - margins
109 if self.rotated:
110 sfactor = min(unit.topt(paperheight)/bbox.width_pt(), unit.topt(paperwidth)/bbox.height_pt())
111 else:
112 sfactor = min(unit.topt(paperwidth)/bbox.width_pt(), unit.topt(paperheight)/bbox.height_pt())
114 pagetrafo = pagetrafo.scaled(sfactor, sfactor, self.margin + 0.5*paperwidth, self.margin + 0.5*paperheight)
116 bbox.transform(pagetrafo)
117 from . import canvas as canvasmodule
118 cc = canvasmodule.canvas()
119 cc.insert(self.canvas, [pagetrafo])
120 else:
121 cc = self.canvas
123 getattr(style.linewidth.normal, processMethod)(contentfile, writer, context, registry)
124 if self.pagebbox:
125 bbox = bbox.copy() # don't alter the bbox provided to the constructor -> use a copy
126 getattr(cc, processMethod)(contentfile, writer, context, registry, bbox)
128 def processPS(self, *args):
129 self._process("processPS", *args)
131 def processPDF(self, *args):
132 self._process("processPDF", *args)
135 def _outputstream(file, suffix):
136 """returns a tuple: the open file handler and a boolean indicating
137 whether the file should be closed at the end or not"""
138 if file is None:
139 if not sys.argv[0].endswith(".py"):
140 raise RuntimeError("could not auto-guess filename")
141 return open("%s.%s" % (sys.argv[0][:-3], suffix), "wb"), True
142 if file == "-":
143 return sys.stdout.buffer, False
144 try:
145 file.write(b"")
146 return file, True
147 except:
148 if not file.endswith(".%s" % suffix):
149 return open("%s.%s" % (file, suffix), "wb"), True
150 return open(file, "wb"), True
153 class document:
155 """holds a collection of page instances which are output as pages of a document"""
157 def __init__(self, pages=None):
158 if pages is None:
159 self.pages = []
160 else:
161 self.pages = pages
163 def append(self, page):
164 self.pages.append(page)
166 def writeEPSfile(self, file=None, **kwargs):
167 f, close = _outputstream(file, "eps")
168 pswriter.EPSwriter(self, f, **kwargs)
169 if close:
170 f.close()
172 def writePSfile(self, file=None, **kwargs):
173 f, close = _outputstream(file, "eps")
174 pswriter.PSwriter(self, f, **kwargs)
175 if close:
176 f.close()
178 def writePDFfile(self, file=None, **kwargs):
179 f, close = _outputstream(file, "eps")
180 pdfwriter.PDFwriter(self, f, **kwargs)
181 if close:
182 f.close()
184 def writetofile(self, filename, **kwargs):
185 for suffix, method in [("eps", pswriter.writeEPSfile),
186 ("ps", pswriter.writePSfile),
187 ("pdf", pdfwriter.writePDFfile)]:
188 if filename.endswith(".{}".format(suffix)):
189 f = open(filename, "wb")
190 method(self, f, **kwargs)
191 f.close()
192 return
193 raise ValueError("unknown file extension")