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

« back to all changes in this revision

Viewing changes to www/media/common/util.js

  • Committer: mattgiuca
  • Date: 2008-01-10 22:11:40 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:170
browser: Added CSS and JS files (not much in them).
media/common: Added json2.js, a minified version of the official JSON
    JavaScript library.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/* IVLE - Informatics Virtual Learning Environment
2
 
 * Copyright (C) 2007-2008 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
 
 * Module: JavaScript Utilities
19
 
 * Author: Matt Giuca
20
 
 * Date: 11/1/2008
21
 
 *
22
 
 * Defines some generic JavaScript utility functions.
23
 
 */
24
 
 
25
 
/** Removes all children of a given DOM element
26
 
 * \param elem A DOM Element. Will be modified.
27
 
 */
28
 
function dom_removechildren(elem)
29
 
{
30
 
    while (elem.lastChild != null)
31
 
        elem.removeChild(elem.lastChild);
32
 
}
33
 
 
34
 
/** Creates a DOM element with simple text inside it.
35
 
 * \param tagname String. Name of the element's tag (eg. "p").
36
 
 * \param text String. Text to be placed inside the element.
37
 
 * \return DOM Element object.
38
 
 */
39
 
function dom_make_text_elem(tagname, text)
40
 
{
41
 
    var elem = document.createElement(tagname);
42
 
    elem.appendChild(document.createTextNode(text));
43
 
    return elem;
44
 
}
45
 
 
46
 
/** Creates a DOM element with hyperlinked text inside it.
47
 
 * \param tagname String. Name of the element's tag (eg. "p").
48
 
 * \param text String. Text to be placed inside the element.
49
 
 * \param href String. URL the text will link to. This is a raw string,
50
 
 *  it will automatically be URL-encoded.
51
 
 * \param onclick Optional string. Will be set as the "onclick" attribute
52
 
 *  of the "a" element.
53
 
 * \return DOM Element object.
54
 
 */
55
 
function dom_make_link_elem(tagname, text, href, onclick)
56
 
{
57
 
    var elem = document.createElement(tagname);
58
 
    var link = document.createElement("a");
59
 
    link.setAttribute("href", encodeURI(href));
60
 
    if (onclick != null)
61
 
        link.setAttribute("onclick", onclick);
62
 
    link.appendChild(document.createTextNode(text));
63
 
    elem.appendChild(link);
64
 
    return elem;
65
 
}
66
 
 
67
 
/** Given a number of bytes, returns a string representing the file size in a
68
 
 * human-readable format.
69
 
 * eg. nice_filesize(6) -> "6 bytes"
70
 
 *     nice_filesize(81275) -> "79.4 kB"
71
 
 *     nice_filesize(13498346) -> "12.9 MB"
72
 
 * \param bytes Number of bytes. Must be an integer.
73
 
 * \return String.
74
 
 */
75
 
function nice_filesize(bytes)
76
 
{
77
 
    var size;
78
 
    if (bytes < 1024)
79
 
        return bytes.toString() + " bytes";
80
 
    size = bytes / 1024;
81
 
    if (size < 1024)
82
 
        return size.toFixed(1) + " kB";
83
 
    size = size / 1024;
84
 
    if (size < 1024)
85
 
        return size.toFixed(1) + " MB";
86
 
    size = size / 1024;
87
 
    return size.toFixed(1) + " GB";
88
 
}
89
 
 
90
 
/** Given a URL, returns an object containing a number of attributes
91
 
 * describing the components of the URL, similar to CGI request variables.
92
 
 * The object has the following attributes:
93
 
 * - scheme
94
 
 * - server_name
95
 
 * - server_port
96
 
 * - path
97
 
 * - query_string
98
 
 * - args
99
 
 * The first five of these are strings, which comprise the URL as follows:
100
 
 * <scheme> "://" <server_name> ":" <server_port> <path> "?" <query_string>
101
 
 * Any of these strings may be set to null if not found.
102
 
 *
103
 
 * "args" is an object whose attributes are the query_string arguments broken
104
 
 * up.
105
 
 * Args values are strings for single values, arrays of strings for values
106
 
 * whose names appear multiple times.
107
 
 * args is never null, though it may be empty.
108
 
 *
109
 
 * All strings are decoded/unescaped. Reserved characters
110
 
 * (; , / ? : @ & = + * $) are not decoded except in args.
111
 
 *
112
 
 * \param url String. A URL. To read from the current browser window, use
113
 
 *  window.location.href.
114
 
 * \return The above described object.
115
 
 */
116
 
function parse_url(url)
117
 
{
118
 
    var obj = {};
119
 
    var index;
120
 
    var serverpart;
121
 
    var args;
122
 
 
123
 
    url = decodeURI(url);
124
 
 
125
 
    /* Split scheme from rest */
126
 
    index = url.indexOf("://");
127
 
    if (index < 0)
128
 
        obj.scheme = null;
129
 
    else
130
 
    {
131
 
        obj.scheme = url.substr(0, index);
132
 
        url = url.substr(index+3);
133
 
    }
134
 
 
135
 
    /* Split server name/port from rest */
136
 
    index = url.indexOf("/");
137
 
    if (index < 0)
138
 
    {
139
 
        serverpart = url;
140
 
        url = null;
141
 
    }
142
 
    else
143
 
    {
144
 
        serverpart = url.substr(0, index);
145
 
        url = url.substr(index+1);
146
 
    }
147
 
 
148
 
    /* Split server name from port */
149
 
    index = serverpart.indexOf(":");
150
 
    if (index < 0)
151
 
    {
152
 
        obj.server_name = serverpart;
153
 
        obj.server_port = null;
154
 
    }
155
 
    else
156
 
    {
157
 
        obj.server_name = serverpart.substr(0, index);
158
 
        obj.server_port = serverpart.substr(index+1);
159
 
    }
160
 
 
161
 
    /* Split path from query string */
162
 
    if (url == null)
163
 
    {
164
 
        obj.path = null;
165
 
        obj.query_string = null;
166
 
    }
167
 
    else
168
 
    {
169
 
        index = url.indexOf("?");
170
 
        if (index < 0)
171
 
        {
172
 
            obj.path = url;
173
 
            obj.query_string = null;
174
 
        }
175
 
        else
176
 
        {
177
 
            obj.path = url.substr(0, index);
178
 
            obj.query_string = url.substr(index+1);
179
 
        }
180
 
    }
181
 
 
182
 
    /* Split query string into arguments */
183
 
    args = {};
184
 
    if (obj.query_string != null)
185
 
    {
186
 
        var args_strs = obj.query_string.split("&");
187
 
        var arg_str;
188
 
        var arg_key, arg_val;
189
 
        for (var i=0; i<args_strs.length; i++)
190
 
        {
191
 
            arg_str = args_strs[i];
192
 
            index = arg_str.indexOf("=");
193
 
            /* Ignore malformed args */
194
 
            if (index >= 0)
195
 
            {
196
 
                arg_key = decodeURIComponent(arg_str.substr(0, index));
197
 
                arg_val = decodeURIComponent(arg_str.substr(index+1));
198
 
                if (arg_key in args)
199
 
                {
200
 
                    /* Collision - make an array */
201
 
                    if (args[arg_key] instanceof Array)
202
 
                        args[arg_key][args[arg_key].length] = arg_val;
203
 
                    else
204
 
                        args[arg_key] = [args[arg_key], arg_val];
205
 
                }
206
 
                else
207
 
                    args[arg_key] = arg_val;
208
 
            }
209
 
        }
210
 
    }
211
 
    obj.args = args;
212
 
 
213
 
    return obj;
214
 
}
215
 
 
216
 
/** Builds a query_string from an args object. Encodes the arguments.
217
 
 * \param args Args object as described in parse_url.
218
 
 * \return Query string portion of a URL.
219
 
 */
220
 
function make_query_string(args)
221
 
{
222
 
    var query_string = "";
223
 
    var arg_val;
224
 
    for (var arg_key in args)
225
 
    {
226
 
        arg_val = args[arg_key];
227
 
        if (arg_val instanceof Array)
228
 
            for (var i=0; i<arg_val.length; i++)
229
 
                query_string += "&" + encodeURIComponent(arg_key) + "=" +
230
 
                    encodeURIComponent(arg_val[i]);
231
 
        else
232
 
            query_string += "&" + encodeURIComponent(arg_key) + "=" +
233
 
                encodeURIComponent(arg_val);
234
 
    }
235
 
    if (query_string == "")
236
 
        query_string = null;
237
 
    else
238
 
        /* Drop the first "&" */
239
 
        query_string = query_string.substr(1);
240
 
 
241
 
    return query_string;
242
 
}
243
 
 
244
 
/** Given an object exactly of the form described for the output of parseurl,
245
 
 * returns a URL string built from those parameters. The URL is properly
246
 
 * encoded.
247
 
 * parseurl and buildurl are strict inverses of each other.
248
 
 * Note that either query_string or args may be supplied. If both are
249
 
 * supplied, query_string is preferred (because it keeps the argument order).
250
 
 * If you take a url from parseurl, modify args, and pass to buildurl,
251
 
 * you need to set query_string to null to use the new args.
252
 
 * \param obj Object as returned by parseurl.
253
 
 * \return String, a URL.
254
 
 */
255
 
function build_url(obj)
256
 
{
257
 
    var url = "";
258
 
    var query_string = null;
259
 
 
260
 
    if (("scheme" in obj) && obj.scheme != null)
261
 
        url = obj.scheme.toString() + "://";
262
 
    if (("server_name" in obj) && obj.server_name != null)
263
 
        url += obj.server_name.toString();
264
 
    if (("server_port" in obj) && obj.server_port != null)
265
 
        url += ":" + obj.server_port.toString();
266
 
    if (("path" in obj) && obj.path != null)
267
 
    {
268
 
        var path = obj.path.toString();
269
 
        if (url.length > 0 && path.length > 0 && path[0] != "/")
270
 
            path = "/" + path;
271
 
        url += path;
272
 
    }
273
 
    if (("query_string" in obj) && obj.query_string != null)
274
 
        query_string = obj.query_string.toString();
275
 
    else if (("args" in obj) && obj.args != null)
276
 
        query_string = make_query_string(obj.args);
277
 
 
278
 
    if (query_string != null)
279
 
        url += "?" + query_string;
280
 
 
281
 
    return encodeURI(url);
282
 
}
283
 
 
284
 
/** Given an argument map, as output in the args parameter of the return of
285
 
 * parseurl, gets the first occurence of an argument in the URL string.
286
 
 * If the argument was not found, returns null.
287
 
 * If there was a single argument, returns the argument.
288
 
 * If there were multiple arguments, returns the first.
289
 
 * \param args Object mapping arguments to strings or arrays of strings.
290
 
 * \param arg String. Argument name.
291
 
 * \return String.
292
 
 */
293
 
function arg_getfirst(args, arg)
294
 
{
295
 
    if (!(arg in args))
296
 
        return null;
297
 
    var r = args[arg];
298
 
    if (r instanceof Array)
299
 
        return r[0];
300
 
    else
301
 
        return r;
302
 
}
303
 
 
304
 
/** Given an argument map, as output in the args parameter of the return of
305
 
 * parseurl, gets all occurences of an argument in the URL string, as an
306
 
 * array.
307
 
 * If the argument was not found, returns [].
308
 
 * Otherwise, returns all occurences as an array, even if there was only one.
309
 
 * \param args Object mapping arguments to strings or arrays of strings.
310
 
 * \param arg String. Argument name.
311
 
 * \return Array of strings.
312
 
 */
313
 
function arg_getlist(args, arg)
314
 
{
315
 
    if (!(arg in args))
316
 
        return [];
317
 
    var r = args[arg];
318
 
    if (r instanceof Array)
319
 
        return r;
320
 
    else
321
 
        return [r];
322
 
}
323
 
 
324
 
/** Joins one or more paths together. Accepts 1 or more arguments.
325
 
 */
326
 
function path_join(path1 /*, path2, ... */)
327
 
{
328
 
    var arg;
329
 
    path = path1;
330
 
    for (var i=1; i<arguments.length; i++)
331
 
    {
332
 
        arg = arguments[i];
333
 
        if (arg.length == 0) continue;
334
 
        if (arg[0] == '/')
335
 
            path = arg;
336
 
        else
337
 
        {
338
 
            if (path[path.length-1] != '/')
339
 
                path += '/';
340
 
            path += arg;
341
 
        }
342
 
    }
343
 
    return path;
344
 
}
345
 
 
346
 
 
347
 
/** Builds a multipart_formdata string from an args object. Similar to
348
 
 * make_query_string, but it returns data of type "multipart/form-data"
349
 
 * instead of "application/x-www-form-urlencoded". This is good for
350
 
 * encoding large strings such as text objects from the editor.
351
 
 * Should be written with a Content-Type of
352
 
 * "multipart/form-data, boundary=<boundary>".
353
 
 * All fields are sent with a Content-Type of text/plain.
354
 
 * \param args Args object as described in parse_url.
355
 
 * \param boundary Random "magic" string which DOES NOT appear in any of
356
 
 *  the argument values. This should match the "boundary=" value written to
357
 
 *  the Content-Type header.
358
 
 * \return String in multipart/form-data format.
359
 
 */
360
 
function make_multipart_formdata(args, boundary)
361
 
{
362
 
    var data = "";
363
 
    var arg_val;
364
 
    /* Mutates data */
365
 
    var extend_data = function(arg_key, arg_val)
366
 
    {
367
 
        /* FIXME: Encoding not supported here (should not matter if we
368
 
         * only use ASCII names */
369
 
        data += "--" + boundary + "\n"
370
 
            + "Content-Disposition: form-data; name=\"" + arg_key
371
 
            + "\"\n\n"
372
 
            + arg_val + "\n";
373
 
    }
374
 
 
375
 
    for (var arg_key in args)
376
 
    {
377
 
        arg_val = args[arg_key];
378
 
        if (arg_val instanceof Array)
379
 
            for (var i=0; i<arg_val.length; i++)
380
 
            {
381
 
                extend_data(arg_key, arg_val[i]);
382
 
            }
383
 
        else
384
 
            extend_data(arg_key, arg_val);
385
 
    }
386
 
    /* End boundary */
387
 
    data += "--" + boundary + "--\n";
388
 
 
389
 
    return data;
390
 
}
391
 
 
392
 
/** Converts a list of directories into a path name, with a slash at the end.
393
 
 * \param pathlist List of strings.
394
 
 * \return String.
395
 
 */
396
 
function pathlist_to_path(pathlist)
397
 
{
398
 
    ret = path_join.apply(null, pathlist);
399
 
    if (ret[ret.length-1] != '/')
400
 
        ret += '/';
401
 
    return ret;
402
 
}
403
 
 
404
 
/** Given a path relative to the IVLE root, gives a path relative to
405
 
 * the site root.
406
 
 */
407
 
function make_path(path)
408
 
{
409
 
    return path_join(root_dir, path);
410
 
}
411
 
 
412
 
/** Makes an XMLHttpRequest call to the server. Waits (synchronously) for a
413
 
 * response, and returns an XMLHttpRequest object containing the completed
414
 
 * response.
415
 
 *
416
 
 * \param app IVLE app to call (such as "fileservice").
417
 
 * \param path URL path to make the request to, within the application.
418
 
 * \param args Argument object, as described in parse_url and friends.
419
 
 * \param method String; "GET" or "POST"
420
 
 * \param content_type String, optional. Only applies if method is "POST".
421
 
 *      May be "application/x-www-form-urlencoded" or "multipart/form-data".
422
 
 *      Defaults to "application/x-www-form-urlencoded".
423
 
 * \return An XMLHttpRequest object containing the completed response.
424
 
 */
425
 
function ajax_call(app, path, args, method, content_type)
426
 
{
427
 
    if (content_type != "multipart/form-data")
428
 
        content_type = "application/x-www-form-urlencoded";
429
 
    path = make_path(path_join(app, path));
430
 
    var url;
431
 
    /* A random string, for multipart/form-data
432
 
     * (This is not checked against anywhere else, it is solely defined and
433
 
     * used within this function) */
434
 
    var boundary = "48234n334nu7n4n2ynonjn234t683jyh80j";
435
 
    var xhr = new XMLHttpRequest();
436
 
    if (method == "GET")
437
 
    {
438
 
        /* GET sends the args in the URL */
439
 
        url = build_url({"path": path, "args": args});
440
 
        /* open's 3rd argument = false -> SYNCHRONOUS (wait for response)
441
 
         * (No need for a callback function) */
442
 
        xhr.open(method, url, false);
443
 
        xhr.send("");
444
 
    }
445
 
    else
446
 
    {
447
 
        /* POST sends the args in application/x-www-form-urlencoded */
448
 
        url = encodeURI(path);
449
 
        xhr.open(method, url, false);
450
 
        var message;
451
 
        if (content_type == "multipart/form-data")
452
 
        {
453
 
            xhr.setRequestHeader("Content-Type",
454
 
                "multipart/form-data, boundary=" + boundary);
455
 
            message = make_multipart_formdata(args, boundary);
456
 
        }
457
 
        else
458
 
        {
459
 
            xhr.setRequestHeader("Content-Type", content_type);
460
 
            message = make_query_string(args);
461
 
        }
462
 
        xhr.send(message);
463
 
    }
464
 
    return xhr;
465
 
}
466