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

« back to all changes in this revision

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

  • Committer: Matt Giuca
  • Date: 2010-02-25 01:53:19 UTC
  • Revision ID: matt.giuca@gmail.com-20100225015319-7j0oounlhi1bj6fp
Fixed broken console, due to function called with not enough arguments.

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
import urllib
 
23
 
 
24
import genshi.template
 
25
 
 
26
from ivle.webapp.media import media_url
 
27
from ivle.webapp.core import Plugin as CorePlugin
 
28
from ivle.webapp.base.views import BaseView
 
29
from ivle.webapp.base.plugins import ViewPlugin, OverlayPlugin
 
30
from ivle.webapp.errors import HTTPError, Unauthorized
 
31
from ivle.webapp.publisher import NoPath
 
32
from ivle.webapp.breadcrumbs import Breadcrumber
 
33
 
 
34
class XHTMLView(BaseView):
 
35
    """
 
36
    A view which provides a base class for views which need to return XHTML
 
37
    It is expected that apps which use this view will be written using Genshi
 
38
    templates.
 
39
    """
 
40
 
 
41
    template = 'template.html'
 
42
    allow_overlays = True
 
43
    breadcrumb_text = None
 
44
    _loader = None
 
45
 
 
46
    def __init__(self, *args, **kwargs):
 
47
        super(XHTMLView, self).__init__(*args, **kwargs)
 
48
 
 
49
        # We use a single loader for all views, so we can cache the
 
50
        # parsed templates. auto_reload is convenient and has a minimal
 
51
        # performance penalty, so we'll leave it on.
 
52
        if self.__class__._loader is None:
 
53
            self.__class__._loader = genshi.template.TemplateLoader(
 
54
                ".", auto_reload=True,
 
55
                max_cache_size=100)
 
56
 
 
57
        self.overlay_blacklist = []
 
58
 
 
59
        self.plugin_scripts = {}
 
60
        self.plugin_styles = {}
 
61
        self.scripts_init = []
 
62
 
 
63
        self.extra_breadcrumbs = []
 
64
        self.overlay_blacklist = []
 
65
 
 
66
    def get_context_ancestry(self, req):
 
67
        return req.publisher.get_ancestors(self.context)
 
68
 
 
69
    def filter(self, stream, ctx):
 
70
        return stream
 
71
 
 
72
    def render(self, req):
 
73
        req.content_type = 'text/html' # TODO: Detect application/xhtml+xml
 
74
 
 
75
        # View template
 
76
        viewctx = genshi.template.Context()
 
77
        self.populate(req, viewctx)
 
78
 
 
79
        # The template is found in the directory of the module containing the
 
80
        # view.
 
81
        app_template = os.path.join(os.path.dirname(
 
82
                        inspect.getmodule(self).__file__), self.template) 
 
83
        tmpl = self._loader.load(app_template)
 
84
        app = self.filter(tmpl.generate(viewctx), viewctx)
 
85
 
 
86
        view_scripts = []
 
87
        for plugin in self.plugin_scripts:
 
88
            for path in self.plugin_scripts[plugin]:
 
89
                view_scripts.append(media_url(req, plugin, path))
 
90
 
 
91
        view_styles = []
 
92
        for plugin in self.plugin_styles:
 
93
            for path in self.plugin_styles[plugin]:
 
94
                view_styles.append(media_url(req, plugin, path))
 
95
 
 
96
        # Global template
 
97
        ctx = genshi.template.Context()
 
98
 
 
99
        overlay_bits = self.render_overlays(req) if req.user else [[]]*4
 
100
        ctx['overlays'] = overlay_bits[0]
 
101
 
 
102
        ctx['styles'] = [media_url(req, CorePlugin, 'ivle.css')]
 
103
        ctx['styles'] += view_styles
 
104
        ctx['styles'] += overlay_bits[1]
 
105
 
 
106
        ctx['scripts'] = [media_url(req, CorePlugin, path) for path in
 
107
                           ('util.js', 'json2.js', 'md5.js')]
 
108
        ctx['scripts'].append(media_url(req, '+external/jquery', 'jquery.js'))
 
109
        ctx['scripts'] += view_scripts
 
110
        ctx['scripts'] += overlay_bits[2]
 
111
 
 
112
        ctx['scripts_init'] = self.scripts_init + overlay_bits[3]
 
113
        ctx['app_template'] = app
 
114
        ctx['title_img'] = media_url(req, CorePlugin,
 
115
                                     "images/chrome/root-breadcrumb.png")
 
116
        try:
 
117
            ancestry = self.get_context_ancestry(req)
 
118
        except NoPath:
 
119
            ancestry = []
 
120
 
 
121
        crumber = Breadcrumber(req)
 
122
 
 
123
        ctx['breadcrumbs'] = []
 
124
        if not req.publicmode:
 
125
            for ancestor in ancestry:
 
126
                crumb = crumber.crumb(ancestor)
 
127
                if crumb is None:
 
128
                    continue
 
129
 
 
130
                if hasattr(crumb, 'extra_breadcrumbs_before'):
 
131
                    ctx['breadcrumbs'].extend(crumb.extra_breadcrumbs_before)
 
132
                ctx['breadcrumbs'].append(crumb)
 
133
                if hasattr(crumb, 'extra_breadcrumbs_after'):
 
134
                    ctx['breadcrumbs'].extend(crumb.extra_breadcrumbs_after)
 
135
 
 
136
            # If the view has specified text for a breadcrumb, add one.
 
137
            if self.breadcrumb_text:
 
138
                ctx['breadcrumbs'].append(ViewBreadcrumb(req, self))
 
139
 
 
140
            # Allow the view to add its own fake breadcrumbs.
 
141
            ctx['breadcrumbs'].extend(self.extra_breadcrumbs)
 
142
 
 
143
        self.populate_headings(req, ctx)
 
144
        tmpl = self._loader.load(os.path.join(os.path.dirname(__file__), 
 
145
                                                        'ivle-headings.html'))
 
146
        req.write(tmpl.generate(ctx).render('xhtml', doctype='xhtml'))
 
147
        
 
148
    def populate(self, req, ctx):
 
149
        raise NotImplementedError()
 
150
 
 
151
    def populate_headings(self, req, ctx):
 
152
        ctx['favicon'] = None
 
153
        ctx['root_dir'] = req.config['urls']['root']
 
154
        ctx['public_host'] = req.config['urls']['public_host']
 
155
        ctx['svn_base'] = req.config['urls']['svn_addr']
 
156
        ctx['write_javascript_settings'] = req.write_javascript_settings
 
157
        if req.user:
 
158
            ctx['login'] = req.user.login
 
159
            ctx['logged_in'] = True
 
160
            ctx['nick'] = req.user.nick
 
161
        else:
 
162
            ctx['login'] = None
 
163
            ctx['logged_in'] = False
 
164
        ctx['publicmode'] = req.publicmode
 
165
        if hasattr(self, 'help'):
 
166
            ctx['help_path'] = self.help
 
167
 
 
168
        ctx['apps_in_tabs'] = []
 
169
        for plugin in req.config.plugin_index[ViewPlugin]:
 
170
            if not hasattr(plugin, 'tabs'):
 
171
                continue
 
172
 
 
173
            for tab in plugin.tabs:
 
174
                # tab is a tuple: name, title, desc, icon, path, weight, admin
 
175
                # (Admin is optional, defaults to false)
 
176
                new_app = {}
 
177
                new_app['this_app'] = hasattr(self, 'tab') \
 
178
                                      and tab[0] == self.tab
 
179
 
 
180
                # Icon name
 
181
                if tab[3] is not None:
 
182
                    new_app['has_icon'] = True
 
183
                    icon_url = media_url(req, plugin, tab[3])
 
184
                    new_app['icon_url'] = icon_url
 
185
                    if new_app['this_app']:
 
186
                        ctx['favicon'] = icon_url
 
187
                else:
 
188
                    new_app['has_icon'] = False
 
189
                # The following check is here, so it is AFTER setting the
 
190
                # icon, but BEFORE actually installing the tab in the menu
 
191
                if len(tab) > 6 and tab[6]:
 
192
                    # Admin-only tab
 
193
                    if not (req.user and req.user.admin):
 
194
                        break
 
195
                new_app['path'] = req.make_path(tab[4])
 
196
                new_app['desc'] = tab[2]
 
197
                new_app['name'] = tab[1]
 
198
                new_app['weight'] = tab[5]
 
199
                ctx['apps_in_tabs'].append(new_app)
 
200
 
 
201
        ctx['apps_in_tabs'].sort(key=lambda tab: tab['weight'])
 
202
 
 
203
    def render_overlays(self, req):
 
204
        """Generate XML streams for the overlays.
 
205
        
 
206
        Returns a list of streams. Populates the scripts, styles, and 
 
207
        scripts_init.
 
208
        """
 
209
        overlays = []
 
210
        styles = []
 
211
        scripts = []
 
212
        scripts_init = []
 
213
        if not self.allow_overlays:
 
214
            return (overlays, styles, scripts, scripts_init)
 
215
 
 
216
        for plugin in req.config.plugin_index[OverlayPlugin]:
 
217
            for overclass in plugin.overlays:
 
218
                if overclass in self.overlay_blacklist:
 
219
                    continue
 
220
                overlay = overclass(req)
 
221
                #TODO: Re-factor this to look nicer
 
222
                for mplugin in overlay.plugin_scripts:
 
223
                    for path in overlay.plugin_scripts[mplugin]:
 
224
                        scripts.append(media_url(req, mplugin, path))
 
225
 
 
226
                for mplugin in overlay.plugin_styles:
 
227
                    for path in overlay.plugin_styles[mplugin]:
 
228
                        styles.append(media_url(req, mplugin, path))
 
229
 
 
230
                scripts_init += overlay.plugin_scripts_init
 
231
 
 
232
                overlays.append(overlay.render(req))
 
233
        return (overlays, styles, scripts, scripts_init)
 
234
 
 
235
    @classmethod
 
236
    def get_error_view(cls, e):
 
237
        view_map = {HTTPError:    XHTMLErrorView,
 
238
                    Unauthorized: XHTMLUnauthorizedView}
 
239
        for exccls in inspect.getmro(type(e)):
 
240
            if exccls in view_map:
 
241
                return view_map[exccls]
 
242
 
 
243
class XHTMLErrorView(XHTMLView):
 
244
    template = 'xhtmlerror.html'
 
245
 
 
246
    def __init__(self, req, context, lastobj):
 
247
        super(XHTMLErrorView, self).__init__(req, context)
 
248
        self.lastobj = lastobj
 
249
 
 
250
    def get_context_ancestry(self, req):
 
251
        return req.publisher.get_ancestors(self.lastobj)
 
252
 
 
253
    def populate(self, req, ctx):
 
254
        ctx['req'] = req
 
255
        ctx['exception'] = self.context
 
256
        req.headers_out['X-IVLE-Error'] = self.context.message
 
257
 
 
258
class XHTMLUnauthorizedView(XHTMLErrorView):
 
259
    template = 'xhtmlunauthorized.html'
 
260
 
 
261
    def __init__(self, req, exception, lastobj):
 
262
        super(XHTMLUnauthorizedView, self).__init__(req, exception, lastobj)
 
263
 
 
264
        if not req.publicmode and req.user is None:
 
265
            # Not logged in. Redirect to login page.
 
266
            if req.uri == '/':
 
267
                query_string = ''
 
268
            else:
 
269
                query_string = '?url=' + urllib.quote(req.uri, safe="/~")
 
270
            req.throw_redirect('/+login' + query_string)
 
271
 
 
272
        req.status = 403
 
273
 
 
274
class ViewBreadcrumb(object):
 
275
    def __init__(self, req, context):
 
276
        self.req = req
 
277
        self.context = context
 
278
 
 
279
    @property
 
280
    def text(self):
 
281
        return self.context.breadcrumb_text