1#!/usr/bin/env python3
2# -*- coding: utf-8; mode: python -*-
3# pylint: disable=C0330, R0903, R0912
4
5u"""
6    flat-table
7    ~~~~~~~~~~
8
9    Implementation of the ``flat-table`` reST-directive.
10
11    :copyright:  Copyright (C) 2016  Markus Heiser
12    :license:    GPL Version 2, June 1991 see linux/COPYING for details.
13
14    The ``flat-table`` (:py:class:`FlatTable`) is a double-stage list similar to
15    the ``list-table`` with some additional features:
16
17    * *column-span*: with the role ``cspan`` a cell can be extended through
18      additional columns
19
20    * *row-span*: with the role ``rspan`` a cell can be extended through
21      additional rows
22
23    * *auto span* rightmost cell of a table row over the missing cells on the
24      right side of that table-row.  With Option ``:fill-cells:`` this behavior
25      can changed from *auto span* to *auto fill*, which automaticly inserts
26      (empty) cells instead of spanning the last cell.
27
28    Options:
29
30    * header-rows:   [int] count of header rows
31    * stub-columns:  [int] count of stub columns
32    * widths:        [[int] [int] ... ] widths of columns
33    * fill-cells:    instead of autospann missing cells, insert missing cells
34
35    roles:
36
37    * cspan: [int] additionale columns (*morecols*)
38    * rspan: [int] additionale rows (*morerows*)
39"""
40
41# ==============================================================================
42# imports
43# ==============================================================================
44
45import sys
46
47from docutils import nodes
48from docutils.parsers.rst import directives, roles
49from docutils.parsers.rst.directives.tables import Table
50from docutils.utils import SystemMessagePropagation
51
52# ==============================================================================
53# common globals
54# ==============================================================================
55
56# The version numbering follows numbering of the specification
57# (Documentation/books/kernel-doc-HOWTO).
58__version__  = '1.0'
59
60PY3 = sys.version_info[0] == 3
61PY2 = sys.version_info[0] == 2
62
63if PY3:
64    # pylint: disable=C0103, W0622
65    unicode     = str
66    basestring  = str
67
68# ==============================================================================
69def setup(app):
70# ==============================================================================
71
72    app.add_directive("flat-table", FlatTable)
73    roles.register_local_role('cspan', c_span)
74    roles.register_local_role('rspan', r_span)
75
76    return dict(
77        version = __version__,
78        parallel_read_safe = True,
79        parallel_write_safe = True
80    )
81
82# ==============================================================================
83def c_span(name, rawtext, text, lineno, inliner, options=None, content=None):
84# ==============================================================================
85    # pylint: disable=W0613
86
87    options  = options if options is not None else {}
88    content  = content if content is not None else []
89    nodelist = [colSpan(span=int(text))]
90    msglist  = []
91    return nodelist, msglist
92
93# ==============================================================================
94def r_span(name, rawtext, text, lineno, inliner, options=None, content=None):
95# ==============================================================================
96    # pylint: disable=W0613
97
98    options  = options if options is not None else {}
99    content  = content if content is not None else []
100    nodelist = [rowSpan(span=int(text))]
101    msglist  = []
102    return nodelist, msglist
103
104
105# ==============================================================================
106class rowSpan(nodes.General, nodes.Element): pass # pylint: disable=C0103,C0321
107class colSpan(nodes.General, nodes.Element): pass # pylint: disable=C0103,C0321
108# ==============================================================================
109
110# ==============================================================================
111class FlatTable(Table):
112# ==============================================================================
113
114    u"""FlatTable (``flat-table``) directive"""
115
116    option_spec = {
117        'name': directives.unchanged
118        , 'class': directives.class_option
119        , 'header-rows': directives.nonnegative_int
120        , 'stub-columns': directives.nonnegative_int
121        , 'widths': directives.positive_int_list
122        , 'fill-cells' : directives.flag }
123
124    def run(self):
125
126        if not self.content:
127            error = self.state_machine.reporter.error(
128                'The "%s" directive is empty; content required.' % self.name,
129                nodes.literal_block(self.block_text, self.block_text),
130                line=self.lineno)
131            return [error]
132
133        title, messages = self.make_title()
134        node = nodes.Element()          # anonymous container for parsing
135        self.state.nested_parse(self.content, self.content_offset, node)
136
137        tableBuilder = ListTableBuilder(self)
138        tableBuilder.parseFlatTableNode(node)
139        tableNode = tableBuilder.buildTableNode()
140        # SDK.CONSOLE()  # print --> tableNode.asdom().toprettyxml()
141        if title:
142            tableNode.insert(0, title)
143        return [tableNode] + messages
144
145
146# ==============================================================================
147class ListTableBuilder(object):
148# ==============================================================================
149
150    u"""Builds a table from a double-stage list"""
151
152    def __init__(self, directive):
153        self.directive = directive
154        self.rows      = []
155        self.max_cols  = 0
156
157    def buildTableNode(self):
158
159        colwidths    = self.directive.get_column_widths(self.max_cols)
160        stub_columns = self.directive.options.get('stub-columns', 0)
161        header_rows  = self.directive.options.get('header-rows', 0)
162
163        table = nodes.table()
164        tgroup = nodes.tgroup(cols=len(colwidths))
165        table += tgroup
166
167
168        for colwidth in colwidths:
169            colspec = nodes.colspec(colwidth=colwidth)
170            # FIXME: It seems, that the stub method only works well in the
171            # absence of rowspan (observed by the html buidler, the docutils-xml
172            # build seems OK).  This is not extraordinary, because there exists
173            # no table directive (except *this* flat-table) which allows to
174            # define coexistent of rowspan and stubs (there was no use-case
175            # before flat-table). This should be reviewed (later).
176            if stub_columns:
177                colspec.attributes['stub'] = 1
178                stub_columns -= 1
179            tgroup += colspec
180        stub_columns = self.directive.options.get('stub-columns', 0)
181
182        if header_rows:
183            thead = nodes.thead()
184            tgroup += thead
185            for row in self.rows[:header_rows]:
186                thead += self.buildTableRowNode(row)
187
188        tbody = nodes.tbody()
189        tgroup += tbody
190
191        for row in self.rows[header_rows:]:
192            tbody += self.buildTableRowNode(row)
193        return table
194
195    def buildTableRowNode(self, row_data, classes=None):
196        classes = [] if classes is None else classes
197        row = nodes.row()
198        for cell in row_data:
199            if cell is None:
200                continue
201            cspan, rspan, cellElements = cell
202
203            attributes = {"classes" : classes}
204            if rspan:
205                attributes['morerows'] = rspan
206            if cspan:
207                attributes['morecols'] = cspan
208            entry = nodes.entry(**attributes)
209            entry.extend(cellElements)
210            row += entry
211        return row
212
213    def raiseError(self, msg):
214        error =  self.directive.state_machine.reporter.error(
215            msg
216            , nodes.literal_block(self.directive.block_text
217                                  , self.directive.block_text)
218            , line = self.directive.lineno )
219        raise SystemMessagePropagation(error)
220
221    def parseFlatTableNode(self, node):
222        u"""parses the node from a :py:class:`FlatTable` directive's body"""
223
224        if len(node) != 1 or not isinstance(node[0], nodes.bullet_list):
225            self.raiseError(
226                'Error parsing content block for the "%s" directive: '
227                'exactly one bullet list expected.' % self.directive.name )
228
229        for rowNum, rowItem in enumerate(node[0]):
230            row = self.parseRowItem(rowItem, rowNum)
231            self.rows.append(row)
232        self.roundOffTableDefinition()
233
234    def roundOffTableDefinition(self):
235        u"""Round off the table definition.
236
237        This method rounds off the table definition in :py:member:`rows`.
238
239        * This method inserts the needed ``None`` values for the missing cells
240        arising from spanning cells over rows and/or columns.
241
242        * recount the :py:member:`max_cols`
243
244        * Autospan or fill (option ``fill-cells``) missing cells on the right
245          side of the table-row
246        """
247
248        y = 0
249        while y < len(self.rows):
250            x = 0
251
252            while x < len(self.rows[y]):
253                cell = self.rows[y][x]
254                if cell is None:
255                    x += 1
256                    continue
257                cspan, rspan = cell[:2]
258                # handle colspan in current row
259                for c in range(cspan):
260                    try:
261                        self.rows[y].insert(x+c+1, None)
262                    except: # pylint: disable=W0702
263                        # the user sets ambiguous rowspans
264                        pass # SDK.CONSOLE()
265                # handle colspan in spanned rows
266                for r in range(rspan):
267                    for c in range(cspan + 1):
268                        try:
269                            self.rows[y+r+1].insert(x+c, None)
270                        except: # pylint: disable=W0702
271                            # the user sets ambiguous rowspans
272                            pass # SDK.CONSOLE()
273                x += 1
274            y += 1
275
276        # Insert the missing cells on the right side. For this, first
277        # re-calculate the max columns.
278
279        for row in self.rows:
280            if self.max_cols < len(row):
281                self.max_cols = len(row)
282
283        # fill with empty cells or cellspan?
284
285        fill_cells = False
286        if 'fill-cells' in self.directive.options:
287            fill_cells = True
288
289        for row in self.rows:
290            x =  self.max_cols - len(row)
291            if x and not fill_cells:
292                if row[-1] is None:
293                    row.append( ( x - 1, 0, []) )
294                else:
295                    cspan, rspan, content = row[-1]
296                    row[-1] = (cspan + x, rspan, content)
297            elif x and fill_cells:
298                for i in range(x):
299                    row.append( (0, 0, nodes.comment()) )
300
301    def pprint(self):
302        # for debugging
303        retVal = "[   "
304        for row in self.rows:
305            retVal += "[ "
306            for col in row:
307                if col is None:
308                    retVal += ('%r' % col)
309                    retVal += "\n    , "
310                else:
311                    content = col[2][0].astext()
312                    if len (content) > 30:
313                        content = content[:30] + "..."
314                    retVal += ('(cspan=%s, rspan=%s, %r)'
315                               % (col[0], col[1], content))
316                    retVal += "]\n    , "
317            retVal = retVal[:-2]
318            retVal += "]\n  , "
319        retVal = retVal[:-2]
320        return retVal + "]"
321
322    def parseRowItem(self, rowItem, rowNum):
323        row = []
324        childNo = 0
325        error   = False
326        cell    = None
327        target  = None
328
329        for child in rowItem:
330            if (isinstance(child , nodes.comment)
331                or isinstance(child, nodes.system_message)):
332                pass
333            elif isinstance(child , nodes.target):
334                target = child
335            elif isinstance(child, nodes.bullet_list):
336                childNo += 1
337                cell = child
338            else:
339                error = True
340                break
341
342        if childNo != 1 or error:
343            self.raiseError(
344                'Error parsing content block for the "%s" directive: '
345                'two-level bullet list expected, but row %s does not '
346                'contain a second-level bullet list.'
347                % (self.directive.name, rowNum + 1))
348
349        for cellItem in cell:
350            cspan, rspan, cellElements = self.parseCellItem(cellItem)
351            if target is not None:
352                cellElements.insert(0, target)
353            row.append( (cspan, rspan, cellElements) )
354        return row
355
356    def parseCellItem(self, cellItem):
357        # search and remove cspan, rspan colspec from the first element in
358        # this listItem (field).
359        cspan = rspan = 0
360        if not len(cellItem):
361            return cspan, rspan, []
362        for elem in cellItem[0]:
363            if isinstance(elem, colSpan):
364                cspan = elem.get("span")
365                elem.parent.remove(elem)
366                continue
367            if isinstance(elem, rowSpan):
368                rspan = elem.get("span")
369                elem.parent.remove(elem)
370                continue
371        return cspan, rspan, cellItem[:]
372