~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-25 03:53:12 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:308
util.js: Multipart/form-data output: Newlines are \r\n instead of \n.
    \n caused mod_python's handler to complain.

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.
 
72
 * \param dontencode Optional boolean. If true, will not encode the href.
 
73
 *  if including query strings, you must set this to true and use build_url
 
74
 *  to escape the URI correctly.
53
75
 * \return DOM Element object.
54
76
 */
55
 
function dom_make_link_elem(tagname, text, href, onclick)
 
77
function dom_make_link_elem(tagname, text, title, href, onclick, dontencode)
56
78
{
 
79
    if (text == null) text = "";
 
80
    if (href == null) href = "";
57
81
    var elem = document.createElement(tagname);
58
82
    var link = document.createElement("a");
59
 
    link.setAttribute("href", encodeURI(href));
 
83
    if (dontencode != true)
 
84
        href = urlencode_path(href);
 
85
    link.setAttribute("href", href);
 
86
    if (title != null)
 
87
        link.setAttribute("title", title);
60
88
    if (onclick != null)
61
89
        link.setAttribute("onclick", onclick);
62
90
    link.appendChild(document.createTextNode(text));
64
92
    return elem;
65
93
}
66
94
 
 
95
/** Creates a DOM img element. All parameters are optional except src.
 
96
 * If alt (compulsory in HTML) is omitted, will be set to "".
 
97
 */
 
98
function dom_make_img(src, width, height, title, alt)
 
99
{
 
100
    var img = document.createElement("img");
 
101
    img.setAttribute("src", urlencode_path(src));
 
102
    if (width != null)
 
103
        img.setAttribute("width", width);
 
104
    if (height != null)
 
105
        img.setAttribute("height", height);
 
106
    if (title != null)
 
107
        img.setAttribute("title", title);
 
108
    if (alt == null) alt = "";
 
109
    img.setAttribute("alt", alt);
 
110
    return img;
 
111
}
 
112
 
 
113
/** Given a number of bytes, returns a string representing the file size in a
 
114
 * human-readable format.
 
115
 * eg. nice_filesize(6) -> "6 bytes"
 
116
 *     nice_filesize(81275) -> "79.4 kB"
 
117
 *     nice_filesize(13498346) -> "12.9 MB"
 
118
 * \param bytes Number of bytes. Must be an integer.
 
119
 * \return String.
 
120
 */
 
121
function nice_filesize(bytes)
 
122
{
 
123
    if (bytes == null) return "";
 
124
    var size;
 
125
    if (bytes < 1024)
 
126
        return bytes.toString() + " B";
 
127
    size = bytes / 1024;
 
128
    if (size < 1024)
 
129
        return size.toFixed(1) + " kB";
 
130
    size = size / 1024;
 
131
    if (size < 1024)
 
132
        return size.toFixed(1) + " MB";
 
133
    size = size / 1024;
 
134
    return size.toFixed(1) + " GB";
 
135
}
 
136
 
67
137
/** Given a URL, returns an object containing a number of attributes
68
138
 * describing the components of the URL, similar to CGI request variables.
69
139
 * The object has the following attributes:
84
154
 * args is never null, though it may be empty.
85
155
 *
86
156
 * All strings are decoded/unescaped. Reserved characters
87
 
 * (; , / ? : @ & = + * $) are not decoded except in args.
 
157
 * (; , / ? : @ & = + * $) are not decoded except in args and path.
88
158
 *
89
159
 * \param url String. A URL. To read from the current browser window, use
90
160
 *  window.location.href.
97
167
    var serverpart;
98
168
    var args;
99
169
 
100
 
    url = decodeURI(url);
101
 
 
102
170
    /* Split scheme from rest */
103
171
    index = url.indexOf("://");
104
172
    if (index < 0)
119
187
    else
120
188
    {
121
189
        serverpart = url.substr(0, index);
122
 
        url = url.substr(index+1);
 
190
        url = url.substr(index);
123
191
    }
124
192
 
125
193
    /* Split server name from port */
155
223
            obj.query_string = url.substr(index+1);
156
224
        }
157
225
    }
 
226
    obj.path = decodeURIComponent(obj.path);
158
227
 
159
228
    /* Split query string into arguments */
160
229
    args = {};
242
311
        url += ":" + obj.server_port.toString();
243
312
    if (("path" in obj) && obj.path != null)
244
313
    {
245
 
        var path = obj.path.toString();
 
314
        var path = urlencode_path(obj.path.toString());
246
315
        if (url.length > 0 && path.length > 0 && path[0] != "/")
247
316
            path = "/" + path;
248
317
        url += path;
249
318
    }
250
319
    if (("query_string" in obj) && obj.query_string != null)
251
 
        query_string = obj.query_string.toString();
 
320
        query_string = encodeURI(obj.query_string.toString());
252
321
    else if (("args" in obj) && obj.args != null)
253
322
        query_string = make_query_string(obj.args);
254
323
 
255
324
    if (query_string != null)
256
325
        url += "?" + query_string;
257
326
 
258
 
    return encodeURI(url);
 
327
    return url;
 
328
}
 
329
 
 
330
/** URL-encodes a path. This is a special case of URL encoding as all
 
331
 * characters *except* the slash must be encoded.
 
332
 */
 
333
function urlencode_path(path)
 
334
{
 
335
    /* Split up the path, URLEncode each segment with encodeURIComponent,
 
336
     * and rejoin.
 
337
     */
 
338
    var split = path.split('/');
 
339
    for (var i=0; i<split.length; i++)
 
340
        split[i] = encodeURIComponent(split[i]);
 
341
    path = path_join.apply(null, split);
 
342
    if (split[0] == "" && split.length > 1) path = "/" + path;
 
343
    return path;
259
344
}
260
345
 
261
346
/** Given an argument map, as output in the args parameter of the return of
303
388
function path_join(path1 /*, path2, ... */)
304
389
{
305
390
    var arg;
306
 
    path = path1;
307
 
    for (var i=1; i<arguments.length; i++)
 
391
    var path = "";
 
392
    for (var i=0; i<arguments.length; i++)
308
393
    {
309
394
        arg = arguments[i];
310
395
        if (arg.length == 0) continue;
312
397
            path = arg;
313
398
        else
314
399
        {
315
 
            if (path[path.length-1] != '/')
 
400
            if (path.length > 0 && path[path.length-1] != '/')
316
401
                path += '/';
317
402
            path += arg;
318
403
        }
320
405
    return path;
321
406
}
322
407
 
 
408
 
 
409
/** Builds a multipart_formdata string from an args object. Similar to
 
410
 * make_query_string, but it returns data of type "multipart/form-data"
 
411
 * instead of "application/x-www-form-urlencoded". This is good for
 
412
 * encoding large strings such as text objects from the editor.
 
413
 * Should be written with a Content-Type of
 
414
 * "multipart/form-data, boundary=<boundary>".
 
415
 * All fields are sent with a Content-Type of text/plain.
 
416
 * \param args Args object as described in parse_url.
 
417
 * \param boundary Random "magic" string which DOES NOT appear in any of
 
418
 *  the argument values. This should match the "boundary=" value written to
 
419
 *  the Content-Type header.
 
420
 * \return String in multipart/form-data format.
 
421
 */
 
422
function make_multipart_formdata(args, boundary)
 
423
{
 
424
    var data = "";
 
425
    var arg_val;
 
426
    /* Mutates data */
 
427
    var extend_data = function(arg_key, arg_val)
 
428
    {
 
429
        /* FIXME: Encoding not supported here (should not matter if we
 
430
         * only use ASCII names */
 
431
        data += "--" + boundary + "\r\n"
 
432
            + "Content-Disposition: form-data; name=\"" + arg_key
 
433
            + "\"\r\n\r\n"
 
434
            + arg_val + "\r\n";
 
435
    }
 
436
 
 
437
    for (var arg_key in args)
 
438
    {
 
439
        arg_val = args[arg_key];
 
440
        if (arg_val instanceof Array)
 
441
            for (var i=0; i<arg_val.length; i++)
 
442
            {
 
443
                extend_data(arg_key, arg_val[i]);
 
444
            }
 
445
        else
 
446
            extend_data(arg_key, arg_val);
 
447
    }
 
448
    /* End boundary */
 
449
    data += "--" + boundary + "--\r\n";
 
450
 
 
451
    return data;
 
452
}
 
453
 
323
454
/** Converts a list of directories into a path name, with a slash at the end.
324
455
 * \param pathlist List of strings.
325
456
 * \return String.
340
471
    return path_join(root_dir, path);
341
472
}
342
473
 
 
474
/** Shorthand for make_path(path_join(app, ...))
 
475
 * Creates an absolute path for a given path within a given app.
 
476
 */
 
477
function app_path(app /*,...*/)
 
478
{
 
479
    return make_path(path_join.apply(null, arguments));
 
480
}
 
481
 
 
482
/** Given a path, gets the "basename" (the last path segment).
 
483
 */
 
484
function path_basename(path)
 
485
{
 
486
    segments = path.split("/");
 
487
    if (segments[segments.length-1].length == 0)
 
488
        return segments[segments.length-2];
 
489
    else
 
490
        return segments[segments.length-1];
 
491
}
 
492
 
 
493
/** Given a string str, determines whether it ends with substr */
 
494
function endswith(str, substring)
 
495
{
 
496
    if (str.length < substring.length) return false;
 
497
    return str.substr(str.length - substring.length) == substring;
 
498
}
 
499
 
 
500
/** Equivalent to Python's repr.
 
501
 * Gets the JavaScript string representation.
 
502
 * Actually just calls JSON.stringify.
 
503
 */
 
504
function repr(str)
 
505
{
 
506
    return JSON.stringify(str);
 
507
}
 
508
 
 
509
/** Removes all occurences of a value from an array.
 
510
 */
 
511
Array.prototype.removeall = function(val)
 
512
{
 
513
    var i, j;
 
514
    var arr = this;
 
515
    j = 0;
 
516
    for (i=0; i<arr.length; i++)
 
517
    {
 
518
        arr[j] = arr[i];
 
519
        if (arr[i] != val) j++;
 
520
    }
 
521
    arr.splice(j, i-j);
 
522
}
 
523
 
343
524
/** Makes an XMLHttpRequest call to the server. Waits (synchronously) for a
344
525
 * response, and returns an XMLHttpRequest object containing the completed
345
526
 * response.
348
529
 * \param path URL path to make the request to, within the application.
349
530
 * \param args Argument object, as described in parse_url and friends.
350
531
 * \param method String; "GET" or "POST"
 
532
 * \param content_type String, optional. Only applies if method is "POST".
 
533
 *      May be "application/x-www-form-urlencoded" or "multipart/form-data".
 
534
 *      Defaults to "application/x-www-form-urlencoded".
351
535
 * \return An XMLHttpRequest object containing the completed response.
352
536
 */
353
 
function ajax_call(app, path, args, method)
 
537
function ajax_call(app, path, args, method, content_type)
354
538
{
355
 
    path = make_path(path_join(app, path));
 
539
    if (content_type != "multipart/form-data")
 
540
        content_type = "application/x-www-form-urlencoded";
 
541
    path = app_path(app, path);
356
542
    var url;
 
543
    /* A random string, for multipart/form-data
 
544
     * (This is not checked against anywhere else, it is solely defined and
 
545
     * used within this function) */
 
546
    var boundary = "48234n334nu7n4n2ynonjn234t683jyh80j";
357
547
    var xhr = new XMLHttpRequest();
358
548
    if (method == "GET")
359
549
    {
362
552
        /* open's 3rd argument = false -> SYNCHRONOUS (wait for response)
363
553
         * (No need for a callback function) */
364
554
        xhr.open(method, url, false);
365
 
        xhr.send("");
 
555
        xhr.send(null);
366
556
    }
367
557
    else
368
558
    {
369
559
        /* POST sends the args in application/x-www-form-urlencoded */
370
560
        url = encodeURI(path);
371
561
        xhr.open(method, url, false);
372
 
        xhr.setRequestHeader("Content-Type",
373
 
            "application/x-www-form-urlencoded");
374
 
        var message = make_query_string(args);
 
562
        var message;
 
563
        if (content_type == "multipart/form-data")
 
564
        {
 
565
            xhr.setRequestHeader("Content-Type",
 
566
                "multipart/form-data, boundary=" + boundary);
 
567
            message = make_multipart_formdata(args, boundary);
 
568
        }
 
569
        else
 
570
        {
 
571
            xhr.setRequestHeader("Content-Type", content_type);
 
572
            message = make_query_string(args);
 
573
        }
375
574
        xhr.send(message);
376
575
    }
377
576
    return xhr;
378
577
}
 
578