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