summaryrefslogtreecommitdiff
path: root/sandbox/richard/pythonpoint/pythonpoint.py
blob: ad0f96d1ae8b83a1021d55b73151bbf8eef65d37 (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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
import cStringIO, cgi, sys, urllib
import docutils.utils
from docutils.parsers.restructuredtext import Parser

class DumbPythonPointFormatter:
    def __init__(self):
        self.out = cStringIO.StringIO()
        self.w = self.out.write
        self.section = 0
        self.closers = []
        self.slidenum = 1

    def format(self, node):
        '''Format a node
        '''
        for entry in node:
            self.formatOneTag(entry)

    def formatOneTag(self, tag):
        if tag.tagname == '#text':
            meth = self.format__text
        else:
            if not hasattr(self, 'format_'+tag.tagname):
                print >>sys.stderr, '**skipping %s'%tag.tagname
                return
            else:
                meth = getattr(self, 'format_'+tag.tagname)
        meth(tag)

    def open_slide(self, node):
        if node.attributes.has_key('dupname'):
            name = node.attributes['dupname']
        else:
            name = node.attributes['name']
        self.w('<slide id="Slide%03d" title="%s">\n'%(self.slidenum, name))
        self.slidenum += 1

    def open_frame(self):
        self.w('<frame x="160" y="72" width="600" height="432" leftmargin="36" rightmargin="0">\n')

    #
    # Root Element
    #
    # ((title, subtitle?)?, docinfo?, %structure.model;)
    #
    def format_document(self, document):
        ''' ((title, subtitle?)?, docinfo?, %structure.model;)

            
        '''
        self.document = document

        # make sure the structure is what we're expecting
        self.w('<presentation>\n')

        # TODO: get this into the stx
        self.w('<stylesheet module="modern" function="getParagraphStyles"/>\n')

        self.w('<section name="Main">\n')

        # TODO: get this into the stx
        self.w('<fixedimage filename="logo.gif" x="0" y="0" width="134" height="70"/>\n')

        # now for the body
        for entry in document:
            assert entry.tagname == 'section'
            self.formatOneTag(entry)

        self.w('</section>\n')
        self.w('</presentation>\n')

        return self.out.getvalue()

    def format_title(self, node):
        self.w('<para style="Heading2">')
        if node.children: self.format(node)
        self.w('</para>\n')

    def format_section(self, node):
        self.open_slide(node)
        self.open_frame()
        if node.children: self.format(node)
        self.w('</frame>\n')
        self.w('</slide>\n')

    def format_paragraph(self, node):
        ''' %text.model;
        '''
        # TODO: there are situations where the <p> </p> are unnecessary
        self.w('<para>')
        if node.children: self.format(node)
        self.w('</para>\n')

    # Simple lists
    def format_bullet_list(self, node):
        if node.children: self.format(node)

    def format_enumerated_list(self, node):
        if node.children: self.format(node)

    def format_list_item(self, node):
        self.w('<para style="Bullet">')
        if node.children: self.format(node[0])
        self.w('</para>\n')

    # Definition List
    def format_definition_list(self, node):
        if node.children: self.format(node)

    def format_definition_list_item(self, node):
        '''  (term, classifier?, definition)
        '''
        if node.children: self.format(node)

    def format_term(self, node):
        ''' %text.model;
        '''
        self.w('<para><b>')
        if node.children:self.format(node[0])
        self.w('</b>')

    def format_classifier(self, node):
        ''' %text.model;
        '''
        # TODO: handle the classifier better
        self.w('<i>')
        if node.children: self.format(node[0])
        self.w('</i>')

    def format_definition(self, node):
        ''' (%body.elements;)+
        '''
        self.w('</para>\n<para style="Definition">')
        for child in node.children:
            self.w(child[0].data)
        self.w('</para>\n')

    # Literal Block
    def format_literal_block(self, node):
        self.w('<pre>')
        if node.children: self.format(node)
        self.w('</pre>\n')

    # Block Quote
    def format_block_quote(self, node):
        self.w('<para style="Indent">')
        if node.children: self.format(node)
        self.w('</para>\n')

    def format_image(self, node):
        ''' EMPTY
            uri       CDATA     #REQUIRED
            alt       CDATA     #IMPLIED
            height    NMTOKEN   #IMPLIED
            width     NMTOKEN   #IMPLIED
            scale     NMTOKEN   #IMPLIED
        '''
        attrs = node.attributes
        l = ['src="%(uri)s"'%attrs]
        # TODO: scale
        self.w('<image filename="%s">'%node.attributes['uri'])

    #
    # Tables:
    #  NOT IN DOM YET
    #
    def format_table(self, node):
        '''
            +------------------------+------------+----------+----------+
            | Header row, column 1   | Header 2   | Header 3 | Header 4 |
            | (header rows optional) |            |          |          |
            +========================+============+==========+==========+
            | body row 1, column 1   | column 2   | column 3 | column 4 |
            +------------------------+------------+----------+----------+
            | body row 2             | Cells may span columns.          |
            +------------------------+------------+---------------------+
            | body row 3             | Cells may  | - Table cells       |
            +------------------------+ span rows. | - contain           |
            | body row 4             |            | - body elements.    |
            +------------------------+------------+---------------------+
        '''
        self.w('<table border=1>\n')
        if node.children: self.format(node)
        self.w('</table>\n')

    def format_tgroup(self, node):
        # we get the number of columns, if that's important
        if node.children: self.format(node)

    def format_colspec(self, node):
        # we get colwidth, but don't need it
        pass

    def format_thead(self, node):
        for row in node.children:
            self.w('<tr>')
            for cell in row.children:
                s = ''
                attrs = cell.attributes
                if attrs.has_key('morecols'):
                    s = s + ' colspan=%d'%(attrs['morecols']+1)
                if attrs.has_key('morerows'):
                    s = s + ' rowspan=%d'%(attrs['morerows']+1)
                self.w('<th valign="top" align="left"%s>'%s)
                if cell.children: self.format(cell)
                self.w('</th>\n')
            self.w('</tr>\n')

    def format_tbody(self, node):
        for row in node.children:
            self.w('<tr>')
            for cell in row.children:
                s = ''
                attrs = cell.attributes
                if attrs.has_key('morecols'):
                    s = s + ' colspan=%d'%(attrs['morecols']+1)
                if attrs.has_key('morerows'):
                    s = s + ' rowspan=%d'%(attrs['morerows']+1)
                self.w('<td valign="top" align="left"%s>'%s)
                if cell.children: self.format(cell)
                self.w('</td>\n')
            self.w('</tr>\n')

    #
    # Inline Elements
    #
    # Inline elements occur within the text contents of body elements. Some
    # nesting of inline elements is allowed by these definitions, with the
    # following caveats:
    # - An inline element may not contain a nested element of the same type
    #   (e.g. <strong> may not contain another <strong>).
    # - Nested inline elements may or may not be supported by individual
    #   applications using this DTD.
    # - The inline elements <footnote_reference>, <literal>, and <image> do
    #   not support nesting.
    #
    #  What that means is that all of these take (%text.model;) except:
    #   literal (#PCDATA)
    #   footnote_reference (#PCDATA)
    #
    # text.model:
    # (#PCDATA | %inline.elements;)*
    #
    def format_emphasis(self, node):
        ''' (%text.model;)
        '''
        self.w('<i>')
        if node.children: self.format(node)
        self.w('</i>')

    def format_strong(self, node):
        ''' (%text.model;)
        '''
        self.w('<b>')
        if node.children: self.format(node)
        self.w('</b>')

    def format_interpreted(self, node):
        ''' (%text.model;)
            type      CDATA     #IMPLIED
        '''
        pass #raise NotImplementedError, node

    def format_literal(self, node):
        ''' (#PCDATA)
        '''
        self.w('<tt>')
        for literal in node.children:
            self.w(cgi.escape(literal.data))
        self.w('</tt>')

    def format_reference(self, node):
        ''' (%text.model;)
            %reference.atts;
            %anonymous.att;
        '''
        attrs = node.attributes
        doc = self.document
        ok = 1
        print node
        if attrs.has_key('refuri'):
            self.w('<a href="%s">'%attrs['refuri'])
        elif doc.explicit_targets.has_key(attrs['refname']):
            # an external reference has been defined
            ref = doc.explicit_targets[attrs['refname']]
            if ref.attributes.has_key('refuri'):
                self.w('<a href="%s">'%ref.attributes['refuri'])
            else:
                self.w('<a href="#%s">'%attrs['refname'])
        elif doc.implicit_targets.has_key(attrs['refname']):
            # internal reference
            name = attrs['refname']
            self.w('<a href="#%s">'%urllib.quote(name))
        else:
            ok = 0
            self.w('<span class="formatter_error">target "%s" '
                'undefined</span>'%attrs['refname'])
        if node.children: self.format(node)
        if ok:
            self.w('</a>')

    def format_footnote_reference(self, node):
        ''' (#PCDATA)
            %reference.atts;
            %auto.att;
        '''
        raise NotImplementedError, node

    def format_substitution_reference(self, node):
        ''' (%text.model;)
            %refname.att;
        '''
        #raise NotImplementedError, node
        pass

    def format_problematic(self, node):
        ''' (%text.model;)
        '''
        raise NotImplementedError, node

    def format_system_message(self, node):
        ''' just print it to stderr
        '''
        print >>sys.stderr, '%s: %s'%(node.attributes['type'], node[0][0].data)

    #
    # Finally, #text
    #
    def format__text(self, node):
        self.w(cgi.escape(node.data))

def main(filename, debug=0):
    parser = Parser()
    input = open(filename).read()
    document = dps.utils.newdocument()
    parser.parse(input, document)
    if debug == 1:
        print document.pformat()
    else:
        formatter = DumbPythonPointFormatter()
        print formatter.format_document(document)

if __name__ == '__main__':
    if len(sys.argv) > 2:
        main(sys.argv[1], debug=1)
    else:
        main(sys.argv[1])