1
/* IVLE - Informatics Virtual Learning Environment
2
* Copyright (C) 2007-2008 The University of Melbourne
4
* This program is free software; you can redistribute it and/or modify
5
* it under the terms of the GNU General Public License as published by
6
* the Free Software Foundation; either version 2 of the License, or
7
* (at your option) any later version.
9
* This program is distributed in the hope that it will be useful,
10
* but WITHOUT ANY WARRANTY; without even the implied warranty of
11
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
* GNU General Public License for more details.
14
* You should have received a copy of the GNU General Public License
15
* along with this program; if not, write to the Free Software
16
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
* Module: Console (Client-side JavaScript)
19
* Author: Tom Conway, Matt Giuca
25
/* Begin religious debate (tabs vs spaces) here: */
26
/* (This string will be inserted in the console when the user presses the Tab
30
/* Console DOM objects */
32
console_filler = null;
34
windowpane_mode = false;
35
server_started = false;
40
function get_console_start_directory()
42
if((typeof(current_path) != 'undefined') && current_file)
44
// We have a current_path - give a suggestion to the server
46
if (current_file.isdir)
49
return path_join("/home", current_path);
53
// Editor - need to chop off filename
54
var tmp_path = current_path.split('/');
56
return path_join("/home", tmp_path.join('/'));
61
// No current_path - let the server decide
66
/* Starts the console server, if it isn't already.
67
* This can be called any number of times - it only starts the one server.
68
* Note that this is asynchronous. It will return after signalling to start
69
* the server, but there is no guarantee that it has been started yet.
70
* This is a separate step from console_init, as the server is only to be
71
* started once the first command is entered.
72
* Does not return a value. Writes to global variables
73
* server_host, and server_port.
75
* \param callback Function which will be called after the server has been
76
* started. No parameters are passed. May be null.
78
function start_server(callback)
85
var callback1 = function(xhr)
87
var json_text = xhr.responseText;
90
server_key = JSON.parse(json_text).key;
91
server_started = true;
93
"ivle.op": "chat", "kind": "splash", "key": server_key
95
var callback2 = function(xhr)
97
console_response(null, null, xhr.responseText);
101
ajax_call(callback2, "console", "service", args, "POST");
105
alert("An error occured when starting the IVLE console. " +
106
"Please refresh the page and try again.\n" +
107
"Details have been logged for further examination.")
111
$("#console_output").append(
112
'<span class="console_message">IVLE console starting up...</span>\n');
113
console_maximize(true);
115
callback1, "console", "service",
116
{"ivle.op": "start", "cwd": get_console_start_directory()},
120
/** Start up the console backend before the user has entered text.
121
* This will disable the text input, start a backend, and enable the input
124
function start_server_early()
126
var inputbox = document.getElementById("console_inputText");
127
inputbox.setAttribute("disabled", "disabled");
128
var callback = function(xhr)
130
inputbox.removeAttribute("disabled")
132
start_server(callback);
135
/** Initialises the console. All apps which import console are required to
136
* call this function.
137
* Optional "windowpane" (bool), if true, will cause the console to go into
138
* "window pane" mode which will allow it to be opened and closed, and float
140
* (Defaults to closed).
142
function console_init(windowpane)
144
/* Set up the console as a floating pane */
145
console_body = document.getElementById("console_body");
146
/* If there is no console body, don't worry.
147
* (This lets us import console.js even on pages without a console box */
148
if (console_body == null) return;
149
console_filler = document.getElementById("console_filler");
152
windowpane_mode = true;
157
/** Hide the main console panel, so the console minimizes to just an input box
158
* at the page bottom. */
159
function console_minimize()
161
if (!windowpane_mode) return;
162
console_body.setAttribute("class", "console_body windowpane minimal");
163
console_filler.setAttribute("class", "windowpane minimal");
166
/** Show the main console panel, so it enlarges out to its full size.
168
function console_maximize(do_not_start)
170
if (!windowpane_mode) return;
171
if (!do_not_start && !server_started) start_server_early();
172
console_body.setAttribute("class", "console_body windowpane maximal");
173
console_filler.setAttribute("class", "windowpane maximal");
176
/* current_text is the string currently on the command line.
177
* If non-empty, it will be stored at the bottom of the history.
179
function historyUp(current_text)
181
/* Remember the changes made to this item */
182
this.edited[this.cursor] = current_text;
187
this.earliestCursor = this.cursor;
190
function historyDown(current_text)
192
/* Remember the changes made to this item */
193
this.edited[this.cursor] = current_text;
194
if (this.cursor < this.items.length - 1)
200
function historyCurr()
202
return this.edited[this.cursor];
205
function historySubmit(text)
207
/* Copy the selected item's "edited" version over the permanent version of
209
this.items[this.items.length-1] = text;
210
/* Add a new blank item */
211
this.items[this.items.length] = "";
212
this.cursor = this.items.length-1;
213
/* Blow away all the edited versions, replacing them with the existing
215
* Not the whole history - just start from the earliest edited one.
216
* (This avoids slowdown over extended usage time).
218
for (var i=this.earliestCursor; i<=this.cursor; i++)
219
this.edited[i] = this.items[i];
220
this.earliestCursor = this.cursor;
223
function historyShow()
226
for (var i = 0; i < this.items.length; i++)
228
if (i == this.cursor)
232
res += this.items[i].toString();
233
if (i == this.cursor)
239
if (this.cursor == this.items.length)
247
* This is a fairly complex mechanism due to complications when editing
248
* history items. We store two arrays. "items" is the permanent history of
249
* each item. "edited" is a "volatile" version of items - the edits made to
250
* the history between now and last time you hit "enter".
251
* This is because the user can go back and edit any of the previous items,
252
* and the edits are remembered until they hit enter.
254
* When hitting enter, the "edited" version of the currently selected item
255
* replaces the "item" version of the last item in the list.
256
* Then a new blank item is created, for the new line of input.
257
* Lastly, all the "edited" versions are replaced with their stable versions.
259
* Cursor never points to an invalid location.
263
this.items = new Array("");
264
this.edited = new Array("");
266
this.earliestCursor = 0;
268
this.down = historyDown;
269
this.curr = historyCurr;
270
this.submit = historySubmit;
271
this.show = historyShow;
274
var hist = new History();
276
function set_interrupt()
281
function clear_output()
283
var output = document.getElementById("console_output");
284
while (output.firstChild)
286
output.removeChild(output.firstChild);
290
/** Send a line of text to the Python server, wait for its return, and react
291
* to its response by writing to the output box.
292
* Also maximize the console window if not already.
294
function console_enter_line(inputbox, which)
298
// Open up the console so we can see the output
301
if (typeof(inputbox) == "string")
303
var inputline = inputbox + "\n";
308
/* Disable the text box */
309
inputbox.setAttribute("disabled", "disabled");
311
var inputline = inputbox.value + "\n";
313
var output = document.getElementById("console_output");
316
var span = document.createElement("span");
317
span.setAttribute("class", "inputPrompt");
318
span.appendChild(document.createTextNode(
319
document.getElementById("console_prompt").firstChild.nodeValue)
321
output.appendChild(span);
322
// Print input line itself in a span
323
var span = document.createElement("span");
324
span.setAttribute("class", "inputMsg");
325
span.appendChild(document.createTextNode(inputline));
326
output.appendChild(span);
327
divScroll.activeScroll();
330
"ivle.op": "chat", "kind": which, "key": server_key,
331
"text": inputline, "cwd": get_console_start_directory()
333
var callback = function(xhr)
335
console_response(inputbox, inputline, xhr.responseText);
337
ajax_call(callback, "console", "service", args, "POST");
340
function console_response(inputbox, inputline, responseText)
344
var res = JSON.parse(responseText);
348
alert("An internal error occurred in the python console.");
351
var output = document.getElementById("console_output");
352
if (res.hasOwnProperty('okay'))
357
output.appendChild(document.createTextNode(res.okay + "\n"));
358
output.appendChild(span);
359
divScroll.activeScroll();
361
// set the prompt to >>>
364
else if (res.hasOwnProperty('exc'))
367
// print out the error message (res.exc)
368
print_error(res.exc);
370
// set the prompt to >>>
373
else if (res.hasOwnProperty('restart') && res.hasOwnProperty('key'))
375
// Server has indicated that the console should be restarted
377
// Get the new key (host, port, magic)
378
server_key = res.key;
380
// Print a reason to explain why we'd do such a horrible thing
381
// (console timeout, server error etc.)
383
"IVLE console restarted: " + res.restart, "console_message");
385
// set the prompt to >>>
388
else if (res.hasOwnProperty('more'))
390
// Need more input, so set the prompt to ...
393
else if (res.hasOwnProperty('output'))
395
if (res.output.length > 0)
397
output.appendChild(document.createTextNode(res.output));
398
divScroll.activeScroll();
400
var callback = function(xhr)
402
console_response(inputbox, null, xhr.responseText);
406
var kind = "interrupt";
413
"ivle.op": "chat", "kind": kind, "key": server_key,
414
"text": '', "cwd": get_console_start_directory()
416
ajax_call(callback, "console", "service", args, "POST");
418
// Open up the console so we can see the output
421
// Return early, so we don't re-enable the input box.
424
else if (res.hasOwnProperty('input'))
430
alert("An internal error occurred in the python console.");
434
if (inputbox != null)
436
/* Re-enable the text box */
437
inputbox.removeAttribute("disabled");
442
divScroll.activeScroll();
444
// Focus the input box by default
445
document.getElementById("console_output").focus();
446
document.getElementById("console_inputText").focus();
449
function catch_input(key)
451
var inp = document.getElementById('console_inputText');
454
case 9: /* Tab key */
455
var selstart = inp.selectionStart;
456
var selend = inp.selectionEnd;
457
if (selstart == selend)
459
/* No selection, just a carat. Insert a tab here. */
460
inp.value = inp.value.substr(0, selstart)
461
+ TAB_STRING + inp.value.substr(selstart);
465
/* Text is selected. Just indent the whole line
466
* by inserting a tab at the start */
467
inp.value = TAB_STRING + inp.value;
469
/* Update the selection so the same characters as before are selected
471
inp.selectionStart = selstart + TAB_STRING.length;
472
inp.selectionEnd = inp.selectionStart + (selend - selstart);
473
/* Cancel the event, so the TAB key doesn't move focus away from this
476
/* Note: If it happens that some browsers don't support event
477
* cancelling properly, this hack might work instead:
479
"document.getElementById('console_inputText').focus()",
483
case 13: /* Enter key */
484
var callback = function()
486
/* Send the line of text to the server */
487
console_enter_line(inp, "chat");
488
hist.submit(inp.value);
489
inp.value = hist.curr();
492
/* Disable the text box. This will be redone by
493
* console_enter_line, but we do it here too in case start_server
496
inp.setAttribute("disabled", "disabled");
497
/* Start the server if it hasn't already been started */
498
start_server(callback);
500
case 38: /* Up arrow */
502
inp.value = hist.curr();
503
/* Inhibit further responses to this event, or WebKit moves the
504
* cursor to the start. */
507
case 40: /* Down arrow */
508
hist.down(inp.value);
509
inp.value = hist.curr();
515
/** Resets the console by signalling the old console to expire and starting a
518
function console_reset()
520
// FIXME: We show some feedback here - either disable input or at very
521
// least the reset button.
523
// Restart the console
530
xhr = ajax_call(null, "console", "service", {"ivle.op": "chat", "kind": "terminate", "key": server_key, "cwd": get_console_start_directory()}, "POST");
531
console_response(null, null, xhr.responseText);
535
/** Prints an error line in the console **/
536
function print_error(error, cls)
541
var output = document.getElementById("console_output");
544
var span = document.createElement("span");
545
span.setAttribute("class", cls);
546
span.appendChild(document.createTextNode(error + "\n"));
547
output.appendChild(span);
550
divScroll.activeScroll();
553
/** Sets the prompt text **/
554
function set_prompt(prompt_text)
556
var prompt = document.getElementById("console_prompt");
557
prompt.replaceChild(document.createTextNode(prompt_text + " "), prompt.firstChild);
560
/**** Following Code modified from ******************************************/
561
/**** http://radio.javaranch.com/pascarello/2006/08/17/1155837038219.html ***/
562
/****************************************************************************/
563
var chatscroll = new Object();
565
chatscroll.Pane = function(scrollContainerId)
567
this.scrollContainerId = scrollContainerId;
570
chatscroll.Pane.prototype.activeScroll = function()
572
var scrollDiv = document.getElementById(this.scrollContainerId);
573
var currentHeight = 0;
575
if (scrollDiv.scrollHeight > 0)
576
currentHeight = scrollDiv.scrollHeight;
577
else if (scrollDiv.offsetHeight > 0)
578
currentHeight = scrollDiv.offsetHeight;
580
scrollDiv.scrollTop = currentHeight;
585
var divScroll = new chatscroll.Pane('console_output');