~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-14 21:34:08 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:228
common/ivle.css: changed font family from "sans" to "sans-serif" (this is
the correct name for the generic family - now it will display correctly on all
browsers).
common/interpret.py: Same change.

Show diffs side-by-side

added added

removed removed

Lines of Context:
22
22
 * Defines some generic JavaScript utility functions.
23
23
 */
24
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
 
25
31
/** Removes all children of a given DOM element
26
32
 * \param elem A DOM Element. Will be modified.
27
33
 */
34
40
/** Creates a DOM element with simple text inside it.
35
41
 * \param tagname String. Name of the element's tag (eg. "p").
36
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).
37
45
 * \return DOM Element object.
38
46
 */
39
 
function dom_make_text_elem(tagname, text)
 
47
function dom_make_text_elem(tagname, text, title)
40
48
{
 
49
    if (text == null) text = "";
41
50
    var elem = document.createElement(tagname);
42
 
    elem.appendChild(document.createTextNode(text));
 
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);
43
61
    return elem;
44
62
}
45
63
 
46
64
/** Creates a DOM element with hyperlinked text inside it.
47
65
 * \param tagname String. Name of the element's tag (eg. "p").
48
66
 * \param text String. Text to be placed inside the element.
 
67
 * \param title String, optional. Sets a tooltip for the link.
49
68
 * \param href String. URL the text will link to. This is a raw string,
50
69
 *  it will automatically be URL-encoded.
51
70
 * \param onclick Optional string. Will be set as the "onclick" attribute
52
71
 *  of the "a" element.
53
72
 * \return DOM Element object.
54
73
 */
55
 
function dom_make_link_elem(tagname, text, href, onclick)
 
74
function dom_make_link_elem(tagname, text, title, href, onclick)
56
75
{
 
76
    if (text == null) text = "";
 
77
    if (href == null) href = "";
57
78
    var elem = document.createElement(tagname);
58
79
    var link = document.createElement("a");
59
 
    link.setAttribute("href", encodeURI(href));
 
80
    link.setAttribute("href", urlencode_path(href));
 
81
    if (title != null)
 
82
        link.setAttribute("title", title);
60
83
    if (onclick != null)
61
84
        link.setAttribute("onclick", onclick);
62
85
    link.appendChild(document.createTextNode(text));
64
87
    return elem;
65
88
}
66
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
 
67
132
/** Given a URL, returns an object containing a number of attributes
68
133
 * describing the components of the URL, similar to CGI request variables.
69
134
 * The object has the following attributes:
84
149
 * args is never null, though it may be empty.
85
150
 *
86
151
 * All strings are decoded/unescaped. Reserved characters
87
 
 * (; , / ? : @ & = + * $) are not decoded except in args.
 
152
 * (; , / ? : @ & = + * $) are not decoded except in args and path.
88
153
 *
89
154
 * \param url String. A URL. To read from the current browser window, use
90
155
 *  window.location.href.
97
162
    var serverpart;
98
163
    var args;
99
164
 
100
 
    url = decodeURI(url);
101
 
 
102
165
    /* Split scheme from rest */
103
166
    index = url.indexOf("://");
104
167
    if (index < 0)
119
182
    else
120
183
    {
121
184
        serverpart = url.substr(0, index);
122
 
        url = url.substr(index+1);
 
185
        url = url.substr(index);
123
186
    }
124
187
 
125
188
    /* Split server name from port */
155
218
            obj.query_string = url.substr(index+1);
156
219
        }
157
220
    }
 
221
    obj.path = decodeURIComponent(obj.path);
158
222
 
159
223
    /* Split query string into arguments */
160
224
    args = {};
242
306
        url += ":" + obj.server_port.toString();
243
307
    if (("path" in obj) && obj.path != null)
244
308
    {
245
 
        var path = obj.path.toString();
 
309
        var path = urlencode_path(obj.path.toString());
246
310
        if (url.length > 0 && path.length > 0 && path[0] != "/")
247
311
            path = "/" + path;
248
312
        url += path;
249
313
    }
250
314
    if (("query_string" in obj) && obj.query_string != null)
251
 
        query_string = obj.query_string.toString();
 
315
        query_string = encodeURI(obj.query_string.toString());
252
316
    else if (("args" in obj) && obj.args != null)
253
317
        query_string = make_query_string(obj.args);
254
318
 
255
319
    if (query_string != null)
256
320
        url += "?" + query_string;
257
321
 
258
 
    return encodeURI(url);
 
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;
259
339
}
260
340
 
261
341
/** Given an argument map, as output in the args parameter of the return of
303
383
function path_join(path1 /*, path2, ... */)
304
384
{
305
385
    var arg;
306
 
    path = path1;
307
 
    for (var i=1; i<arguments.length; i++)
 
386
    var path = "";
 
387
    for (var i=0; i<arguments.length; i++)
308
388
    {
309
389
        arg = arguments[i];
310
390
        if (arg.length == 0) continue;
312
392
            path = arg;
313
393
        else
314
394
        {
315
 
            if (path[path.length-1] != '/')
 
395
            if (path.length > 0 && path[path.length-1] != '/')
316
396
                path += '/';
317
397
            path += arg;
318
398
        }
320
400
    return path;
321
401
}
322
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
 
323
449
/** Converts a list of directories into a path name, with a slash at the end.
324
450
 * \param pathlist List of strings.
325
451
 * \return String.
340
466
    return path_join(root_dir, path);
341
467
}
342
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
 
343
504
/** Makes an XMLHttpRequest call to the server. Waits (synchronously) for a
344
505
 * response, and returns an XMLHttpRequest object containing the completed
345
506
 * response.
348
509
 * \param path URL path to make the request to, within the application.
349
510
 * \param args Argument object, as described in parse_url and friends.
350
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".
351
515
 * \return An XMLHttpRequest object containing the completed response.
352
516
 */
353
 
function ajax_call(app, path, args, method)
 
517
function ajax_call(app, path, args, method, content_type)
354
518
{
355
 
    path = make_path(path_join(app, path));
 
519
    if (content_type != "multipart/form-data")
 
520
        content_type = "application/x-www-form-urlencoded";
 
521
    path = app_path(app, path);
356
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";
357
527
    var xhr = new XMLHttpRequest();
358
528
    if (method == "GET")
359
529
    {
362
532
        /* open's 3rd argument = false -> SYNCHRONOUS (wait for response)
363
533
         * (No need for a callback function) */
364
534
        xhr.open(method, url, false);
365
 
        xhr.send("");
 
535
        xhr.send(null);
366
536
    }
367
537
    else
368
538
    {
369
539
        /* POST sends the args in application/x-www-form-urlencoded */
370
540
        url = encodeURI(path);
371
541
        xhr.open(method, url, false);
372
 
        xhr.setRequestHeader("Content-Type",
373
 
            "application/x-www-form-urlencoded");
374
 
        var message = make_query_string(args);
 
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
        }
375
554
        xhr.send(message);
376
555
    }
377
556
    return xhr;
378
557
}
 
558