summaryrefslogtreecommitdiff
path: root/source/docbook.py
blob: a9edad619a7dee15e2c861926d3d909c2bd9834a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
import sys
import globals, node

class FilePathSorter:

    def __init__ (self, filepaths):
        self.filepaths = filepaths
        self.root = node.Root()

    def buildPaths (self):
        for filepath in self.filepaths:
            # NOTE: we assume that none of the file names begin with '/'.
            hier = filepath.split('/')
            curnode = self.root
            for _dir in hier[:-1]:
                temp = curnode.firstChildByName(_dir)
                if temp == None:
                    # new directory node.
                    curnode = curnode.appendElement(_dir)
                else:
                    # directory node already exists.
                    curnode = temp

            # append file as a content node.
            curnode.appendContent(hier[-1])
            
    def sortPaths (self):
        self.__sortNode(self.root)

    def __sortNode (self, _node):

        # sort the files based on the file-1st-directory-2nd rule.
        contents = {}
        elements = {}
        for child in _node.getChildNodes():
            if child.nodeType == node.NodeType.Content:
                contents[child.content] = child
            elif child.nodeType == node.NodeType.Element:
                elements[child.name] = child
                self.__sortNode(child)

        # build a new set of child node list.
        children = []

        # contents first.
        contentNames = contents.keys()
        contentNames.sort()
        for name in contentNames:
            children.append(contents[name])

        # elements next.
        elementNames = elements.keys()
        elementNames.sort()
        if _node.nodeType == node.NodeType.Element and _node.name == 'text':
            # 'swriter', 'scalc', 'simpress', 'sdraw', 'schart' are ranked higher in this order.
            l = ['swriter', 'scalc', 'simpress', 'sdraw', 'smath', 'schart']
            newElemNames = []
            for elem in l:
                if elem in elementNames:
                    pos = elementNames.index(elem)
                    poped = elementNames.pop(pos)
                    newElemNames.append(poped)
            newElemNames.extend(elementNames)
            elementNames = newElemNames

        for name in elementNames:
            children.append(elements[name])
        _node.setChildNodes(children)

    def sort (self):
        self.buildPaths()
        self.sortPaths()
        return self.getFilePaths()

    def getFilePaths (self):
        """Return a list of sorted file names."""
        self.filepaths = [] # empty the existing list first.
        self.__walkToContent(self.root)
        return self.filepaths

    def __walkToContent (self, _node):
        if _node.nodeType == node.NodeType.Content:
            s = _node.content
            n = _node.parent
            while n.nodeType == node.NodeType.Element:
                s = n.name + '/' + s
                n = n.parent
            self.filepaths.append(s)
        elif _node.nodeType == node.NodeType.Element or _node.nodeType == node.NodeType.Root:
            for child in _node.getChildNodes():
                self.__walkToContent(child)


class DocBookConverter:

    elemRelTable = {
        'book': 'chapter',
        'chapter': 'sect1',
        'sect1': 'sect2',
        'sect2': 'sect3',
        'sect3': 'sect4',
        'sect4': 'sect5'
    }

    @staticmethod
    def startSubSection (src):
        if DocBookConverter.elemRelTable.has_key(src.name):
            return src.appendElement(DocBookConverter.elemRelTable[src.name])
        else:
            return None

    def __init__ (self, treeroot, xhproots, embeds):
        self.treeroot = treeroot
        self.xhproots = xhproots
        self.embeds = embeds
        self.root = node.Root()
        self.headingParent = None

    def convert (self):
        book = self.root.appendElement('book')
        bookinfo = book.appendElement('bookinfo')
        title = bookinfo.appendElement('title')
        title.appendContent(globals.productName + " Help")
        
        for section in self.treeroot.getChildNodes():
            self.__walk(section, book)

    def __walk (self, src, dest):
        # src element is either 'section' or 'content'.
        if src.name == 'section':
            title = src.getAttr('title')
            elem = DocBookConverter.startSubSection(dest)
            elem.appendElement('title').appendContent(title)
            for child in src.getChildNodes():
                self.__walk(child, elem)
        elif src.name == 'content':
            # this element has 'title' and 'path' attributes, and has no more child nodes.
            title = src.getAttr('title')
            sect = DocBookConverter.startSubSection(dest)
            sect.appendElement('title').appendContent(title)
            xhppath = src.getAttr('path')
            if self.xhproots.has_key(xhppath):
                self.__getContentFromXHP(xhppath, sect)
            else:
                sect.appendElement('para').appendContent('get content from ' + src.getAttr('path'))

    def __getContentFromXHP (self, xhppath, dest):
        xhproot = self.xhproots[xhppath]
        xhpbody = xhproot.firstChild().firstChildByName('body')
        # parent element for the xhp 'heading' paragraphs which should start a 
        # new sub-section when converting to docbook.
        self.headingParent = None 
        for xhpelem in xhpbody.getChildNodes():
            dest = self.__walkXHP(xhpelem, dest)

    def __getEmbedNode (self, href):
        filename, id = href.split('#')
        if filename.startswith('/'):
            filename = filename[1:]
        if self.embeds.has_key(filename) and self.embeds[filename].has_key(id):
            return self.embeds[filename][id]
        return None

    def __walkXHP (self, src, dest):

        if src.nodeType == node.NodeType.Content:
            # content node.
            content = src.content.strip()
            if len(content) > 0:
                dest.appendContent(content)

        elif src.name == 'comment':
            # we can ignore these elements.
            pass
        elif src.name == 'embed':
            # embed takes its content from another xhp file.
            href = src.getAttr('href')
            embed = self.__getEmbedNode(href)
            if embed == None:
                dest.appendElement('warning').appendContent('take embedded content from ' + href)
            else:
                dest = self.__walkXHP(embed, dest)

        elif src.name == 'switchinline':
            # For now, always select the <defaultinline> child element.
            content = src.firstChildByName('defaultinline').getContent()
            dest.appendContent(content)
            
        elif src.name == 'item':
            # an <item> element has a 'type' attribute that specifies how this 
            # text span should be formatted.
            dest.appendContent(src.getContent())

        elif src.name == 'list':
            # type may be 'unordered' (bulleted) or 'ordered' (numbered).
            listType = src.getAttr('type')
            lnode = None
            if listType == 'unordered':
                lnode = dest.appendElement('itemizedlist')
            elif listType == 'ordered':
                lnode = dest.appendElement('orderedlist')
            
            if lnode != None:
                for child in src.getChildNodes():
                    self.__walkXHP(child, lnode)
            else:
                dest.appendElement('warning').appendContent('unknown list type: ' + listType)

        elif src.name == 'listitem':
            # This one needs no translation.
            li = dest.appendElement('listitem')
            for child in src.getChildNodes():
                self.__walkXHP(child, li)

        elif src.name == 'link':
            for child in src.getChildNodes():
                self.__walkXHP(child, dest)

        elif src.name == 'paragraph':
            # normal paragraph content.
            role = src.getAttr('role')
            if role != None and role == 'heading':
                # finish the current sub-section, adn start a new one.
                title = src.getContent()
                if self.headingParent == None:
                    self.headingParent = dest
                elem = DocBookConverter.startSubSection(self.headingParent)
                elem.appendElement('title').appendContent(title)
                return elem
            else:
                paraName = 'para'
                if role != None:
                    if role == 'note':
                        paraName = 'note'
                    elif role == 'warning':
                        paraName = 'warning'
                    elif role == 'tip':
                        paraName = 'tip'
                para = dest.appendElement(paraName)
                for child in src.getChildNodes():
                    self.__walkXHP(child, para)

        elif src.name == 'emph':
            dest.appendElement('emphasis').appendContent(src.getContent())

        elif src.name == 'section' or src.name == 'variable':
            # we can probably just ignore this element for now.  Section elements
            # are used only to group multiple elements together.  Same with 
            # the variable elements.
            for child in src.getChildNodes():
                dest = self.__walkXHP(child, dest)

        elif src.name == 'table':
            tab = dest.appendElement('table').appendElement('tgroup').appendElement('tbody')
            for child in src.getChildNodes():
                self.__walkXHP(child, tab)

        elif src.name == 'tablerow':
            tab = dest.appendElement('row')
            for child in src.getChildNodes():
                self.__walkXHP(child, tab)

        elif src.name == 'tablecell':
            tab = dest.appendElement('entry')
            for child in src.getChildNodes():
                self.__walkXHP(child, tab)

        else:
            # unhandled element.  My work is done when these elements go away.
            dest.appendElement('warning').appendContent("unhandled element '%s'"%src.name)

        return dest


    def prettyPrint (self, fd):
        node.prettyPrint(fd, self.root)