~azzar1/unity/add-show-desktop-key

« back to all changes in this revision

Viewing changes to ivle/webapp/base/xhtml.py

Merge from new-dispatch.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# IVLE - Informatics Virtual Learning Environment
 
2
# Copyright (C) 2007-2009 The University of Melbourne
 
3
#
 
4
# This program is free software; you can redistribute it and/or modify
 
5
# it under the terms of the GNU General Public License as published by
 
6
# the Free Software Foundation; either version 2 of the License, or
 
7
# (at your option) any later version.
 
8
#
 
9
# This program is distributed in the hope that it will be useful,
 
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
12
# GNU General Public License for more details.
 
13
#
 
14
# You should have received a copy of the GNU General Public License
 
15
# along with this program; if not, write to the Free Software
 
16
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 
17
 
 
18
# Author: Nick Chadwick
 
19
 
 
20
import inspect
 
21
import os.path
 
22
 
 
23
import genshi.template
 
24
 
 
25
from ivle.webapp.media import media_url
 
26
from ivle.webapp.core import Plugin as CorePlugin
 
27
from ivle.webapp.base.views import BaseView
 
28
from ivle.webapp.base.plugins import ViewPlugin, OverlayPlugin
 
29
from ivle.webapp.errors import HTTPError, Unauthorized
 
30
import ivle.conf
 
31
import ivle.util
 
32
 
 
33
class XHTMLView(BaseView):
 
34
    """
 
35
    A view which provides a base class for views which need to return XHTML
 
36
    It is expected that apps which use this view will be written using Genshi
 
37
    templates.
 
38
    """
 
39
 
 
40
    template = 'template.html'
 
41
    plugin_scripts = {}
 
42
    plugin_styles = {}
 
43
    overlay_blacklist = []
 
44
 
 
45
    def __init__(self, req, **kwargs):
 
46
        for key in kwargs:
 
47
            setattr(self, key, kwargs[key])
 
48
 
 
49
    def render(self, req):
 
50
        req.content_type = 'text/html' # TODO: Detect application/xhtml+xml
 
51
 
 
52
        # View template
 
53
        viewctx = genshi.template.Context()
 
54
        self.populate(req, viewctx)
 
55
 
 
56
        # The template is found in the directory of the module containing the
 
57
        # view.
 
58
        app_template = os.path.join(os.path.dirname(
 
59
                        inspect.getmodule(self).__file__), self.template) 
 
60
        req.write_html_head_foot = False
 
61
        loader = genshi.template.TemplateLoader(".", auto_reload=True)
 
62
        tmpl = loader.load(app_template)
 
63
        app = tmpl.generate(viewctx)
 
64
 
 
65
        for plugin in self.plugin_scripts:
 
66
            for path in self.plugin_scripts[plugin]:
 
67
                req.scripts.append(media_url(req, plugin, path))
 
68
 
 
69
        for plugin in self.plugin_styles:
 
70
            for path in self.plugin_styles[plugin]:
 
71
                req.styles.append(media_url(req, plugin, path))
 
72
 
 
73
        # Global template
 
74
        ctx = genshi.template.Context()
 
75
        # XXX: Leave this here!! (Before req.styles is read)
 
76
        ctx['overlays'] = self.render_overlays(req)
 
77
 
 
78
        ctx['styles'] = [media_url(req, CorePlugin, 'ivle.css')]
 
79
        ctx['styles'] += req.styles
 
80
 
 
81
        ctx['scripts'] = [media_url(req, CorePlugin, path) for path in
 
82
                           ('util.js', 'json2.js', 'md5.js', 'tos.js')]
 
83
        ctx['scripts'] += req.scripts
 
84
 
 
85
        ctx['scripts_init'] = req.scripts_init
 
86
        ctx['app_template'] = app
 
87
        self.populate_headings(req, ctx)
 
88
        tmpl = loader.load(os.path.join(os.path.dirname(__file__), 
 
89
                                                        'ivle-headings.html'))
 
90
        req.write(tmpl.generate(ctx).render('xhtml', doctype='xhtml'))
 
91
        
 
92
    def populate(self, req, ctx):
 
93
        raise NotImplementedError()
 
94
 
 
95
    def populate_headings(self, req, ctx):
 
96
        ctx['favicon'] = None
 
97
        ctx['root_dir'] = ivle.conf.root_dir
 
98
        ctx['public_host'] = ivle.conf.public_host
 
99
        ctx['write_javascript_settings'] = req.write_javascript_settings
 
100
        if req.user:
 
101
            ctx['login'] = req.user.login
 
102
            ctx['logged_in'] = True
 
103
            ctx['nick'] = req.user.nick
 
104
        else:
 
105
            ctx['login'] = None
 
106
            ctx['logged_in'] = False
 
107
        ctx['publicmode'] = req.publicmode
 
108
        if hasattr(self, 'help'):
 
109
            ctx['help_path'] = self.help
 
110
 
 
111
        ctx['apps_in_tabs'] = []
 
112
        for plugin in req.plugin_index[ViewPlugin]:
 
113
            if not hasattr(plugin, 'tabs'):
 
114
                continue
 
115
 
 
116
            for tab in plugin.tabs:
 
117
                # tab is a tuple: name, title, desc, icon, path
 
118
                new_app = {}
 
119
                new_app['this_app'] = hasattr(self, 'appname') \
 
120
                                      and tab[0] == self.appname
 
121
 
 
122
                # Icon name
 
123
                if tab[3] is not None:
 
124
                    new_app['has_icon'] = True
 
125
                    icon_url = media_url(req, plugin, tab[3])
 
126
                    new_app['icon_url'] = icon_url
 
127
                    if new_app['this_app']:
 
128
                        ctx['favicon'] = icon_url
 
129
                else:
 
130
                    new_app['has_icon'] = False
 
131
                new_app['path'] = ivle.util.make_path(tab[4])
 
132
                new_app['desc'] = tab[2]
 
133
                new_app['name'] = tab[1]
 
134
                new_app['weight'] = tab[5]
 
135
                ctx['apps_in_tabs'].append(new_app)
 
136
 
 
137
        ctx['apps_in_tabs'].sort(key=lambda tab: tab['weight'])
 
138
 
 
139
    def render_overlays(self, req):
 
140
        """Generate XML streams for the overlays.
 
141
        
 
142
        Returns a list of streams. Populates the scripts, styles, and 
 
143
        scripts_init.
 
144
        """
 
145
        overlays = []
 
146
        for plugin in req.plugin_index[OverlayPlugin]:
 
147
            for overclass in plugin.overlays:
 
148
                if overclass in self.overlay_blacklist:
 
149
                    continue
 
150
                overlay = overclass(req)
 
151
                #TODO: Re-factor this to look nicer
 
152
                for mplugin in overlay.plugin_scripts:
 
153
                    for path in overlay.plugin_scripts[mplugin]:
 
154
                        req.scripts.append(media_url(req, mplugin, path))
 
155
 
 
156
                for mplugin in overlay.plugin_styles:
 
157
                    for path in overlay.plugin_styles[mplugin]:
 
158
                        req.styles.append(media_url(req, mplugin, path))
 
159
 
 
160
                req.scripts_init += overlay.plugin_scripts_init
 
161
 
 
162
                overlays.append(overlay.render(req))
 
163
        return overlays
 
164
 
 
165
    @classmethod
 
166
    def get_error_view(cls, e):
 
167
        view_map = {HTTPError:    XHTMLErrorView,
 
168
                    Unauthorized: XHTMLUnauthorizedView}
 
169
        for exccls in inspect.getmro(type(e)):
 
170
            if exccls in view_map:
 
171
                return view_map[exccls]
 
172
 
 
173
class XHTMLErrorView(XHTMLView):
 
174
    template = 'xhtmlerror.html'
 
175
 
 
176
    def __init__(self, req, exception):
 
177
        self.context = exception
 
178
 
 
179
    def populate(self, req, ctx):
 
180
        ctx['exception'] = self.context
 
181
 
 
182
class XHTMLUnauthorizedView(XHTMLErrorView):
 
183
    template = 'xhtmlunauthorized.html'
 
184
 
 
185
    def __init__(self, req, exception):
 
186
        super(XHTMLUnauthorizedView, self).__init__(req, exception)
 
187
        if req.user is None:
 
188
            # Not logged in. Redirect to login page.
 
189
            req.throw_redirect('/') # XXX: Need proper URL.
 
190
 
 
191
        req.status = 403