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