~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-09 21:33:56 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:144
Trunk, and all subdirectories with Python files:
    Added to svn:ignore all *.pyc *.pyo, to avoid compiled files
    showing up in svn st / diff / commit lists.
    Added to svn:ignore trampoline/trampoline.

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