Package doconce :: Module DocWriter
[hide private]
[frames] | no frames]

Source Code for Module doconce.DocWriter

   1  """ 
   2  DocWriter is a tool for writing documents in ASCII, HTML, 
   3  LaTeX, Doconce, and other formats based on input from Python 
   4  datastructures. 
   5   
   6  The base class _BaseWriter defines common functions and data 
   7  structures, while subclasses HTML, Doconce, etc.  implement (i.e., 
   8  write to) various formats. 
   9   
  10  This module works, but is unifinished and needs documentation! 
  11  """ 
  12   
  13  from StringIO import StringIO 
  14  import re, os, glob, commands 
  15   
16 -class _BaseWriter:
17 """ 18 Base class for document writing classes. 19 Each subclass implements a specific format (html, latex, 20 rst, etc.). 21 """
22 - def __init__(self, format, filename_extension):
23 # use StringIO as a string "file" for writing the document: 24 self.file = StringIO() 25 self.filename_extension = filename_extension 26 self.format = format 27 self._footer_called = False
28 29 document = property(fget=lambda self: self.file.getvalue(), 30 doc='Formatted document as a string') 31
32 - def write_to_file(self, filename):
33 """ 34 Write formatted document to a file. 35 Just give the stem of the file name; 36 the extension will be automatically added (depending on the 37 document format). 38 """ 39 # footer? 40 if not self._footer_called: 41 self.footer() 42 self._footer_called = True 43 44 f = open(filename + self.filename_extension, 'w') 45 f.write(self.document) 46 f.close()
47
48 - def __str__(self):
49 """Return formatted document.""" 50 return self.document
51
52 - def header(self):
53 """Header as required by format. Called in constructor.""" 54 pass
55
56 - def footer(self):
57 """Footer as required by format. Called in write_to_file.""" 58 pass
59
60 - def not_impl(self, method):
61 raise NotImplementedError, \ 62 'method "%s" in class "%s" is not implemented' % \ 63 (method, self.__class__.__name__)
64
65 - def title(self, title, authors_and_institutions=[], date='today'):
66 """ 67 Provide title and authors. 68 69 @param title: document title (string). 70 @param authors_and_institutions: list of authors and their 71 associated institutions, where each list item is a tuple/list 72 with author as first element followed by the name of all 73 institutions this author is associated with. 74 @param date: None implies no date, while 'today' generates 75 the current date, otherwise a string is supplied. 76 """ 77 self.not_impl('title')
78
79 - def today_date(self):
80 """Return a string with today's date suitably formatted.""" 81 import time 82 return time.strftime('%a, %d %b %Y (%H:%M)')
83
84 - def section(self, title, label=None):
85 """ 86 Write a section heading with the given title and an optional 87 label (for navigation). 88 """ 89 self.not_impl('section')
90
91 - def subsection(self, title, label=None):
92 """ 93 Write a subsection heading with the given title and an optional 94 label (for navigation). 95 """ 96 self.not_impl('subsection')
97
98 - def subsubsection(self, title, label=None):
99 """ 100 Write a subsubsection heading with the given title and an optional 101 label (for navigation). 102 """ 103 self.not_impl('subsubsection')
104
105 - def paragraph(self, title, ending='.', label=None):
106 """ 107 Write a paragraph heading with the given title and an ending 108 (period, question mark, colon) and an optional label (for navigation). 109 """ 110 self.not_impl('paragraph')
111
112 - def paragraph_separator(self):
113 """ 114 Add a (space) separator between running paragraphs. 115 """ 116 self.not_impl('paragraph_separator')
117
118 - def text(self, text, indent=0):
119 """ 120 Write plain text. Each line can be idented by a given number 121 of spaces. 122 """ 123 # do the indentation here, subclasses should call this method first 124 text = '\n'.join([' '*indent + line for line in text.split('\n')]) 125 # subclasses must substitute Doconce simple formatting 126 # using the expandtext method 127 return text
128
129 - def expandtext(self, text, tags, tags_replacements):
130 """ 131 In a string text, replace all occurences of strings defined in tags 132 by the corresponding strings defined in tags_replacements. 133 Both tags and tags_replacements are dictionaries with keys such 134 as 'bold', 'emphasize', 'verbatim', 'math', and values consisting of 135 regular expression patterns. 136 137 This method allows application code to use some generic ways of 138 writing emphasized, boldface, and verbatim text, typically in the 139 Doconce format with *emphasized text*, _boldface text_, and 140 `verbatim fixed font width text`. 141 """ 142 for tag in tags: 143 tag_pattern = tags[tag] 144 c = re.compile(tag_pattern, re.MULTILINE) 145 try: 146 tag_replacement = tags_replacements[tag] 147 except KeyError: 148 continue 149 if tag_replacement is not None: 150 text = c.sub(tag_replacement, text) 151 return text
152
153 - def list(self, items, listtype='itemize'):
154 """ 155 Write list or nested lists. 156 157 @param items: list of items. 158 @param listtype: 'itemize', 'enumerate', or 'description'. 159 """ 160 # call _BaseWriter.unfold_list to traverse the list 161 # and use self.item_handler to typeset each item 162 self.not_impl('list')
163
164 - def unfold_list(self, items, item_handler, listtype, level=0):
165 """ 166 Traverse a possibly nested list and call item_handler for 167 each item. To be used in subclasses for easy list handling. 168 169 @param items: list to be processed. 170 @param item_handler: callable, see that method for doc of arguments. 171 @param listtype: 'itemize', 'enumerate', or 'description'. 172 @param level: the level of a sublist (0 is main list, increased by 1 173 for each sublevel). 174 """ 175 # check for common error (a trailing comma...): 176 if isinstance(items, tuple) and len(items) == 1: 177 raise ValueError, 'list is a 1-tuple, error? If there is '\ 178 'only one item in the list, make a real Python list '\ 179 'object instead - current list is\n(%s,)' % items 180 item_handler('_begin', listtype, level) 181 for i, item in enumerate(items): 182 if isinstance(item, (list,tuple)): 183 self.unfold_list(item, item_handler, listtype, level+1) 184 elif isinstance(item, basestring): 185 if listtype == 'description': 186 # split out keyword in a description list: 187 parts = item.split(':') 188 keyword = parts[0] 189 item = ':'.join(parts[1:]) 190 item_handler(item, listtype, level, keyword) 191 else: 192 item_handler(item, listtype, level) 193 else: 194 raise TypeError, 'wrong %s for item' % type(item) 195 item_handler('_end', listtype, level)
196
197 - def item_handler(self, item, listtype, level, keyword=None):
198 """ 199 Write out the syntax for an item in a list. 200 201 @param item: text assoicated with the current list item. If item 202 equals '_begin' or '_end', appropriate begin/end formatting of 203 the list is written instead of an ordinary item. 204 @param listtype: 'itemize, 'enumerate', or 'description'. 205 @param level: list level number, 0 is the mainlist, increased by 1 206 for each sublist (the level number implies the amount of indentation). 207 @param keyword: the keyword of the item in a 'description' list. 208 """ 209 self.not_impl('item_handler')
210
211 - def verbatim(self, code):
212 """ 213 Write verbatim text in fixed-width form 214 (typically for computer code). 215 """ 216 self.not_impl('verbatim')
217
218 - def math(self, text):
219 """Write block of mathematical text (equations).""" 220 # default: dump raw 221 self.raw(text)
222
223 - def raw(self, text):
224 """Write text directly 'as is' to output.""" 225 self.file.write(text)
226
227 - def figure_conversion(self, filename, extensions):
228 """ 229 Convert filename to an image with type according to 230 extension(s). 231 232 The first existing file with an extension encountered in the extensions 233 list is returned. If no files with the right extensions are found, 234 the convert utility from the ImageMagick suite is used to 235 convert filename.ps or filename.eps to filename + extensions[0]. 236 """ 237 if not isinstance(extensions, (list,tuple)): 238 extensions = [extensions] 239 for ext in extensions: 240 final = filename + ext 241 if os.path.isfile(final): 242 return final 243 244 final = filename + extensions[0] # convert to first mentioned type 245 files = glob.glob(filename + '*') 246 # first convert from ps or eps to other things: 247 for file in files: 248 stem, ext = os.path.splitext(file) 249 if ext == '.ps' or ext == '.eps': 250 cmd = 'convert %s %s' % (file, final) 251 print cmd 252 failure = os.system(cmd) 253 if failure: 254 print 'Could not convert;\n %s' % cmd 255 return final 256 # try to convert from the first file to the disired format: 257 file = files[0] 258 cmd = 'convert %s %s' % (file, final) 259 print cmd 260 failure, outtext = commands.getstatusoutput(cmd) 261 if failure: 262 print 'Could not convert;\n %s' % cmd 263 return final
264
265 - def figure(self, filename, caption, width=None, height=None, label=None):
266 """ 267 Insert a figure into the document. 268 filename should be without extension; a proper extension is added, 269 and if the figure is not available in that image format, the 270 convert utility from ImageMagick is called to convert the format. 271 """ 272 self.not_impl('figure')
273
274 - def table(self, table, column_headline_pos='c', column_pos='c'):
275 """ 276 Translates a two-dimensional list of data, containing strings or 277 numbers, to a suitable "tabular" environment in the output. 278 279 @param table: list of list with rows/columns in table, including 280 (optional) column-headline 1st row and row-headline 1st column. 281 @param column_pos: specify the l/c/r position of data 282 entries in columns, give either (e.g.) 'llrrc' or one char 283 (if all are equal). 284 @param column_headline_pos : position l/c/r for the headline row 285 """ 286 self.not_impl('table')
287
288 - def url(self, url_address, link_text=None):
289 """Typeset an URL (with an optional link).""" 290 self.not_impl('url')
291
295 296 # what about LaTeX references to labels in equations, pages, labels? 297
298 -def makedocstr(parent_class, subclass_method):
299 """ 300 Compose a string (to be used as doc string) from a method's 301 doc string in a parent class and an additional doc string 302 in a subclass version of the method. 303 304 @param parent_class: class object for parent class. 305 @param subclass_method: method object for subclass. 306 @return: parent_class.method.__doc__ + subclass_method.__doc__ 307 """ 308 parent_method = getattr(parent_class, subclass_method.__name__) 309 docstr = parent_method.__doc__ 310 if subclass_method.__doc__ is not None and \ 311 subclass_method is not parent_method: 312 docstr += subclass_func.__doc__ 313 return docstr
314 315 316 # regular expressions for inline tags: 317 # (these are taken from doconce.common.INLINE_TAGS) 318 inline_tag_begin = r'(?P<begin>(^|[(\s]))' 319 inline_tag_end = r'(?P<end>($|[.,?!;:)\s]))' 320 INLINE_TAGS = { 321 # math: text inside $ signs, as in $a = b$, with space before the 322 # first $ and space, comma, period, colon, semicolon, or question 323 # mark after the enclosing $. 324 'math': 325 r'%s\$(?P<subst>[^ `][^$`]*)\$%s' % \ 326 (inline_tag_begin, inline_tag_end), 327 328 # $latex text$|$pure text alternative$ 329 'math2': 330 r'%s\$(?P<latexmath>[^ `][^$`]*)\$\|\$(?P<puretext>[^ `][^$`]*)\$%s' % \ 331 (inline_tag_begin, inline_tag_end), 332 333 # *emphasized words* 334 'emphasize': 335 r'%s\*(?P<subst>[^ `][^*`]*)\*%s' % \ 336 (inline_tag_begin, inline_tag_end), 337 338 # `verbatim inline text is enclosed in back quotes` 339 'verbatim': 340 r'%s`(?P<subst>[^ ][^`]*)`%s' % \ 341 (inline_tag_begin, inline_tag_end), 342 343 # _underscore before and after signifies bold_ 344 'bold': 345 r'%s_(?P<subst>[^ `][^_`]*)_%s' % \ 346 (inline_tag_begin, inline_tag_end), 347 } 348
349 -class Doconce(_BaseWriter):
350 - def __init__(self):
351 _BaseWriter.__init__(self, 'Doconce', '.do.txt')
352
353 - def title(self, title, authors_and_institutions=[], date='today'):
354 s = '\nTITLE: %s\n' % title 355 for ai in authors_and_institutions: 356 authorinfo = '; '.join(ai) 357 s += 'AUTHOR: %s\n' % authorinfo 358 if date is not None: 359 if date == 'today': 360 date = self.today_date() 361 s += 'DATE: %s\n' % date 362 self.file.write(s) 363 self.paragraph_separator()
364
365 - def heading(self, underscores, title, label=None):
366 underscores = '_'*underscores 367 self.file.write('\n%s%s%s\n\n' % (underscores, title, underscores))
368
369 - def section(self, title, label=None):
370 self.heading(7, title, label)
371
372 - def subsection(self, title, label=None):
373 self.heading(5, title, label)
374
375 - def subsubsection(self, title, label=None):
376 self.heading(3, title, label)
377
378 - def paragraph(self, title, ending='.', label=None):
379 s = '\n\n__%s%s__ ' % (title, ending) 380 self.file.write(s)
381
382 - def paragraph_separator(self):
383 self.file.write('\n\n')
384
385 - def text(self, text, indent=0):
386 text = _BaseWriter.text(self, text, indent) 387 # not necessary since Doconce is the format for text: 388 #text = _BaseWriter.expandtext(self, text, 389 # INLINE_TAGS, HTML.INLINE_TAGS_SUBST) 390 self.file.write(text)
391
392 - def list(self, items, listtype='itemize'):
393 self.unfold_list(items, self.item_handler, listtype)
394
395 - def item_handler(self, item, listtype, level, keyword=None):
396 indent = ' '*level 397 s = '' 398 if item == '_begin': 399 if level == 1: 400 s += '\n' 401 elif item == '_end': 402 if level == 1: 403 s += '\n' 404 else: 405 # ordinary item: 406 if item is not None: 407 if listtype == 'itemize': 408 s += '\n%s%s* %s' % (indent, indent, item) 409 elif listtype == 'enumerate': 410 s += '\n%s%so %s' % (indent, indent, item) 411 elif listtype == 'description': 412 s += '\n%s%s- %s: %s' % (indent, indent, keyword, item) 413 self.file.write(s)
414
415 - def verbatim(self, code):
416 self.file.write('\n!bc\n' + r'%s' % code + '\n!ec\n')
417
418 - def figure(self, filename, caption, width=None, height=None, label=None):
419 filename = self.figure_conversion(filename, \ 420 ('.jpg', '.gif', '.png', '.ps', '.eps')) 421 s = '\nFIGURE:[%s,' % filename 422 if width: 423 s += ' width=%s ' % width 424 if height: 425 s += ' height=%s ' % width 426 s += '] ' + caption + '\n' 427 self.file.write(s)
428
429 - def table(self, table, column_headline_pos='c', column_pos='c'):
430 # find max column width 431 mcw = 0 432 for row in table: 433 mcw = max(mcw, max([len(str(c)) for c in row])) 434 formatted_table = [] # table where all columns have equal width 435 column_format = '%%-%ds' % mcw 436 for row in table: 437 formatted_table.append([column_format % c for c in row]) 438 width = len(' | '.join(formatted_table[0])) + 4 439 s = '\n\n |' + '-'*(width-2) + '|\n' 440 for row in formatted_table: 441 s += ' | ' + ' | '.join(row) + ' |\n' 442 s += ' |' + '-'*(width-2) + '|\n\n' 443 self.file.write(s)
444
445 - def url(self, url_address, link_text=None):
446 if link_text is None: 447 link_text = 'link' # problems with Doconce and empty link text 448 self.file.write(' %s<%s>' % (url_address, link_text))
449 452 453 # autogenerate doc strings by combining parent class doc strings 454 # with subclass doc strings: 455 for method in [title, section, subsection, subsubsection, 456 paragraph, text, 457 verbatim, # not defined here: math, raw, 458 figure, table, url, 459 list, item_handler,]: 460 method.__doc__ = makedocstr(_BaseWriter, method)
461 462 463
464 -class HTML(_BaseWriter):
465 # class variables: 466 table_border = '2' 467 table_cellpadding = '5' 468 table_cellspacing = '2' 469 470 INLINE_TAGS_SUBST = { # from inline tags to HTML tags 471 # keep math as is: 472 'math': None, # indicates no substitution 473 'math2': r'\g<begin>\g<puretext>\g<end>', 474 'emphasize': r'\g<begin><em>\g<subst></em>\g<end>', 475 'bold': r'\g<begin><b>\g<subst></b>\g<end>', 476 'verbatim': r'\g<begin><tt>\g<subst></tt>\g<end>', 477 } 478
479 - def __init__(self):
480 _BaseWriter.__init__(self, 'html', '.html') 481 self.header()
482
483 - def header(self):
484 s = """\ 485 <!-- HTML document generated by %s.%s --> 486 <html> 487 <body bgcolor="white"> 488 """ % (__name__, self.__class__.__name__) 489 self.file.write(s)
490
491 - def footer(self):
492 s = """ 493 </body> 494 </html> 495 """ 496 self.file.write(s)
497
498 - def title(self, title, authors_and_institutions=[], date='today'):
499 s = """ 500 <title>%s</title> 501 <center><h1>%s</h1></center> 502 """ % (title, title) 503 for ai in authors_and_institutions: 504 author = ai[0] 505 s += """ 506 <center> 507 <h4>%s</h4>""" % author 508 for inst in ai[1:]: 509 s += """ 510 <h6>%s</h6>""" % inst 511 s += """\n</center>\n\n""" 512 if date is not None: 513 if date == 'today': 514 date = self.today_date() 515 s += """<center>%s</center>\n\n\n""" % date 516 self.file.write(s) 517 self.paragraph_separator()
518
519 - def heading(self, level, title, label=None):
520 if label is None: 521 s = """\n<h%d>%s</h%d>\n""" % (level, title, level) 522 else: 523 s = """\n<h%d><a href="%s">%s</h%d>\n""" % \ 524 (level, label, title, level) 525 self.file.write(s)
526
527 - def section(self, title, label=None):
528 self.heading(1, title, label)
529
530 - def subsection(self, title, label=None):
531 self.heading(3, title, label)
532
533 - def subsubsection(self, title, label=None):
534 self.heading(4, title, label)
535
536 - def paragraph(self, title, ending='.', label=None):
537 s = '\n\n<p><!-- paragraph with heading -->\n<b>%s%s</b>\n' \ 538 % (title, ending) 539 if label is not None: 540 s += '<a name="%s">\n' % label 541 self.file.write(s)
542
543 - def paragraph_separator(self):
544 self.file.write('\n<p>\n')
545
546 - def text(self, text, indent=0):
547 text = _BaseWriter.text(self, text, indent) 548 text = _BaseWriter.expandtext(self, text, 549 INLINE_TAGS, HTML.INLINE_TAGS_SUBST) 550 self.file.write(text)
551
552 - def list(self, items, listtype='itemize'):
553 self.unfold_list(items, self.item_handler, listtype)
554
555 - def item_handler(self, item, listtype, level, keyword=None):
556 indent = ' '*level 557 s = '' 558 if item == '_begin': 559 if listtype == 'itemize': 560 s += '\n%s<ul>' % indent 561 elif listtype == 'enumerate': 562 s += '\n%s<ol>' % indent 563 elif listtype == 'description': 564 s += '\n%s<dl>' % indent 565 s += ' <!-- start of "%s" list -->\n' % listtype 566 elif item == '_end': 567 if listtype == 'itemize': 568 s += '%s</ul>' % indent 569 elif listtype == 'enumerate': 570 s += '%s</ol>' % indent 571 elif listtype == 'description': 572 s += '%s</dl>' % indent 573 s += ' <!-- end of "%s" list -->\n' % listtype 574 else: 575 # ordinary item: 576 if item is not None: 577 if listtype in ('itemize', 'enumerate'): 578 s += '%s%s<p><li> %s\n' % (indent, indent, item) 579 else: 580 s += '%s%s<p><dt>%s</dt><dd>%s</dd>\n' % \ 581 (indent, indent, keyword, item) 582 self.file.write(s)
583
584 - def verbatim(self, code):
585 self.file.write('\n<pre>' + r'%s' % code + '\n</pre>\n')
586
587 - def figure(self, filename, caption, width=None, height=None, label=None):
588 filename = self.figure_conversion(filename, ('.jpg', '.gif', '.png')) 589 if width: 590 width = ' width=%s ' % width 591 else: 592 width = '' 593 if height: 594 height = ' width=%s ' % width 595 else: 596 height = '' 597 s = '\n<hr><img src="%s"%s%s>\n<p><em>%s</em>\n<hr><p>\n' % \ 598 (filename, width, height, caption) 599 self.file.write(s)
600
601 - def table(self, table, column_headline_pos='c', column_pos='c'):
602 s = '\n<p>\n<table border="%s" cellpadding="%s" cellspacing="%s">\n' %\ 603 (HTML.table_border, HTML.table_cellpadding, HTML.table_cellspacing) 604 for line in table: 605 s += '<tr>' 606 for column in line: 607 s += '<td>%s</td>' % column 608 s += '</tr>\n' 609 s += '</table>\n\n' 610 self.file.write(s)
611
612 - def url(self, url_address, link_text=None):
613 if link_text is None: 614 link_text = url_address 615 self.file.write('\n<a href="%s">%s</a>\n' % (url_address, link_text))
616 619 620 # autogenerate doc strings by combining parent class doc strings 621 # with subclass doc strings: 622 for method in [title, section, subsection, subsubsection, 623 paragraph, text, 624 verbatim, # not defined here: math, raw, 625 figure, table, url, 626 list, item_handler,]: 627 method.__doc__ = makedocstr(_BaseWriter, method)
628 629
630 -class LaTeX(_BaseWriter):
631 - def __init__(self):
632 raise NotImplementedError, \ 633 'Use Doconce class instead and filter to LaTeX'
634 635 # Efficient way of generating class DocWriter. 636 # A better way (for pydoc and other API references) is to 637 # explicitly list all methods and their arguments and then add 638 # the body for writer in self.writers: writer.method(arg1, arg2, ...) 639
640 -class DocWriter:
641 """ 642 DocWriter can write documents in several formats at once. 643 """ 644 methods = 'title', 'section', 'subsection', 'subsubsection', \ 645 'paragraph', 'paragraph_separator', 'text', 'list', \ 646 'verbatim', 'math', 'raw', 'url', 'link', \ 647 'write_to_file', 'figure', 'table', 648 649
650 - def __init__(self, *formats):
651 """ 652 @param formats: sequence of strings specifying the desired formats. 653 """ 654 self.writers = [eval(format)() for format in formats]
655
656 - def documents(self):
657 return [writer.document for writer in self.writers]
658
659 - def __str__(self):
660 s = '' 661 for writer in self.writers: 662 s += '*'*60 + \ 663 '\nDocWriter: format=%s (without footer)\n' % \ 664 writer.__class__.__name__ + '*'*60 665 s += str(writer) 666 return s
667
668 - def dispatcher(self, *args, **kwargs):
669 #print 'in dispatcher for', self.method_name, 'with args', args, kwargs 670 #self.history = (self.method_name, args, kwargs) 671 for writer in self.writers: 672 s = getattr(writer, self.method_name)(*args, **kwargs)
673 674 ''' 675 Alternative to attaching separate global functions: 676 def __getattribute__(self, name): 677 print 'calling __getattribute__ with', name 678 if name in DocWriter.methods: 679 self.method_name = name 680 return self.dispatcher 681 else: 682 return object.__getattribute__(self, name) 683 684 # can use inspect module to extract doc of all methods and 685 # put this doc in __doc__ 686 '''
687 688 # Autogenerate methods in class DocWriter (with right 689 # method signature and doc strings stolen from class _BaseWriter (!)): 690 691 import inspect 692
693 -def func_to_method(func, class_, method_name=None):
694 setattr(class_, method_name or func.__name__, func)
695 696 for method in DocWriter.methods: 697 docstring = eval('_BaseWriter.%s.__doc__' % method) 698 # extract function signature: 699 a = inspect.getargspec(eval('_BaseWriter.%s' % method)) 700 if a[3] is not None: # keyword arguments? 701 kwargs = ['%s=%r' % (arg, value) \ 702 for arg, value in zip(a[0][-len(a[3]):], a[3])] 703 args = a[0][:-len(a[3])] 704 allargs = args + kwargs 705 else: 706 allargs = a[0] 707 #print method, allargs, '\n', a 708 signature_def = '%s(%s)' % (method, ', '.join(allargs)) 709 signature_call = '%s(%s)' % (method, ', '.join(a[0][1:])) # exclude self 710 code = """\ 711 def _%s: 712 '''\ 713 %s 714 ''' 715 for writer in self.writers: 716 writer.%s 717 718 func_to_method(_%s, DocWriter, '%s') 719 """ % (signature_def, docstring, signature_call, method, method) 720 #print 'Autogenerating\n', code 721 exec code 722
723 -def html_movie(plotfiles, interval_ms=300, width=800, height=600, 724 casename='movie'):
725 """ 726 Takes a list plotfiles which should be for example of the form:: 727 728 ['frame00.png', 'frame01.png', ... ] 729 730 where each string should be the name of an image file and they should be 731 in the proper order for viewing as an animation. 732 733 The result is html text strings that incorporate javascript to 734 loop through the plots one after another. The html text also features 735 buttons for controlling the movie. 736 The parameter iterval_ms is the time interval between loading 737 successive images and is in milliseconds. 738 739 The width and height parameters do not seem to have any effect 740 for reasons not understood. 741 742 The following strings are returned: header, javascript code, form 743 with movie and buttons, and footer. Concatenating these strings 744 and dumping to an html file yields a kind of movie file to be 745 viewed in a browser. The images variable in the javascript code 746 is unique for each movie, because it is annotated by the casename 747 string, so several such javascript sections can be used in the 748 same html file. 749 750 This function is based on code written by R.J. LeVeque, based on 751 a template from Alan McIntyre. 752 """ 753 import os 754 if not isinstance(plotfiles, (tuple,list)): 755 raise TypeError('html_movie: plotfiles=%s of wrong type %s' % 756 (str(plotfiles), type(plotfiles))) 757 # Check that the plot files really exist 758 missing_files = [fname for fname in plotfiles if not os.path.isfile(fname)] 759 if missing_files: 760 raise ValueError('Missing plot files: %s' % str(missing_files)[1:-1]) 761 762 ext = os.path.splitext(plotfiles[0])[-1] 763 if ext == '.png' or ext == '.jpg' or ext == '.jpeg' or ext == 'gif': 764 pass 765 else: 766 raise ValueError('Plotfiles (%s, ...) must be PNG files with '\ 767 'extension .png' % plotfiles[0]) 768 header = """\ 769 <html> 770 <head> 771 </head> 772 <body> 773 """ 774 no_images = len(plotfiles) 775 jscode = """ 776 <script language="Javascript"> 777 <!--- 778 var num_images_%(casename)s = %(no_images)d; 779 var img_width = %(width)d; 780 var img_height = %(height)d; 781 var interval = %(interval_ms)d; 782 var images_%(casename)s = new Array(); 783 784 function preload_images_%(casename)s() 785 { 786 t = document.getElementById("progress"); 787 """ % vars() 788 789 i = 0 790 for fname in plotfiles: 791 jscode += """ 792 t.innerHTML = "Preloading image "; 793 images_%(casename)s[%(i)s] = new Image(img_width, img_height); 794 images_%(casename)s[%(i)s].src = "%(fname)s"; 795 """ % vars() 796 i = i+1 797 jscode += """ 798 t.innerHTML = ""; 799 } 800 801 function tick_%(casename)s() 802 { 803 if (frame_%(casename)s > num_images_%(casename)s - 1) 804 frame_%(casename)s = 0; 805 806 document.movie.src = images_%(casename)s[frame_%(casename)s].src; 807 frame_%(casename)s += 1; 808 tt = setTimeout("tick_%(casename)s()", interval); 809 } 810 811 function startup_%(casename)s() 812 { 813 preload_images_%(casename)s(); 814 frame_%(casename)s = 0; 815 setTimeout("tick_%(casename)s()", interval); 816 } 817 818 function stopit() 819 { clearTimeout(tt); } 820 821 function restart_%(casename)s() 822 { tt = setTimeout("tick_%(casename)s()", interval); } 823 824 function slower() 825 { interval = interval/0.7; } 826 827 function faster() 828 { interval = interval*0.7; } 829 830 // ---> 831 </script> 832 """ % vars() 833 plotfile0 = plotfiles[0] 834 form = """ 835 <form> 836 &nbsp; 837 <input type="button" value="Start movie" onClick="startup_%(casename)s()"> 838 <input type="button" value="Pause movie" onClick="stopit()"> 839 <input type="button" value="Restart movie" onClick="restart_%(casename)s()"> 840 &nbsp; 841 <input type="button" value="Slower" onClick="slower()"> 842 <input type="button" value="Faster" onClick="faster()"> 843 </form> 844 845 <p><div ID="progress"></div></p> 846 <img src="%(plotfile0)s" name="movie" border=2/> 847 """ % vars() 848 footer = '\n</body>\n</html>\n' 849 return header, jscode, form, footer
850
851 -def html_movie_embed(moviefile, width=400, height=400):
852 """ 853 Return HTML for embedding a moviefile using the default 854 handling of such files. 855 """ 856 text = """ 857 <embed src="%(moviefile)s" 858 width="%(width)s" 859 height="%(height)s" 860 autoplay="false" 861 loop="true"> 862 </embed> 863 """ % vars() 864 return text
865
866 -def html_movie_embed_wmp(moviefile, width=400, height=400):
867 """Return HTML text for embedding a movie file 868 (Windows Media Player code).""" 869 text = """ 870 <object id="MediaPlayer1" width="180" height="200" 871 classid="CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95" 872 codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701" 873 standby="Loading Microsoft Windows Media Player components..." 874 type="application/x-oleobject" align="middle"> 875 <param name="FileName" value="%(moviefile)s"> 876 <param name="ShowStatusBar" value="True"> 877 <param name="DefaultFrame" value="mainFrame"> 878 <param name="autostart" value="false"> 879 <embed type="application/x-mplayer2" 880 pluginspage = "http://www.microsoft.com/Windows/MediaPlayer/" 881 src="%(moviefile)s" 882 autostart="false" 883 align="middle" 884 width="%(width)s" 885 height="%(height)s" 886 loop="100" 887 defaultframe="rightFrame" 888 showstatusbar="true"> 889 </embed> 890 </object> 891 <!-- 892 <a href="%(moviefile)s"><font size="2">Download movie file</font></a> 893 <a href="http://www.microsoft.com/windows/windowsmedia/mp10/default.aspx"> 894 <font size="1">Download Windows Media Player</font></a></p> 895 --> 896 <!-- 897 Attributes of the <embed> tag are: 898 src - tells what file to use. 899 autostart="true" - tells the computer to start the Video playing upon loading the page. 900 autostart="false" - tells the computer not to start the Video playing upon loading the page. You must click the start button to make the Video play. 901 align=middle - tells the computer to put the start/stop buttons to the middle. 902 width= and height= - are the dimensions of a small button panel that will appear when the page loads and contains both a START & STOP button so the visitor can start/stop the Video. 903 loop=2 - will play the Video for two complete loops. 904 --> 905 """ % vars() 906 return text
907
908 -def html_movie_embed_qt(moviefile, width=400, height=400):
909 """Return HTML for embedding a moviefile (QuickTime code).""" 910 text = """ 911 <object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" 912 codebase="http://www.apple.com/qtactivex/qtplugin.cab" 913 width="%(width)s" height="%(height)s" > 914 <param name="src" value="%(moviefile)s" > 915 <param name="autoplay" value="false" > 916 <embed src="%(moviefile)s" 917 pluginspage="http://www.apple.com/quicktime/download" 918 width="%(width)s" height="%(height)s" autoplay="false"> 919 </embed> 920 </object> 921 """ % vars() 922 return text
923 924 925
926 -def _test(d):
927 # d is formatclass() or DocWriter(HTML, LaTeX, ...) 928 print '\n\n', '*'*70, \ 929 '\n*** Testing class "%s"\n' % d.__class__.__name__, '*'*70 930 931 d.title('My Test of Class %s' % d.__class__.__name__, 932 [('Hans Petter Langtangen', 933 'Simula Research Laboratory', 934 'Dept. of Informatics, Univ. of Oslo'), 935 ]) 936 d.section('First Section') 937 d.text(""" 938 Here is some 939 text for section 1. 940 941 This is a *first* example of using the _DocWriter 942 module_ for writing documents from *Python* scripts. 943 It could be a nice tool since we do not need to bother 944 with special typesetting, such as `fixed width fonts` 945 in plain text. 946 """) 947 d.subsection('First Subsection') 948 d.text('Some text for the subsection.') 949 d.paragraph('Test of a Paragraph') 950 d.text(""" 951 Some paragraph text taken from "Documenting Python": The Python language 952 has a substantial body of documentation, much of it contributed by various 953 authors. The markup used for the Python documentation is based on 954 LaTeX and requires a significant set of macros written specifically 955 for documenting Python. This document describes the macros introduced 956 to support Python documentation and how they should be used to support 957 a wide range of output formats. 958 959 This document describes the document classes and special markup used 960 in the Python documentation. Authors may use this guide, in 961 conjunction with the template files provided with the distribution, to 962 create or maintain whole documents or sections. 963 964 If you're interested in contributing to Python's documentation, 965 there's no need to learn LaTeX if you're not so inclined; plain text 966 contributions are more than welcome as well. 967 """) 968 d.text('Here is an enumerate list:') 969 samplelist = ['item1', 'item2', 970 ['subitem1', 'subitem2'], 971 'item3', 972 ['subitem3', 'subitem4']] 973 d.list(samplelist, listtype='enumerate') 974 d.text('...with some trailing text.') 975 d.subsubsection('First Subsubsection with an Itemize List') 976 d.list(samplelist, listtype='itemize') 977 d.text('Here is some Python code:') 978 d.verbatim(""" 979 class A: 980 pass 981 982 class B(A): 983 pass 984 985 b = B() 986 b.item = 0 # create a new attribute 987 """) 988 d.section('Second Section') 989 d.text('Here is a description list:') 990 d.list(['keyword1: item1', 'keyword2: item2 goes here, with a colon : and some text after', 991 ['key3: subitem1', 'key4: subitem2'], 992 'key5: item3', 993 ['key6: subitem3', 'key7: subitem4']], 994 listtype='description') 995 d.paragraph_separator() 996 d.text('And here is a table:') 997 d.table([['a', 'b'], ['c', 'd'], ['e', 'and a longer text']]) 998 print d 999 d.write_to_file('tmp_%s' % d.__class__.__name__)
1000 1001 if __name__ == '__main__': 1002 formats = HTML, Doconce 1003 for format in formats: 1004 d = format() 1005 _test(d) 1006 formats_str = [format.__name__ for format in formats] 1007 d = DocWriter(*formats_str) 1008 _test(d) 1009