summaryrefslogtreecommitdiff
path: root/giscanner/mallardwriter.py
blob: 1492254060968a508682e0ab58408082c569fdb6 (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
#!/usr/bin/env python
# -*- Mode: Python -*-
# GObject-Introspection - a framework for introspecting GObject libraries
# Copyright (C) 2010 Zach Goldberg
# Copyright (C) 2011 Johan Dahlin
# Copyright (C) 2011 Shaun McCance
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#

import os
import re

from xml.sax import saxutils
from mako.template import Template
from mako.runtime import supports_caller

from . import ast

class MallardFormatter(object):
    @classmethod
    def escape(cls, text):
        return saxutils.escape(text.encode('utf-8')).decode('utf-8')

    @classmethod
    def format(cls, doc):
        if doc is None:
            return ''

        result = ''
        for para in doc.split('\n\n'):
            result += '<p>'
            result += cls.format_inline(para)
            result += '</p>'
        return result

    @classmethod
    def format_inline(cls, para):
        result = ''

        poss = []
        poss.append((para.find('#'), '#'))
        poss = [pos for pos in poss if pos[0] >= 0]
        poss.sort(cmp=lambda x, y: cmp(x[0], y[0]))
        if len(poss) == 0:
            result += cls.escape(para)
        elif poss[0][1] == '#':
            pos = poss[0][0]
            result += cls.escape(para[:pos])
            rest = para[pos + 1:]
            link = re.split('[^a-zA-Z_:-]', rest, maxsplit=1)[0]
            xref = link #self.writer._xrefs.get(link, link)
            result += '<link xref="%s">%s</link>' % (xref, link)
            if len(link) < len(rest):
                result += cls.format_inline(rest[len(link):])

        return result

    @classmethod
    def format_type(cls, type_):
        raise NotImplementedError

class MallardFormatterC(MallardFormatter):
    @classmethod
    def format_type(cls, type_):
        if type_.ctype is not None:
            return type_.ctype
        else:
            return type_.target_fundamental

class MallardFormatterPython(MallardFormatter):
    pass

class MallardWriter(object):
    def __init__(self, transformer, language):
        if language not in ["Python", "C"]:
            raise SystemExit("Unsupported language: %s" % language)

        self._transformer = transformer
        self._language = language

    def write(self, output):
        self._render_node(self._transformer.namespace, output)
        for node in self._transformer.namespace.itervalues():
            self._render_node(node, output)
            if isinstance(node, (ast.Class, ast.Record)):
                for method in node.methods:
                    self._render_node(method, output)
            if isinstance(node, ast.Class):
                for property_ in node.properties:
                    self._render_node(property_, output)
                for signal in node.signals:
                    self._render_node(signal, output)

    def _render_node(self, node, output):
        namespace = self._transformer.namespace
        if isinstance(node, ast.Namespace):
            template_name = 'mallard-%s-namespace.tmpl' % self._language
            page_id = 'index'
        elif isinstance(node, (ast.Class, ast.Interface)):
            template_name = 'mallard-%s-class.tmpl' % self._language
            page_id = '%s.%s' % (namespace.name, node.name)
        elif isinstance(node, ast.Record):
            template_name = 'mallard-%s-record.tmpl' % self._language
            page_id = '%s.%s' % (namespace.name, node.name)
        elif isinstance(node, ast.Function) and node.parent is not None:
            template_name = 'mallard-%s-method.tmpl' % self._language
            page_id = '%s.%s.%s' % (namespace.name, node.parent.name, node.name)
        elif isinstance(node, ast.Function):
            template_name = 'mallard-%s-function.tmpl' % self._language
            page_id = '%s.%s' % (namespace.name, node.name)
        elif isinstance(node, ast.Property) and node.parent is not None:
            template_name = 'mallard-%s-property.tmpl' % self._language
            page_id = '%s.%s-%s' % (namespace.name, node.parent.name, node.name)
        elif isinstance(node, ast.Signal) and node.parent is not None:
            template_name = 'mallard-%s-signal.tmpl' % self._language
            page_id = '%s.%s-%s' % (namespace.name, node.parent.name, node.name)
        else:
            template_name = 'mallard-%s-default.tmpl' % self._language
            page_id = '%s.%s' % (namespace.name, node.name)

        if 'UNINSTALLED_INTROSPECTION_SRCDIR' in os.environ:
            top_srcdir = os.environ['UNINSTALLED_INTROSPECTION_SRCDIR']
            template_dir = os.path.join(top_srcdir, 'giscanner')
        else:
            template_dir = 'unimplemented'

        file_name = os.path.join(template_dir, template_name)
        template = Template(filename=file_name, output_encoding='utf-8')
        if self._language == 'C':
            formatter = MallardFormatterC
        elif self._language == 'Python':
            formatter = MallardFormatterPython
        else:
            formatter = MallardFormatter
        result = template.render(namespace=namespace,
                                 node=node,
                                 formatter=formatter)

        output_file_name = os.path.join(os.path.dirname(output),
                                        page_id + '.page')
        fp = open(output_file_name, 'w')
        fp.write(result)
        fp.close()

    def _render_page_object_hierarchy(self, page_node):
        parent_chain = self._get_parent_chain(page_node)
        parent_chain.append(page_node)
        lines = []

        for level, parent in enumerate(parent_chain):
            prepend = ""
            if level > 0:
                prepend = _space((level - 1)* 6) + " +----"
            lines.append(_space(2) + prepend + self._formatter.get_class_name(parent))

        self._writer.disable_whitespace()
        self._writer.write_line("\n".join(lines))
        self._writer.enable_whitespace()