2963
|
1 |
#!/usr/bin/env python
|
|
2 |
#Copyright ReportLab Europe Ltd. 2000-2004
|
|
3 |
#see license.txt for license details
|
|
4 |
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/tools/docco/graphdocpy.py
|
|
5 |
|
|
6 |
"""Generate documentation for reportlab.graphics classes.
|
|
7 |
|
|
8 |
Type the following for usage info:
|
|
9 |
|
|
10 |
python graphdocpy.py -h
|
|
11 |
"""
|
|
12 |
|
|
13 |
|
|
14 |
__version__ = '0.8'
|
|
15 |
|
|
16 |
|
|
17 |
import sys
|
|
18 |
sys.path.insert(0, '.')
|
|
19 |
import os, re, types, string, getopt, pickle, copy, time, pprint, traceback
|
|
20 |
from string import find, join, split, replace, expandtabs, rstrip
|
|
21 |
import reportlab
|
|
22 |
from reportlab import rl_config
|
|
23 |
|
|
24 |
from docpy import PackageSkeleton0, ModuleSkeleton0
|
|
25 |
from docpy import DocBuilder0, PdfDocBuilder0, HtmlDocBuilder0
|
|
26 |
from docpy import htmlescape, htmlrepr, defaultformat, \
|
|
27 |
getdoc, reduceDocStringLength
|
|
28 |
from docpy import makeHtmlSection, makeHtmlSubSection, \
|
|
29 |
makeHtmlInlineImage
|
|
30 |
|
|
31 |
from reportlab.lib.units import inch, cm
|
|
32 |
from reportlab.lib.pagesizes import A4
|
|
33 |
from reportlab.lib import colors
|
|
34 |
from reportlab.lib.enums import TA_CENTER, TA_LEFT
|
|
35 |
from reportlab.lib.utils import getStringIO
|
|
36 |
#from StringIO import StringIO
|
|
37 |
#getStringIO=StringIO
|
|
38 |
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
|
|
39 |
from reportlab.pdfgen import canvas
|
|
40 |
from reportlab.platypus.flowables import Flowable, Spacer
|
|
41 |
from reportlab.platypus.paragraph import Paragraph
|
|
42 |
from reportlab.platypus.tableofcontents import TableOfContents
|
|
43 |
from reportlab.platypus.flowables \
|
|
44 |
import Flowable, Preformatted,Spacer, Image, KeepTogether, PageBreak
|
|
45 |
from reportlab.platypus.xpreformatted import XPreformatted
|
|
46 |
from reportlab.platypus.frames import Frame
|
|
47 |
from reportlab.platypus.doctemplate \
|
|
48 |
import PageTemplate, BaseDocTemplate
|
|
49 |
from reportlab.platypus.tables import TableStyle, Table
|
|
50 |
from reportlab.graphics.shapes import NotImplementedError
|
|
51 |
import inspect
|
|
52 |
|
|
53 |
# Needed to draw Widget/Drawing demos.
|
|
54 |
|
|
55 |
from reportlab.graphics.widgetbase import Widget
|
|
56 |
from reportlab.graphics.shapes import Drawing
|
|
57 |
from reportlab.graphics import shapes
|
|
58 |
from reportlab.graphics import renderPDF
|
|
59 |
|
|
60 |
VERBOSE = rl_config.verbose
|
|
61 |
VERIFY = 1
|
|
62 |
|
|
63 |
_abstractclasserr_re = re.compile(r'^\s*abstract\s*class\s*(\w+)\s*instantiated',re.I)
|
|
64 |
|
|
65 |
####################################################################
|
|
66 |
#
|
|
67 |
# Stuff needed for building PDF docs.
|
|
68 |
#
|
|
69 |
####################################################################
|
|
70 |
|
|
71 |
def mainPageFrame(canvas, doc):
|
|
72 |
"The page frame used for all PDF documents."
|
|
73 |
|
|
74 |
canvas.saveState()
|
|
75 |
|
|
76 |
pageNumber = canvas.getPageNumber()
|
|
77 |
canvas.line(2*cm, A4[1]-2*cm, A4[0]-2*cm, A4[1]-2*cm)
|
|
78 |
canvas.line(2*cm, 2*cm, A4[0]-2*cm, 2*cm)
|
|
79 |
if pageNumber > 1:
|
|
80 |
canvas.setFont('Times-Roman', 12)
|
|
81 |
canvas.drawString(4 * inch, cm, "%d" % pageNumber)
|
|
82 |
if hasattr(canvas, 'headerLine'): # hackish
|
|
83 |
headerline = string.join(canvas.headerLine, ' \xc2\x8d ')
|
|
84 |
canvas.drawString(2*cm, A4[1]-1.75*cm, headerline)
|
|
85 |
|
|
86 |
canvas.setFont('Times-Roman', 8)
|
|
87 |
msg = "Generated with docpy. See http://www.reportlab.com!"
|
|
88 |
canvas.drawString(2*cm, 1.65*cm, msg)
|
|
89 |
|
|
90 |
canvas.restoreState()
|
|
91 |
|
|
92 |
|
|
93 |
class MyTemplate(BaseDocTemplate):
|
|
94 |
"The document template used for all PDF documents."
|
|
95 |
|
|
96 |
_invalidInitArgs = ('pageTemplates',)
|
|
97 |
|
|
98 |
def __init__(self, filename, **kw):
|
|
99 |
frame1 = Frame(2.5*cm, 2.5*cm, 15*cm, 25*cm, id='F1')
|
|
100 |
self.allowSplitting = 0
|
|
101 |
apply(BaseDocTemplate.__init__, (self, filename), kw)
|
|
102 |
self.addPageTemplates(PageTemplate('normal', [frame1], mainPageFrame))
|
|
103 |
|
|
104 |
def afterFlowable(self, flowable):
|
|
105 |
"Takes care of header line, TOC and outline entries."
|
|
106 |
|
|
107 |
if flowable.__class__.__name__ == 'Paragraph':
|
|
108 |
f = flowable
|
|
109 |
|
|
110 |
# Build a list of heading parts.
|
|
111 |
# So far, this is the *last* item on the *previous* page...
|
|
112 |
if f.style.name[:8] == 'Heading0':
|
|
113 |
self.canv.headerLine = [f.text] # hackish
|
|
114 |
elif f.style.name[:8] == 'Heading1':
|
|
115 |
if len(self.canv.headerLine) == 2:
|
|
116 |
del self.canv.headerLine[-1]
|
|
117 |
elif len(self.canv.headerLine) == 3:
|
|
118 |
del self.canv.headerLine[-1]
|
|
119 |
del self.canv.headerLine[-1]
|
|
120 |
self.canv.headerLine.append(f.text)
|
|
121 |
elif f.style.name[:8] == 'Heading2':
|
|
122 |
if len(self.canv.headerLine) == 3:
|
|
123 |
del self.canv.headerLine[-1]
|
|
124 |
self.canv.headerLine.append(f.text)
|
|
125 |
|
|
126 |
if f.style.name[:7] == 'Heading':
|
|
127 |
# Register TOC entries.
|
|
128 |
headLevel = int(f.style.name[7:])
|
|
129 |
self.notify('TOCEntry', (headLevel, flowable.getPlainText(), self.page))
|
|
130 |
|
|
131 |
# Add PDF outline entries.
|
|
132 |
c = self.canv
|
|
133 |
title = f.text
|
|
134 |
key = str(hash(f))
|
|
135 |
lev = int(f.style.name[7:])
|
|
136 |
try:
|
|
137 |
if lev == 0:
|
|
138 |
isClosed = 0
|
|
139 |
else:
|
|
140 |
isClosed = 1
|
|
141 |
c.bookmarkPage(key)
|
|
142 |
c.addOutlineEntry(title, key, level=lev, closed=isClosed)
|
|
143 |
c.showOutline()
|
|
144 |
except:
|
|
145 |
if VERBOSE:
|
|
146 |
# AR hacking in exception handlers
|
|
147 |
print 'caught exception in MyTemplate.afterFlowable with heading text %s' % f.text
|
|
148 |
traceback.print_exc()
|
|
149 |
else:
|
|
150 |
pass
|
|
151 |
|
|
152 |
|
|
153 |
####################################################################
|
|
154 |
#
|
|
155 |
# Utility functions
|
|
156 |
#
|
|
157 |
####################################################################
|
|
158 |
def indentLevel(line, spacesPerTab=4):
|
|
159 |
"""Counts the indent levels on the front.
|
|
160 |
|
|
161 |
It is assumed that one tab equals 4 spaces.
|
|
162 |
"""
|
|
163 |
|
|
164 |
x = 0
|
|
165 |
nextTab = 4
|
|
166 |
for ch in line:
|
|
167 |
if ch == ' ':
|
|
168 |
x = x + 1
|
|
169 |
elif ch == '\t':
|
|
170 |
x = nextTab
|
|
171 |
nextTab = x + spacesPerTab
|
|
172 |
else:
|
|
173 |
return x
|
|
174 |
|
|
175 |
|
|
176 |
assert indentLevel('hello') == 0, 'error in indentLevel'
|
|
177 |
assert indentLevel(' hello') == 1, 'error in indentLevel'
|
|
178 |
assert indentLevel(' hello') == 2, 'error in indentLevel'
|
|
179 |
assert indentLevel(' hello') == 3, 'error in indentLevel'
|
|
180 |
assert indentLevel('\thello') == 4, 'error in indentLevel'
|
|
181 |
assert indentLevel(' \thello') == 4, 'error in indentLevel'
|
|
182 |
assert indentLevel('\t hello') == 5, 'error in indentLevel'
|
|
183 |
|
|
184 |
####################################################################
|
|
185 |
#
|
|
186 |
# Special-purpose document builders
|
|
187 |
#
|
|
188 |
####################################################################
|
|
189 |
|
|
190 |
class GraphPdfDocBuilder0(PdfDocBuilder0):
|
|
191 |
"""A PDF document builder displaying widgets and drawings.
|
|
192 |
|
|
193 |
This generates a PDF file where only methods named 'demo' are
|
|
194 |
listed for any class C. If C happens to be a subclass of Widget
|
|
195 |
and has a 'demo' method, this method is assumed to generate and
|
|
196 |
return a sample widget instance, that is then appended graphi-
|
|
197 |
cally to the Platypus story.
|
|
198 |
|
|
199 |
Something similar happens for functions. If their names start
|
|
200 |
with 'sample' they are supposed to generate and return a sample
|
|
201 |
drawing. This is then taken and appended graphically to the
|
|
202 |
Platypus story, as well.
|
|
203 |
"""
|
|
204 |
|
|
205 |
fileSuffix = '.pdf'
|
|
206 |
|
|
207 |
def begin(self, name='', typ=''):
|
|
208 |
styleSheet = getSampleStyleSheet()
|
|
209 |
self.code = styleSheet['Code']
|
|
210 |
self.bt = styleSheet['BodyText']
|
|
211 |
self.story = []
|
|
212 |
|
|
213 |
# Cover page
|
|
214 |
t = time.gmtime(time.time())
|
|
215 |
timeString = time.strftime("%Y-%m-%d %H:%M", t)
|
|
216 |
self.story.append(Paragraph('<font size=18>Documentation for %s "%s"</font>' % (typ, name), self.bt))
|
|
217 |
self.story.append(Paragraph('<font size=18>Generated by: graphdocpy.py version %s</font>' % __version__, self.bt))
|
|
218 |
self.story.append(Paragraph('<font size=18>Date generated: %s</font>' % timeString, self.bt))
|
|
219 |
self.story.append(Paragraph('<font size=18>Format: PDF</font>', self.bt))
|
|
220 |
self.story.append(PageBreak())
|
|
221 |
|
|
222 |
# Table of contents
|
|
223 |
toc = TableOfContents()
|
|
224 |
self.story.append(toc)
|
|
225 |
self.story.append(PageBreak())
|
|
226 |
|
|
227 |
|
|
228 |
def end(self, fileName=None):
|
|
229 |
if fileName: # overrides output path
|
|
230 |
self.outPath = fileName
|
|
231 |
elif self.packageName:
|
|
232 |
self.outPath = self.packageName + self.fileSuffix
|
|
233 |
elif self.skeleton:
|
|
234 |
self.outPath = self.skeleton.getModuleName() + self.fileSuffix
|
|
235 |
else:
|
|
236 |
self.outPath = ''
|
|
237 |
|
|
238 |
if self.outPath:
|
|
239 |
doc = MyTemplate(self.outPath)
|
|
240 |
doc.multiBuild(self.story)
|
|
241 |
|
|
242 |
|
|
243 |
def beginModule(self, name, doc, imported):
|
|
244 |
story = self.story
|
|
245 |
bt = self.bt
|
|
246 |
|
|
247 |
# Defer displaying the module header info to later...
|
|
248 |
self.shouldDisplayModule = (name, doc, imported)
|
|
249 |
self.hasDisplayedModule = 0
|
|
250 |
|
|
251 |
|
|
252 |
def endModule(self, name, doc, imported):
|
|
253 |
if self.hasDisplayedModule:
|
|
254 |
DocBuilder0.endModule(self, name, doc, imported)
|
|
255 |
|
|
256 |
|
|
257 |
def beginClasses(self, names):
|
|
258 |
# Defer displaying the module header info to later...
|
|
259 |
if self.shouldDisplayModule:
|
|
260 |
self.shouldDisplayClasses = names
|
|
261 |
|
|
262 |
|
|
263 |
# Skip all methods.
|
|
264 |
def beginMethod(self, name, doc, sig):
|
|
265 |
pass
|
|
266 |
|
|
267 |
|
|
268 |
def endMethod(self, name, doc, sig):
|
|
269 |
pass
|
|
270 |
|
|
271 |
|
|
272 |
def beginClass(self, name, doc, bases):
|
|
273 |
"Append a graphic demo of a Widget or Drawing at the end of a class."
|
|
274 |
|
|
275 |
if VERBOSE:
|
|
276 |
print 'GraphPdfDocBuilder.beginClass(%s...)' % name
|
|
277 |
|
|
278 |
aClass = eval('self.skeleton.moduleSpace.' + name)
|
|
279 |
if issubclass(aClass, Widget):
|
|
280 |
if self.shouldDisplayModule:
|
|
281 |
modName, modDoc, imported = self.shouldDisplayModule
|
|
282 |
self.story.append(Paragraph(modName, self.makeHeadingStyle(self.indentLevel-2, 'module')))
|
|
283 |
self.story.append(XPreformatted(modDoc, self.bt))
|
|
284 |
self.shouldDisplayModule = 0
|
|
285 |
self.hasDisplayedModule = 1
|
|
286 |
if self.shouldDisplayClasses:
|
|
287 |
self.story.append(Paragraph('Classes', self.makeHeadingStyle(self.indentLevel-1)))
|
|
288 |
self.shouldDisplayClasses = 0
|
|
289 |
PdfDocBuilder0.beginClass(self, name, doc, bases)
|
|
290 |
self.beginAttributes(aClass)
|
|
291 |
|
|
292 |
elif issubclass(aClass, Drawing):
|
|
293 |
if self.shouldDisplayModule:
|
|
294 |
modName, modDoc, imported = self.shouldDisplayModule
|
|
295 |
self.story.append(Paragraph(modName, self.makeHeadingStyle(self.indentLevel-2, 'module')))
|
|
296 |
self.story.append(XPreformatted(modDoc, self.bt))
|
|
297 |
self.shouldDisplayModule = 0
|
|
298 |
self.hasDisplayedModule = 1
|
|
299 |
if self.shouldDisplayClasses:
|
|
300 |
self.story.append(Paragraph('Classes', self.makeHeadingStyle(self.indentLevel-1)))
|
|
301 |
self.shouldDisplayClasses = 0
|
|
302 |
PdfDocBuilder0.beginClass(self, name, doc, bases)
|
|
303 |
|
|
304 |
|
|
305 |
def beginAttributes(self, aClass):
|
|
306 |
"Append a list of annotated attributes of a class."
|
|
307 |
|
|
308 |
self.story.append(Paragraph(
|
|
309 |
'Public Attributes',
|
|
310 |
self.makeHeadingStyle(self.indentLevel+1)))
|
|
311 |
|
|
312 |
map = aClass._attrMap
|
|
313 |
if map:
|
|
314 |
map = map.items()
|
|
315 |
map.sort()
|
|
316 |
else:
|
|
317 |
map = []
|
|
318 |
for name, typ in map:
|
|
319 |
if typ != None:
|
|
320 |
if hasattr(typ, 'desc'):
|
|
321 |
desc = typ.desc
|
|
322 |
else:
|
|
323 |
desc = '<i>%s</i>' % typ.__class__.__name__
|
|
324 |
else:
|
|
325 |
desc = '<i>None</i>'
|
|
326 |
self.story.append(Paragraph(
|
|
327 |
"<b>%s</b> %s" % (name, desc), self.bt))
|
|
328 |
self.story.append(Paragraph("", self.bt))
|
|
329 |
|
|
330 |
|
|
331 |
def endClass(self, name, doc, bases):
|
|
332 |
"Append a graphic demo of a Widget or Drawing at the end of a class."
|
|
333 |
|
|
334 |
PdfDocBuilder0.endClass(self, name, doc, bases)
|
|
335 |
|
|
336 |
aClass = eval('self.skeleton.moduleSpace.' + name)
|
|
337 |
if hasattr(aClass, '_nodoc'):
|
|
338 |
pass
|
|
339 |
elif issubclass(aClass, Widget):
|
|
340 |
try:
|
|
341 |
widget = aClass()
|
|
342 |
except AssertionError, err:
|
|
343 |
if _abstractclasserr_re.match(str(err)): return
|
|
344 |
raise
|
|
345 |
self.story.append(Spacer(0*cm, 0.5*cm))
|
|
346 |
self._showWidgetDemoCode(widget)
|
|
347 |
self.story.append(Spacer(0*cm, 0.5*cm))
|
|
348 |
self._showWidgetDemo(widget)
|
|
349 |
self.story.append(Spacer(0*cm, 0.5*cm))
|
|
350 |
self._showWidgetProperties(widget)
|
|
351 |
self.story.append(PageBreak())
|
|
352 |
elif issubclass(aClass, Drawing):
|
|
353 |
drawing = aClass()
|
|
354 |
self.story.append(Spacer(0*cm, 0.5*cm))
|
|
355 |
self._showDrawingCode(drawing)
|
|
356 |
self.story.append(Spacer(0*cm, 0.5*cm))
|
|
357 |
self._showDrawingDemo(drawing)
|
|
358 |
self.story.append(Spacer(0*cm, 0.5*cm))
|
|
359 |
|
|
360 |
|
|
361 |
def beginFunctions(self, names):
|
|
362 |
srch = string.join(names, ' ')
|
|
363 |
if string.find(string.join(names, ' '), ' sample') > -1:
|
|
364 |
PdfDocBuilder0.beginFunctions(self, names)
|
|
365 |
|
|
366 |
|
|
367 |
# Skip non-sample functions.
|
|
368 |
def beginFunction(self, name, doc, sig):
|
|
369 |
"Skip function for 'uninteresting' names."
|
|
370 |
|
|
371 |
if name[:6] == 'sample':
|
|
372 |
PdfDocBuilder0.beginFunction(self, name, doc, sig)
|
|
373 |
|
|
374 |
|
|
375 |
def endFunction(self, name, doc, sig):
|
|
376 |
"Append a drawing to the story for special function names."
|
|
377 |
|
|
378 |
if name[:6] != 'sample':
|
|
379 |
return
|
|
380 |
|
|
381 |
if VERBOSE:
|
|
382 |
print 'GraphPdfDocBuilder.endFunction(%s...)' % name
|
|
383 |
PdfDocBuilder0.endFunction(self, name, doc, sig)
|
|
384 |
aFunc = eval('self.skeleton.moduleSpace.' + name)
|
|
385 |
drawing = aFunc()
|
|
386 |
|
|
387 |
self.story.append(Spacer(0*cm, 0.5*cm))
|
|
388 |
self._showFunctionDemoCode(aFunc)
|
|
389 |
self.story.append(Spacer(0*cm, 0.5*cm))
|
|
390 |
self._showDrawingDemo(drawing)
|
|
391 |
|
|
392 |
self.story.append(PageBreak())
|
|
393 |
|
|
394 |
|
|
395 |
def _showFunctionDemoCode(self, function):
|
|
396 |
"""Show a demo code of the function generating the drawing."""
|
|
397 |
# Heading
|
|
398 |
self.story.append(Paragraph("<i>Example</i>", self.bt))
|
|
399 |
self.story.append(Paragraph("", self.bt))
|
|
400 |
|
|
401 |
# Sample code
|
|
402 |
codeSample = inspect.getsource(function)
|
|
403 |
self.story.append(Preformatted(codeSample, self.code))
|
|
404 |
|
|
405 |
|
|
406 |
def _showDrawingCode(self, drawing):
|
|
407 |
"""Show code of the drawing class."""
|
|
408 |
# Heading
|
|
409 |
#className = drawing.__class__.__name__
|
|
410 |
self.story.append(Paragraph("<i>Example</i>", self.bt))
|
|
411 |
|
|
412 |
# Sample code
|
|
413 |
codeSample = inspect.getsource(drawing.__class__.__init__)
|
|
414 |
self.story.append(Preformatted(codeSample, self.code))
|
|
415 |
|
|
416 |
|
|
417 |
def _showDrawingDemo(self, drawing):
|
|
418 |
"""Show a graphical demo of the drawing."""
|
|
419 |
|
|
420 |
# Add the given drawing to the story.
|
|
421 |
# Ignored if no GD rendering available
|
|
422 |
# or the demo method does not return a drawing.
|
|
423 |
try:
|
|
424 |
flo = renderPDF.GraphicsFlowable(drawing)
|
|
425 |
self.story.append(Spacer(6,6))
|
|
426 |
self.story.append(flo)
|
|
427 |
self.story.append(Spacer(6,6))
|
|
428 |
except:
|
|
429 |
if VERBOSE:
|
|
430 |
print 'caught exception in _showDrawingDemo'
|
|
431 |
traceback.print_exc()
|
|
432 |
else:
|
|
433 |
pass
|
|
434 |
|
|
435 |
|
|
436 |
def _showWidgetDemo(self, widget):
|
|
437 |
"""Show a graphical demo of the widget."""
|
|
438 |
|
|
439 |
# Get a demo drawing from the widget and add it to the story.
|
|
440 |
# Ignored if no GD rendering available
|
|
441 |
# or the demo method does not return a drawing.
|
|
442 |
try:
|
|
443 |
if VERIFY:
|
|
444 |
widget.verify()
|
|
445 |
drawing = widget.demo()
|
|
446 |
flo = renderPDF.GraphicsFlowable(drawing)
|
|
447 |
self.story.append(Spacer(6,6))
|
|
448 |
self.story.append(flo)
|
|
449 |
self.story.append(Spacer(6,6))
|
|
450 |
except:
|
|
451 |
if VERBOSE:
|
|
452 |
print 'caught exception in _showWidgetDemo'
|
|
453 |
traceback.print_exc()
|
|
454 |
else:
|
|
455 |
pass
|
|
456 |
|
|
457 |
|
|
458 |
def _showWidgetDemoCode(self, widget):
|
|
459 |
"""Show a demo code of the widget."""
|
|
460 |
# Heading
|
|
461 |
#className = widget.__class__.__name__
|
|
462 |
self.story.append(Paragraph("<i>Example</i>", self.bt))
|
|
463 |
|
|
464 |
# Sample code
|
|
465 |
codeSample = inspect.getsource(widget.__class__.demo)
|
|
466 |
self.story.append(Preformatted(codeSample, self.code))
|
|
467 |
|
|
468 |
|
|
469 |
def _showWidgetProperties(self, widget):
|
|
470 |
"""Dump all properties of a widget."""
|
|
471 |
|
|
472 |
props = widget.getProperties()
|
|
473 |
keys = props.keys()
|
|
474 |
keys.sort()
|
|
475 |
lines = []
|
|
476 |
for key in keys:
|
|
477 |
value = props[key]
|
|
478 |
|
|
479 |
f = getStringIO()
|
|
480 |
pprint.pprint(value, f)
|
|
481 |
value = f.getvalue()[:-1]
|
|
482 |
valueLines = string.split(value, '\n')
|
|
483 |
for i in range(1, len(valueLines)):
|
|
484 |
valueLines[i] = ' '*(len(key)+3) + valueLines[i]
|
|
485 |
value = string.join(valueLines, '\n')
|
|
486 |
|
|
487 |
lines.append('%s = %s' % (key, value))
|
|
488 |
|
|
489 |
text = join(lines, '\n')
|
|
490 |
self.story.append(Paragraph("<i>Properties of Example Widget</i>", self.bt))
|
|
491 |
self.story.append(Paragraph("", self.bt))
|
|
492 |
self.story.append(Preformatted(text, self.code))
|
|
493 |
|
|
494 |
|
|
495 |
class GraphHtmlDocBuilder0(HtmlDocBuilder0):
|
|
496 |
"A class to write the skeleton of a Python source."
|
|
497 |
|
|
498 |
fileSuffix = '.html'
|
|
499 |
|
|
500 |
def beginModule(self, name, doc, imported):
|
|
501 |
# Defer displaying the module header info to later...
|
|
502 |
self.shouldDisplayModule = (name, doc, imported)
|
|
503 |
self.hasDisplayedModule = 0
|
|
504 |
|
|
505 |
|
|
506 |
def endModule(self, name, doc, imported):
|
|
507 |
if self.hasDisplayedModule:
|
|
508 |
HtmlDocBuilder0.endModule(self, name, doc, imported)
|
|
509 |
|
|
510 |
|
|
511 |
def beginClasses(self, names):
|
|
512 |
# Defer displaying the module header info to later...
|
|
513 |
if self.shouldDisplayModule:
|
|
514 |
self.shouldDisplayClasses = names
|
|
515 |
|
|
516 |
|
|
517 |
# Skip all methods.
|
|
518 |
def beginMethod(self, name, doc, sig):
|
|
519 |
pass
|
|
520 |
|
|
521 |
|
|
522 |
def endMethod(self, name, doc, sig):
|
|
523 |
pass
|
|
524 |
|
|
525 |
|
|
526 |
def beginClass(self, name, doc, bases):
|
|
527 |
"Append a graphic demo of a widget at the end of a class."
|
|
528 |
|
|
529 |
aClass = eval('self.skeleton.moduleSpace.' + name)
|
|
530 |
if issubclass(aClass, Widget):
|
|
531 |
if self.shouldDisplayModule:
|
|
532 |
modName, modDoc, imported = self.shouldDisplayModule
|
|
533 |
self.outLines.append('<H2>%s</H2>' % modName)
|
|
534 |
self.outLines.append('<PRE>%s</PRE>' % modDoc)
|
|
535 |
self.shouldDisplayModule = 0
|
|
536 |
self.hasDisplayedModule = 1
|
|
537 |
if self.shouldDisplayClasses:
|
|
538 |
self.outLines.append('<H2>Classes</H2>')
|
|
539 |
self.shouldDisplayClasses = 0
|
|
540 |
|
|
541 |
HtmlDocBuilder0.beginClass(self, name, doc, bases)
|
|
542 |
|
|
543 |
|
|
544 |
def endClass(self, name, doc, bases):
|
|
545 |
"Append a graphic demo of a widget at the end of a class."
|
|
546 |
|
|
547 |
HtmlDocBuilder0.endClass(self, name, doc, bases)
|
|
548 |
|
|
549 |
aClass = eval('self.skeleton.moduleSpace.' + name)
|
|
550 |
if issubclass(aClass, Widget):
|
|
551 |
widget = aClass()
|
|
552 |
self._showWidgetDemoCode(widget)
|
|
553 |
self._showWidgetDemo(widget)
|
|
554 |
self._showWidgetProperties(widget)
|
|
555 |
|
|
556 |
|
|
557 |
def beginFunctions(self, names):
|
|
558 |
if string.find(string.join(names, ' '), ' sample') > -1:
|
|
559 |
HtmlDocBuilder0.beginFunctions(self, names)
|
|
560 |
|
|
561 |
|
|
562 |
# Skip non-sample functions.
|
|
563 |
def beginFunction(self, name, doc, sig):
|
|
564 |
"Skip function for 'uninteresting' names."
|
|
565 |
|
|
566 |
if name[:6] == 'sample':
|
|
567 |
HtmlDocBuilder0.beginFunction(self, name, doc, sig)
|
|
568 |
|
|
569 |
|
|
570 |
def endFunction(self, name, doc, sig):
|
|
571 |
"Append a drawing to the story for special function names."
|
|
572 |
|
|
573 |
if name[:6] != 'sample':
|
|
574 |
return
|
|
575 |
|
|
576 |
HtmlDocBuilder0.endFunction(self, name, doc, sig)
|
|
577 |
aFunc = eval('self.skeleton.moduleSpace.' + name)
|
|
578 |
drawing = aFunc()
|
|
579 |
|
|
580 |
self._showFunctionDemoCode(aFunc)
|
|
581 |
self._showDrawingDemo(drawing, aFunc.__name__)
|
|
582 |
|
|
583 |
|
|
584 |
def _showFunctionDemoCode(self, function):
|
|
585 |
"""Show a demo code of the function generating the drawing."""
|
|
586 |
# Heading
|
|
587 |
self.outLines.append('<H3>Example</H3>')
|
|
588 |
|
|
589 |
# Sample code
|
|
590 |
codeSample = inspect.getsource(function)
|
|
591 |
self.outLines.append('<PRE>%s</PRE>' % codeSample)
|
|
592 |
|
|
593 |
|
|
594 |
def _showDrawingDemo(self, drawing, name):
|
|
595 |
"""Show a graphical demo of the drawing."""
|
|
596 |
|
|
597 |
# Add the given drawing to the story.
|
|
598 |
# Ignored if no GD rendering available
|
|
599 |
# or the demo method does not return a drawing.
|
|
600 |
try:
|
|
601 |
from reportlab.graphics import renderPM
|
|
602 |
modName = self.skeleton.getModuleName()
|
|
603 |
path = '%s-%s.jpg' % (modName, name)
|
|
604 |
renderPM.drawToFile(drawing, path, fmt='JPG')
|
|
605 |
self.outLines.append('<H3>Demo</H3>')
|
|
606 |
self.outLines.append(makeHtmlInlineImage(path))
|
|
607 |
except:
|
|
608 |
if VERBOSE:
|
|
609 |
print 'caught exception in GraphHTMLDocBuilder._showDrawingDemo'
|
|
610 |
traceback.print_exc()
|
|
611 |
else:
|
|
612 |
pass
|
|
613 |
|
|
614 |
|
|
615 |
def _showWidgetDemo(self, widget):
|
|
616 |
"""Show a graphical demo of the widget."""
|
|
617 |
|
|
618 |
# Get a demo drawing from the widget and add it to the story.
|
|
619 |
# Ignored if no GD rendering available
|
|
620 |
# or the demo method does not return a drawing.
|
|
621 |
try:
|
|
622 |
from reportlab.graphics import renderPM
|
|
623 |
drawing = widget.demo()
|
|
624 |
if VERIFY:
|
|
625 |
widget.verify()
|
|
626 |
modName = self.skeleton.getModuleName()
|
|
627 |
path = '%s-%s.jpg' % (modName, widget.__class__.__name__)
|
|
628 |
renderPM.drawToFile(drawing, path, fmt='JPG')
|
|
629 |
self.outLines.append('<H3>Demo</H3>')
|
|
630 |
self.outLines.append(makeHtmlInlineImage(path))
|
|
631 |
except:
|
|
632 |
if VERBOSE:
|
|
633 |
|
|
634 |
print 'caught exception in GraphHTMLDocBuilder._showWidgetDemo'
|
|
635 |
traceback.print_exc()
|
|
636 |
else:
|
|
637 |
pass
|
|
638 |
|
|
639 |
|
|
640 |
def _showWidgetDemoCode(self, widget):
|
|
641 |
"""Show a demo code of the widget."""
|
|
642 |
# Heading
|
|
643 |
#className = widget.__class__.__name__
|
|
644 |
self.outLines.append('<H3>Example Code</H3>')
|
|
645 |
|
|
646 |
# Sample code
|
|
647 |
codeSample = inspect.getsource(widget.__class__.demo)
|
|
648 |
self.outLines.append('<PRE>%s</PRE>' % codeSample)
|
|
649 |
self.outLines.append('')
|
|
650 |
|
|
651 |
|
|
652 |
def _showWidgetProperties(self, widget):
|
|
653 |
"""Dump all properties of a widget."""
|
|
654 |
|
|
655 |
props = widget.getProperties()
|
|
656 |
keys = props.keys()
|
|
657 |
keys.sort()
|
|
658 |
lines = []
|
|
659 |
for key in keys:
|
|
660 |
value = props[key]
|
|
661 |
|
|
662 |
# Method 3
|
|
663 |
f = getStringIO()
|
|
664 |
pprint.pprint(value, f)
|
|
665 |
value = f.getvalue()[:-1]
|
|
666 |
valueLines = string.split(value, '\n')
|
|
667 |
for i in range(1, len(valueLines)):
|
|
668 |
valueLines[i] = ' '*(len(key)+3) + valueLines[i]
|
|
669 |
value = string.join(valueLines, '\n')
|
|
670 |
|
|
671 |
lines.append('%s = %s' % (key, value))
|
|
672 |
text = join(lines, '\n')
|
|
673 |
self.outLines.append('<H3>Properties of Example Widget</H3>')
|
|
674 |
self.outLines.append('<PRE>%s</PRE>' % text)
|
|
675 |
self.outLines.append('')
|
|
676 |
|
|
677 |
|
|
678 |
# Highly experimental!
|
|
679 |
class PlatypusDocBuilder0(DocBuilder0):
|
|
680 |
"Document the skeleton of a Python module as a Platypus story."
|
|
681 |
|
|
682 |
fileSuffix = '.pps' # A pickled Platypus story.
|
|
683 |
|
|
684 |
def begin(self, name='', typ=''):
|
|
685 |
styleSheet = getSampleStyleSheet()
|
|
686 |
self.code = styleSheet['Code']
|
|
687 |
self.bt = styleSheet['BodyText']
|
|
688 |
self.story = []
|
|
689 |
|
|
690 |
|
|
691 |
def end(self):
|
|
692 |
if self.packageName:
|
|
693 |
self.outPath = self.packageName + self.fileSuffix
|
|
694 |
elif self.skeleton:
|
|
695 |
self.outPath = self.skeleton.getModuleName() + self.fileSuffix
|
|
696 |
else:
|
|
697 |
self.outPath = ''
|
|
698 |
|
|
699 |
if self.outPath:
|
|
700 |
f = open(self.outPath, 'w')
|
|
701 |
pickle.dump(self.story, f)
|
|
702 |
|
|
703 |
|
|
704 |
def beginPackage(self, name):
|
|
705 |
DocBuilder0.beginPackage(self, name)
|
|
706 |
self.story.append(Paragraph(name, self.bt))
|
|
707 |
|
|
708 |
|
|
709 |
def beginModule(self, name, doc, imported):
|
|
710 |
story = self.story
|
|
711 |
bt = self.bt
|
|
712 |
|
|
713 |
story.append(Paragraph(name, bt))
|
|
714 |
story.append(XPreformatted(doc, bt))
|
|
715 |
|
|
716 |
|
|
717 |
def beginClasses(self, names):
|
|
718 |
self.story.append(Paragraph('Classes', self.bt))
|
|
719 |
|
|
720 |
|
|
721 |
def beginClass(self, name, doc, bases):
|
|
722 |
bt = self.bt
|
|
723 |
story = self.story
|
|
724 |
if bases:
|
|
725 |
bases = map(lambda b:b.__name__, bases) # hack
|
|
726 |
story.append(Paragraph('%s(%s)' % (name, join(bases, ', ')), bt))
|
|
727 |
else:
|
|
728 |
story.append(Paragraph(name, bt))
|
|
729 |
|
|
730 |
story.append(XPreformatted(doc, bt))
|
|
731 |
|
|
732 |
|
|
733 |
def beginMethod(self, name, doc, sig):
|
|
734 |
bt = self.bt
|
|
735 |
story = self.story
|
|
736 |
story.append(Paragraph(name+sig, bt))
|
|
737 |
story.append(XPreformatted(doc, bt))
|
|
738 |
|
|
739 |
|
|
740 |
def beginFunctions(self, names):
|
|
741 |
if names:
|
|
742 |
self.story.append(Paragraph('Functions', self.bt))
|
|
743 |
|
|
744 |
|
|
745 |
def beginFunction(self, name, doc, sig):
|
|
746 |
bt = self.bt
|
|
747 |
story = self.story
|
|
748 |
story.append(Paragraph(name+sig, bt))
|
|
749 |
story.append(XPreformatted(doc, bt))
|
|
750 |
|
|
751 |
|
|
752 |
####################################################################
|
|
753 |
#
|
|
754 |
# Main
|
|
755 |
#
|
|
756 |
####################################################################
|
|
757 |
|
|
758 |
def printUsage():
|
|
759 |
"""graphdocpy.py - Automated documentation for the RL Graphics library.
|
|
760 |
|
|
761 |
Usage: python graphdocpy.py [options]
|
|
762 |
|
|
763 |
[options]
|
|
764 |
-h Print this help message.
|
|
765 |
|
|
766 |
-f name Use the document builder indicated by 'name',
|
|
767 |
e.g. Html, Pdf.
|
|
768 |
|
|
769 |
-m module Generate document for module named 'module'.
|
|
770 |
'module' may follow any of these forms:
|
|
771 |
- docpy.py
|
|
772 |
- docpy
|
|
773 |
- c:\\test\\docpy
|
|
774 |
and can be any of these:
|
|
775 |
- standard Python modules
|
|
776 |
- modules in the Python search path
|
|
777 |
- modules in the current directory
|
|
778 |
|
|
779 |
-p package Generate document for package named 'package'
|
|
780 |
(default is 'reportlab.graphics').
|
|
781 |
'package' may follow any of these forms:
|
|
782 |
- reportlab
|
|
783 |
- reportlab.graphics.charts
|
|
784 |
- c:\\test\\reportlab
|
|
785 |
and can be any of these:
|
|
786 |
- standard Python packages (?)
|
|
787 |
- packages in the Python search path
|
|
788 |
- packages in the current directory
|
|
789 |
|
|
790 |
-s Silent mode (default is unset).
|
|
791 |
|
|
792 |
Examples:
|
|
793 |
|
|
794 |
python graphdocpy.py reportlab.graphics
|
|
795 |
python graphdocpy.py -m signsandsymbols.py -f Pdf
|
|
796 |
python graphdocpy.py -m flags.py -f Html
|
|
797 |
python graphdocpy.py -m barchart1.py
|
|
798 |
"""
|
|
799 |
|
|
800 |
|
|
801 |
# The following functions, including main(), are actually
|
|
802 |
# the same as in docpy.py (except for some defaults).
|
|
803 |
|
|
804 |
def documentModule0(pathOrName, builder, opts={}):
|
|
805 |
"""Generate documentation for one Python file in some format.
|
|
806 |
|
|
807 |
This handles Python standard modules like string, custom modules
|
|
808 |
on the Python search path like e.g. docpy as well as modules
|
|
809 |
specified with their full path like C:/tmp/junk.py.
|
|
810 |
|
|
811 |
The doc file will always be saved in the current directory with
|
|
812 |
a basename equal to that of the module, e.g. docpy.
|
|
813 |
"""
|
|
814 |
cwd = os.getcwd()
|
|
815 |
|
|
816 |
# Append directory to Python search path if we get one.
|
|
817 |
dirName = os.path.dirname(pathOrName)
|
|
818 |
if dirName:
|
|
819 |
sys.path.append(dirName)
|
|
820 |
|
|
821 |
# Remove .py extension from module name.
|
|
822 |
if pathOrName[-3:] == '.py':
|
|
823 |
modname = pathOrName[:-3]
|
|
824 |
else:
|
|
825 |
modname = pathOrName
|
|
826 |
|
|
827 |
# Remove directory paths from module name.
|
|
828 |
if dirName:
|
|
829 |
modname = os.path.basename(modname)
|
|
830 |
|
|
831 |
# Load the module.
|
|
832 |
try:
|
|
833 |
module = __import__(modname)
|
|
834 |
except:
|
|
835 |
print 'Failed to import %s.' % modname
|
|
836 |
os.chdir(cwd)
|
|
837 |
return
|
|
838 |
|
|
839 |
# Do the real documentation work.
|
|
840 |
s = ModuleSkeleton0()
|
|
841 |
s.inspect(module)
|
|
842 |
builder.write(s)
|
|
843 |
|
|
844 |
# Remove appended directory from Python search path if we got one.
|
|
845 |
if dirName:
|
|
846 |
del sys.path[-1]
|
|
847 |
|
|
848 |
os.chdir(cwd)
|
|
849 |
|
|
850 |
|
|
851 |
def _packageWalkCallback((builder, opts), dirPath, files):
|
|
852 |
"A callback function used when waking over a package tree."
|
|
853 |
#must CD into a directory to document the module correctly
|
|
854 |
cwd = os.getcwd()
|
|
855 |
os.chdir(dirPath)
|
|
856 |
|
|
857 |
|
|
858 |
# Skip __init__ files.
|
|
859 |
files = filter(lambda f:f != '__init__.py', files)
|
|
860 |
|
|
861 |
files = filter(lambda f:f[-3:] == '.py', files)
|
|
862 |
for f in files:
|
|
863 |
path = os.path.join(dirPath, f)
|
|
864 |
## if not opts.get('isSilent', 0):
|
|
865 |
## print path
|
|
866 |
builder.indentLevel = builder.indentLevel + 1
|
|
867 |
#documentModule0(path, builder)
|
|
868 |
documentModule0(f, builder)
|
|
869 |
builder.indentLevel = builder.indentLevel - 1
|
|
870 |
#CD back out
|
|
871 |
os.chdir(cwd)
|
|
872 |
|
|
873 |
def documentPackage0(pathOrName, builder, opts={}):
|
|
874 |
"""Generate documentation for one Python package in some format.
|
|
875 |
|
|
876 |
'pathOrName' can be either a filesystem path leading to a Python
|
|
877 |
package or package name whose path will be resolved by importing
|
|
878 |
the top-level module.
|
|
879 |
|
|
880 |
The doc file will always be saved in the current directory with
|
|
881 |
a basename equal to that of the package, e.g. reportlab.lib.
|
|
882 |
"""
|
|
883 |
|
|
884 |
# Did we get a package path with OS-dependant seperators...?
|
|
885 |
if os.sep in pathOrName:
|
|
886 |
path = pathOrName
|
|
887 |
name = os.path.splitext(os.path.basename(path))[0]
|
|
888 |
# ... or rather a package name?
|
|
889 |
else:
|
|
890 |
name = pathOrName
|
|
891 |
package = __import__(name)
|
|
892 |
# Some special care needed for dotted names.
|
|
893 |
if '.' in name:
|
|
894 |
subname = 'package' + name[find(name, '.'):]
|
|
895 |
package = eval(subname)
|
|
896 |
path = os.path.dirname(package.__file__)
|
|
897 |
|
|
898 |
cwd = os.getcwd()
|
|
899 |
os.chdir(path)
|
|
900 |
builder.beginPackage(name)
|
|
901 |
os.path.walk(path, _packageWalkCallback, (builder, opts))
|
|
902 |
builder.endPackage(name)
|
|
903 |
os.chdir(cwd)
|
|
904 |
|
|
905 |
|
|
906 |
def makeGraphicsReference(outfilename):
|
|
907 |
"Make graphics_reference.pdf"
|
|
908 |
builder = GraphPdfDocBuilder0()
|
|
909 |
|
|
910 |
builder.begin(name='reportlab.graphics', typ='package')
|
|
911 |
documentPackage0('reportlab.graphics', builder, {'isSilent': 0})
|
|
912 |
builder.end(outfilename)
|
|
913 |
print 'made graphics reference in %s' % outfilename
|
|
914 |
|
|
915 |
def main():
|
|
916 |
"Handle command-line options and trigger corresponding action."
|
|
917 |
|
|
918 |
opts, args = getopt.getopt(sys.argv[1:], 'hsf:m:p:')
|
|
919 |
|
|
920 |
# Make an options dictionary that is easier to use.
|
|
921 |
optsDict = {}
|
|
922 |
for k, v in opts:
|
|
923 |
optsDict[k] = v
|
|
924 |
hasOpt = optsDict.has_key
|
|
925 |
|
|
926 |
# On -h print usage and exit immediately.
|
|
927 |
if hasOpt('-h'):
|
|
928 |
print printUsage.__doc__
|
|
929 |
sys.exit(0)
|
|
930 |
|
|
931 |
# On -s set silent mode.
|
|
932 |
isSilent = hasOpt('-s')
|
|
933 |
|
|
934 |
# On -f set the appropriate DocBuilder to use or a default one.
|
|
935 |
builder = { 'Pdf': GraphPdfDocBuilder0,
|
|
936 |
'Html': GraphHtmlDocBuilder0,
|
|
937 |
}[optsDict.get('-f', 'Pdf')]()
|
|
938 |
|
|
939 |
# Set default module or package to document.
|
|
940 |
if not hasOpt('-p') and not hasOpt('-m'):
|
|
941 |
optsDict['-p'] = 'reportlab.graphics'
|
|
942 |
|
|
943 |
# Save a few options for further use.
|
|
944 |
options = {'isSilent':isSilent}
|
|
945 |
|
|
946 |
# Now call the real documentation functions.
|
|
947 |
if hasOpt('-m'):
|
|
948 |
nameOrPath = optsDict['-m']
|
|
949 |
if not isSilent:
|
|
950 |
print "Generating documentation for module %s..." % nameOrPath
|
|
951 |
builder.begin(name=nameOrPath, typ='module')
|
|
952 |
documentModule0(nameOrPath, builder, options)
|
|
953 |
elif hasOpt('-p'):
|
|
954 |
nameOrPath = optsDict['-p']
|
|
955 |
if not isSilent:
|
|
956 |
print "Generating documentation for package %s..." % nameOrPath
|
|
957 |
builder.begin(name=nameOrPath, typ='package')
|
|
958 |
documentPackage0(nameOrPath, builder, options)
|
|
959 |
builder.end()
|
|
960 |
|
|
961 |
if not isSilent:
|
|
962 |
print "Saved %s." % builder.outPath
|
|
963 |
|
|
964 |
#if doing the usual, put a copy in docs
|
|
965 |
if builder.outPath == 'reportlab.graphics.pdf':
|
|
966 |
import shutil, reportlab
|
|
967 |
dst = os.path.join(os.path.dirname(reportlab.__file__),'docs','graphics_reference.pdf')
|
|
968 |
shutil.copyfile('reportlab.graphics.pdf', dst)
|
|
969 |
if not isSilent:
|
|
970 |
print 'copied to '+dst
|
|
971 |
|
|
972 |
def makeSuite():
|
|
973 |
"standard test harness support - run self as separate process"
|
|
974 |
from reportlab.test.utils import ScriptThatMakesFileTest
|
|
975 |
return ScriptThatMakesFileTest('tools/docco',
|
|
976 |
'graphdocpy.py',
|
|
977 |
'reportlab.graphics.pdf')
|
|
978 |
|
|
979 |
if __name__ == '__main__':
|
|
980 |
main()
|