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

« back to all changes in this revision

Viewing changes to www/media/browser/browser.js

  • Committer: mattgiuca
  • Date: 2008-01-12 16:13:31 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:203
browser: Removed all directory-listing specific HTML from the Python-generated
    html. This can't be static because different handlers need different
    content inside the page body (eg. binary files don't use a table).
    The JavaScript now clears a lot more of the page and rebuilds the entire
    directory listing table dynamically.

Show diffs side-by-side

added added

removed removed

Lines of Context:
22
22
 
23
23
/* Url names for apps */
24
24
this_app = "files";
25
 
edit_app = "edit";
26
25
service_app = "fileservice";
27
 
serve_app = "serve";
28
 
download_app = "download";
29
26
 
30
27
/* Mapping MIME types onto handlers.
31
28
 * "text" : When navigating to a text file, the text editor is opened.
43
40
    "application/x-javascript" : "text",
44
41
    "application/javascript" : "text",
45
42
    "application/json" : "text",
46
 
    "application/xml" : "text"
 
43
    "application/xml" : "text",
47
44
};
48
45
 
49
46
/* Mapping MIME types to icons, just the file's basename */
50
47
type_icons = {
51
48
    "text/directory": "dir.png",
52
 
    "text/x-python": "py.png"
 
49
    "text/x-python": "py.png",
53
50
};
54
51
 
55
52
default_type_icon = "txt.png";
56
53
 
57
54
/* Relative to IVLE root */
58
 
type_icons_path = "+media/ivle.webapp.core/images/mime";
59
 
type_icons_path_large = "+media/ivle.webapp.core/images/mime/large";
 
55
type_icons_path = "media/images/mime";
 
56
type_icons_path_large = "media/images/mime/large";
60
57
 
61
58
/* Mapping SVN status to icons, just the file's basename */
62
59
svn_icons = {
63
60
    "unversioned": "unversioned.png",
64
 
    "ignored": null,                    /* Supposed to be innocuous */
65
61
    "normal": "normal.png",
66
 
    "added": "added.png",
67
 
    "missing": "missing.png",
68
 
    "deleted": "deleted.png",
69
 
    "replaced": "replaced.png",
70
62
    "modified": "modified.png",
71
 
    "conflicted": "conflicted.png",
72
 
    "revision": "revision.png"
73
 
};
74
 
 
75
 
/* Mapping SVN status to "nice" strings */
76
 
svn_nice = {
77
 
    "unversioned": "Temporary file",
78
 
    "ignored": "Temporary file (ignored)",
79
 
    "normal": "Permanent file",
80
 
    "added": "Temporary file (scheduled to be added)",
81
 
    "missing": "Permanent file (missing)",
82
 
    "deleted": "Permanent file (scheduled for deletion)",
83
 
    "replaced": "Permanent file (replaced)",
84
 
    "modified": "Permanent file (modified)",
85
 
    "merged": "Permanent file (merged)",
86
 
    "conflicted": "Permanent file (conflicted)",
87
 
    "revision": "Past Permanent file (revision)"
88
 
};
89
 
 
90
 
default_svn_icon = null;
91
 
default_svn_nice = "Unknown status";
92
 
 
93
 
svn_icons_path = "+media/ivle.webapp.core/images/svn";
94
 
 
95
 
published_icon = "+media/ivle.webapp.core/images/interface/published.png";
 
63
};
 
64
 
 
65
default_svn_icon = "normal.png";
 
66
 
 
67
svn_icons_path = "media/images/svn";
96
68
 
97
69
/* List of MIME types considered "executable" by the system.
98
70
 * Executable files offer a "run" link, implying that the "serve"
99
71
 * application can interpret them.
100
72
 */
101
73
types_exec = [
102
 
    "text/x-python"
 
74
    "text/x-python",
103
75
];
104
76
 
105
 
 
106
 
/* Global variables */
107
 
 
108
 
/** The listing object returned by the server as JSON */
109
 
file_listing = null;
110
 
current_file = null;
111
 
current_revision = null;
112
 
current_path = "";
113
 
 
114
 
/** Filenames of all files selected
115
 
 * (Only used by dir listings, but still needs to be [] for files, so that
116
 
 * update_actions knows that nothing is selected).
117
 
 */
118
 
selected_files = [];
119
 
 
120
 
upload_callback_count = 0;      /* See upload_callback */
121
 
 
122
77
/** Calls the server using Ajax, performing an action on the server side.
123
78
 * Receives the response from the server and performs a refresh of the page
124
79
 * contents, updating it to display the returned data (such as a directory
137
92
 *      May be "application/x-www-form-urlencoded" or "multipart/form-data".
138
93
 *      Defaults to "application/x-www-form-urlencoded".
139
94
 *      "multipart/form-data" is recommended for large uploads.
140
 
 * \param callback, optional.
141
 
 *      A callback function for after the action has been handled.
142
95
 */
143
 
function do_action(action, path, args, content_type, callback)
 
96
function do_action(action, path, args, content_type)
144
97
{
145
98
    args.action = action;
146
 
    /* Callback action, when the server returns */
147
 
    var callback_inner = function(response)
148
 
        {
149
 
            /* Check for action errors reported by the server, and report them
150
 
             * to the user */
151
 
            var error = response.getResponseHeader("X-IVLE-Action-Error");
152
 
            if (error != null && error != "")
153
 
                /* Note: This header (in particular) comes URI-encoded, to
154
 
                 * allow multi-line error messages. Decode */
155
 
                alert("Error: " + decodeURIComponent(error.toString()) + ".");
156
 
            /* Now read the response and set up the page accordingly */
157
 
            if (callback != null)
158
 
                callback(path, response);
159
 
        }
160
99
    /* Call the server and perform the action. This mutates the server. */
161
 
    ajax_call(callback_inner, service_app, path, args, "POST", content_type);
 
100
    response = ajax_call(service_app, path, args, "POST", content_type);
 
101
    /* Check for action errors reported by the server, and report them to the
 
102
     * user */
 
103
    error = response.getResponseHeader("X-IVLE-Action-Error");
 
104
    if (error != null)
 
105
        alert("Error: " + error.toString() + ".");
 
106
    /* Now read the response and set up the page accordingly */
 
107
    handle_response(path, response);
162
108
}
163
109
 
164
110
/** Calls the server using Ajax, requesting a directory listing. This should
171
117
 */
172
118
function navigate(path)
173
119
{
174
 
    callback = function(response)
175
 
        {
176
 
            /* Read the response and set up the page accordingly */
177
 
            handle_response(path, response, false, url.args);
178
 
        }
179
 
    /* Get any query strings */
180
 
    url = parse_url(window.location.href);
181
 
    
182
 
    /* Call the server and request the listing. */
183
 
    ajax_call(callback, service_app, path, url.args, "GET");
184
 
}
185
 
 
186
 
/* Refreshes the current view.
187
 
 * Calls navigate on the current path.
188
 
 */
189
 
function refresh()
190
 
{
191
 
    if (maybe_save('All changes since the last save will be lost!'))
192
 
        navigate(current_path);
193
 
}
194
 
 
195
 
/** Determines the "handler type" from a MIME type.
196
 
 * The handler type is a string, either "text", "image", "audio" or "binary".
197
 
 */
198
 
function get_handler_type(content_type)
199
 
{
200
 
    if (!content_type)
201
 
        return null;
202
 
    if (content_type in type_handlers)
203
 
        return type_handlers[content_type];
204
 
    else
205
 
    {   /* Based on the first part of the MIME type */
206
 
        var handler_type = content_type.split('/')[0];
207
 
        if (handler_type != "text" && handler_type != "image" &&
208
 
            handler_type != "audio")
209
 
            handler_type = "binary";
210
 
        return handler_type;
211
 
    }
 
120
    /* Call the server and request the listing. This mutates the server. */
 
121
    response = ajax_call(service_app, path, null, "GET");
 
122
    /* Now read the response and set up the page accordingly */
 
123
    handle_response(path, response);
212
124
}
213
125
 
214
126
/** Given an HTTP response object, cleans up and rebuilds the contents of the
221
133
 * things) be used to update the URL in the location bar.
222
134
 * \param response XMLHttpRequest object returned by the server. Should
223
135
 * contain all the response data.
224
 
 * \param is_action Boolean. True if this is the response to an action, false
225
 
 * if this is the response to a simple listing. This is used in handling the
226
 
 * error.
227
 
 * \param url_args Arguments dict, for the arguments passed to the URL
228
 
 * in the browser's address bar (will be forwarded along).
229
136
 */
230
 
function handle_response(path, response, is_action, url_args)
 
137
function handle_response(path, response)
231
138
{
232
139
    /* TODO: Set location bar to "path" */
233
 
    current_path = path;
234
140
 
235
141
    /* Clear away the existing page contents */
236
142
    clearpage();
 
143
    /* Display the path at the top, for navigation */
 
144
    presentpath(path);
237
145
 
238
146
    /* Check the status, and if not 200, read the error and handle this as an
239
147
     * error. */
246
154
        return;
247
155
    }
248
156
 
249
 
    var subjects = null;
250
 
    /* Remove trailing slash (or path==username won't compare properly) */
251
 
    if (path[path.length-1] == "/")
252
 
        path = path.substr(0, path.length-1);
253
 
    var top_level_dir = path==username;
254
 
    if (top_level_dir)
255
 
    {
256
 
        var req = ajax_call(null, "userservice", "get_enrolments", null, "GET")
257
 
        subjects = decode_response(req);
258
 
    }
259
 
 
260
 
 
261
 
    /* This will always return a listing, whether it is a dir or a file.
262
 
     */
263
 
    var listing = response.responseText;
264
 
    /* The listing SHOULD be valid JSON text. Parse it into an object. */
265
 
    try
266
 
    {
267
 
        listing = JSON.parse(listing);
268
 
        file_listing = listing.listing;     /* Global */
269
 
    }
270
 
    catch (e)
271
 
    {
272
 
        if (is_action)
273
 
        {
274
 
            var err = document.createElement("div");
275
 
            var p = dom_make_text_elem("p", "Error: "
276
 
                    + "There was an unexpected server error processing "
277
 
                    + "the selected command.");
278
 
            err.appendChild(p);
279
 
            p = dom_make_text_elem("p", "If the problem persists, please "
280
 
                    + "contact the system administrator.")
281
 
            err.appendChild(p);
282
 
            p = document.createElement("p");
283
 
            var refresh = document.createElement("input");
284
 
            refresh.setAttribute("type", "button");
285
 
            refresh.setAttribute("value", "Back to file view");
286
 
            refresh.setAttribute("onclick", "refresh()");
287
 
            p.appendChild(refresh);
288
 
            err.appendChild(p);
289
 
            handle_error(err);
290
 
        }
291
 
        else
292
 
        {
293
 
            var err = document.createElement("div");
294
 
            var p = dom_make_text_elem("p", "Error: "
295
 
                    + "There was an unexpected server error retrieving "
296
 
                    + "the requested file or directory.");
297
 
            err.appendChild(p);
298
 
            p = dom_make_text_elem("p", "If the problem persists, please "
299
 
                    + "contact the system administrator.")
300
 
            err.appendChild(p);
301
 
            handle_error(err);
302
 
        }
303
 
        return;
304
 
    }
305
 
    /* Get "." out, it's special */
306
 
    current_file = file_listing["."];     /* Global */
307
 
    delete file_listing["."];
308
 
 
309
 
    if ('revision' in listing)
310
 
    {
311
 
        current_revision = listing.revision;
312
 
    }
313
 
 
314
157
    /* Check if this is a directory listing or file contents */
315
 
    var isdir = response.getResponseHeader("X-IVLE-Return") == "Dir";
316
 
    if (isdir)
 
158
    if (response.getResponseHeader("X-IVLE-Return") == "Dir")
317
159
    {
318
 
        setup_for_listing();
319
 
        if (top_level_dir)
320
 
        {
321
 
            /* Top-level dir, with subjects */
322
 
            special_home_listing(listing, subjects, path);
323
 
        }
324
 
        else
325
 
        {
326
 
            /* Not the top-level dir. Do a normal dir listing. */
327
 
            handle_dir_listing(path, listing.listing);
328
 
        }
 
160
        var listing = response.responseText;
 
161
        /* The listing SHOULD be valid JSON text. Parse it into an object. */
 
162
        try
 
163
        {
 
164
            listing = JSON.parse(listing);
 
165
        }
 
166
        catch (e)
 
167
        {
 
168
            handle_error("The server returned an invalid directory listing");
 
169
            return;
 
170
        }
 
171
        handle_dir_listing(path, listing);
329
172
    }
330
173
    else
331
174
    {
332
 
        /* Need to make a 2nd ajax call, this time get the actual file
333
 
         * contents */
334
 
        callback = function(response)
335
 
            {
336
 
                /* Read the response and set up the page accordingly */
337
 
                handle_contents_response(path, response);
338
 
            }
339
 
        /* Call the server and request the listing. */
340
 
        if (url_args)
341
 
            args = shallow_clone_object(url_args);
 
175
        /* Treat this as an ordinary file. Get the file type. */
 
176
        var content_type = response.getResponseHeader("Content-Type");
 
177
        var handler_type;
 
178
        if (content_type in type_handlers)
 
179
            handler_type = type_handlers[content_type];
342
180
        else
343
 
            args = {};
344
 
        /* This time, get the contents of the file, not its metadata */
345
 
        args['return'] = "contents";
346
 
        ajax_call(callback, service_app, path, args, "GET");
347
 
    }
348
 
    update_actions(isdir);
349
 
}
350
 
 
351
 
function handle_contents_response(path, response)
352
 
{
353
 
    /* Treat this as an ordinary file. Get the file type. */
354
 
    var content_type = response.getResponseHeader("Content-Type");
355
 
    var handler_type = get_handler_type(content_type);
356
 
    would_be_handler_type = handler_type;
357
 
    /* handler_type should now be set to either
358
 
     * "text", "image", "audio" or "binary". */
359
 
    switch (handler_type)
360
 
    {
361
 
    case "text":
362
 
        handle_text(path, response.responseText,
363
 
            would_be_handler_type);
364
 
        break;
365
 
    case "image":
366
 
        /* TODO: Custom image handler */
367
 
        handle_binary(path, response.responseText);
368
 
        break;
369
 
    case "audio":
370
 
        /* TODO: Custom audio handler */
371
 
        handle_binary(path, response.responseText);
372
 
        break;
373
 
    case "binary":
374
 
        handle_binary(path);
375
 
        break;
376
 
    }
377
 
}
378
 
 
379
 
/* Called when a form upload comes back (from an iframe).
380
 
 * Refreshes the page.
381
 
 */
382
 
function upload_callback()
383
 
{
384
 
    /* This has a pretty nasty hack, which happens to work.
385
 
     * upload_callback is set as the "onload" callback for the iframe which
386
 
     * receives the response from the server for uploading a file.
387
 
     * This means it gets called twice. Once when initialising the iframe, and
388
 
     * a second time when the actual response comes back.
389
 
     * All we want to do is call navigate to refresh the page. But we CAN'T do
390
 
     * that on the first load or it will just go into an infinite cycle of
391
 
     * refreshing. We need to refresh the page ONLY on the second refresh.
392
 
     * upload_callback_count is reset to 0 just before the iframe is created.
393
 
     */
394
 
    upload_callback_count++;
395
 
    if (upload_callback_count >= 2)
396
 
    {
397
 
        myFrame = frames['upload_iframe'].document;
398
 
        /* Browsers will turn the raw returned JSON into an HTML document. We
399
 
         * need to get the <pre> from inside the <body>, and look at its text.
400
 
         */
401
 
        data = myFrame.firstChild.getElementsByTagName(
402
 
            'body')[0].firstChild.firstChild.nodeValue;
403
 
        data = JSON.parse(data);
404
 
        if ('Error' in data)
405
 
            alert("Error: " + decodeURIComponent(data['Error']));
406
 
        document.getElementsByName('data')[0].value = '';
407
 
        refresh();
 
181
        {   /* Based on the first part of the MIME type */
 
182
            handler_type = content_type.split('/')[0];
 
183
            if (handler_type != "text" && handler_type != "image" &&
 
184
                handler_type != "audio")
 
185
                handler_type = "binary";
 
186
        }
 
187
        /* handler_type should now be set to either
 
188
         * "text", "image", "audio" or "binary". */
 
189
        switch (handler_type)
 
190
        {
 
191
        case "text":
 
192
            handle_text(path, response.responseText);
 
193
            break;
 
194
        case "image":
 
195
            /* TODO: Custom image handler */
 
196
            handle_binary(path, response.responseText);
 
197
            break;
 
198
        case "audio":
 
199
            /* TODO: Custom audio handler */
 
200
            handle_binary(path, response.responseText);
 
201
            break;
 
202
        case "binary":
 
203
            handle_binary(path);
 
204
            break;
 
205
        }
408
206
    }
409
207
}
410
208
 
414
212
 */
415
213
function clearpage()
416
214
{
 
215
    dom_removechildren(document.getElementById("path"));
417
216
    dom_removechildren(document.getElementById("filesbody"));
418
217
}
419
218
 
420
 
/* Checks if a file needs to be saved. If it does, the user will be asked
421
 
 * if they want to continue anyway. The caller must specify a warning
422
 
 * sentence which indicates the consequences of continuing.
423
 
 * Returns true if we should continue, and false if we should not.
424
 
 */
425
 
function maybe_save(warning)
426
 
{
427
 
    if (warning == null) warning = '';
428
 
    if (current_file == null || current_file.isdir) return true;
429
 
    if (document.getElementById("save_button").disabled) return true;
430
 
    return confirm("This file has unsaved changes. " + warning +
431
 
                   "\nAre you sure you wish to continue?");
432
 
}
433
 
 
434
219
/** Deletes all "dynamic" content on the page necessary to navigate from
435
220
 * one directory listing to another (does not clear as much as clearpage
436
221
 * does).
447
232
/*** HANDLERS for different types of responses (such as dir listing, file,
448
233
 * etc). */
449
234
 
450
 
/* handle_error.
451
 
 * message may either be a string, or a DOM node, which will be placed inside
452
 
 * a div.
453
 
 */
454
235
function handle_error(message)
455
236
{
456
 
    var files = document.getElementById("filesbody");
457
 
    var txt_elem;
458
 
    if (typeof(message) == "string")
459
 
    {
460
 
        txt_elem = dom_make_text_elem("div", "Error: "
461
 
                   + message.toString() + ".")
462
 
    }
463
 
    else
464
 
    {
465
 
        /* Assume message is a DOM node */
466
 
        txt_elem = document.createElement("div");
467
 
        txt_elem.appendChild(message);
468
 
    }
469
 
    txt_elem.setAttribute("class", "padding error");
470
 
    files.appendChild(txt_elem);
 
237
    /* TODO: Find a better place to put this message. */
 
238
    var files = document.getElementById("files");
 
239
    var tr = document.createElement("tr");
 
240
    var td = document.createElement("td");
 
241
    tr.appendChild(td);
 
242
    var td = document.createElement("td");
 
243
    tr.appendChild(td);
 
244
    var td = document.createElement("td");
 
245
    tr.appendChild(td);
 
246
    var txt_elem = dom_make_text_elem("td", "Error: "
 
247
        + message.toString() + ".")
 
248
    txt_elem.setAttribute("class", "error");
 
249
    tr.appendChild(txt_elem);
 
250
    var td = document.createElement("td");
 
251
    tr.appendChild(td);
 
252
    var td = document.createElement("td");
 
253
    tr.appendChild(td);
 
254
    files.appendChild(tr);
471
255
}
472
256
 
473
 
/** Given a path, filename and optional revision, returns a URL to open that
474
 
 *  revision of that file.
 
257
/** Presents a path list (address bar inside the page) for clicking.
475
258
 */
476
 
function build_revision_url(path, filename, revision)
 
259
function presentpath(path)
477
260
{
478
 
    bits = {'path': app_path(this_app, path, filename)};
479
 
    if (current_revision)
 
261
    var dom_path = document.getElementById("path");
 
262
    var href_path = make_path(this_app);
 
263
    var nav_path = "";
 
264
 
 
265
    /* Create all of the paths */
 
266
    for each (dir in path.split("/"))
480
267
    {
481
 
        bits['query_string'] = 'r=' + revision;
 
268
        if (dir == "") continue;
 
269
        /* Make an 'a' element */
 
270
        href_path = path_join(href_path, dir);
 
271
        nav_path = path_join(nav_path, dir);
 
272
        var link = dom_make_link_elem("a", dir, "Navigate to " + nav_path,
 
273
                href_path, "navigate(" + href_path + ")");
 
274
        dom_path.appendChild(link);
 
275
        dom_path.appendChild(document.createTextNode("/"));
482
276
    }
483
 
    return build_url(bits);
484
277
}
485
278
 
486
279
/** Given a mime type, returns the path to the icon.
505
298
/** Given an svnstatus, returns the path to the icon.
506
299
 * \param type String, svn status.
507
300
 * \return Path to the icon. Has applied make_path, so it is relative to site
508
 
 * root. May return null to indicate no SVN icon.
 
301
 * root.
509
302
 */
510
303
function svnstatus_to_icon(svnstatus)
511
304
{
514
307
        filename = svn_icons[svnstatus];
515
308
    else
516
309
        filename = default_svn_icon;
517
 
    if (filename == null) return null;
518
310
    return make_path(path_join(svn_icons_path, filename));
519
311
}
520
312
 
521
 
/** Given an svnstatus, returns the "nice" string.
522
 
 */
523
 
function svnstatus_to_string(svnstatus)
524
 
{
525
 
    if (svnstatus in svn_nice)
526
 
        return svn_nice[svnstatus];
527
 
    else
528
 
        return default_svn_nice;
529
 
}
530
 
 
531
 
/** Returns true if a file is versioned (not unversioned or ignored).
532
 
 */
533
 
function svnstatus_versioned(svnstatus)
534
 
{
535
 
    return svnstatus != "unversioned" && svnstatus != "ignored";
 
313
/** Initialises the DOM elements required to present a dir listing,
 
314
 * assuming that clear_page has just been called or the page just
 
315
 * loaded for the first time.
 
316
 */
 
317
function setup_for_dir_listing()
 
318
{
 
319
    var filesbody = document.getElementById("filesbody");
 
320
 
 
321
    /* Using a table-based layout, for reasons of sanity */
 
322
    /* One row, 2 columns */
 
323
    var middle = document.createElement("table");
 
324
    filesbody.appendChild(middle);
 
325
    middle.setAttribute("id", "middle");
 
326
    var middle_tbody = document.createElement("tbody");
 
327
    middle.appendChild(middle_tbody);
 
328
    var middle_tr = document.createElement("tr");
 
329
    middle_tbody.appendChild(middle_tr);
 
330
 
 
331
    /* Column 1: File table */
 
332
    var filetable = document.createElement("td");
 
333
    middle_tr.appendChild(filetable);
 
334
    filetable.setAttribute("id", "filetable");
 
335
    var filetablediv = document.createElement("div");
 
336
    filetable.appendChild(filetablediv);
 
337
    filetablediv.setAttribute("id", "filetablediv");
 
338
    /* A nested table within this div - the actual files listing */
 
339
    var filetabletable = document.createElement("table");
 
340
    filetablediv.appendChild(filetabletable);
 
341
    filetabletable.setAttribute("width", "100%");
 
342
    var filetablethead = document.createElement("thead");
 
343
    filetabletable.appendChild(filetablethead);
 
344
    var filetablethead_tr = document.createElement("tr");
 
345
    filetablethead.appendChild(filetablethead_tr);
 
346
    filetablethead_tr.setAttribute("class", "rowhead");
 
347
    /* Row headers */
 
348
    var filetablethead_th = document.createElement("th");
 
349
    filetablethead_tr.appendChild(filetablethead_th);
 
350
    filetablethead_th.setAttribute("class", "col-check");
 
351
    filetablethead_th = dom_make_link_elem("th", "Filename",
 
352
        "Sort by filename", "")
 
353
    filetablethead_tr.appendChild(filetablethead_th);
 
354
    filetablethead_th.setAttribute("class", "col-filename");
 
355
    filetablethead_th.setAttribute("colspan", 3);
 
356
    filetablethead_th = dom_make_link_elem("th", "Size",
 
357
        "Sort by file size", "")
 
358
    filetablethead_tr.appendChild(filetablethead_th);
 
359
    filetablethead_th.setAttribute("class", "col-size");
 
360
    filetablethead_th = dom_make_link_elem("th", "Modified",
 
361
        "Sort by date modified", "")
 
362
    filetablethead_tr.appendChild(filetablethead_th);
 
363
    filetablethead_th.setAttribute("class", "col-date");
 
364
    /* Empty body */
 
365
    var filetabletbody = document.createElement("tbody");
 
366
    filetabletable.appendChild(filetabletbody);
 
367
    filetabletbody.setAttribute("id", "files");
 
368
 
 
369
    /* Column 2: Side-panel */
 
370
    var sidepanel = document.createElement("td");
 
371
    middle_tr.appendChild(sidepanel);
 
372
    sidepanel.setAttribute("id", "sidepanel");
 
373
 
 
374
 
 
375
    /* Now after the table "middle", there is a status bar */
 
376
    var statusbar = dom_make_text_elem("div", "5 files, 14 kB");
 
377
    filesbody.appendChild(statusbar);
 
378
    statusbar.setAttribute("id", "statusbar");
 
379
}
 
380
 
 
381
/** Presents the directory listing.
 
382
 */
 
383
function handle_dir_listing(path, listing)
 
384
{
 
385
    setup_for_dir_listing();
 
386
    var row_toggle = 1;
 
387
    /* Nav through the top-level of the JSON to the actual listing object. */
 
388
    var listing = listing.listing;
 
389
 
 
390
    /* Get "." out, it's special */
 
391
    var thisdir = listing["."];
 
392
    delete listing["."];
 
393
    /* Is this dir under svn? */
 
394
    var under_subversion = "svnstatus" in thisdir;
 
395
 
 
396
    var files = document.getElementById("files");
 
397
    var file;
 
398
    var row;
 
399
    var td;
 
400
    var checkbox;
 
401
 
 
402
    /* Create all of the files */
 
403
    for (var filename in listing)
 
404
    {
 
405
        file = listing[filename];
 
406
        /* Make a 'tr' element */
 
407
        row = document.createElement("tr");
 
408
        /* Column 1: Selection checkbox */
 
409
        row.setAttribute("class", "row" + row_toggle.toString())
 
410
        row_toggle = row_toggle == 1 ? 2 : 1;
 
411
        td = document.createElement("td");
 
412
        checkbox = document.createElement("input");
 
413
        checkbox.setAttribute("type", "checkbox");
 
414
        checkbox.setAttribute("title", "Select this file");
 
415
        td.appendChild(checkbox);
 
416
        row.appendChild(td);
 
417
        if (file.isdir)
 
418
        {
 
419
            /* Column 2: Filetype and subversion icons. */
 
420
            td = document.createElement("td");
 
421
            td.setAttribute("class", "thincol");
 
422
            td.appendChild(dom_make_img(mime_type_to_icon("text/directory"),
 
423
                22, 22, file.type));
 
424
            row.appendChild(td);
 
425
            td = document.createElement("td");
 
426
            td.setAttribute("class", "thincol");
 
427
            if (under_subversion)
 
428
                td.appendChild(dom_make_img(svnstatus_to_icon(file.svnstatus),
 
429
                    22, 22, file.svnstatus));
 
430
            row.appendChild(td);
 
431
            /* Column 3: Filename */
 
432
            row.appendChild(dom_make_link_elem("td", filename,
 
433
                "Navigate to " + path_join(path, filename),
 
434
                make_path(path_join(this_app, path, filename)),
 
435
                "navigate(" + path_join(path, filename) + ")"));
 
436
        }
 
437
        else
 
438
        {
 
439
            /* Column 2: Filetype and subversion icons. */
 
440
            td = document.createElement("td");
 
441
            td.setAttribute("class", "thincol");
 
442
            td.appendChild(dom_make_img(mime_type_to_icon(file.type),
 
443
                22, 22, file.type));
 
444
            row.appendChild(td);
 
445
            td = document.createElement("td");
 
446
            td.setAttribute("class", "thincol");
 
447
            if (under_subversion)
 
448
                td.appendChild(dom_make_img(svnstatus_to_icon(file.svnstatus),
 
449
                    22, 22, file.svnstatus));
 
450
            row.appendChild(td);
 
451
            /* Column 3: Filename */
 
452
            row.appendChild(dom_make_text_elem("td", filename));
 
453
        }
 
454
        /* Column 4: Size */
 
455
        row.appendChild(dom_make_text_elem("td", nice_filesize(file.size)));
 
456
        /* Column 4: Date */
 
457
        row.appendChild(dom_make_text_elem("td", file.mtime_short,
 
458
            file.mtime_nice));
 
459
        files.appendChild(row);
 
460
    }
 
461
 
 
462
}
 
463
 
 
464
/** Presents the text editor.
 
465
 */
 
466
function handle_text(path, text)
 
467
{
 
468
    /* TODO */
 
469
    alert(text);
536
470
}
537
471
 
538
472
/** Displays a download link to the binary file.
539
473
 */
540
474
function handle_binary(path)
541
475
{
542
 
    var files = document.getElementById("filesbody");
543
 
    var div = document.createElement("div");
544
 
    files.appendChild(div);
545
 
    div.setAttribute("class", "padding");
546
 
    var download_link = app_url(download_app, path);
547
 
    var par1 = dom_make_text_elem("p",
548
 
        "The file " + path + " is a binary file. To download this file, " +
549
 
        "click the following link:");
550
 
    var par2 = dom_make_link_elem("p",
551
 
        "Download " + path, "Download " + path, download_link);
552
 
    div.appendChild(par1);
553
 
    div.appendChild(par2);
554
 
}
555
 
 
556
 
/* Enable or disable actions1 moreactions actions. Takes either a single
557
 
 * name, or an array of them.*/
558
 
function set_action_state(names, which, allow_on_revision)
559
 
{
560
 
    if (!(names instanceof Array)) names = Array(names);
561
 
 
562
 
    for (var i=0; i < names.length; i++)
563
 
    {
564
 
        element = document.getElementById('act_' + names[i]);
565
 
        if (which &&
566
 
            !(current_file.svnstatus == 'revision' && !allow_on_revision))
567
 
        {
568
 
            /* Enabling */
569
 
            element.setAttribute("class", "choice");
570
 
            element.removeAttribute("disabled");
571
 
        }
572
 
        else
573
 
        {
574
 
            /* Disabling */
575
 
            element.setAttribute("class", "disabled");
576
 
            element.setAttribute("disabled", "disabled");
577
 
        }
578
 
    }
579
 
}
580
 
 
581
 
/* Updates the list of available actions based on files selected */
582
 
function update_actions()
583
 
{
584
 
    var file;
585
 
    var numsel = selected_files.length;
586
 
    var svn_selection = false;
587
 
    
588
 
    if (numsel > 0)
589
 
    {
590
 
        svn_selection = true;
591
 
        for (var i = 0; i < selected_files.length; i++){
592
 
            if (!svnstatus_versioned(file_listing[selected_files[i]].svnstatus))
593
 
            {
594
 
                svn_selection = false;
595
 
            }
596
 
        }
597
 
    }
598
 
    
599
 
    if (numsel <= 1)
600
 
    {
601
 
        if (numsel == 0)
602
 
        {
603
 
            /* Display information about the current directory instead */
604
 
            filename = path_basename(current_path);
605
 
            file = current_file;
606
 
        }
607
 
        else if (numsel == 1)
608
 
        {
609
 
            filename = selected_files[0];
610
 
            file = file_listing[filename];
611
 
        }
612
 
 
613
 
        /* Update each action node in the topbar.
614
 
         * This includes enabling/disabling actions as appropriate, and
615
 
         * setting href/onclick attributes. */
616
 
    }
617
 
 
618
 
    /* Open */
619
 
    /* Available if exactly one file is selected */
620
 
    var open = document.getElementById("act_open");
621
 
    if (numsel == 1)
622
 
    {
623
 
        open.setAttribute("class", "choice");
624
 
        if (file.isdir)
625
 
            open.setAttribute("title",
626
 
                "Navigate to this directory in the file browser");
627
 
        else
628
 
            open.setAttribute("title",
629
 
                "Edit or view this file");
630
 
        open.setAttribute("href", build_revision_url(current_path, filename,
631
 
                                                     current_revision));
632
 
    }
633
 
    else
634
 
    {
635
 
        open.setAttribute("class", "disabled");
636
 
        open.removeAttribute("title");
637
 
        open.removeAttribute("href");
638
 
    }
639
 
 
640
 
    /* Serve */
641
 
    /* Available if zero or one files are selected,
642
 
     * and only if this is a file, not a directory */
643
 
    var serve = document.getElementById("act_serve");
644
 
    if (numsel <= 1 && !file.isdir && current_file.svnstatus != 'revision')
645
 
    {
646
 
        serve.setAttribute("class", "choice");
647
 
        serve.setAttribute("onclick",
648
 
              "return maybe_save('The last saved version will be served.')");
649
 
        if (numsel == 0)
650
 
            serve.setAttribute("href",
651
 
                app_url(serve_app, current_path));
652
 
        else
653
 
            serve.setAttribute("href",
654
 
                app_url(serve_app, current_path, filename));
655
 
    }
656
 
    else
657
 
    {
658
 
        serve.setAttribute("class", "disabled");
659
 
        serve.removeAttribute("href");
660
 
        serve.removeAttribute("onclick");
661
 
    }
662
 
 
663
 
    /* Run */
664
 
    /* Available if exactly one file is selected,
665
 
     * and it is a Python file.
666
 
     */
667
 
    var run = document.getElementById("act_run");
668
 
     
669
 
    if (numsel <= 1 && !file.isdir && file.type == "text/x-python" 
670
 
            && current_file.svnstatus != 'revision')
671
 
    {
672
 
        if (numsel == 0)
673
 
        {
674
 
            // In the edit window
675
 
            var localpath = path_join('/home', current_path);
676
 
        }
677
 
        else
678
 
        {
679
 
            // In the browser window
680
 
            var localpath = path_join('/home', current_path, filename);
681
 
        }
682
 
        run.setAttribute("class", "choice");
683
 
        run.setAttribute("onclick", "runfile('" + localpath + "')");
684
 
    }
685
 
    else
686
 
    {
687
 
        run.setAttribute("class", "disabled");
688
 
        run.removeAttribute("onclick");
689
 
    }
690
 
 
691
 
    /* Download */
692
 
    /* Always available for current files.
693
 
     * If 0 files selected, download the current file or directory as a ZIP.
694
 
     * If 1 directory selected, download it as a ZIP.
695
 
     * If 1 non-directory selected, download it.
696
 
     * If >1 files selected, download them all as a ZIP.
697
 
     */
698
 
    var download = document.getElementById("act_download");
699
 
    if (current_file.svnstatus == 'revision')
700
 
    {
701
 
        download.setAttribute("class", "disabled");
702
 
        download.removeAttribute("onclick");
703
 
    }
704
 
    else if (numsel <= 1)
705
 
    {
706
 
        download.setAttribute("class", "choice")
707
 
        if (numsel == 0)
708
 
        {
709
 
            download.setAttribute("href",
710
 
                app_url(download_app, current_path));
711
 
            if (file.isdir)
712
 
                download.setAttribute("title",
713
 
                    "Download the current directory as a ZIP file");
714
 
            else
715
 
                download.setAttribute("title",
716
 
                    "Download the current file");
717
 
        }
718
 
        else
719
 
        {
720
 
            download.setAttribute("href",
721
 
                app_url(download_app, current_path, filename));
722
 
            if (file.isdir)
723
 
                download.setAttribute("title",
724
 
                    "Download the selected directory as a ZIP file");
725
 
            else
726
 
                download.setAttribute("title",
727
 
                    "Download the selected file");
728
 
        }
729
 
    }
730
 
    else
731
 
    {
732
 
        /* Make a query string with all the files to download */
733
 
        var dlpath = app_url(download_app, current_path) + "?";
734
 
        for (var i=0; i<numsel; i++)
735
 
            dlpath += "path=" + encodeURIComponent(selected_files[i]) + "&";
736
 
        dlpath = dlpath.substr(0, dlpath.length-1);
737
 
        download.setAttribute("class", "choice")
738
 
        download.setAttribute("href", dlpath);
739
 
        download.setAttribute("title",
740
 
            "Download the selected files as a ZIP file");
741
 
    }
742
 
 
743
 
    /* Refresh - No changes required */
744
 
 
745
 
    /* Publish and Submit */
746
 
    /* If this directory is under subversion and selected/unselected file is a
747
 
     * directory. */
748
 
    var publish = document.getElementById("act_publish");
749
 
    var submit = document.getElementById("act_submit");
750
 
    var pubcond = numsel <= 1 && file.isdir;
751
 
    if (pubcond)
752
 
    {
753
 
        /* If this dir is already published, call it "Unpublish" */
754
 
        if (file.published)
755
 
        {
756
 
            publish.setAttribute("value", "unpublish");
757
 
            publish.setAttribute("title" ,"Make it so this directory "
758
 
                + "can not be seen by anyone on the web");
759
 
            publish.firstChild.nodeValue = "Unpublish";
760
 
        } else {
761
 
            publish.setAttribute("value", "publish");
762
 
            publish.setAttribute("title","Make it so this directory "
763
 
                + "can be seen by anyone on the web");
764
 
            publish.firstChild.nodeValue = "Publish";
765
 
        }
766
 
    }
767
 
    set_action_state(["publish", "submit"], pubcond);
768
 
 
769
 
    /* Share */
770
 
    /* If exactly 1 non-directory file is selected, and its parent
771
 
     * directory is published.
772
 
     */
773
 
    set_action_state("share", numsel == 1 && !file.isdir &&
774
 
                     current_file.published);
775
 
 
776
 
    /* Rename */
777
 
    /* If exactly 1 file is selected */
778
 
    set_action_state("rename", numsel == 1);
779
 
 
780
 
    /* Delete, cut, copy */
781
 
    /* If >= 1 file is selected */
782
 
    set_action_state(["delete", "cut", "copy"], numsel >= 1);
783
 
 
784
 
    /* Paste, new file, new directory, upload */
785
 
    /* Disable if the current file is not a directory */
786
 
    set_action_state(["paste", "newfile", "mkdir", "upload"], current_file.isdir);
787
 
 
788
 
    /* Subversion actions */
789
 
    /* These are only useful if we are in a versioned directory and have some
790
 
     * files selected. */
791
 
    set_action_state(["svnadd"], numsel >= 1 && current_file.svnstatus);
792
 
    /* And these are only useful is ALL the selected files are versioned */
793
 
    set_action_state(["svnremove", "svnrevert", "svncopy", "svncut"],
794
 
            numsel >= 1 && current_file.svnstatus && svn_selection);
795
 
    /* Commit is useful if ALL selected files are versioned, or the current
796
 
     * directory is versioned */
797
 
    set_action_state(["svncommit"], current_file.svnstatus &&
798
 
            (numsel >= 1 && svn_selection || numsel == 0));
799
 
 
800
 
    /* Diff, log and update only support one path at the moment, so we must
801
 
     * have 0 or 1 versioned files selected. If 0, the directory must be
802
 
     * versioned. */
803
 
    single_versioned_path = (
804
 
         (
805
 
          (numsel == 1 && (svnst = file_listing[selected_files[0]].svnstatus)) ||
806
 
          (numsel == 0 && (svnst = current_file.svnstatus))
807
 
         ) && svnstatus_versioned(svnst));
808
 
    set_action_state(["svndiff", "svnupdate"], single_versioned_path);
809
 
 
810
 
    /* We can resolve if we have a file selected and it is conflicted. */
811
 
    set_action_state("svnresolved", single_versioned_path && numsel == 1 && svnst == "conflicted");
812
 
 
813
 
    /* Log should be available for revisions as well. */
814
 
    set_action_state("svnlog", single_versioned_path, true);
815
 
 
816
 
    /* Cleanup should be available for revisions as well. */
817
 
    set_action_state("svncleanup", single_versioned_path, true);
818
 
 
819
 
    single_ivle_versioned_path = (
820
 
         (
821
 
          (numsel == 1 && (stat = file_listing[selected_files[0]])) ||
822
 
          (numsel == 0 && (stat = current_file))
823
 
         ) && svnstatus_versioned(stat.svnstatus)
824
 
           && stat.svnurl
825
 
           && stat.svnurl.substr(0, svn_base.length) == svn_base);
826
 
    set_action_state(["submit"], single_ivle_versioned_path);
827
 
 
828
 
    /* There is currently nothing on the More Actions menu of use
829
 
     * when the current file is not a directory. Hence, just remove
830
 
     * it entirely.
831
 
     * (This makes some of the above decisions somewhat redundant).
832
 
     * We also take this opportunity to show the appropriate actions2
833
 
     * bar for this path. It should either be a save or upload widget.
834
 
     */
835
 
    if (current_file.isdir)
836
 
    {
837
 
        var actions2_directory = document.getElementById("actions2_directory");
838
 
        actions2_directory.setAttribute("style", "display: inline;");
839
 
        var moreactions = document.getElementById("moreactions_area");
840
 
        moreactions.setAttribute("style", "display: inline;");
841
 
    }
842
 
    else
843
 
    {
844
 
        var actions2_file = document.getElementById("actions2_file");
845
 
        actions2_file.setAttribute("style", "display: inline;");
846
 
    }
847
 
 
848
 
    return;
849
 
}
850
 
 
851
 
/** Event handler for when an item of the "More actions..." dropdown box is
852
 
 * selected. Performs the selected action. */
853
 
function handle_moreactions()
854
 
{
855
 
    var moreactions = document.getElementById("moreactions");
856
 
    if (moreactions.value == "top")
857
 
        return;
858
 
    var selectedaction = moreactions.value;
859
 
    /* Reset to "More actions..." */
860
 
    moreactions.selectedIndex = 0;
861
 
 
862
 
    /* If 0 files selected, filename is the name of the current dir.
863
 
     * If 1 file selected, filename is that file.
864
 
     */
865
 
    if (selected_files.length == 0)
866
 
        filename = path_basename(current_path);
867
 
    else if (selected_files.length == 1)
868
 
        filename = selected_files[0];
869
 
    else
870
 
        filename = null;
871
 
 
872
 
    /* Now handle the selected action */
873
 
    switch(selectedaction)
874
 
    {
875
 
    case "publish":
876
 
        action_publish(selected_files);
877
 
        break;
878
 
    case "unpublish":
879
 
        action_unpublish(selected_files);
880
 
        break;
881
 
    case "share":
882
 
        window.open(public_app_url("~" + current_path, filename), 'share')
883
 
        break;
884
 
    case "submit":
885
 
        if (selected_files.length == 1)
886
 
            stat = file_listing[selected_files[0]];
887
 
        else
888
 
            stat = current_file;
889
 
        url = stat.svnurl.substr(svn_base.length);      // URL-encoded
890
 
        path = decodeURIComponent(url);
891
 
 
892
 
        /* The working copy might not have an up-to-date version of the
893
 
         * directory. While submitting like this could yield unexpected
894
 
         * results, we should really submit the latest revision to minimise
895
 
         * terrible mistakes - so we run off and ask fileservice for the
896
 
         * latest revision.*/
897
 
        $.post(app_path(service_app, current_path),
898
 
            {"action": "svnrepostat", "path": path},
899
 
            function(result)
900
 
            {
901
 
                window.location = path_join(app_path('+submit'), url) + '?revision=' + result.svnrevision;
902
 
            },
903
 
            "json");
904
 
 
905
 
        break;
906
 
    case "rename":
907
 
        action_rename(filename);
908
 
        break;
909
 
    case "delete":
910
 
        action_delete(selected_files);
911
 
        break;
912
 
    case "copy":
913
 
        action_copy(selected_files);
914
 
        break;
915
 
    case "cut":
916
 
        action_cut(selected_files);
917
 
        break;
918
 
    case "paste":
919
 
        action_paste();
920
 
        break;
921
 
    case "newfile":
922
 
        action_newfile();
923
 
        break;
924
 
    case "mkdir":
925
 
        action_mkdir();
926
 
        break;
927
 
    case "upload":
928
 
        show_uploadpanel(true);
929
 
        break;
930
 
    case "svnadd":
931
 
        action_add(selected_files);
932
 
        break;
933
 
    case "svnremove":
934
 
        action_remove(selected_files);
935
 
        break;
936
 
    case "svnrevert":
937
 
        action_revert(selected_files);
938
 
        break;
939
 
    case "svndiff":
940
 
        window.location = path_join(app_url('diff'), current_path, selected_files[0] || '');
941
 
        break;
942
 
    case "svnupdate":
943
 
        action_update(selected_files);
944
 
        break;
945
 
    case "svnresolved":
946
 
        action_resolved(selected_files);
947
 
        break;
948
 
    case "svncommit":
949
 
        action_commit(selected_files);
950
 
        break;
951
 
    case "svnlog":
952
 
        window.location = path_join(app_url('svnlog'), current_path, selected_files[0] || '');
953
 
        break;
954
 
    case "svncopy":
955
 
        action_svncopy(selected_files);
956
 
        break;
957
 
    case "svncut":
958
 
        action_svncut(selected_files);
959
 
        break;
960
 
    case "svncleanup":
961
 
        action_svncleanup(".");
962
 
        break;
963
 
    }
964
 
}
965
 
 
966
 
/** User clicks "Run" button.
967
 
 * Do an Ajax call and print the test output.
968
 
 */
969
 
function runfile(localpath)
970
 
{
971
 
    if (!maybe_save('The last saved version will be run.')) return false;
972
 
 
973
 
    /* Dump the entire file to the console */
974
 
    var callback = function()
975
 
    {
976
 
        console_enter_line("execfile('" + localpath + "')", "block");
977
 
    }
978
 
    start_server(callback)
979
 
    return;
 
476
    /* TODO */
 
477
    alert(path);
980
478
}
981
479
 
982
480
/** Called when the page loads initially.
983
481
 */
984
 
function browser_init()
 
482
window.onload = function()
985
483
{
986
484
    /* Navigate (internally) to the path in the URL bar.
987
485
     * This causes the page to be populated with whatever is at that address,
988
486
     * whether it be a directory or a file.
989
487
     */
990
 
    var path = get_path();
991
 
    navigate(path);
992
 
}
993
 
 
994
 
/** Gets the current path of the window */
995
 
function get_path() {
996
488
    var path = parse_url(window.location.href).path;
997
489
    /* Strip out root_dir + "/files" from the front of the path */
998
 
    var strip = make_path(this_app);
999
 
    if (path.substr(0, strip.length) == strip)
1000
 
        path = path.substr(strip.length+1);
1001
 
    else
1002
 
    {
1003
 
        /* See if this is an edit path */
1004
 
        strip = make_path(edit_app);
1005
 
        if (path.substr(0, strip.length) == strip)
1006
 
        {
1007
 
            path = path.substr(strip.length+1);
1008
 
        }
1009
 
    }
 
490
    strip_chars = make_path(this_app).length + 1;
 
491
    path = path.substr(strip_chars);
1010
492
 
1011
493
    if (path.length == 0)
1012
494
    {
1015
497
        path = username;
1016
498
    }
1017
499
 
1018
 
    return path;
 
500
    navigate(path);
1019
501
}