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

« back to all changes in this revision

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

ivle.webapp.base.rest#RESTView: Remove broken old render() - it should be
                                implemented by subclasses.
                     #JSONRESTView: Remove an impossible assertion, and fix
                                    some exception message spacing.
ivle.webapp.base.test.test_rest: Add a named operation with both default and
                                 non-default arguments, and check that we die
                                 properly when the non-default is unspecified.

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
23
22
 
24
23
import genshi.template
25
24
 
26
 
from ivle.webapp.media import media_url
27
 
from ivle.webapp.core import Plugin as CorePlugin
28
25
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.routing import NoPath
 
26
import ivle.conf
 
27
import ivle.util
32
28
 
33
29
class XHTMLView(BaseView):
34
30
    """
36
32
    It is expected that apps which use this view will be written using Genshi
37
33
    templates.
38
34
    """
39
 
 
40
 
    template = 'template.html'
41
 
 
42
 
    plugin_scripts = {}
43
 
    plugin_styles = {}
44
 
    scripts_init = []
45
 
 
46
 
    allow_overlays = True
47
 
    overlay_blacklist = []
48
 
 
49
 
    def filter(self, stream, ctx):
50
 
        return stream
 
35
    def __init__(self, req, **kwargs):
 
36
        for key in kwargs:
 
37
            setattr(self, key, kwargs[key])
51
38
 
52
39
    def render(self, req):
53
40
        req.content_type = 'text/html' # TODO: Detect application/xhtml+xml
60
47
        # view.
61
48
        app_template = os.path.join(os.path.dirname(
62
49
                        inspect.getmodule(self).__file__), self.template) 
 
50
        req.write_html_head_foot = False
63
51
        loader = genshi.template.TemplateLoader(".", auto_reload=True)
64
52
        tmpl = loader.load(app_template)
65
 
        app = self.filter(tmpl.generate(viewctx), viewctx)
66
 
 
67
 
        view_scripts = []
68
 
        for plugin in self.plugin_scripts:
69
 
            for path in self.plugin_scripts[plugin]:
70
 
                view_scripts.append(media_url(req, plugin, path))
71
 
 
72
 
        view_styles = []
73
 
        for plugin in self.plugin_styles:
74
 
            for path in self.plugin_styles[plugin]:
75
 
                view_styles.append(media_url(req, plugin, path))
 
53
        app = tmpl.generate(viewctx)
76
54
 
77
55
        # Global template
78
56
        ctx = genshi.template.Context()
79
 
 
80
 
        overlay_bits = self.render_overlays(req) if req.user else [[]]*4
81
 
        ctx['overlays'] = overlay_bits[0]
82
 
 
83
 
        ctx['styles'] = [media_url(req, CorePlugin, 'ivle.css')]
84
 
        ctx['styles'] += view_styles
85
 
        ctx['styles'] += overlay_bits[1]
86
 
 
87
 
        ctx['scripts'] = [media_url(req, CorePlugin, path) for path in
88
 
                           ('util.js', 'json2.js', 'md5.js')]
89
 
        ctx['scripts'].append(media_url(req, '+external/jquery', 'jquery.js'))
90
 
        ctx['scripts'] += view_scripts
91
 
        ctx['scripts'] += overlay_bits[2]
92
 
 
93
 
        ctx['scripts_init'] = self.scripts_init + overlay_bits[3]
 
57
        ctx['app_styles'] = req.styles
 
58
        ctx['scripts'] = req.scripts
 
59
        ctx['scripts_init'] = req.scripts_init
94
60
        ctx['app_template'] = app
95
 
        ctx['title_img'] = media_url(req, CorePlugin,
96
 
                                     "images/chrome/root-breadcrumb.png")
97
 
        try:
98
 
            ctx['ancestry'] = req.router.get_ancestors(self.context)
99
 
        except NoPath:
100
 
            ctx['ancestry'] = []
101
 
        ctx['breadcrumb_text'] = lambda x: x # TODO: Do it properly.
102
 
        ctx['url'] = req.router.generate
103
61
        self.populate_headings(req, ctx)
104
62
        tmpl = loader.load(os.path.join(os.path.dirname(__file__), 
105
63
                                                        'ivle-headings.html'))
106
64
        req.write(tmpl.generate(ctx).render('xhtml', doctype='xhtml'))
107
 
        
108
 
    def populate(self, req, ctx):
109
 
        raise NotImplementedError()
110
65
 
111
66
    def populate_headings(self, req, ctx):
112
67
        ctx['favicon'] = None
113
 
        ctx['root_dir'] = req.config['urls']['root']
114
 
        ctx['public_host'] = req.config['urls']['public_host']
115
 
        ctx['svn_base'] = req.config['urls']['svn_addr']
 
68
        ctx['root_dir'] = ivle.conf.root_dir
 
69
        ctx['public_host'] = ivle.conf.public_host
116
70
        ctx['write_javascript_settings'] = req.write_javascript_settings
117
71
        if req.user:
118
72
            ctx['login'] = req.user.login
120
74
            ctx['nick'] = req.user.nick
121
75
        else:
122
76
            ctx['login'] = None
123
 
            ctx['logged_in'] = False
124
77
        ctx['publicmode'] = req.publicmode
125
 
        if hasattr(self, 'help'):
126
 
            ctx['help_path'] = self.help
127
 
 
128
78
        ctx['apps_in_tabs'] = []
129
 
        for plugin in req.config.plugin_index[ViewPlugin]:
130
 
            if not hasattr(plugin, 'tabs'):
131
 
                continue
132
 
 
133
 
            for tab in plugin.tabs:
134
 
                # tab is a tuple: name, title, desc, icon, path
135
 
                new_app = {}
136
 
                new_app['this_app'] = hasattr(self, 'tab') \
137
 
                                      and tab[0] == self.tab
138
 
 
139
 
                # Icon name
140
 
                if tab[3] is not None:
141
 
                    new_app['has_icon'] = True
142
 
                    icon_url = media_url(req, plugin, tab[3])
143
 
                    new_app['icon_url'] = icon_url
144
 
                    if new_app['this_app']:
145
 
                        ctx['favicon'] = icon_url
146
 
                else:
147
 
                    new_app['has_icon'] = False
148
 
                new_app['path'] = req.make_path(tab[4])
149
 
                new_app['desc'] = tab[2]
150
 
                new_app['name'] = tab[1]
151
 
                new_app['weight'] = tab[5]
152
 
                ctx['apps_in_tabs'].append(new_app)
153
 
 
154
 
        ctx['apps_in_tabs'].sort(key=lambda tab: tab['weight'])
155
 
 
156
 
    def render_overlays(self, req):
157
 
        """Generate XML streams for the overlays.
158
 
        
159
 
        Returns a list of streams. Populates the scripts, styles, and 
160
 
        scripts_init.
161
 
        """
162
 
        overlays = []
163
 
        styles = []
164
 
        scripts = []
165
 
        scripts_init = []
166
 
        if not self.allow_overlays:
167
 
            return (overlays, styles, scripts, scripts_init)
168
 
 
169
 
        for plugin in req.config.plugin_index[OverlayPlugin]:
170
 
            for overclass in plugin.overlays:
171
 
                if overclass in self.overlay_blacklist:
172
 
                    continue
173
 
                overlay = overclass(req)
174
 
                #TODO: Re-factor this to look nicer
175
 
                for mplugin in overlay.plugin_scripts:
176
 
                    for path in overlay.plugin_scripts[mplugin]:
177
 
                        scripts.append(media_url(req, mplugin, path))
178
 
 
179
 
                for mplugin in overlay.plugin_styles:
180
 
                    for path in overlay.plugin_styles[mplugin]:
181
 
                        styles.append(media_url(req, mplugin, path))
182
 
 
183
 
                scripts_init += overlay.plugin_scripts_init
184
 
 
185
 
                overlays.append(overlay.render(req))
186
 
        return (overlays, styles, scripts, scripts_init)
187
 
 
188
 
    @classmethod
189
 
    def get_error_view(cls, e):
190
 
        view_map = {HTTPError:    XHTMLErrorView,
191
 
                    Unauthorized: XHTMLUnauthorizedView}
192
 
        for exccls in inspect.getmro(type(e)):
193
 
            if exccls in view_map:
194
 
                return view_map[exccls]
195
 
 
196
 
class XHTMLErrorView(XHTMLView):
197
 
    template = 'xhtmlerror.html'
198
 
 
199
 
    def populate(self, req, ctx):
200
 
        ctx['req'] = req
201
 
        ctx['exception'] = self.context
202
 
 
203
 
class XHTMLUnauthorizedView(XHTMLErrorView):
204
 
    template = 'xhtmlunauthorized.html'
205
 
 
206
 
    def __init__(self, req, exception):
207
 
        super(XHTMLUnauthorizedView, self).__init__(req, exception)
208
 
 
209
 
        if req.user is None:
210
 
            # Not logged in. Redirect to login page.
211
 
            if req.uri == '/':
212
 
                query_string = ''
 
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
213
91
            else:
214
 
                query_string = '?url=' + urllib.quote(req.uri, safe="/~")
215
 
            req.throw_redirect('/+login' + query_string)
216
 
 
217
 
        req.status = 403
 
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)