Debian Codegraph @

terps/tads/tads3/lib/webuires/cmdwin.js

raw symbols SCIP
1 /* Copyright (c) 2010 by Michael J. Roberts. All Rights Reserved. */
2 /*
3 * Command input window scripts for TADS 3 Web UI. These scripts are for
4 * the command-line window. This window type simulates the traditional
5 * console model, with a mix of text output and command-line input. This
6 * is a "widget" that can be plugged into an iframe in a layout window, so
7 * a single browser window can contain multiple command windows. For
8 * example, you could use one command window for a game transcript, and
9 * another for player-to-player chat.
10 */
11
12 // command window initialization
13 function cmdWinInit()
14 {
15 // set up our window and document event handlers
16 addEventHandler(window, "scroll", onWinScroll);
17 addEventHandler(window, "resize", onWinResize);
18 addEventHandler(document, "mouseup", onDocMouseUp);
19 addEventHandler(document, "mousedown", onDocMouseDown);
20 addKeyHandler(document, onDocKey);
21
22 // initialize the utility package
23 utilInit();
24
25 // get the initial state
26 getInitState();
27
28 // load preference styles
29 $win().prefsToCSS(null, window);
30
31 // Set up a workaround for an annoying IE bug. Here's the situation:
32 // when an <A> is dragged and dropped, it gets into this weird half-focus
33 // state where IE thinks it has focus, but Windows *doesn't*. Windows
34 // leaves focus wherever it was before the drag. When a keyboard event
35 // comes in, IE does the JS event bubble according to its internal notion
36 // that the <A> has focus, but Windows actually sends the keystroke to
37 // the old focus control. So what you get is a keystroke going to a
38 // control without any JS events being generated. This is a problem
39 // when the keystroke is Enter and the control is our command line field:
40 // IE simply inserts the newline into the field without telling us about
41 // it. I can't find any good workaround other than a timer, to check
42 // after the fact for this weird situation. Checking a few times a
43 // second shouldn't bog things down too much but should correct the
44 // problem before it's noticeable in the UI.
45 setInterval(function() {
46 var fld = $("cmdline");
47 if (fld && fld.nodeName == "SPAN")
48 {
49 var txt = fld.innerHTML;
50 if (txt && txt.search(/<BR>|[\r\n]/) >= 0)
51 {
52 setCommandText(fld, getCommandText(fld).replace(/[\r\n]/g, ""));
53 handleEnterKey(fld);
54 }
55 }
56 }, 250);
57 }
58
59 /* ------------------------------------------------------------------------ */
60 /*
61 * Process a game event from the server
62 */
63 function onGameEvent(req, resp)
64 {
65 // check what we have
66 if (xmlHasChild(resp, "say"))
67 {
68 window.closeCommandLine(null, null, false);
69 window.writeText(xmlChildText(resp, "say"));
70 }
71 if (xmlHasChild(resp, "closeInputLine"))
72 {
73 var c = xmlChild(resp, "closeInputLine")[0];
74 var txt = xmlChildText(c, "text");
75 var user = xmlChildText(c, "user");
76 window.closeCommandLine(txt, user, false, null);
77 }
78 if (xmlHasChild(resp, "cancelInputLine"))
79 {
80 window.cancelCommandLine(
81 xpath(resp, "cancelInputLine.reset") == "yes");
82 }
83 if (xmlHasChild(resp, "inputLine"))
84 {
85 window.openCommandLine();
86 }
87 if (xmlHasChild(resp, "scrollToBottom"))
88 {
89 scrollToAnchor();
90 }
91 if (xmlHasChild(resp, "clearWindow"))
92 {
93 window.clearWindow();
94 }
95 if (xmlHasChild(resp, "morePrompt"))
96 {
97 window.showMorePrompt();
98 }
99 if (xmlHasChild(resp, "setsize"))
100 {
101 // update our window layout
102 parent.setWinLayout(this, xmlChildText(resp, "setsize"));
103 }
104 if (xmlHasChild(resp, "resize"))
105 {
106 // recalculate our window layout
107 parent.calcLayout();
108 }
109 }
110
111 function onGameState(req, resp)
112 {
113 // read the scrollback items and write them as text
114 var hist = [];
115 xpath(resp, "scrollback/sbitem[*]").forEach(function(s)
116 {
117 // write this output text passage
118 window.writeText(xpath(s, "text#text"));
119
120 // if there's an input line for this block, add it
121 var i = xpath(s, "input");
122 if (i)
123 {
124 // get the appropriate style for the old command line text
125 var style = xmlHasChild(i, "interrupted")
126 ? "cmdlineInterrupted" : "cmdlineOld";
127
128 // add the command line text
129 var t = xmlNodeText(i);
130 window.writeText("<span class=\"" + style + "\">"
131 + t.htmlify() + "</span><br>");
132
133 // save it in our new history list
134 hist.push(t);
135 }
136 });
137
138 // if there's no global history list (probably because we're refreshing
139 // the page), use the new history list that we built from the scrollback
140 // information as the active history list
141 if (cmdLineHistory.length == 0)
142 {
143 // trim it to the maximum retention count
144 while (hist.length > cmdLineHistoryLimit)
145 hist.shift();
146
147 // install it as the active command history
148 cmdLineHistory = hist;
149
150 // select the last item
151 cmdLineHistoryIdx = hist.length;
152 }
153
154 switch (xmlChildText(resp, "mode"))
155 {
156 case "working":
157 break;
158
159 case "inputLine":
160 window.openCommandLine();
161 break;
162
163 case "moreMode":
164 window.showMorePrompt();
165 break;
166 }
167 }
168
169 /* ------------------------------------------------------------------------ */
170 /*
171 * Document event handlers
172 */
173
174 function onDocKey(desc)
175 {
176 // if there's an explicit More prompt showing, release it
177 if (morePromptDiv && desc && !desc.modifier)
178 {
179 // set the new scroll anchor
180 scrollAnchor = getObjectRect(morePromptDiv).y - 5;
181
182 // remove the division
183 $("maindiv").removeChild(morePromptDiv);
184 morePromptDiv = null;
185
186 // let the server know that the More prompt is done
187 serverRequest("/webui/morePromptDone?window=" + pageName,
188 ServerRequest.Command);
189
190 // we're done with the key - don't process it further
191 return false;
192 }
193
194 // do the generic focus processing
195 genericDocKeyFocus(desc);
196 }
197
198 function onDocMouseDown(ev)
199 {
200 // apply the default processing
201 return true;
202 }
203
204 function onDocMouseUp(ev)
205 {
206 // apply the default processing
207 return true;
208 }
209
210 var docFocusThread = null;
211 function onFieldFocus()
212 {
213 if (docFocusThread)
214 {
215 clearTimeout(docFocusThread);
216 docFocusThread = null;
217 }
218 }
219
220 /*
221 * Process a selection change in the field. We call this from the
222 * 'onselect' event in the field, which fires whenever the selection
223 * changes to a new non-empty selection; and also on mouseup and mousedown
224 * messages (since these can move the cursor, but don't generate 'onselect'
225 * events if the selection range is empty); and also on key events (since
226 * these can also change the selection, and again don't generate 'onselect'
227 * events for empty selections).
228 */
229 var lastFldSel = null;
230 function onFieldSelect()
231 {
232 // remember the new selection range in the field, if we have one
233 var sel = getSelRangeInEle("cmdline");
234 if (sel)
235 lastFldSel = sel;
236 }
237
238 /*
239 * Process a mouse event (mousedown or mouseup) in the field. Mouse clicks
240 * can cause selection changes that don't generate 'onselect' events, so
241 * note the selection after processing each click.
242 */
243 function onFieldMouse()
244 {
245 // note the new selection after the click has been fully processed
246 setTimeout(onFieldSelect, 0);
247 }
248
249 /*
250 * Set the default focus for a keyboard event. This moves focus to the
251 * command line if there's an active command line, and focus isn't already
252 * in the command line or some other focus-taking object.
253 */
254 function setDefaultFocusChild(desc, fromWin)
255 {
256 // if the command line doesn't exist, do nothing
257 var fld = $("cmdline");
258 if (!fld)
259 return;
260
261 // if the command line already has focus, do nothing
262 var ae = document.activeElement;
263 if (ae == fld && document.hasFocus && document.hasFocus())
264 return;
265
266 // if some other input control has focus, do nothing
267 if (ae && ae != fld && eleKeepsFocus(ae, desc))
268 return;
269
270 // remember current selection, since focusing will set a new default
271 // selection in the field
272 var sel = lastFldSel;
273
274 // note the current text in the field
275 var oldTxt = getCommandText(fld);
276
277 // set focus after finishing with this key event
278 setTimeout(function()
279 {
280 // move focus to the field
281 try
282 {
283 fld.focus();
284 }
285 catch (e)
286 {
287 // couldn't set focus - the field must have been deleted
288 return;
289 }
290
291 // Note if the field's contents have changed since we read them.
292 // IE has some buggy behavior in certain situations where the
293 // field *kind of* loses focus, but not quite: for JS purposes,
294 // IE reports that the field doesn't have focus, but internally
295 // the underlying control actually does have focus. The result
296 // is that the field turns out to process the key even though
297 // IE assures us that it won't. We can detect many of these
298 // cases by checking the before and after field contents; if
299 // the field changed between the key event and the timeout,
300 // the event must have made some change to the field after
301 // all, so we don't want to insert buffered characters
302 // after all.
303 var newTxt = getCommandText(fld);
304 var changed = newTxt != oldTxt;
305
306 // re-select the original range as of when we last lost focus
307 if (sel && !changed)
308 setSelRangeInEle(fld, sel);
309
310 // make sure the field is fully in view
311 var rcFld = getObjectRect(fld);
312 var rcDiv = getObjectRect(fld.parentNode);
313 var s = rcDiv.y + rcDiv.height - getWindowRect().height
314 + rcFld.height/2;
315 var scur = getScrollPos();
316 if (s > scur.y)
317 window.scrollTo(scur.x, s);
318
319 // process buffered keys
320 readKeyBuf(fld, changed);
321
322 }, 0);
323
324 // If it's an Up or Down key, cancel the default behavior, so that
325 // the browser doesn't scroll the window. These keys step through
326 // the command history when a command line is active, so we don't
327 // want to also scroll the window.
328 if (desc && (desc.keyName == "Up" || desc.keyName == "Down"))
329 preventDefault(desc.event);
330 }
331
332 // Process keys in the top window's keyboard buffer. The buffer captures
333 // keystrokes when there's no focus, so that we can deliver them to the
334 // field when it initially gains focus or regains focus.
335 function readKeyBuf(fld, changed)
336 {
337 // get the key buffer
338 var buf = $win().keybuf;
339
340 // read each key
341 for (var done = false ; buf.length && !done ; )
342 {
343 // get the next key - take the oldest key first so that we process
344 // keys in the same order as they were typed
345 var desc = buf.shift();
346
347 // if the field changed since we buffered the key, ignore everything
348 // except certain command keys
349 if (changed && desc.keyName != "Enter")
350 continue;
351
352 // note the current selection in the field
353 var r = getSelRangeInEle(fld) || { start: 0, end: 0 };
354
355 // if it's a character key, replace the selection with the
356 // character; otherwise process the special key
357 if (desc.ch && desc.ch.charCodeAt(0) > 27)
358 {
359 // pretend we typed the character
360 replaceSelRange(fld, desc.ch, false);
361 }
362 else switch (desc.keyName)
363 {
364 case "U+0008":
365 // Backspace - delete the selection, or the character to the left.
366 // If nothing's selected, select the character to the left.
367 if (r.start == r.end && r.start > 0)
368 setSelRangeInEle(fld, {start: r.start - 1, end: r.start});
369
370 // delete the selection
371 replaceSelRange(fld, "", false);
372 break;
373
374 case "U+007F":
375 // Delete - delete the selection, or the character to the right.
376 // If nothing's selected, select the character to the right.
377 if (r.start == r.end)
378 setSelRangeInEle(fld, {start: r.start, end: r.start + 1});
379
380 // delete the selection
381 replaceSelRange(fld, "", false);
382 break;
383
384 case "Enter":
385 // process the enter key
386 handleEnterKey(fld);
387
388 // stop processing buffered keys, since we're no longer active
389 done = true;
390 break;
391
392 case "Left":
393 // move to the start of the selection, or left one character
394 if (r.start == 0)
395 r = {start: 0, end: 0};
396 else if (r.start == r.end)
397 r = {start: r.start - 1, end: r.start - 1};
398 else
399 r = {start: r.start, end: r.start};
400 setSelRangeInEle(fld, r);
401 break;
402
403 case "Right":
404 // move to the end of the selection, or right one character
405 if (r.start == r.end)
406 r = {start: r.start + 1, end: r.start + 1};
407 else
408 r = {start: r.end, end: r.end};
409 setSelRangeInEle(fld, r);
410 break;
411
412 default:
413 // try running others through the normal key handler
414 cmdlineKey(desc, fld);
415 break;
416 }
417 }
418 }
419
420 /*
421 * IE-specific Paste filtering for the command line. We make sure that the
422 * pasted data doesn't contain any newlines or formatted text.
423 */
424 function onFieldPaste()
425 {
426 // get the clipboard contents
427 var txt = window.clipboardData.getData("Text");
428 if (txt != null)
429 {
430 // remove any newlines (replace each run of newlines with one space)
431 txt = txt.replace(/[\r\n]+/g, " ");
432
433 // Manually do the past into the field's current selection. Do
434 // this rather than allowing the native paste to proceed, because
435 // the native paste will insert formatted HTML text. There's not
436 // a way to tell IE to paste the plain text version that it shows
437 // us; it always just pastes the HTML. So we have to simulate the
438 // effect by doing the replacement manually.
439 replaceSelRange("cmdline", txt, true);
440
441 // stop the rest of the paste
442 return false;
443 }
444 else
445 {
446 // no text available - do the native paste operation instead
447 return true;
448 }
449 }
450
451 function onWinScroll(ev)
452 {
453 // the user has presumably scrolled the window manually, so set
454 // the new anchor position to the current scroll position (assuming
455 // it's below the old scroll anchor)
456 var y = getScrollPos().y;
457 if (y > scrollAnchor)
458 scrollAnchor = y;
459
460 // if there's a pending command line, try opening it
461 if (cmdLinePending)
462 maybeOpenCommandLine();
463
464 // continue to the default browser processing
465 return true;
466 }
467
468 function onWinResize(event)
469 {
470 // if there's a pending command line, try opening it - the resize might
471 // have brought the new command line real estate into view
472 maybeOpenCommandLine();
473
474 // adjust the command line width
475 adjustCmdlineWidth();
476
477 // apply the default processing
478 return true;
479 }
480
481 /* ------------------------------------------------------------------------ */
482 /*
483 * Clear the window
484 */
485 function clearWindow()
486 {
487 // end the current output division
488 outputDiv = null;
489
490 // If the active element is the body, explicitly move focus there if
491 // possible. This avoids a weird glitch on IE. I think what's going
492 // on is that IE has some residual memory of the focus being in the
493 // division that contained the most recent command line, and removing
494 // that division below causes IE to send the focus off into some
495 // off-screen limbo to follow the removed element. Once focus goes
496 // to limbo, we can't seem to get it back programmatically; the user
497 // has to manually click on the window, which is irritating for the
498 // user. Explicitly establishing focus in the body element before we
499 // remove anything seems to keep focus in the window after the clear.
500 var ae = document.activeElement;
501 if (ae == document.body && ae.focus)
502 ae.focus();
503
504 // remove all of the "outputdiv" children of the "maindiv" division
505 var main = $("maindiv");
506 for (var chi = main.firstChild, nxt = null ; chi ; chi = nxt)
507 {
508 // note the next child, in case we delete this one
509 nxt = chi.nextSibling;
510
511 // if this is an "outputdiv" division, delete it
512 if (chi.className == "outputdiv")
513 main.removeChild(chi);
514 }
515 }
516
517 /* ------------------------------------------------------------------------ */
518 /*
519 * Window text writer
520 */
521
522 // current output division, and current source text for the division
523 var outputDiv = null;
524 var outputDivTxt = null;
525
526 /*
527 * Write text to the window. This adds the text at the end of the current
528 * output division in the document.
529 */
530 function writeText(txt)
531 {
532 // open an output division if necessary
533 openOutputDiv();
534
535 // add the text to the running source for the division
536 outputDivTxt += BrowserInfo.adjustText(txt);
537
538 // set the text in the division
539 outputDiv.innerHTML = outputDivTxt;
540 }
541
542 /*
543 * Open an output division
544 */
545 function openOutputDiv()
546 {
547 // if there's no output division open, create one
548 if (!outputDiv)
549 {
550 // create a new division
551 outputDiv = document.createElement("div");
552 outputDiv.className = "outputdiv";
553
554 // add it at the end of the main division
555 var md = $("maindiv");
556 md.appendChild(outputDiv);
557
558 // start a new running division text section
559 outputDivTxt = '';
560 }
561 }
562
563 /* ------------------------------------------------------------------------ */
564 /*
565 * "More" prompt
566 */
567 function showMorePrompt()
568 {
569 // if there's already a More prompt division, do nothing
570 if (morePromptDiv)
571 return;
572
573 // create the "More" prompt division
574 var mp = morePromptDiv = document.createElement("div");
575 mp.className = "morePrompt";
576
577 // add it at the end of the main division
578 var main = $("maindiv");
579 main.appendChild(mp);
580
581 // fill it in
582 mp.innerHTML = "Press a key to continue...";
583
584 // scroll it into view, if possible
585 scrollToAnchor();
586 }
587
588
589 /* ------------------------------------------------------------------------ */
590 /*
591 * Command line processing
592 */
593
594 /* command-line globals */
595 var scrollAnchor = 0;
596 var cmdLinePending = null;
597 var cmdLineHistory = [];
598 var cmdLineHistoryIdx = 0;
599 var cmdLineHistoryLimit = 20;
600 var cmdLineNum = 1;
601
602 /*
603 * Get the contents of an open text field
604 */
605 function getCommandText(fld)
606 {
607 // we use a <SPAN contentEditable=true> on some browsers, and an
608 // <INPUT TYPE=TEXT> field on others
609 var txt = fld.nodeName == "SPAN" ? fld.innerText : fld.value;
610
611 // if it's null, make it an empty string
612 if (txt == null)
613 txt = "";
614
615 // return the text
616 return txt;
617 }
618
619 /*
620 * Set the contents of an open text field
621 */
622 function setCommandText(fld, txt)
623 {
624 // before setting the text, make sure the field is big enough for it
625 var probe = $("cmdline_probe.<SPAN>");
626 probe.innerHTML = (txt.htmlify() + 'MMMM').replace(/ /g, '&nbsp;');
627 if (probe.offsetWidth > fld.offsetWidth)
628 fld.style.width = probe.offsetWidth + "px";
629
630 // set the contents, according to the input element type
631 if (fld.nodeName == "SPAN")
632 fld.innerText = txt;
633 else
634 fld.value = txt;
635
636 // move the cursor to the end of the new text
637 setSelRangeInEle(fld, {start: txt.length, end: txt.length});
638 }
639
640 /*
641 * Open a command line. This closes the current output division and adds a
642 * new input editor after it.
643 */
644 function openCommandLine()
645 {
646 // add an empty span as a wrapper for the command line
647 var id = "cmdline_" + cmdLineNum;
648 writeText("&#65279;<span id=\"" + id + "\" class=\"cmdline\"></span>");
649 cmdLinePending = $(id);
650
651 // Try opening the new command line immediately, if possible. (Whether
652 // we can depends on the scrolling situation.)
653 maybeOpenCommandLine();
654
655 // scroll down as far as possible
656 scrollToAnchor();
657 }
658
659 /*
660 * Scroll down as far as possible to bring new text into view. This
661 * scrolls down to the bottom of the document, or to the point where the
662 * "scroll anchor" just goes out of view, whichever distance is shorter.
663 * The scroll anchor is the last vertical position that we can safely
664 * assume the user has seen: it's the bottom of the document at the time of
665 * the last pause for user interaction, such as a command line input or key
666 * input wait.
667 */
668 var inMoreMode = false, morePromptDiv = null;
669 function scrollToAnchor()
670 {
671 // get the main division, and figure its bottom position in doc coords
672 var main = $("maindiv");
673 var rcMain = getObjectRect(main);
674
675 // get the window size and current scroll position
676 var rcWin = getWindowRect();
677 var curScroll = getScrollPos();
678
679 // the most we'd want to scroll would be far enough to bring the bottom
680 // of the main division into view, so start with that
681 var s = rcMain.y + rcMain.height - rcWin.height;
682
683 // if that's beyond the anchor position, only scroll as far as the anchor
684 if (s > scrollAnchor)
685 s = scrollAnchor;
686
687 // if we're not already scrolled past the target, scroll there now
688 if (s > curScroll.y)
689 window.scrollTo(curScroll.x, s);
690 }
691
692 /*
693 * Try opening the command line for editing. This creates the actual
694 * <input> text field that we use to present the input editor in the UI.
695 */
696 function maybeOpenCommandLine()
697 {
698 // IE seems to trigger some events recursively at surprising times.
699 // In particular, IE seems to do queued processing on virtually any
700 // system call, even seemingly non-blocking things like object size
701 // retrievals, and this can trigger event calls. Since this routine
702 // is called from a number of events, that means that we can be
703 // invoked recursively seemingly at random. To avoid reentrancy
704 // problems, privatize our globals while we're working.
705 var cl = cmdLinePending;
706 cmdLinePending = null;
707
708 // if there's no command line pending, there's nothing to do
709 if (!cl)
710 return;
711
712 // Check to see if the new command line is in view. We've set up
713 // the wrapper division for the new command line at the bottom of
714 // the stream division, so we simply have to see if the bottom of
715 // division is in view.
716 var rcMain = getObjectRect($("maindiv"));
717
718 // figure the distance from the scroll anchor to the bottom of the div
719 var dist = rcMain.y + rcMain.height - scrollAnchor;
720
721 // if that doesn't fit in the window, don't open the command line yet
722 var rcWin = getWindowRect();
723 if (dist > rcWin.height)
724 {
725 // set a More prompt in the status line (this doesn't work on most
726 // newer browsers, and there's no workaround, since most browsers
727 // now prohibit javascript from tampering with the status line for
728 // security reasons; but just in case)
729 window.status = "*** More ***";
730
731 // note that More mode was activated
732 inMoreMode = true;
733
734 // restore the pending command line and return
735 cmdLinePending = cl;
736 return;
737 }
738
739 // if we activated More mode in the past, turn it off
740 if (inMoreMode)
741 {
742 // remove any More prompt
743 window.status = "";
744
745 // Consider any keys that were typed up to this point to have been
746 // consumed by the More mode, so clear the keystroke buffer.
747 $win().keybuf = [];
748
749 // no longer in More mode
750 inMoreMode = false;
751 }
752
753 // hide the bottom spacer while the command line is open, so that
754 // the command line is at the very bottom of the window
755 // $("bottomSpacerDiv").style.display = "none";
756
757 // figure the font - use the computed font of the enclosing span
758 var font = "font: " + getStyle(cl, "font").replace(/'/g, '') + ";";
759
760 // set up the event handlers for the input field
761 var events =
762 "onkeypress=\"javascript:return $kp(event, cmdlineKey, this);\" "
763 + "onkeydown=\"javascript:return $kd(event, cmdlineKey, this);\" "
764 + "onmousedown=\"javascript:onFieldMouse();return true;\" "
765 + "onmouseup=\"javascript:adjustCmdlineWidth();onFieldMouse();"
766 + "return true;\" "
767 + "ondrop=\"javascript:adjustCmdlineWidth();return true;\" "
768 + "onpaste=\"javascript:adjustCmdlineWidth();return true;\" "
769 + "onfocus=\"javascript:onFieldFocus();\" ";
770
771 // fill in the command line wrapper with the input field
772 if (BrowserInfo.ie)
773 {
774 // IE seems impossibly fiddly with text field alignment; as far as
775 // I can tell it's simply not possible to get a field to line up
776 // seamlessly with the surrounding text for arbitrary font size.
777 // We could always make manual adjustments, but I can't even figure
778 // out a way to predict what the adjustment needs to be - it seems
779 // to vary across different fonts and sizes. Fortunately, there's
780 // the contentEditable property, which lets us make an ordinary SPAN
781 // into an editable field. This actually works on most of the other
782 // browsers as well, but it has some other quirks of its own, so
783 // we'll only use it where we absolutely have to (so far just IE).
784
785 // Add the IE-specific "before deactivate" event, to capture the
786 // selection range before we lose focus. Also intercept Paste
787 // events, so that we can limit pasting to single-line unformatted
788 // text.
789 events += "onbeforedeactivate=\""
790 + "javascript:onFieldSelect();return true;\" "
791 + "onpaste=\"javascript:return onFieldPaste();\" ";
792
793 // create the content-editable span
794 cl.innerHTML =
795 "<span contentEditable=true class='cmdline' id='cmdline' "
796 + events
797 + "style='" + font + "' "
798 + "></span>";
799 }
800 else
801 {
802 // some browsers need some slight tweaks to the positioning
803 // to get everything aligned properly
804 var hacks = "";
805 if (BrowserInfo.safari || BrowserInfo.opera)
806 hacks = "margin: -1px 0 0 -1px;";
807 else if (BrowserInfo.firefox && BrowserInfo.firefox >= 3.05)
808 hacks = "position: relative; left: -1px;";
809
810 // We're using an <input type=text>, so monitor selection changes
811 // directly on the input field. Also, adjust the field width as
812 // we edit it to keep it large enough for the text.
813 events += "onselect=\"javascript:onFieldSelect();\" "
814 + "oninput=\"javascript:adjustCmdlineWidth();"
815 + "return true;\" ";
816
817 // all of the other browsers seem to get the alignment fine with
818 // a regular text field, so use a regular text field
819 cl.innerHTML =
820 "<input type='text' class='cmdline' id='cmdline' length=1024 "
821 + "style='" + hacks + font + "' "
822 + events
823 + ">";
824 }
825
826 // set focus on the new input field - do this in a timeout to give
827 // the browser a chance to process events related to creating the
828 // new objects, to make sure the object exists in the UI before we
829 // try to give it the focus
830 docFocusThread = setTimeout(function()
831 {
832 // if we have an interrupted command line (such as from a timeout
833 // interruption), restore the saved state
834 if (interruptedCommandLine)
835 {
836 // get the field
837 var fld = $("cmdline");
838
839 // restore the editing state
840 setCommandText(fld, interruptedCommandLine.text);
841 setSelRangeInEle(fld, interruptedCommandLine.sel);
842
843 // done with the interrupted editing state
844 interruptedCommandLine = null;
845 }
846
847 // set the default focus
848 $win().setDefaultFocus(null, null);
849
850 // We only open the command line when it's in view, so it must
851 // be in view. Reset the scroll anchor to the new command line
852 // on the assumption that the user has had a chance to view
853 // everything up to this point.
854 scrollAnchor = getObjectRect("cmdline").y - 5;
855 }, 0);
856
857 // set the initial field width
858 adjustCmdlineWidth();
859
860 // add a history item for the active command line
861 cmdLineHistory.push("");
862 }
863
864 /*
865 * Explicitly cancel the command line. This is used to interrupt a command
866 * line in progress, usually due to a timeout. If 'reset' is true, clear
867 * the input line state, so that the next new command line starts out
868 * empty. Otherwise, save the state from the current command line editing
869 * session, so that we can restore it on the next open.
870 */
871 var interruptedCommandLine = null;
872 function cancelCommandLine(reset)
873 {
874 // get the active command field; if there isn't an open command line,
875 // there's nothing we need to do
876 var fld = $("cmdline");
877 if (!fld)
878 return;
879
880 // close the command line, using the interrupted style
881 closeCommandLine(null, null, false, "cmdlineInterrupted");
882
883 // remove the placeholder top history item
884 cmdLineHistory.pop();
885 }
886
887 /*
888 * Close the command line. If 'style' is specified, it's the CSS class
889 * name to use to show the static text of the now-closed command line.
890 */
891 function closeCommandLine(txt, user, reset, style)
892 {
893 // if the style is null, use the default
894 if (!style)
895 style = "cmdlineOld";
896
897 // get the text input field
898 var fld = $("cmdline");
899 var div = null;
900 var height = "";
901 if (fld)
902 {
903 // if we're not resetting, save away the current editing info
904 var s;
905 if (reset)
906 s = null;
907 else {
908 s = {
909 text: getCommandText(fld),
910 sel: getSelRangeInEle(fld),
911 lastSel: lastFldSel
912 };
913 }
914
915 // store the saved command line info
916 interruptedCommandLine = s;
917
918 // get its contents, if the caller didn't specify overriding text
919 if (txt == null)
920 txt = getCommandText(fld);
921
922 // Note the actual height of the input field. This allows us to
923 // set a matching height for the static text span that will replace
924 // the field now that we're closing the editor. An input field
925 // doesn't usually have the exactly same native height as a regular
926 // text span with the same contents, so this explicit setting is
927 // needed to keep the line spacing from visibly changing when we
928 // change the command line from an input field to a <SPAN>.
929 height = "height:" + getObjectRect(fld).height + "px";
930
931 // remove focus from the field
932 fld.blur();
933
934 // forget the last selection
935 lastFldSel = null;
936
937 // the command line division is the field's parent
938 div = fld.parentNode;
939 }
940 else if (cmdLinePending)
941 {
942 // We have a pending command line that we never activated. This
943 // happens when there's unviewed text past the bottom of the
944 // window; we wait to activate the command line until the user
945 // scrolls its location into view. We do have a placeholder
946 // division in this case, though, so we can just plug in the
947 // entered command there - that's where it would ultimately have
948 // gone anyway, it's just that we skip the entire creation and
949 // deletion of the field within the division.
950 div = cmdLinePending;
951
952 // there's no longer a pending command line
953 cmdLinePending = null;
954 }
955 else
956 {
957 // no command line is open or pending - there's nothing to close
958 return;
959 }
960
961 // IE doesn't respect the "white-space: pre" style on inline elements,
962 // so to work around this we change spaces into &nbsp's.
963 var spanTxt = txt.htmlify();
964 if (BrowserInfo.ie)
965 spanTxt = spanTxt.replace(/ /g, '&nbsp;');
966
967 // if a user name was provided add it
968 var userPrefix = "";
969 if (user)
970 userPrefix = "<span class=\"cmdFromUser\">[" + user + "]</span> ";
971
972 // replace the field with the text that was entered
973 var lastCmdLineID = "closedCmdLine" + (cmdLineNum++);
974 div.innerHTML =
975 "<span class=\"" + style + "\" id=\"" + lastCmdLineID
976 + "\" style=\"" + height + "\">"
977 + userPrefix
978 + spanTxt + "</span>";
979
980 // remember the last command line object
981 var lastCmdLine = $(lastCmdLineID);
982
983 // start a new output division
984 outputDiv = null;
985
986 // return the command line text
987 return txt;
988 }
989
990 /*
991 * Set the command line font
992 */
993 function setCommandLineFont()
994 {
995 // get the active input field
996 var fld = $("cmdline");
997
998 // if we have a field, set its font
999 if (fld)
1000 fld.style.font = getStyle(fld.parentNode, "font");
1001 }
1002
1003 /*
1004 * Adjust the command-line width. We call this automatically as the user
1005 * types, to keep the field as least as wide as the text it contains. This
1006 * ensures that we don't scroll the contents of the input field, but rather
1007 * scroll the whole window. Scrolling the input field's contents is
1008 * confusing because we try to make the field fade into the background as
1009 * much as possible: we don't show a border or separate background color.
1010 * We want it to look like an input line in a regular terminal window,
1011 * which doesn't look any different from the surrounding output text.
1012 */
1013 function adjustCmdlineWidth()
1014 {
1015 // give the browser a few moments to digest events, then adjust the width
1016 // of the field so that it's large enough for the field's contents
1017 setTimeout(function() {
1018
1019 // get the field
1020 var fld = $("cmdline");
1021 if (!fld)
1022 return;
1023
1024 // get the "probe" element, for measuring the font size
1025 var probe = $("cmdline_probe.<SPAN>");
1026
1027 // set the probe's font and contents to match the real input's,
1028 // with a little extra space to spare for the cursor at the end
1029 var txt = getCommandText(fld);
1030 probe.innerHTML = (txt.htmlify() + 'MMMM').replace(/ /g, '&nbsp;');
1031
1032 // set the new width
1033 fld.style.width = probe.offsetWidth + "px";
1034
1035 }, 10);
1036 }
1037
1038 // Common keypress/keydown handler.
1039 function cmdlineKey(desc, fld)
1040 {
1041 // Set the scroll anchor to the command line field. Since the user
1042 // is typing into the field, it's safe to assume they've had a chance
1043 // to read everything above this point in the document. (Take off
1044 // a few pixels for a little margin of visual context.)
1045 scrollAnchor = getObjectRect(fld).y - 5;
1046
1047 // Check for a selection change after processing the key through
1048 // the default handling.
1049 setTimeout(onFieldSelect, 0);
1050
1051 // check for a change in the field width
1052 adjustCmdlineWidth();
1053
1054 // see what we have
1055 switch (desc.keyName)
1056 {
1057 case "Up": // up arrow
1058 // recall the previous history item
1059 if (cmdLineHistoryIdx > 0)
1060 {
1061 // if we're at the top of the list, save the current text
1062 if (cmdLineHistoryIdx + 1 == cmdLineHistory.length)
1063 cmdLineHistory[cmdLineHistoryIdx] = getCommandText(fld);
1064
1065 // recall the previous item
1066 setCommandText(fld, cmdLineHistory[--cmdLineHistoryIdx]);
1067 }
1068
1069 // we've fully handled the event
1070 return false;
1071
1072 case "Down": // down arrow
1073 // recall the next history item
1074 if (cmdLineHistoryIdx + 1 < cmdLineHistory.length)
1075 setCommandText(fld, cmdLineHistory[++cmdLineHistoryIdx]);
1076
1077 // we've fully handled the event
1078 return false;
1079
1080 case "PageUp": // Page Up
1081 case "PageDown": // Page Down
1082 // Input fields sometimes capture the page up/down keys for
1083 // cursor navigation. For our single-line inputs, that's
1084 // not desirable; instead, treat it as a document scroll event.
1085
1086 // get the direction
1087 var dir = (desc.keyName == "PageUp" ? -1 : 1);
1088
1089 // get the window height, for the scroll distance
1090 var wrc = getWindowRect();
1091
1092 // scroll by a little less than a page
1093 var dist = wrc.height;
1094 if (dist > 20)
1095 dist -= 20;
1096
1097 // do the scrolling
1098 window.scrollBy(0, dist * dir);
1099
1100 // handled
1101 return false;
1102
1103 case "U+001B": // Escape
1104 // Clear the command line. Do this after finishing with the
1105 // keystroke: in Firefox, at least, Escape seems to be sort of
1106 // a super-Undo that restores the last thing that was in the
1107 // field, so the browser undoes our work here if we do it in-line.
1108 // This seems to happen even with the preventDefault() below, so
1109 // I'm not sure where the value reset is coming from, but it's
1110 // someplace we can't seem to override. Clearing the field in a
1111 // timeout lets us take care of it after the browser has finished
1112 // the un-overridable super-Undo.
1113 setTimeout(function() { setCommandText(fld, ""); }, 0);
1114
1115 // prevent the default handling for Escape - this is a command key
1116 // in many browsers meaning "cancel page load", which can also
1117 // cancel in-progress ajax requests
1118 preventDefault(desc.event);
1119
1120 // handled
1121 return false;
1122
1123 case "U+0055": // 'U'
1124 // check for Ctrl+U
1125 if (desc.ctrlKey)
1126 {
1127 // clear the line
1128 setCommandText(fld, "");
1129
1130 // on IE, block the Ctrl+U underline handling
1131 if (BrowserInfo.ie)
1132 {
1133 preventDefault(desc.event);
1134 return false;
1135 }
1136 }
1137
1138 // it's not Ctrl+U, so we don't handle it here
1139 return true;
1140
1141 case "U+0042": // 'B'
1142 case "U+0049": // 'I'
1143 case "U+004B": // 'K'
1144 // When editing a 'contentEditable' span in IE, IE enables the
1145 // traditional rich-text formatting keys: Ctrl+B for Bold,
1146 // Ctrl+I for italic, Ctrl+U for underline, Ctrl+K for Hyperlink.
1147 // We don't want to allow formatted text, so disable these for IE.
1148 if (BrowserInfo.ie
1149 && desc.ctrlKey
1150 && document.activeElement
1151 && document.activeElement.nodeName == "SPAN"
1152 && document.activeElement.isContentEditable)
1153 {
1154 // in a content-editable span - suppress formatting command keys
1155 preventDefault(desc.event);
1156 return false;
1157 }
1158
1159 // otherwise, apply the default handling
1160 return true;
1161
1162 case "Enter":
1163 handleEnterKey(fld);
1164
1165 // no need for further handling
1166 return false;
1167
1168 default:
1169 // we don't handle anything else, so use the default behavior
1170 return true;
1171 }
1172 }
1173
1174 // handle (or simulate) an enter key
1175 function handleEnterKey()
1176 {
1177 // immediately scroll down by the height of the field, and to the left
1178 // edge
1179 var rc = getObjectRect("cmdline");
1180 var curScroll = getScrollPos();
1181 window.scrollBy(-curScroll.x, rc.height);
1182
1183 // close the current command line
1184 var txt = closeCommandLine(null, null, true);
1185
1186 // If they selected and entered a past history item without changing
1187 // anything, stay at the current position in the history. Otherwise,
1188 // add the new item to the end of the history and reset the index
1189 // to the latest item.
1190 if (cmdLineHistoryIdx + 1 < cmdLineHistory.length
1191 && cmdLineHistory[cmdLineHistoryIdx] == txt)
1192 {
1193 // We've selected and entered a past item without making any
1194 // changes. The temporary last history item we added for the
1195 // new command line was never committed, so delete it.
1196 cmdLineHistory.pop();
1197 }
1198 else if (txt == "")
1199 {
1200 // don't add empty lines to the history
1201 cmdLineHistory.pop();
1202 }
1203 else
1204 {
1205 // We've entered a new item. Save it as the last history item.
1206 // There's already an array item for it, since we added a temporary
1207 // item for the new command line when we opened it - so we just
1208 // need to set the value in the last item.
1209 cmdLineHistory[cmdLineHistory.length-1] = txt;
1210
1211 // trim the history if it's getting too long
1212 if (cmdLineHistory.length > cmdLineHistoryLimit)
1213 cmdLineHistory.shift();
1214 }
1215
1216 // put the history cursor at the end of the list
1217 cmdLineHistoryIdx = cmdLineHistory.length;
1218
1219 // process the command through the registered callback
1220 if (window.onCloseCommandLine)
1221 window.onCloseCommandLine(txt);
1222
1223 // send the text to the server
1224 serverRequest("/webui/inputLine?txt=" + encodeURIComponent(txt)
1225 + "&window=" + pageName,
1226 ServerRequest.Command);
1227 }
1228
1229 // handle a command hyperlink
1230 function gamehref(ev, href, win, ele)
1231 {
1232 // if we have a window path, ask our parent to find the window
1233 if (win)
1234 {
1235 // send it to the given window, if we can find it
1236 if (win = $win(win))
1237 return win.gamehref(ev, href, null, ele);
1238 else
1239 return false;
1240 }
1241
1242 // there's no path, so it's directed to us - put it in our command buffer
1243 var fld = $("cmdline");
1244 if (fld)
1245 {
1246 // set the text in the field
1247 setCommandText(fld, href);
1248
1249 // enter the command
1250 handleEnterKey();
1251
1252 // we've handled the event, so don't bubble it up
1253 return false;
1254 }
1255 else
1256 {
1257 // there's no active command line, so send the click to the main
1258 // window, in case the server wants it as an href event
1259 $win().clickToServer(ev, href, ele);
1260 }
1261
1262 // bubble the event, but prevent the default browser handling
1263 preventDefault(getEvent(ev));
1264 return true;
1265 }
1266