__init__.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. # copyright 2003-2011 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
  2. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
  3. #
  4. # This file is part of logilab-common.
  5. #
  6. # logilab-common is free software: you can redistribute it and/or modify it under
  7. # the terms of the GNU Lesser General Public License as published by the Free
  8. # Software Foundation, either version 2.1 of the License, or (at your option) any
  9. # later version.
  10. #
  11. # logilab-common is distributed in the hope that it will be useful, but WITHOUT
  12. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  13. # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
  14. # details.
  15. #
  16. # You should have received a copy of the GNU Lesser General Public License along
  17. # with logilab-common. If not, see <http://www.gnu.org/licenses/>.
  18. """Universal report objects and some formatting drivers.
  19. A way to create simple reports using python objects, primarily designed to be
  20. formatted as text and html.
  21. """
  22. from __future__ import generators
  23. __docformat__ = "restructuredtext en"
  24. import sys
  25. from cStringIO import StringIO
  26. from StringIO import StringIO as UStringIO
  27. from logilab.common.textutils import linesep
  28. def get_nodes(node, klass):
  29. """return an iterator on all children node of the given klass"""
  30. for child in node.children:
  31. if isinstance(child, klass):
  32. yield child
  33. # recurse (FIXME: recursion controled by an option)
  34. for grandchild in get_nodes(child, klass):
  35. yield grandchild
  36. def layout_title(layout):
  37. """try to return the layout's title as string, return None if not found
  38. """
  39. for child in layout.children:
  40. if isinstance(child, Title):
  41. return ' '.join([node.data for node in get_nodes(child, Text)])
  42. def build_summary(layout, level=1):
  43. """make a summary for the report, including X level"""
  44. assert level > 0
  45. level -= 1
  46. summary = List(klass='summary')
  47. for child in layout.children:
  48. if not isinstance(child, Section):
  49. continue
  50. label = layout_title(child)
  51. if not label and not child.id:
  52. continue
  53. if not child.id:
  54. child.id = label.replace(' ', '-')
  55. node = Link('#'+child.id, label=label or child.id)
  56. # FIXME: Three following lines produce not very compliant
  57. # docbook: there are some useless <para><para>. They might be
  58. # replaced by the three commented lines but this then produces
  59. # a bug in html display...
  60. if level and [n for n in child.children if isinstance(n, Section)]:
  61. node = Paragraph([node, build_summary(child, level)])
  62. summary.append(node)
  63. # summary.append(node)
  64. # if level and [n for n in child.children if isinstance(n, Section)]:
  65. # summary.append(build_summary(child, level))
  66. return summary
  67. class BaseWriter(object):
  68. """base class for ureport writers"""
  69. def format(self, layout, stream=None, encoding=None):
  70. """format and write the given layout into the stream object
  71. unicode policy: unicode strings may be found in the layout;
  72. try to call stream.write with it, but give it back encoded using
  73. the given encoding if it fails
  74. """
  75. if stream is None:
  76. stream = sys.stdout
  77. if not encoding:
  78. encoding = getattr(stream, 'encoding', 'UTF-8')
  79. self.encoding = encoding or 'UTF-8'
  80. self.__compute_funcs = []
  81. self.out = stream
  82. self.begin_format(layout)
  83. layout.accept(self)
  84. self.end_format(layout)
  85. def format_children(self, layout):
  86. """recurse on the layout children and call their accept method
  87. (see the Visitor pattern)
  88. """
  89. for child in getattr(layout, 'children', ()):
  90. child.accept(self)
  91. def writeln(self, string=''):
  92. """write a line in the output buffer"""
  93. self.write(string + linesep)
  94. def write(self, string):
  95. """write a string in the output buffer"""
  96. try:
  97. self.out.write(string)
  98. except UnicodeEncodeError:
  99. self.out.write(string.encode(self.encoding))
  100. def begin_format(self, layout):
  101. """begin to format a layout"""
  102. self.section = 0
  103. def end_format(self, layout):
  104. """finished to format a layout"""
  105. def get_table_content(self, table):
  106. """trick to get table content without actually writing it
  107. return an aligned list of lists containing table cells values as string
  108. """
  109. result = [[]]
  110. cols = table.cols
  111. for cell in self.compute_content(table):
  112. if cols == 0:
  113. result.append([])
  114. cols = table.cols
  115. cols -= 1
  116. result[-1].append(cell)
  117. # fill missing cells
  118. while len(result[-1]) < cols:
  119. result[-1].append('')
  120. return result
  121. def compute_content(self, layout):
  122. """trick to compute the formatting of children layout before actually
  123. writing it
  124. return an iterator on strings (one for each child element)
  125. """
  126. # use cells !
  127. def write(data):
  128. try:
  129. stream.write(data)
  130. except UnicodeEncodeError:
  131. stream.write(data.encode(self.encoding))
  132. def writeln(data=''):
  133. try:
  134. stream.write(data+linesep)
  135. except UnicodeEncodeError:
  136. stream.write(data.encode(self.encoding)+linesep)
  137. self.write = write
  138. self.writeln = writeln
  139. self.__compute_funcs.append((write, writeln))
  140. for child in layout.children:
  141. stream = UStringIO()
  142. child.accept(self)
  143. yield stream.getvalue()
  144. self.__compute_funcs.pop()
  145. try:
  146. self.write, self.writeln = self.__compute_funcs[-1]
  147. except IndexError:
  148. del self.write
  149. del self.writeln
  150. from logilab.common.ureports.nodes import *
  151. from logilab.common.ureports.text_writer import TextWriter
  152. from logilab.common.ureports.html_writer import HTMLWriter