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

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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# IVLE
# Copyright (C) 2007-2008 The University of Melbourne
#
# 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 St, Fifth Floor, Boston, MA  02110-1301  USA

# App: subjects
# Author: Matt Giuca
# Date: 29/2/2008

# This is an IVLE application.
# A sample / testing application for IVLE.

import os
import os.path
import urllib
import urlparse
import cgi

from storm.locals import Desc
import genshi
from genshi.filters import HTMLFormFiller
from genshi.template import Context, TemplateLoader
import formencode

from ivle.webapp.base.xhtml import XHTMLView
from ivle.webapp.base.plugins import ViewPlugin, MediaPlugin
from ivle.webapp.errors import NotFound

from ivle.database import Subject, Semester, Offering, Enrolment, User,\
                          ProjectSet, Project, ProjectSubmission
from ivle import util
import ivle.date

from ivle.webapp.admin.projectservice import ProjectSetRESTView,\
                                             ProjectRESTView
from ivle.webapp.admin.offeringservice import OfferingRESTView


class SubjectsView(XHTMLView):
    '''The view of the list of subjects.'''
    template = 'templates/subjects.html'
    tab = 'subjects'

    def authorize(self, req):
        return req.user is not None

    def populate(self, req, ctx):
        ctx['user'] = req.user
        ctx['semesters'] = []
        for semester in req.store.find(Semester).order_by(Desc(Semester.year),
                                                     Desc(Semester.semester)):
            enrolments = semester.enrolments.find(user=req.user)
            if enrolments.count():
                ctx['semesters'].append((semester, enrolments))


class UserValidator(formencode.FancyValidator):
    """A FormEncode validator that turns a username into a user.

    The state must have a 'store' attribute, which is the Storm store
    to use."""
    def _to_python(self, value, state):
        user = User.get_by_login(state.store, value)
        if user:
            return user
        else:
            raise formencode.Invalid('User does not exist', value, state)


class NoEnrolmentValidator(formencode.FancyValidator):
    """A FormEncode validator that ensures absence of an enrolment.

    The state must have an 'offering' attribute.
    """
    def _to_python(self, value, state):
        if state.offering.get_enrolment(value):
            raise formencode.Invalid('User already enrolled', value, state)
        return value


class EnrolSchema(formencode.Schema):
    user = formencode.All(NoEnrolmentValidator(), UserValidator())


class EnrolView(XHTMLView):
    """A form to enrol a user in an offering."""
    template = 'templates/enrol.html'
    tab = 'subjects'
    permission = 'edit'

    def __init__(self, req, subject, year, semester):
        """Find the given offering by subject, year and semester."""
        self.context = req.store.find(Offering,
            Offering.subject_id == Subject.id,
            Subject.short_name == subject,
            Offering.semester_id == Semester.id,
            Semester.year == year,
            Semester.semester == semester).one()

        if not self.context:
            raise NotFound()

    def filter(self, stream, ctx):
        return stream | HTMLFormFiller(data=ctx['data'])

    def populate(self, req, ctx):
        if req.method == 'POST':
            data = dict(req.get_fieldstorage())
            try:
                validator = EnrolSchema()
                req.offering = self.context # XXX: Getting into state.
                data = validator.to_python(data, state=req)
                self.context.enrol(data['user'])
                req.store.commit()
                req.throw_redirect(req.uri)
            except formencode.Invalid, e:
                errors = e.unpack_errors()
        else:
            data = {}
            errors = {}

        ctx['data'] = data or {}
        ctx['offering'] = self.context
        ctx['errors'] = errors

class OfferingProjectsView(XHTMLView):
    """View the projects for an offering."""
    template = 'templates/offering_projects.html'
    permission = 'edit'
    tab = 'subjects'
    
    def __init__(self, req, subject, year, semester):
        self.context = req.store.find(Offering,
            Offering.subject_id == Subject.id,
            Subject.short_name == subject,
            Offering.semester_id == Semester.id,
            Semester.year == year,
            Semester.semester == semester).one()

        if not self.context:
            raise NotFound()

    def project_url(self, projectset, project):
        return "/subjects/%s/%s/%s/+projects/%s" % (
                    self.context.subject.short_name,
                    self.context.semester.year,
                    self.context.semester.semester,
                    project.short_name
                    )

    def new_project_url(self, projectset):
        return "/api/subjects/" + self.context.subject.short_name + "/" +\
                self.context.semester.year + "/" + \
                self.context.semester.semester + "/+projectsets/" +\
                str(projectset.id) + "/+projects/+new"
    
    def populate(self, req, ctx):
        self.plugin_styles[Plugin] = ["project.css"]
        self.plugin_scripts[Plugin] = ["project.js"]
        ctx['offering'] = self.context
        ctx['projectsets'] = []

        #Open the projectset Fragment, and render it for inclusion
        #into the ProjectSets page
        #XXX: This could be a lot cleaner
        loader = genshi.template.TemplateLoader(".", auto_reload=True)

        set_fragment = os.path.join(os.path.dirname(__file__),
                "templates/projectset_fragment.html")
        project_fragment = os.path.join(os.path.dirname(__file__),
                "templates/project_fragment.html")

        for projectset in self.context.project_sets:
            settmpl = loader.load(set_fragment)
            setCtx = Context()
            setCtx['projectset'] = projectset
            setCtx['new_project_url'] = self.new_project_url(projectset)
            setCtx['projects'] = []

            for project in projectset.projects:
                projecttmpl = loader.load(project_fragment)
                projectCtx = Context()
                projectCtx['project'] = project
                projectCtx['project_url'] = self.project_url(projectset, project)

                setCtx['projects'].append(
                        projecttmpl.generate(projectCtx))

            ctx['projectsets'].append(settmpl.generate(setCtx))


class ProjectView(XHTMLView):
    """View the submissions for a ProjectSet"""
    template = "templates/project.html"
    permission = "edit"
    tab = 'subjects'

    def __init__(self, req, subject, year, semester, project):
        self.context = req.store.find(Project,
                Project.short_name == project,
                Project.project_set_id == ProjectSet.id,
                ProjectSet.offering_id == Offering.id,
                Offering.semester_id == Semester.id,
                Semester.year == year,
                Semester.semester == semester,
                Offering.subject_id == Subject.id,
                Subject.short_name == subject).one()
        if self.context is None:
            raise NotFound()

    def build_subversion_url(self, svnroot, submission):
        princ = submission.assessed.principal

        if isinstance(princ, User):
            path = 'users/%s' % princ.login
        else:
            path = 'groups/%s_%s_%s_%s' % (
                    princ.project_set.offering.subject.short_name,
                    princ.project_set.offering.semester.year,
                    princ.project_set.offering.semester.semester,
                    princ.name
                    )
        return urlparse.urljoin(
                    svnroot,
                    os.path.join(path, submission.path[1:] if
                                       submission.path.startswith(os.sep) else
                                       submission.path))

    def populate(self, req, ctx):
        self.plugin_styles[Plugin] = ["project.css"]

        ctx['format_datetime_short'] = ivle.date.format_datetime_for_paragraph
        ctx['build_subversion_url'] = self.build_subversion_url
        ctx['svn_addr'] = req.config['urls']['svn_addr']
        ctx['project'] = self.context
        ctx['user'] = req.user

class Plugin(ViewPlugin, MediaPlugin):
    urls = [
        ('subjects/', SubjectsView),
        ('subjects/:subject/:year/:semester/+enrolments/+new', EnrolView),
        ('subjects/:subject/:year/:semester/+projects', OfferingProjectsView),
        ('subjects/:subject/:year/:semester/+projects/:project', ProjectView),
        #API Views
        ('api/subjects/:subject/:year/:semester/+projectsets/+new',
            OfferingRESTView),
        ('api/subjects/:subject/:year/:semester/+projectsets/:projectset/+projects/+new',
            ProjectSetRESTView),
        ('api/subjects/:subject/:year/:semester/+projects/:project', 
            ProjectRESTView),

    ]

    tabs = [
        ('subjects', 'Subjects',
         'View subject content and complete worksheets',
         'subjects.png', 'subjects', 5)
    ]

    media = 'subject-media'