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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
/* IVLE - Informatics Virtual Learning Environment
 * Copyright (C) 2007-2008 The University of Melbourne
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Module: JavaScript Utilities
 * Author: Matt Giuca
 * Date: 11/1/2008
 *
 * Defines some generic JavaScript utility functions.
 */

/* Expects the following variables to have been declared by JavaScript in
 * the HTML generated by the server:
 * - root_dir
 * - username
 */

/** Removes all children of a given DOM element
 * \param elem A DOM Element. Will be modified.
 */
function dom_removechildren(elem)
{
    while (elem.lastChild != null)
        elem.removeChild(elem.lastChild);
}

/** Creates a DOM element with simple text inside it.
 * \param tagname String. Name of the element's tag (eg. "p").
 * \param text String. Text to be placed inside the element.
 * \param title String, optional. Tooltip for the text.
 *  (Note, title creates a span element around the text).
 * \return DOM Element object.
 */
function dom_make_text_elem(tagname, text, title)
{
    if (text == null) text = "";
    var elem = document.createElement(tagname);
    var textnode;
    if (title == null)
        textnode = document.createTextNode(text);
    else
    {
        textnode = document.createElement("span");
        textnode.setAttribute("title", title);
        textnode.appendChild(document.createTextNode(text));
    }
    elem.appendChild(textnode);
    return elem;
}

/** Creates a DOM element with hyperlinked text inside it.
 * \param tagname String. Name of the element's tag (eg. "p").
 * \param text String. Text to be placed inside the element.
 * \param title String, optional. Sets a tooltip for the link.
 * \param href String. URL the text will link to. This is a raw string,
 *  it will automatically be URL-encoded.
 * \param onclick Optional string. Will be set as the "onclick" attribute
 *  of the "a" element.
 * \param dontencode Optional boolean. If true, will not encode the href.
 *  if including query strings, you must set this to true and use build_url
 *  to escape the URI correctly.
 * \return DOM Element object.
 */
function dom_make_link_elem(tagname, text, title, href, onclick, dontencode)
{
    if (text == null) text = "";
    if (href == null) href = "";
    var elem = document.createElement(tagname);
    var link = document.createElement("a");
    if (dontencode != true)
        href = urlencode_path(href);
    link.setAttribute("href", href);
    if (title != null)
        link.setAttribute("title", title);
    if (onclick != null)
        link.setAttribute("onclick", onclick);
    link.appendChild(document.createTextNode(text));
    elem.appendChild(link);
    return elem;
}

/** Creates a DOM img element. All parameters are optional except src.
 * If alt (compulsory in HTML) is omitted, will be set to "".
 */
function dom_make_img(src, width, height, title, alt)
{
    var img = document.createElement("img");
    img.setAttribute("src", urlencode_path(src));
    if (width != null)
        img.setAttribute("width", width);
    if (height != null)
        img.setAttribute("height", height);
    if (title != null)
        img.setAttribute("title", title);
    if (alt == null) alt = "";
    img.setAttribute("alt", alt);
    return img;
}

/** Given a number of bytes, returns a string representing the file size in a
 * human-readable format.
 * eg. nice_filesize(6) -> "6 bytes"
 *     nice_filesize(81275) -> "79.4 kB"
 *     nice_filesize(13498346) -> "12.9 MB"
 * \param bytes Number of bytes. Must be an integer.
 * \return String.
 */
function nice_filesize(bytes)
{
    if (bytes == null) return "";
    var size;
    if (bytes < 1024)
        return bytes.toString() + " B";
    size = bytes / 1024;
    if (size < 1024)
        return size.toFixed(1) + " kB";
    size = size / 1024;
    if (size < 1024)
        return size.toFixed(1) + " MB";
    size = size / 1024;
    return size.toFixed(1) + " GB";
}

/** Given a URL, returns an object containing a number of attributes
 * describing the components of the URL, similar to CGI request variables.
 * The object has the following attributes:
 * - scheme
 * - server_name
 * - server_port
 * - path
 * - query_string
 * - args
 * The first five of these are strings, which comprise the URL as follows:
 * <scheme> "://" <server_name> ":" <server_port> <path> "?" <query_string>
 * Any of these strings may be set to null if not found.
 *
 * "args" is an object whose attributes are the query_string arguments broken
 * up.
 * Args values are strings for single values, arrays of strings for values
 * whose names appear multiple times.
 * args is never null, though it may be empty.
 *
 * All strings are decoded/unescaped. Reserved characters
 * (; , / ? : @ & = + * $) are not decoded except in args and path.
 *
 * \param url String. A URL. To read from the current browser window, use
 *  window.location.href.
 * \return The above described object.
 */
function parse_url(url)
{
    var obj = {};
    var index;
    var serverpart;
    var args;

    /* Split scheme from rest */
    index = url.indexOf("://");
    if (index < 0)
        obj.scheme = null;
    else
    {
        obj.scheme = url.substr(0, index);
        url = url.substr(index+3);
    }

    /* Split server name/port from rest */
    index = url.indexOf("/");
    if (index < 0)
    {
        serverpart = url;
        url = null;
    }
    else
    {
        serverpart = url.substr(0, index);
        url = url.substr(index);
    }

    /* Split server name from port */
    index = serverpart.indexOf(":");
    if (index < 0)
    {
        obj.server_name = serverpart;
        obj.server_port = null;
    }
    else
    {
        obj.server_name = serverpart.substr(0, index);
        obj.server_port = serverpart.substr(index+1);
    }

    /* Split path from query string */
    if (url == null)
    {
        obj.path = null;
        obj.query_string = null;
    }
    else
    {
        index = url.indexOf("?");
        if (index < 0)
        {
            obj.path = url;
            obj.query_string = null;
        }
        else
        {
            obj.path = url.substr(0, index);
            obj.query_string = url.substr(index+1);
        }
    }
    obj.path = decodeURIComponent(obj.path);

    /* Split query string into arguments */
    args = {};
    if (obj.query_string != null)
    {
        var args_strs = obj.query_string.split("&");
        var arg_str;
        var arg_key, arg_val;
        for (var i=0; i<args_strs.length; i++)
        {
            arg_str = args_strs[i];
            index = arg_str.indexOf("=");
            /* Ignore malformed args */
            if (index >= 0)
            {
                arg_key = decodeURIComponent(arg_str.substr(0, index));
                arg_val = decodeURIComponent(arg_str.substr(index+1));
                if (arg_key in args)
                {
                    /* Collision - make an array */
                    if (args[arg_key] instanceof Array)
                        args[arg_key][args[arg_key].length] = arg_val;
                    else
                        args[arg_key] = [args[arg_key], arg_val];
                }
                else
                    args[arg_key] = arg_val;
            }
        }
    }
    obj.args = args;

    return obj;
}

/** Builds a query_string from an args object. Encodes the arguments.
 * \param args Args object as described in parse_url.
 * \return Query string portion of a URL.
 */
function make_query_string(args)
{
    var query_string = "";
    var arg_val;
    for (var arg_key in args)
    {
        arg_val = args[arg_key];
        if (arg_val instanceof Array)
            for (var i=0; i<arg_val.length; i++)
                query_string += "&" + encodeURIComponent(arg_key) + "=" +
                    encodeURIComponent(arg_val[i]);
        else
            query_string += "&" + encodeURIComponent(arg_key) + "=" +
                encodeURIComponent(arg_val);
    }
    if (query_string != "")
        /* Drop the first "&" */
        query_string = query_string.substr(1);

    return query_string;
}

/** Given an object exactly of the form described for the output of parseurl,
 * returns a URL string built from those parameters. The URL is properly
 * encoded.
 * parseurl and buildurl are strict inverses of each other.
 * Note that either query_string or args may be supplied. If both are
 * supplied, query_string is preferred (because it keeps the argument order).
 * If you take a url from parseurl, modify args, and pass to buildurl,
 * you need to set query_string to null to use the new args.
 * \param obj Object as returned by parseurl.
 * \return String, a URL.
 */
function build_url(obj)
{
    var url = "";
    var query_string = null;

    if (("scheme" in obj) && obj.scheme != null)
        url = obj.scheme.toString() + "://";
    if (("server_name" in obj) && obj.server_name != null)
        url += obj.server_name.toString();
    if (("server_port" in obj) && obj.server_port != null)
        url += ":" + obj.server_port.toString();
    if (("path" in obj) && obj.path != null)
    {
        var path = urlencode_path(obj.path.toString());
        if (url.length > 0 && path.length > 0 && path[0] != "/")
            path = "/" + path;
        url += path;
    }
    if (("query_string" in obj) && obj.query_string != null)
        query_string = encodeURI(obj.query_string.toString());
    else if (("args" in obj) && obj.args != null)
        query_string = make_query_string(obj.args);

    if (query_string != "" && query_string != null)
        url += "?" + query_string;

    return url;
}

/** URL-encodes a path. This is a special case of URL encoding as all
 * characters *except* the slash must be encoded.
 */
function urlencode_path(path)
{
    /* Split up the path, URLEncode each segment with encodeURIComponent,
     * and rejoin.
     */
    var split = path.split('/');
    for (var i=0; i<split.length; i++)
        split[i] = encodeURIComponent(split[i]);
    path = path_join.apply(null, split);
    if (split[0] == "" && split.length > 1) path = "/" + path;
    return path;
}

/** Given an argument map, as output in the args parameter of the return of
 * parseurl, gets the first occurence of an argument in the URL string.
 * If the argument was not found, returns null.
 * If there was a single argument, returns the argument.
 * If there were multiple arguments, returns the first.
 * \param args Object mapping arguments to strings or arrays of strings.
 * \param arg String. Argument name.
 * \return String.
 */
function arg_getfirst(args, arg)
{
    if (!(arg in args))
        return null;
    var r = args[arg];
    if (r instanceof Array)
        return r[0];
    else
        return r;
}

/** Given an argument map, as output in the args parameter of the return of
 * parseurl, gets all occurences of an argument in the URL string, as an
 * array.
 * If the argument was not found, returns [].
 * Otherwise, returns all occurences as an array, even if there was only one.
 * \param args Object mapping arguments to strings or arrays of strings.
 * \param arg String. Argument name.
 * \return Array of strings.
 */
function arg_getlist(args, arg)
{
    if (!(arg in args))
        return [];
    var r = args[arg];
    if (r instanceof Array)
        return r;
    else
        return [r];
}

/** Joins one or more paths together. Accepts 1 or more arguments.
 */
function path_join(path1 /*, path2, ... */)
{
    var arg;
    var path = "";
    for (var i=0; i<arguments.length; i++)
    {
        arg = arguments[i];
        if (arg.length == 0) continue;
        if (arg[0] == '/')
            path = arg;
        else
        {
            if (path.length > 0 && path[path.length-1] != '/')
                path += '/';
            path += arg;
        }
    }
    return path;
}


/** Builds a multipart_formdata string from an args object. Similar to
 * make_query_string, but it returns data of type "multipart/form-data"
 * instead of "application/x-www-form-urlencoded". This is good for
 * encoding large strings such as text objects from the editor.
 * Should be written with a Content-Type of
 * "multipart/form-data, boundary=<boundary>".
 * All fields are sent with a Content-Type of text/plain.
 * \param args Args object as described in parse_url.
 * \param boundary Random "magic" string which DOES NOT appear in any of
 *  the argument values. This should match the "boundary=" value written to
 *  the Content-Type header.
 * \return String in multipart/form-data format.
 */
function make_multipart_formdata(args, boundary)
{
    var data = "";
    var arg_val;
    /* Mutates data */
    var extend_data = function(arg_key, arg_val)
    {
        /* FIXME: Encoding not supported here (should not matter if we
         * only use ASCII names */
        data += "--" + boundary + "\r\n"
            + "Content-Disposition: form-data; name=\"" + arg_key
            + "\"\r\n\r\n"
            + arg_val + "\r\n";
    }

    for (var arg_key in args)
    {
        arg_val = args[arg_key];
        if (arg_val instanceof Array)
            for (var i=0; i<arg_val.length; i++)
            {
                extend_data(arg_key, arg_val[i]);
            }
        else
            extend_data(arg_key, arg_val);
    }
    /* End boundary */
    data += "--" + boundary + "--\r\n";

    return data;
}

/** Converts a list of directories into a path name, with a slash at the end.
 * \param pathlist List of strings.
 * \return String.
 */
function pathlist_to_path(pathlist)
{
    ret = path_join.apply(null, pathlist);
    if (ret[ret.length-1] != '/')
        ret += '/';
    return ret;
}

/** Given a path relative to the IVLE root, gives a path relative to
 * the site root.
 */
function make_path(path)
{
    return path_join(root_dir, path);
}

/** Shorthand for make_path(path_join(app, ...))
 * Creates an absolute path for a given path within a given app.
 */
function app_path(app /*,...*/)
{
    return make_path(path_join.apply(null, arguments));
}

/** Given a path, gets the "basename" (the last path segment).
 */
function path_basename(path)
{
    segments = path.split("/");
    if (segments[segments.length-1].length == 0)
        return segments[segments.length-2];
    else
        return segments[segments.length-1];
}

/** Given a string str, determines whether it ends with substr */
function endswith(str, substring)
{
    if (str.length < substring.length) return false;
    return str.substr(str.length - substring.length) == substring;
}

/** Equivalent to Python's repr.
 * Gets the JavaScript string representation.
 * Actually just calls JSON.stringify.
 */
function repr(str)
{
    return JSON.stringify(str);
}

/** Removes all occurences of a value from an array.
 */
Array.prototype.removeall = function(val)
{
    var i, j;
    var arr = this;
    j = 0;
    for (i=0; i<arr.length; i++)
    {
        arr[j] = arr[i];
        if (arr[i] != val) j++;
    }
    arr.splice(j, i-j);
}

/** Shallow-clones an object */
function shallow_clone_object(obj)
{
    o = {};
    for (k in obj)
        o[k] = obj[k];
    return o;
}

/** Returns a new XMLHttpRequest object, in a somewhat browser-agnostic
 * fashion.
 */
function new_xmlhttprequest()
{
    try
    {
        /* Real Browsers */
        return new XMLHttpRequest();
    }
    catch (e)
    {
        /* Internet Explorer */
        try
        {
            return new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            try
            {
                return new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e)
            {
                throw("Your browser does not support AJAX. "
                    + "IVLE requires a modern browser.");
            }
        }
    }
}

/** Makes an asynchronous XMLHttpRequest call to the server.
 * Sends the XMLHttpRequest object containing the completed response to a
 * specified callback function.
 *
 * \param callback A callback function. Will be called when the response is
 *      complete. Passed 1 parameter, an XMLHttpRequest object containing the
 *      completed response.
 * \param app IVLE app to call (such as "fileservice").
 * \param path URL path to make the request to, within the application.
 * \param args Argument object, as described in parse_url and friends.
 * \param method String; "GET" or "POST"
 * \param content_type String, optional. Only applies if method is "POST".
 *      May be "application/x-www-form-urlencoded" or "multipart/form-data".
 *      Defaults to "application/x-www-form-urlencoded".
 */
function ajax_call(callback, app, path, args, method, content_type)
{
    if (content_type != "multipart/form-data")
        content_type = "application/x-www-form-urlencoded";
    path = app_path(app, path);
    var url;
    /* A random string, for multipart/form-data
     * (This is not checked against anywhere else, it is solely defined and
     * used within this function) */
    var boundary = "48234n334nu7n4n2ynonjn234t683jyh80j";
    var xhr = new_xmlhttprequest();
    xhr.onreadystatechange = function()
        {
            if (xhr.readyState == 4)
            {
                callback(xhr);
            }
        }
    if (method == "GET")
    {
        /* GET sends the args in the URL */
        url = build_url({"path": path, "args": args});
        /* open's 3rd argument = true -> asynchronous */
        xhr.open(method, url, true);
        xhr.send(null);
    }
    else
    {
        /* POST sends the args in application/x-www-form-urlencoded */
        url = encodeURI(path);
        xhr.open(method, url, true);
        var message;
        if (content_type == "multipart/form-data")
        {
            xhr.setRequestHeader("Content-Type",
                "multipart/form-data, boundary=" + boundary);
            message = make_multipart_formdata(args, boundary);
        }
        else
        {
            xhr.setRequestHeader("Content-Type", content_type);
            message = make_query_string(args);
        }
        xhr.setRequestHeader("Content-Length", message.length);
        xhr.send(message);
    }
}