~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 05:00:39 UTC
  • mto: This revision was merged to the branch mainline in revision 1731.
  • Revision ID: matt.giuca@gmail.com-20100225050039-s6b1n33hwwucafql
Added new project set edit view. Linked from projects page, project set page.

Show diffs side-by-side

added added

removed removed

Lines of Context:
19
19
 
20
20
import inspect
21
21
import os.path
 
22
import urllib
22
23
 
23
24
import genshi.template
24
25
 
 
26
from ivle.webapp.media import media_url
 
27
from ivle.webapp.core import Plugin as CorePlugin
25
28
from ivle.webapp.base.views import BaseView
26
 
import ivle.conf
27
 
import ivle.util
 
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
28
33
 
29
34
class XHTMLView(BaseView):
30
35
    """
32
37
    It is expected that apps which use this view will be written using Genshi
33
38
    templates.
34
39
    """
35
 
    def __init__(self, req, **kwargs):
36
 
        for key in kwargs:
37
 
          setattr(self, key, kwargs[key])
 
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
38
71
 
39
72
    def render(self, req):
40
73
        req.content_type = 'text/html' # TODO: Detect application/xhtml+xml
47
80
        # view.
48
81
        app_template = os.path.join(os.path.dirname(
49
82
                        inspect.getmodule(self).__file__), self.template) 
50
 
        req.write_html_head_foot = False
51
 
        loader = genshi.template.TemplateLoader(".", auto_reload=True)
52
 
        tmpl = loader.load(app_template)
53
 
        app = tmpl.generate(viewctx)
 
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))
54
95
 
55
96
        # Global template
56
97
        ctx = genshi.template.Context()
57
 
        ctx['app_styles'] = req.styles
58
 
        ctx['scripts'] = req.scripts
59
 
        ctx['scripts_init'] = req.scripts_init
 
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]
60
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
 
61
143
        self.populate_headings(req, ctx)
62
 
        tmpl = loader.load(os.path.join(os.path.dirname(__file__), 
 
144
        tmpl = self._loader.load(os.path.join(os.path.dirname(__file__), 
63
145
                                                        'ivle-headings.html'))
64
146
        req.write(tmpl.generate(ctx).render('xhtml', doctype='xhtml'))
 
147
        
 
148
    def populate(self, req, ctx):
 
149
        raise NotImplementedError()
65
150
 
66
151
    def populate_headings(self, req, ctx):
67
152
        ctx['favicon'] = None
68
 
        ctx['root_dir'] = ivle.conf.root_dir
69
 
        ctx['public_host'] = ivle.conf.public_host
 
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']
70
156
        ctx['write_javascript_settings'] = req.write_javascript_settings
71
157
        if req.user:
72
158
            ctx['login'] = req.user.login
74
160
            ctx['nick'] = req.user.nick
75
161
        else:
76
162
            ctx['login'] = None
 
163
            ctx['logged_in'] = False
77
164
        ctx['publicmode'] = req.publicmode
 
165
        if hasattr(self, 'help'):
 
166
            ctx['help_path'] = self.help
 
167
 
78
168
        ctx['apps_in_tabs'] = []
79
 
        for urlname in ivle.conf.apps.apps_in_tabs:
80
 
            new_app = {}
81
 
            app = ivle.conf.apps.app_url[urlname]
82
 
            new_app['this_app'] = hasattr(self, 'appname') \
83
 
                                  and urlname == self.appname
84
 
            if app.icon:
85
 
                new_app['has_icon'] = True
86
 
                icon_dir = ivle.conf.apps.app_icon_dir
87
 
                icon_url = ivle.util.make_path(os.path.join(icon_dir, app.icon))
88
 
                new_app['icon_url'] = icon_url
89
 
                if new_app['this_app']:
90
 
                    ctx['favicon'] = icon_url
 
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 = ''
91
268
            else:
92
 
                new_app['has_icon'] = False
93
 
            new_app['path'] = ivle.util.make_path(urlname)
94
 
            new_app['desc'] = app.desc
95
 
            new_app['name'] = app.name
96
 
            ctx['apps_in_tabs'].append(new_app)
 
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