~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-15 03:06:54 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:229
Images: Reduced "small" icons from 22x22 to 16x16. Reduced "large" icons from
    128x128 to 96x96.
Changed some of the icons for Subversion so they make a bit more sense.
    (Missing and deleted are now distinct).
Modified JavaScript and CSS so the interface flows with 16x16 icons instead of
22. This makes each file vertically a lot shorter.
Made the bands of colour in the file listing much closer together in colour.

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