~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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
# 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: tutorial
# Author: Matt Giuca
# Date: 25/1/2008

# Tutorial application.
# Displays tutorial content with editable problems, allowing students to test
# and submit their solutions to problems and have them auto-tested.

# URL syntax
# All path segments are optional (omitted path segments will show menus).
# The first path segment is the subject code.
# The second path segment is the worksheet name.

import os
import cgi
import urllib
import re
from xml.dom import minidom

import cjson

from common import util
import conf
import plugins.console

THIS_APP = "tutorial"

# Regex for valid identifiers (subject/worksheet names)
re_ident = re.compile("[0-9A-Za-z_]+")

class Worksheet:
    def __init__(self, id, name):
        self.id = id
        self.name = name
    def __repr__(self):
        return ("Worksheet(id=" + repr(self.id) + ", name=" + repr(self.name)
                + ")")

def make_tutorial_path(subject=None, worksheet=None):
    """Creates an absolute (site-relative) path to a tutorial sheet.
    Subject or worksheet can be None.
    Ensures that top-level or subject-level URLs end in a '/', because they
    are represented as directories.
    """
    if subject is None:
        return util.make_path(THIS_APP + '/')
    else:
        if worksheet is None:
            return util.make_path(os.path.join(THIS_APP, subject + '/'))
        else:
            return util.make_path(os.path.join(THIS_APP, subject, worksheet))

def handle(req):
    """Handler for the Tutorial application."""

    # Set request attributes
    req.content_type = "text/html"
    req.scripts = [
        "media/common/util.js",
        "media/common/json2.js",
        "media/tutorial/tutorial.js",
    ]
    req.styles = [
        "media/tutorial/tutorial.css",
    ]
    # Let the console plugin insert its own styles and scripts
    plugins.console.insert_scripts_styles(req.scripts, req.styles)
    # Note: Don't print write_html_head_foot just yet
    # If we encounter errors later we do not want this

    path_segs = req.path.split(os.sep)
    subject = None
    worksheet = None
    if len(path_segs) > 2:
        req.throw_error(req.HTTP_NOT_FOUND)
    elif len(req.path) > 0:
        subject = path_segs[0]
        if len(path_segs) == 2:
            worksheet = path_segs[1]

    if subject == None:
        handle_toplevel_menu(req)
    elif worksheet == None:
        handle_subject_menu(req, subject)
    else:
        handle_worksheet(req, subject, worksheet)
        plugins.console.present(req, windowpane=True)

def handle_toplevel_menu(req):
    # This is represented as a directory. Redirect and add a slash if it is
    # missing.
    if req.uri[-1] != os.sep:
        req.throw_redirect(make_tutorial_path())
    req.write_html_head_foot = True
    req.write('<div id="ivle_padding">\n')
    req.write("<h1>IVLE Tutorials</h1>\n")
    req.write("""<p>Welcome to the IVLE tutorial system.
  Please select a subject from the list below to take a tutorial problem sheet
  for that subject.</p>\n""")
    # Get list of subjects
    # TODO: Fetch from DB. For now, just get directory listing
    subjects = os.listdir(conf.subjects_base)
    subjects.sort()
    req.write("<h2>Subjects</h2>\n<ul>\n")
    for subject in subjects:
        req.write('  <li><a href="%s">%s</a></li>\n'
            % (urllib.quote(subject) + '/', cgi.escape(subject)))
    req.write("</ul>\n")
    req.write("</div>\n")   # tutorialbody

def is_valid_subjname(subject):
    m = re_ident.match(subject)
    return m is not None and m.end() == len(subject)

def handle_subject_menu(req, subject):
    # This is represented as a directory. Redirect and add a slash if it is
    # missing.
    if req.uri[-1] != os.sep:
        req.throw_redirect(make_tutorial_path(subject))
    # Subject names must be valid identifiers
    if not is_valid_subjname(subject):
        req.throw_error(req.HTTP_NOT_FOUND)
    # Parse the subject description file
    # The subject directory must have a file "subject.xml" in it,
    # or it does not exist (404 error).
    try:
        subjectfile = open(os.path.join(conf.subjects_base, subject,
            "subject.xml"))
    except:
        req.throw_error(req.HTTP_NOT_FOUND)

    # Read in data about the subject
    subjectdom = minidom.parse(subjectfile)
    subjectfile.close()
    # TEMP: All of this is for a temporary XML format, which will later
    # change.
    worksheetsdom = subjectdom.documentElement
    worksheets = []     # List of string IDs
    for worksheetdom in worksheetsdom.childNodes:
        if worksheetdom.nodeType == worksheetdom.ELEMENT_NODE:
            worksheet = Worksheet(worksheetdom.getAttribute("id"),
                worksheetdom.getAttribute("name"))
            worksheets.append(worksheet)

    # Now all the errors are out the way, we can begin writing
    req.title = "Tutorial - %s" % subject
    req.write_html_head_foot = True
    req.write('<div id="ivle_padding">\n')
    req.write("<h1>IVLE Tutorials - %s</h1>\n" % cgi.escape(subject))
    req.write("<h2>Worksheets</h2>\n<ul>\n")
    for worksheet in worksheets:
        req.write('  <li><a href="%s">%s</a></li>\n'
            % (urllib.quote(worksheet.id), cgi.escape(worksheet.name)))
    req.write("</ul>\n")
    req.write("</div>\n")   # tutorialbody

def handle_worksheet(req, subject, worksheet):
    # Subject and worksheet names must be valid identifiers
    if not is_valid_subjname(subject) or not is_valid_subjname(worksheet):
        req.throw_error(req.HTTP_NOT_FOUND)

    # Read in worksheet data
    try:
        worksheetfile = open(os.path.join(conf.subjects_base, subject,
            worksheet + ".xml"))
    except:
        req.throw_error(req.HTTP_NOT_FOUND)

    worksheetdom = minidom.parse(worksheetfile)
    worksheetfile.close()
    # TEMP: All of this is for a temporary XML format, which will later
    # change.
    worksheetdom = worksheetdom.documentElement
    if worksheetdom.tagName != "worksheet":
        # TODO: Nicer error message, to help authors
        req.throw_error(req.HTTP_INTERNAL_SERVER_ERROR)
    worksheetname = worksheetdom.getAttribute("name")

    # Now all the errors are out the way, we can begin writing
    req.title = "Tutorial - %s" % worksheetname
    req.write_html_head_foot = True
    req.write('<div id="ivle_padding">\n')
    req.write("<h1>IVLE Tutorials - %s</h1>\n<h2>%s</h2>\n"
        % (cgi.escape(subject), cgi.escape(worksheetname)))

    # Write each element
    problemid = 0
    for node in worksheetdom.childNodes:
        problemid = present_worksheet_node(req, node, problemid)
    req.write("</div>\n")   # tutorialbody

def present_worksheet_node(req, node, problemid):
    """Given a node of a worksheet XML document, writes it out to the
    request. This recursively searches for "problem" elements and handles
    those specially (presenting their XML problem spec and input box), and
    just dumps the other elements as regular HTML.

    problemid is the ID to use for the first problem.
    Returns the new problemid after all the problems have been written
    (since we need unique IDs for each problem).
    """
    if node.nodeType == node.ELEMENT_NODE:
        if node.tagName == "problem":
            present_problem(req, node.getAttribute("src"), problemid)
            problemid += 1
        else:
            # Some other element. Write out its head and foot, and recurse.
            req.write("<" + node.tagName)
            # Attributes
            attrs = map(lambda (k,v): '%s="%s"'
                    % (cgi.escape(k), cgi.escape(v)), node.attributes.items())
            if len(attrs) > 0:
                req.write(" " + ' '.join(attrs))
            req.write(">")
            for childnode in node.childNodes:
                problemid = present_worksheet_node(req, childnode, problemid)
            req.write("</" + node.tagName + ">")
    else:
        # No need to recurse, so just print this node's contents
        req.write(node.toxml())
    return problemid

def innerXML(elem):
    """Given an element, returns its children as XML strings concatenated
    together."""
    s = ""
    for child in elem.childNodes:
        s += child.toxml()
    return s

def getTextData(element):
    """ Get the text and cdata inside an element
    Leading and trailing whitespace are stripped
    """
    data = ''
    for child in element.childNodes:
        if child.nodeType == child.CDATA_SECTION_NODE:
            data += child.data
        if child.nodeType == child.TEXT_NODE:
            data += child.data

    return data.strip()

def present_problem(req, problemsrc, problemid):
    """Open a problem file, and write out the problem to the request in HTML.
    problemsrc: "src" of the problem file. A path relative to the top-level
        problems base directory, as configured in conf.
    """
    req.write('<div class="tuteproblem" id="problem%d">\n'
        % problemid)
    # First normalise the path
    problemsrc = os.path.normpath(problemsrc)
    # Now if it begins with ".." or separator, then it's illegal
    if problemsrc.startswith("..") or problemsrc.startswith(os.sep):
        problemfile = None
    else:
        problemfile = os.path.join(conf.problems_base, problemsrc)

    try:
        problemfile = open(problemfile)
    except (TypeError, IOError):    # TypeError if problemfile == None
        req.write("<p><b>Server Error</b>: "
            + "Problem file could not be opened.</p>\n")
        req.write("</div>\n")
        return
    
    # Read problem file and present the problem
    # Note: We do not use the testing framework because it does a lot more
    # work than we need. We just need to get the problem name and a few other
    # fields from the XML.

    problemdom = minidom.parse(problemfile)
    problemfile.close()
    problemdom = problemdom.documentElement
    if problemdom.tagName != "problem":
        # TODO: Nicer error message, to help authors
        req.throw_error(req.HTTP_INTERNAL_SERVER_ERROR)
    problemname = problemdom.getAttribute("name")
    # Look for some other fields we need, which are elements:
    # - desc
    # - partial
    problemdesc = None
    problempartial= ""
    for elem in problemdom.childNodes:
        if elem.nodeType == elem.ELEMENT_NODE:
            if elem.tagName == "desc":
                problemdesc = innerXML(elem).strip()
            if elem.tagName == "partial":
                problempartial= getTextData(elem) + '\n'

    # Print this problem out to HTML 
    req.write("<p><b>Problem:</b> %s</p>\n" % problemname)
    if problemdesc is not None:
        req.write("<div>%s</div>\n" % problemdesc)
    req.write('<textarea class="problembox" cols="80" rows="12">%s</textarea>'
            % problempartial)
    filename = cgi.escape(cjson.encode(problemsrc), quote=True)
    req.write("""\n<div class="problembuttons">
  <input type="button" value="Run"
    onclick="runproblem(&quot;problem%d&quot;, %s)" />
  <input type="button" value="Submit"
    onclick="submitproblem(&quot;problem%d&quot;, %s)" />
</div>
<div class="testoutput">
</div>
""" % (problemid, filename, problemid, filename))
    req.write("</div>\n")