Debian Codegraph @

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

raw symbols SCIP
1 /* Copyright (c) 2010 by Michael J. Roberts. All Rights Reserved. */
2 /*
3 * Main window scripts for TADS 3 Web UI. These scripts are for the
4 * top-level layout window, which usually contains one or more "widget"
5 * windows, such as the main game transcript window and the status line.
6 */
7
8 /* ------------------------------------------------------------------------ */
9 /*
10 * main window initialization
11 */
12 function mainInit()
13 {
14 // the top window is always called "main"
15 pageName = "main";
16
17 // check for the Flash plug-in
18 if (getFlashPlayerVersion())
19 {
20 // Flash is available, so load our SWF object. We don't embed the
21 // object statically, because doing so provokes some browsers to
22 // display a UI prompt about installing Flash every single time the
23 // page is loaded, which is annoying to users who intentionally run
24 // sans Flash. But now that we know Flash is present, we can safely
25 // load our SWF, so dynamically insert the <object> tag for it.
26 $("__TADS_swf_div.<DIV>").innerHTML =
27 "<object id='__TADS_swf' "
28 + "classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' "
29 + "codebase='http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0' "
30 + "width='0' height='0' align='middle' tabindex='-1'>"
31 + "<param name='movie' value='/webuires/TADS.swf'/>"
32 + "<param name='quality' value='high'/>"
33 + "<param name='bgcolor' value='#ffffff'/>"
34 + "<param name='allowScriptAccess' value='always'/>"
35 + "<param name='FlashVars' value='onload=TADS_swf.loaded.fire'/>"
36 + "<embed name='__TADS_swf' src='/webuires/TADS.swf' "
37 + "width='0' height='0' quality='high' bgcolor='#ffffff' "
38 + "allowScriptAccess='always' align='middle' "
39 + "type='application/x-shockwave-flash' "
40 + "pluginspage='http://www.macromedia.com/go/getflashplayer' "
41 + "FlashVars='onload=TADS_swf.loaded.fire'/>"
42 + "</object>";
43 }
44 else
45 {
46 // The Flash plug-in isn't available, so we won't be able to run
47 // our SWF object. Fire our load-completion event to signal that
48 // there's nothing to wait for.
49 TADS_swf.loaded.fire();
50 }
51
52 // initialize the utilities and layout window packages
53 utilInit();
54 layoutInit();
55
56 // initialize the XML request frame
57 initXmlFrame();
58
59 // override some handlers
60 window.onresize = mainResize;
61 window.onGameEvent = mainGameEvent;
62 window.onGameState = mainGameState;
63 window.onUload = mainUnload;
64
65 // Cancel any pending events from past incarnations, in case we just
66 // refreshed the page. Lingering events from past loads refer to old
67 // objects from the previous DOM tree, so they won't work with the new
68 // incarnation of the page.
69 serverRequest("/webui/flushEvents");
70
71 // get the initial state
72 getInitState();
73
74 // cache some images that we might need if we lose our connection
75 cacheImage("/webuires/dlg-corners.gif");
76 cacheImage("/webuires/dlg-title-corners.gif");
77 cacheImage("/webuires/modal-cover.png");
78 cacheImage("/webuires/errorPopupBkg.gif");
79 cacheImage("/webuires/warningPopupBkg.gif");
80 cacheImage("/webuires/modal-cover.png");
81 }
82
83 /* ------------------------------------------------------------------------ */
84 /*
85 * Main game window events and state
86 */
87
88 // are we in an inputEvent() wait?
89 var wantInputEvent = false;
90
91 // event handler
92 function mainGameEvent(req, resp)
93 {
94 // check for title changes
95 if (xmlHasChild(resp, "setTitle"))
96 document.title = xmlChildText(resp, "setTitle");
97
98 // check for preference settings changes
99 if (xmlHasChild(resp, "setPrefs"))
100 xmlToPrefs(xmlChild(resp, "setPrefs")[0]);
101
102 // check for preference dialog invocations
103 if (xmlHasChild(resp, "showPrefsDialog"))
104 showPrefsDialog();
105
106 // check for file dialog invocations
107 if (xmlHasChild(resp, "fileDialog"))
108 showFileDialog(xmlChild(resp, "fileDialog")[0]);
109 else if (xmlHasChild(resp, "uploadFileDialog"))
110 showUploadDialog(xmlChild(resp, "uploadFileDialog")[0]);
111
112 // check for downloadable files
113 if (xmlHasChild(resp, "offerDownload"))
114 {
115 var file = xmlChildText(resp, "offerDownload");
116 addDownloadFile(file);
117 addDownloadFrame(file);
118 }
119 if (xmlHasChild(resp, "cancelDownload"))
120 {
121 var file = xmlChildText(resp, "cancelDownload");
122 removeDownloadFile(file);
123 removeDownloadFrame(file);
124 }
125
126 // check for input dialog invocations
127 if (xmlHasChild(resp, "inputDialog"))
128 showInputDialog(xmlChild(resp, "inputDialog")[0]);
129
130 // check for event input waits and cancellations
131 if (xmlHasChild(resp, "getInputEvent"))
132 wantInputEvent = true;
133 else if (xmlHasChild(resp, "cancelInputEvent"))
134 wantInputEvent = false;
135
136 // check for menu system events
137 if (xmlHasChild(resp, "menusys"))
138 showMenuSys(xmlChild(resp, "menusys")[0]);
139
140 // "inherit" the layout window handling
141 layoutGameEvent(req, resp);
142 }
143
144 // state handler
145 function mainGameState(req, resp)
146 {
147 // check for title settings
148 if (xmlHasChild(resp, "title"))
149 document.title = xmlChildText(resp, "title");
150
151 // check for preference settings
152 if (xmlHasChild(resp, "prefs"))
153 xmlToPrefs(xmlChild(resp, "prefs")[0]);
154
155 // "inherit" the layout window handling
156 layoutGameState(req, resp);
157
158 // check for file dialog invocations
159 if (xmlHasChild(resp, "fileDialog"))
160 showFileDialog(xmlChild(resp, "fileDialog")[0]);
161 else if (xmlHasChild(resp, "uploadFileDialog"))
162 showUploadDialog(xmlChild(resp, "uploadFileDialog")[0]);
163
164 // check for input dialog invocations
165 if (xmlHasChild(resp, "inputDialog"))
166 showInputDialog(xmlChild(resp, "inputDialog")[0]);
167
168 // check for input event waits
169 if (xmlHasChild(resp, "getInputEvent"))
170 wantInputEvent = true;
171
172 // check for downloadable files
173 if (xmlHasChild(resp, "offerDownload"))
174 {
175 var lst = xmlChild(resp, "offerDownload");
176 for (var i = 0 ; i < lst.length ; ++i)
177 addDownloadFile(xmlNodeText(lst[i]));
178 }
179
180 // check for menu system dialogs
181 if (xmlHasChild(resp, "menusys"))
182 showMenuSys(xmlChild(resp, "menusys")[0]);
183
184 // This is the main, top-level window, so once we get the initial
185 // state set up, start the "event thread". This is only conceptually
186 // a thread, since javascript is single-threaded, but it acts roughly
187 // like a thread in that the browser sends the request asynchronously
188 // and "resumes" our processing when the request completes, by
189 // invoking our event callback.
190
191 // Ask for our first event. Do this in a timeout rather than directly,
192 // to allow the browser to process any outstanding events in its own
193 // queue; this avoids a problem that shows up in Mobile Safari and IE9
194 // that seems to be related to the timing of receiving the IFRAME
195 // contents on the initial page setup. A zero timeout is fine; we
196 // don't need a delay per se, we just need to order things so that we
197 // don't generate this request until the browser has finished processing
198 // UI events already in its internal queue.
199 setTimeout(function() {
200 serverRequest(
201 "/webui/getEvent", ServerRequest.Subscription, cbGetEvent);
202 }, 0);
203 }
204
205 // getEvent request callback. This handles a response from the server to
206 // a "get event" request we sent earlier. This allows the server to send
207 // us events: we ask the server for an event via a request, and as soon as
208 // the server has an event available, it replies to the request.
209 function cbGetEvent(req, resp)
210 {
211 // get the target window
212 var w = getEventWin(req, resp);
213
214 // If we got found a window, forward the event. If we didn't find
215 // the window, or it's not loaded yet, drop the event. This should
216 // be okay, since the window will ask for a full status refresh when
217 // it first loads - this will compensate for any missed events that
218 // came in before it loaded.
219 if (w && w.onGameEvent)
220 w.onGameEvent(req, resp);
221
222 // if we're shutting down, skip asking for another event
223 if (xmlHasChild(resp, "shutdown"))
224 {
225 // display the disconnecting dialog
226 showDialog({
227 title: "TADS",
228 id: "shutdown",
229 contents: "The game server has terminated the connection."
230 });
231
232 // done
233 return;
234 }
235
236 // go back for the next request
237 serverRequest("/webui/getEvent",
238 ServerRequest.Subscription, cbGetEvent);
239 }
240
241 // Get the window for a state/event reply
242 function getEventWin(req, resp)
243 {
244 // if there's a window spec, get it; assume it's directed to the
245 // main frame window otherwise
246 if (xmlHasChild(resp, "window"))
247 {
248 // get the window from the path
249 return windowFromAbsPath(xmlChildText(resp, "window"));
250 }
251 else
252 {
253 // no window spec, so use the main window
254 return window;
255 }
256 }
257
258 // get a window from the absolute path
259 function windowFromAbsPath(path)
260 {
261 // turn the path string into a list
262 if (typeof(path) == "string")
263 path = path.split(".");
264
265 // make sure it starts with our page name
266 if (path.shift() != pageName)
267 return null;
268
269 // if it's just the one element, it's the main window
270 if (path.length == 0)
271 return window;
272
273 // resolve the rest as a relative path
274 return windowFromPath(path);
275 }
276
277 /* ------------------------------------------------------------------------ */
278 /*
279 * Key event handler for inputEvent() requests from the server. When the
280 * server program wants to solicit an event from the client, it sends us a
281 * <getInputEvent> status message. We set the global variable
282 * wantInputEvent to true when we receive this message; this tells us that
283 * when we get a keystroke or hyperlink click event that isn't handled in
284 * the UI itself, we should send it back to the server as an input event
285 * message.
286 *
287 * All subwindows should forward their unhandled key events here so that we
288 * can transmit the appropriate events to the server. Only unhandled
289 * events should be sent here; if the event is handled within the client
290 * UI, it doesn't have to be sent to the server.
291 */
292
293 function keyToServer(desc)
294 {
295 // if the server wants an input event, send it
296 if (desc && wantInputEvent)
297 {
298 // translate the key from DOM 3 naming to TADS naming
299 var key = DOM3toTADSKey[desc.keyName] || desc.ch;
300
301 // if we don't have a TADS translation for the key, don't send an
302 // event for this key after all
303 if (!key)
304 return;
305
306 // translate control keys to [ctrl-x] notation
307 var ch = key.charCodeAt(0);
308 if (ch == 10 || ch == 13)
309 ch = '\n';
310 else if (ch < 32)
311 key = "[ctrl-" + String.fromCharCode(ch + 64) + "]";
312
313 // send the event
314 serverRequest("/webui/inputEvent?type=key&param="
315 + encodeURIComponent(key));
316
317 // we're no longer waiting for an input event
318 wantInputEvent = false;
319
320 // consider this key handled - don't do the default browser action
321 preventDefault(desc.event);
322 }
323 }
324
325 /* event map from DOM 3 key names to TADS key names */
326 var DOM3toTADSKey = {
327 "U+001B": "[esc]",
328 "Up": "[up]",
329 "Down": "[down]",
330 "Left": "[left]",
331 "Right": "[right]",
332 "Home": "[home]",
333 "End": "[end]",
334 "U+007F": "[del]",
335 "Insert": "[insert]",
336 "ScrollLock": "[scroll]",
337 "PageUp": "[page up]",
338 "PageDown": "[page down]",
339 "F1": "[f1]",
340 "F2": "[f2]",
341 "F3": "[f3]",
342 "F4": "[f4]",
343 "F5": "[f5]",
344 "F6": "[f6]",
345 "F7": "[f7]",
346 "F8": "[f8]",
347 "F9": "[f9]",
348 "F10": "[f10]",
349 "F11": "[f11]",
350 "F12": "[f12]",
351 "U+0008": "[bksp]"
352 };
353
354 /*
355 * Document-level click handler for inputEvent() requests from the server.
356 * Unhandled hyperlink clicks should be sent here, so we can send them on
357 * to the server as inputEvent() results.
358 */
359 function clickToServer(ev, href,ele)
360 {
361 // if the server wants an input event, send it
362 if (wantInputEvent)
363 {
364 // send the event to the server
365 serverRequest("/webui/inputEvent?type=href&param="
366 + encodeURIComponent(href));
367
368 // we're no longer waiting for an input event
369 wantInputEvent = false;
370 }
371 }
372
373
374 /* ------------------------------------------------------------------------ */
375 /*
376 * resize the main window
377 */
378 function mainResize()
379 {
380 // move the errorPopupDiv to the bottom right, if it's visible
381 if (errorPopupVis)
382 {
383 var rc = getWindowRect();
384 var ediv = $("errorPopupDiv");
385 ediv.style.left = (rc.width - ediv.offsetWidth) + "px";
386 ediv.style.top = (rc.height - ediv.offsetHeight) + "px";
387 }
388 if (downloadFiles.length)
389 {
390 var rc = getWindowRect();
391 var ddiv = $("downloadPopupDiv");
392 ddiv.style.left = (rc.width - ddiv.offsetWidth) + "px";
393 var top = rc.height - ddiv.offsetHeight;
394 if (errorPopupVis)
395 top -= ediv.offsetHeight;
396 ddiv.style.top = top + "px";
397 }
398
399 // reposition any dialogs
400 for (var i = 0 ; i < dialogStack.length ; ++i)
401 {
402 if (!dialogStack[i].manuallyPositioned)
403 positionDialog(dialogStack[i].ele, false);
404 }
405
406 // inherit the layout window handling
407 calcLayout();
408 }
409
410 /* ------------------------------------------------------------------------ */
411 /*
412 * Close the window
413 */
414 function mainUnload()
415 {
416 if (debugLogWin)
417 {
418 debugLogWin.close();
419 debugLogWin = null;
420 }
421 }
422
423
424 /* ------------------------------------------------------------------------ */
425 /*
426 * Error logging. This is used mainly for network connection errors.
427 * Network errors are often due to temporary conditions - network
428 * congestion, router latency, server hiccups. Many times, an XML request
429 * will fail due to a network hiccup, but retrying the same request will
430 * succeed. We therefore don't want to be too strident about network
431 * errors, but at the same time we don't want to completely ignore them.
432 * Our compromise is a small message panel that appears at the bottom
433 * corner of the main window when an error occurs. This alerts the user to
434 * the error, and offers an option to see more details. This doesn't
435 * intrude too much into the UI visually, and doesn't intrude at all
436 * modally, since there's no need to acknowledge or dismiss the popup.
437 */
438
439 // error log
440 var errorLog = [];
441
442 // Is the error popup visible? This is the little button that we show
443 // in the bottom right corner when a new error is available to be viewed.
444 var errorPopupVis = false;
445
446 // Add an error to the error log. 'msg' is the explanatory error message
447 // text, and 'detail' is addition technical detail that might be helpful
448 // for a programmer debugging the error (javascript stack trace, bad XML
449 // text, HTTP result code, etc, as appropriate to the specific error
450 // condition).
451 //
452 // 'id' is an optional object that tells us the status of an error that
453 // might be possible to resolve automatically with retries. First, this
454 // serves to tie together a series of errors that results from a series
455 // of retries for the same operation. For example, for XML requests,
456 // the 'id' is the request descriptor object. Tying the retry errors
457 // to the original error is useful because (a) the error log can show
458 // the relationship, so that the user doesn't think five separate things
459 // went wrong when they were really five repeated failed attempts at
460 // the same thing, and (b) if a retry eventually succeeds, the error log
461 // can show that the earlier attempts were eventually resolved and thus
462 // can be ignored. Second, the 'id' object has two fields that tell us
463 // whether the operation is in fact being retried:
464 //
465 // id.failed - true if the operation has permanently failed and will not
466 // be retried, false if the operation is being retried
467 // id.succeeded - true if the operation has succeeded on a retry
468 //
469 // If 'id' is null, we'll supply a default.
470 function logError(msg, detail, id)
471 {
472 // for testing purposes, it's sometimes useful to pop this up
473 // in the separate debug log window, but we don't want to do
474 // this in release builds
475 // debugLog("Error: " + msg + "<br>" + detail + "<br><br>");
476
477 // if there's no 'id' object, supply a default
478 if (!id)
479 id = new LogErrorID();
480
481 // add the message at the start of the error list
482 errorLog.unshift({msg: msg, detail: detail, id: id, viewed: false,
483 timestamp: new Date()});
484
485 // if the error frame isn't visible, show it
486 if (!errorPopupVis)
487 {
488 // mark it as visible, but make it completely transparent
489 errorPopupVis = true;
490 var d = $("errorPopupDiv");
491 setAlpha(d, 0);
492
493 // do an explicit size recalc to position the popup
494 mainResize();
495
496 // start fading it in
497 startFade(d, 1, 700);
498 }
499
500 // If all unviewed errors are being retried automatically, set the
501 // error popup background to orange. Otherwise set it to red.
502 var allRetry = true;
503 for (var i = 0 ; i < errorLog.length ; ++i)
504 {
505 // get this error
506 var e = errorLog[i];
507
508 // if it's unviewed, and it's marked as failed, we have an error
509 // that won't be retried
510 if (!e.viewed && e.id.failed)
511 {
512 allRetry = false;
513 break;
514 }
515 }
516
517 // set the appropriate background color in the popup
518 $("errorPopupDiv.[content]").style.background =
519 (allRetry ? "#ff8000" : "#ff0000");
520 $("errorPopupDiv.[icon]").style.backgroundImage =
521 (allRetry ? "url(/webuires/warningPopupBkg.gif)"
522 : "url(/webuires/errorPopupBkg.gif)");
523 }
524
525 function LogErrorID()
526 {
527 this.succeeded = false;
528 this.failed = true;
529 }
530
531 function openErrorDetail(i)
532 {
533 $("errorDetailDiv-" + i).style.display = "block";
534 $("openErrorDetailLink-" + i).style.display = "none";
535 }
536
537 // Un-log a network error. Call this when a request that failed with an
538 // error subsequently succeeds on a retry.
539 function unlogError(id)
540 {
541 // find the error in the error log
542 var openCnt = 0;
543 for (var i = 0 ; i < errorLog.length ; ++i)
544 {
545 // get this error
546 var e = errorLog[i];
547
548 // if this error isn't resolved and hasn't been viewed,
549 // count it as open
550 if (!e.id.succeeded && !e.viewed)
551 ++openCnt;
552 }
553
554 // if there are now no open errors, the error popup is no longer needed
555 if (openCnt == 0)
556 hideErrorPopup();
557 }
558
559 // display the error log
560 var errorLogViewCount = 0;
561 function showErrorLog()
562 {
563 // build the error list
564 var lst = [];
565 for (var i = 0 ; i < errorLog.length ; ++i)
566 {
567 var msg = errorLog[i].msg;
568 var id = errorLog[i].id;
569 var detail = errorLog[i].detail;
570 var ts = errorLog[i].timestamp;
571 if (detail)
572 {
573 msg +=
574 "<div class=\"errorFooter\">"
575 + ts.toLocaleTimeString()
576 + (errorLogViewCount == 0 ? "" :
577 errorLog[i].viewed ? " | Previously viewed" : " | New")
578 + (id.succeeded
579 ? " | Error was resolved automatically" :
580 !id.failed
581 ? " | Request is being retried automatically" :
582 "")
583 + "<span id=\"openErrorDetailLink-" + i + "\"> | "
584 + "<a href=\"#\" onclick=\"javascript:openErrorDetail("
585 + i + ");return false;\">View Details</a></span>"
586 + "</div>"
587 + "<div class=\"errorDetail\" id=\"errorDetailDiv-"
588 + i + "\">" + detail
589 + "</div>";
590 }
591 lst.push(msg);
592 }
593
594 // count this view of the error log
595 errorLogViewCount++;
596
597 // mark all messages as viewed
598 for (var i = 0 ; i < errorLog.length ; ++i)
599 errorLog[i].viewed = true;
600
601 // If there's a single error, show it as the whole dialog contents.
602 // Otherwise show a scrolling list of the errors.
603 var cont;
604 if (errorLog.length == 0)
605 {
606 cont = "This window shows any errors encountered in the browser "
607 + "since you loaded the page, including network problems "
608 + "and javascript errors. So far, no errors have occurred "
609 + "since you loaded or refreshed the page.";
610 }
611 else if (errorLog.length == 1)
612 {
613 // one error - just show the error
614 cont = lst[0];
615 }
616 else
617 {
618 // Multiple errors - show a scrolling list
619 cont = "The game encountered the following errors (the most "
620 + "recent is listed first):"
621 + "<div class='errorListDiv'>"
622 + lst.join("<hr>")
623 + "</div>";
624 }
625
626 // hide the error popup
627 hideErrorPopup();
628
629 // show the dialog
630 showDialog({ title: "Error Log", id: 'errorLog', contents: cont });
631 }
632
633 // hide the error log popup
634 function hideErrorPopup()
635 {
636 // move the popup division off-screen
637 errorPopupVis = false;
638 var d = $("errorPopupDiv");
639 startFade(d, -1, 250, function() {
640 d.style.top = "-1000px";
641 mainResize();
642 });
643 }
644
645 /* ------------------------------------------------------------------------ */
646 /*
647 * Download popup. This appears at the lower right corner of the window,
648 * just above the error popup if there is one. This shows the list of
649 * outstanding downloadable files sent by the game server.
650 */
651
652 // list of downloadable files
653 var downloadFiles = [];
654
655 // add a downloadable file
656 function addDownloadFile(fname)
657 {
658 // add the file to the list
659 downloadFiles.push(fname);
660
661 // adjust the height
662 var d = $("downloadPopupDiv");
663
664 // rebuild the download list
665 rebuildDownloadDiv();
666
667 // if this is the first file, show the popup
668 if (downloadFiles.length == 1)
669 {
670 // make it completely transparent, and start fading it in
671 setAlpha(d, 0);
672 startFade(d, 1, 700);
673 }
674
675 // do an explicit size recalc to position and resize the popup
676 mainResize();
677 }
678
679 // remove a downloadable file
680 function removeDownloadFile(fname)
681 {
682 // find the file
683 var idx = downloadFiles.indexOf(fname);
684 if (idx >= 0)
685 {
686 // remove it from the list
687 downloadFiles.splice(idx, 1);
688
689 // rebuild the download list
690 rebuildDownloadDiv();
691
692 // if the list is empty, hide the popup, otherwise resize it
693 var cnt = downloadFiles.length;
694 var d = $("downloadPopupDiv");
695 if (cnt == 0)
696 {
697 // empty - fade it out
698 startFade(d, -1, 250, function() {
699 d.style.top = "-1000px";
700 });
701 }
702 else
703 {
704 // do an explicit resize to position and size the popup
705 mainResize();
706 }
707 }
708 }
709
710 // rebuild the download file division contents
711 function rebuildDownloadDiv()
712 {
713 var s = ["<b>Download Files</b>"];
714 downloadFiles.forEach(function(fname) {
715 var shortName = fname.replace(/^.*\//, "").htmlify();
716 var href = encodeURI(fname);
717 s.push("<div class='dlfile'>&bull; "
718 + "<a href=\"#\" onclick=\"javascript:addDownloadFrame('"
719 + href + "');return false;\">" + shortName + "</a>"
720 + " | <a href=\"#\" onclick=\"javascript:cancelDownloadFile('"
721 + href + "');return false;\">Cancel</a>"
722 + "</div>");
723 });
724
725 $("downloadPopupDiv.[content]").innerHTML = s.join("");
726 }
727
728 function cancelDownloadFile(fname)
729 {
730 serverRequest(fname + "?cancel");
731 }
732
733 /* ------------------------------------------------------------------------ */
734 /*
735 * Debugging messages. During development, it's often useful to instrument
736 * the code with message displays; this provides a place to put them that's
737 * less intrusive than 'alert()'. Messages written here are displayed in a
738 * separate popup window that we open the first time this is called.
739 */
740 var debugLogWin = null, debugLogLoaded = new AbsEvent();
741 function debugLog(msg)
742 {
743 // if the log window isn't open yet, or it's been closed, open it
744 if (!debugLogWin || debugLogWin.closed)
745 {
746 debugLogLoaded.isDone = false;
747 debugLogWin = window.open(
748 "/webuires/debuglog.htm", "tadsDebugLog",
749 "location=no, resizable=yes, scrollbars=yes, status=yes, "
750 + "width=550, height=400");
751 }
752
753 // when the log window is loaded, add the message
754 debugLogLoaded.whenDone(function() {
755 debugLogWin.debugLogPrint(msg);
756 });
757 }
758
759 /* ------------------------------------------------------------------------ */
760 /*
761 * Show an HTML dialog. This shows the dialog as a foreground DIV within
762 * the main window, not as an 'alert()' or new window popup.
763 *
764 * 'id' is an optional identification string for identifying the dialog
765 * within the program. This is useful if you want to be sure that the
766 * active dialog is a particular dialog, rather than a nested dialog it
767 * opens. We don't make any of this here; it's purely for the dialog's own
768 * use in other scripts.
769 *
770 * 'params' is an object with the properties listed below. All properties
771 * are optional except the ones marked required.
772 *
773 * title: a string to display in the dialog's title bar. Required.
774 *
775 * contents: a string giving the HTML contents of the dialog, OR a DOM
776 * element whose contents will be duplicated to populate the dialog.
777 * Required.
778 *
779 * buttons: an array of button objects. Each object has these members:
780 *. {
781 *. name: string with the display name of the button
782 *. isDefault: true if pressing the Return key activates this button
783 *. isCancel: true if pressing the Escape key activates this button
784 *. onclick: function to call when clicking the button; if not set,
785 *. clicking the button simply dismisses the dialog
786 *. key: the key that can be used to select this button; applies only
787 *. when focus isn't in an input control; you can specify either an
788 *. ordinary character (using upper-case for letters), or a key
789 *. name (e.g., 'U+0008' for backspace)
790 *. }
791 *
792 * If you omit the name of the button, the button won't be displayed, but
793 * will still be available as a keystroke handler.
794 *
795 * init: a function to call to initialize the dialog. This is called after
796 * the new dialog has been set up, but before it's been displayed. The
797 * dialog's root element is passed as the argument - init(dialogElement).
798 *
799 * initFocus: the control that should initially receive focus. If this
800 * isn't set, we'll search for a focusable control (INPUT, SELECT, <A>) and
801 * set focus there.
802 *
803 * initAfterVisible: a function to call to initialize after the dialog has
804 * been displayed and focus has been set. As with init(), this is called
805 * with the dialog's root element as the argument.
806 *
807 * dismiss: a function to call when dismissing the dialog. This will be
808 * called as dismiss(dialogElement, button), where 'button' is the button
809 * object from the 'buttons' list corresponding to the button the user
810 * clicked to close the dialog. Return true to allow the dialog to close,
811 * false to prevent it from closing. You can use a false return to perform
812 * validation.
813 *
814 * dimensions: an object { width:, height: } with style strings to use for
815 * the dimensions of the dialog. If not provided, we'll let the browser
816 * set dimensions based on the content size.
817 *
818 * fillWidth: true if the dialog contents should be stretched to fill the
819 * whole width of the containing dialog. By default, we'll show the
820 * contents at their natural width, centered in the dialog container. In
821 * some cases we instead want the contents to scale according to the
822 * container, though, such as when the dialog contains an iframe. Set this
823 * to true to stretch the contents to the container width.
824 */
825 var dialogStack = [];
826 var fontSelectorOptions = null;
827 function showDialog(params)
828 {
829 // get the contents, retrieving HTML source if it's a DOM object
830 var contents = params.contents;
831 if (typeof(contents) == "object")
832 contents = contents.innerHTML;
833
834 // assume all we'll need to do is show the dialog
835 var go = function() { showDialogMain(params); };
836
837 // check for $[fontpicker] macros
838 if (contents.match(/\$\[fontpicker([^\]]*)\]/))
839 {
840 // we have one or more font pickers, so we need to build the
841 // list of installed fonts before we can show the dialog
842 var go1 = go;
843 go = function() { TADS_swf.waitForFontList(go1); };
844 }
845
846 // execute the dialog display procedure we've built up
847 go();
848 }
849
850 // main dialog builder
851 function showDialogMain(params)
852 {
853 // figure the z-index for the new dialog
854 var z = 10500 + dialogStack.length*10;
855 var dlgID = "dialogDiv" + (dialogStack.length + 1);
856
857 // create the global descriptor for the dialog
858 var dlgDesc = {
859 title: params.title,
860 dd: dlgID,
861 manuallyPositioned: false,
862 dismiss: params.dismiss,
863 initFocus: params.initFocus,
864 id: params.id
865 };
866
867 // push it onto the active dialog stack
868 dialogStack.push(dlgDesc);
869
870 // create the background cover for the new dialog
871 var bkg = dlgDesc.bkg = document.createElement("div");
872 bkg.className = "dialogCoverDiv";
873 bkg.style.zIndex = z;
874 document.body.appendChild(bkg);
875
876 // create the canvas
877 var canvas = dlgDesc.canvas = document.createElement("div");
878 canvas.className = "dialogCanvas";
879 canvas.style.zIndex = "" + (z + 1);
880 document.body.appendChild(canvas);
881
882 // create the new dialog division
883 var dlg = dlgDesc.ele = document.createElement("div");
884 dlg.id = dlgID;
885 dlg.innerHTML = $("dialogTemplate").innerHTML;
886 dlg.className = "dialogDiv";
887 dlg.style.zIndex = "" + (z + 1);
888 dlg.onkeydown = function(ev) { return $kd(ev, dlgKey, dlgDesc); };
889 dlg.onkeypress = function(ev) { return $kp(ev, dlgKey, dlgDesc); };
890 canvas.appendChild(dlg);
891
892 // if dimensions were given, set them in the dialog element
893 if (params.dimensions && params.dimensions.height)
894 dlg.style.height = params.dimensions.height;
895 if (params.dimensions && params.dimensions.width)
896 dlg.style.width = params.dimensions.width;
897
898 // get a couple of elements for further manipulation
899 var ttl = $(dlg, "[dialogTitle]");
900 var cont = $(dlg, "[dialogContent]");
901
902 // if desired, stretch the content division to fill the dialog
903 if (params.fillWidth)
904 cont.style.width = "100%";
905
906 // fill in the title
907 ttl.innerHTML = params.title;
908
909 // set default buttons if none were given
910 var buttons = params.buttons;
911 if (!buttons)
912 buttons = [{name: "OK", isDefault: true, isCancel: true}];
913
914 // save the buttons in the dialog descriptor
915 dlgDesc.buttons = buttons || [];
916
917 // if it's a pre-defined division, fetch its contents
918 var contents = params.contents;
919 if (typeof(contents) == "object")
920 contents = contents.innerHTML;
921
922 // expand $[fontpicker] macros
923 var fontSizeOptions =
924 [8, 9, 10, 11, 12, 14, 16, 18, 20,
925 22, 24, 26, 28, 30, 32, 36, 48, 72]
926 .map(function(x) {
927 return "<option value=\"" + x + "pt\">" + x + "pt</option>";
928 }).join("");
929 fontSizeOptions = "<option value=\"*\">(Default)</option>"
930 + fontSizeOptions;
931 var fontPickers = [];
932 var preFontCont = contents;
933 contents = contents.replace(
934 /\$\[fontpicker([^\]]*)\]/gm, function(match, attrs) {
935
936 // parse the attributes
937 var pattrs = parseTagAttrs(attrs);
938
939 // add this to the font select pending list
940 fontPickers.push({ attrs: attrs, pattrs: pattrs });
941
942 // Build the font picker: a combo for the font name, another
943 // for the font size, and a color picker for the text color.
944 // Set the font picker select list to initially empty, since
945 // we might have to wait for the font lister thread to finish.
946 return createCombo(pattrs.id, 40, "")
947 + createCombo(pattrs.id + "Size", 5, fontSizeOptions);
948 });
949
950 // note if we actually needed any font pickers - we do if we found
951 // any $[fontpicker] macros to expand
952 var needFonts = (contents != preFontCont);
953
954 // expand $[colorpicker] macros
955 var colorPickers = [];
956 contents = contents.replace(
957 /\$\[colorpicker([^\]]*)\]/gm, function(match, attrs) {
958 var pattrs = parseTagAttrs(attrs);
959 var btnID = dlgID + "." + pattrs.id;
960 colorPickers[pattrs.id] = pattrs;
961 return "<a href=\"#\" " + attrs + " class=\"colorbutton\" "
962 + "onclick=\"javascript:openColorPicker(event, '" + btnID
963 + "', true);return false;\" "
964 + "onkeydown=\"javascript:return $kd(event, colorbuttonKey, ['"
965 + btnID + "',true]);\" "
966 + "onkeypress=\"javascript:return $kp(event, colorbuttonKey, ['"
967 + btnID + "',true]);\">"
968 + "<span></span></a>";
969 });
970
971 // expand $[checkbox]
972 contents = contents.replace(
973 /\$\[checkbox([^\]]*)\]/gm, function(match, attrs) {
974 var pattrs = parseTagAttrs(attrs);
975 return "<label><nobr><input type=\"checkbox\" " + attrs
976 + "><label for=\"" + pattrs.id + "\"> " + pattrs.label
977 + "</label></nobr></label>";
978 });
979
980 // add the buttons to the contents
981 if (buttons.length)
982 {
983 contents += "<div class=\"dialogButtons\">";
984 for (var i = 0 ; i < buttons.length ; ++i)
985 {
986 var b = buttons[i];
987 if (b.name)
988 {
989 contents += "<span style='padding: 0 1em 0 1em;'>"
990 + "<a href='#' "
991 + "onclick='javscript:clickDialogButton("
992 + i + ");return false;'>" + b.name
993 + "</a></span>";
994 }
995 }
996 contents += "</div>";
997 }
998
999 // fill in the contents
1000 cont.innerHTML =
1001 "<div class=\""
1002 + (params.fillWidth ? "dialogZeroMarginDiv" : "dialogMarginDiv")
1003 + "\">" + contents + "</div>";
1004
1005 // call the initializer function
1006 if (params.init)
1007 params.init(dlg, params);
1008
1009 // initialize the contents and adjust the size immediately
1010 positionDialog(dlg, true);
1011
1012 // just in case the browser needs a moment to finish processing the
1013 // innerHTML changes, resize it again in a few moments
1014 setTimeout(function() {
1015 // set the size again
1016 positionDialog(dlg, true);
1017
1018 // set it opaque
1019 setAlpha(canvas, 100);
1020
1021 // set the initial focus
1022 initDialogFocus();
1023
1024 // run the after-visible function
1025 if (params.initAfterVisible)
1026 setTimeout(
1027 function() { params.initAfterVisible(dlg, params); },
1028 10);
1029 }, 1);
1030
1031 // If we needed any font pickers, load the system's font list, if
1032 // we haven't already. When that's done, populate the font pickers.
1033 if (needFonts)
1034 {
1035 // get the cached font list
1036 var fonts = TADS_swf.fontList;
1037
1038 // build the font select list
1039 fontSelectorOptions = fonts.map(function(ele) {
1040 ele = ele.htmlify();
1041 return "<option value=\"" + ele + "\">" + ele + "</option>"
1042 }).join("");
1043
1044 // add "Default" as the first item
1045 fontSelectorOptions = "<option value=\"*\">(Default)</option>"
1046 + fontSelectorOptions;
1047
1048 // populate each font picker
1049 for (var i = 0 ; i < fontPickers.length ; ++i)
1050 {
1051 // get this font picker's field, and from that get the <select>
1052 var f = fontPickers[i];
1053 var fld = $(dlg, f.pattrs.id);
1054 var sel = comboGetElement(fld, "SELECT");
1055
1056 // If we have outerHTML, replace the entire SELECT with a new
1057 // one. This is for IE's sake; IE doesn't rebuild the option
1058 // list if we only replace the SELECT's innerHTML. If we don't
1059 // have outerHTML, replace the innerHTML and hope for the best;
1060 // this seems to work properly on other browsers tested.
1061 //
1062 // (Why bother with the inner/outerHTML at all? Why not just
1063 // rebuild the option list via the Select/Option object API?
1064 // That's arguably the "cleaner" way to do this, but in my
1065 // testing it's *vastly* faster to let the browser rebuild
1066 // the control from HTML. I think the best argument in favor
1067 // of the API approach is that it should perform better than
1068 // going through all that string building and parsing, but in
1069 // this case, at least, it turns out to be just the opposite.
1070 if (sel.outerHTML)
1071 {
1072 // outerHTML available - replace the whole <SELECT>
1073 sel.outerHTML = sel.outerHTML.replace(
1074 /<\/select>/im, fontSelectorOptions + "</SELECT>")
1075 .replace(/size=("[^"]+"|'[^']'|[^'"][^\s>]*)/im,
1076 "size=\"20\"");
1077 }
1078 else
1079 {
1080 // no outerHTML - replace just the option list
1081 sel.innerHTML = fontSelectorOptions;
1082 sel.size = "20";
1083 }
1084 }
1085 }
1086 }
1087
1088 /*
1089 * Initialize focus in the currently active dialog
1090 */
1091 function initDialogFocus()
1092 {
1093 // ignore this if there's no dialog
1094 if (dialogStack.length == 0)
1095 return;
1096
1097 // get the dialog description
1098 var desc = dialogStack.top();
1099 var dlg = desc.ele;
1100
1101 // get the initial focus control specified in the parameters
1102 var f;
1103 if (desc.initFocus)
1104 f = $(dlg, desc.initFocus);
1105
1106 // if that wasn't specified, search for the first focusable object
1107 // within the dialog
1108 if (!f)
1109 {
1110 f = breadthSearch(dlg, function(ele) {
1111 return (ele.focus
1112 && (ele.nodeName == "INPUT"
1113 || ele.nodeName == "TEXTAREA"
1114 || ele.nodeName == "SELECT"
1115 || ele.nodeName == "A"));
1116 });
1117 }
1118
1119 // Move focus to the control, if we found one, or to the dialog
1120 // itself if not. If the dialog doesn't accept focus, just
1121 // remove focus from wherever it is now.
1122 if (f)
1123 {
1124 // move focus to the control
1125 f.focus();
1126
1127 // select its initial text if it's an INPUT or TEXTAREA
1128 if (f.nodeName == "INPUT" || f.nodeName == "TEXTAREA")
1129 setSelRangeInEle(f);
1130 }
1131 else if (dlg.focus)
1132 dlg.focus();
1133 else if (document.activeElement)
1134 document.activeElement.blur();
1135 }
1136
1137 /*
1138 * Reposition a dialog for the current window size
1139 */
1140 function positionDialog(dlg, init)
1141 {
1142 // get the dialog and window areas
1143 var drc = getObjectRect(dlg);
1144 var wrc = getWindowRect();
1145
1146 // center the dialog in the window
1147 var x = (wrc.width - drc.width)/2, y = (wrc.height - drc.height)/2;
1148
1149 // if this is a sub-dialog, show it relative to the parent dialog
1150 // instead of centered
1151 if (init && dialogStack.length > 1)
1152 {
1153 // get the preceding dialog position
1154 var par = dialogStack[dialogStack.length - 2];
1155 var prc = getObjectRect(par.ele);
1156
1157 // move the new dialog below and right of the parent
1158 x = prc.x + 25;
1159 y = prc.y + 25;
1160
1161 // mark this dialog and the parent as manually positioned
1162 par.manuallyPositioned = true;
1163 dialogStack.top().manuallyPositioned = true;
1164 }
1165
1166 // set the position
1167 dlg.style.left = (x > 0 ? x : 0) + "px";
1168 dlg.style.top = (y > 0 ? y : 0) + "px";
1169 }
1170
1171 /*
1172 * handle mouse tracking in a dialog title bar
1173 */
1174 var dlgTrackInfo = null;
1175 function dlgTitleDown(ev)
1176 {
1177 // if there's no dialog, ignore it
1178 if (dialogStack.length == 0)
1179 return;
1180
1181 // get the dialog and its bounding box
1182 var dlg = dialogStack.top().ele;
1183 var rc = getObjectRect(dlg);
1184
1185 // get the event
1186 ev = getEvent(ev);
1187
1188 // note the start offset of the tracking
1189 dlgTrackInfo = { x: ev.clientX - rc.x, y: ev.clientY - rc.y, dlg: dlg };
1190
1191 // track the mouse throughout the document
1192 addEventHandler(document, "mousemove", dlgTitleMove);
1193 addEventHandler(document, "mouseup", dlgTitleUp);
1194 addEventHandler(document, "selectstart", dlgTitleSelect);
1195
1196 // Show the dialog's "move cover" division. This is a transparent
1197 // division that covers the whole dialog at a higher z-index than
1198 // any of its contents. The point is to block out any IFRAME within
1199 // the dialog for the duration of the move, so that events are directed
1200 // to our document rather than to the IFRAME's document. If we didn't
1201 // have this cover, mouse events would disappear into the IFRAME any
1202 // time the mouse moves quickly enough to stray into the IFRAME before
1203 // it generates a mousemove event within our title bar. Cross-domain
1204 // scripting limits prevent those events from bubbling up to our
1205 // document handlers if the IFRAME is showing an outside page (such
1206 // as from the storage server). The dialog cover blocks the IFRAME
1207 // and keeps all the events within our document.
1208 var cover = $(dlg, "[dialogMoveCover]");
1209 cover.style.display = "block";
1210 cover.style.width = rc.width + "px";
1211 cover.style.height = rc.height + "px";
1212
1213 // skip the default handling
1214 return false;
1215 }
1216
1217 // prevent text selection while tracking the mouse in IE
1218 function dlgTitleSelect(ev)
1219 {
1220 return false;
1221 }
1222
1223 function dlgTitleMove(ev)
1224 {
1225 // if we're not tracking a dialog, skip it
1226 if (!dlgTrackInfo)
1227 return;
1228
1229 // get the event
1230 ev = getEvent(ev);
1231
1232 // move the dialog
1233 var dlg = dlgTrackInfo.dlg;
1234 dlg.style.left = (ev.clientX - dlgTrackInfo.x) + "px";
1235 dlg.style.top = (ev.clientY - dlgTrackInfo.y) + "px";
1236
1237 // mark the dialog as manually moved
1238 dialogStack.top().manuallyPositioned = true;
1239
1240 // suppress the default handling
1241 preventDefault(ev);
1242 cancelBubble(ev);
1243 return false;
1244 }
1245
1246 function dlgTitleUp(ev)
1247 {
1248 // if we're not tracking a dialog, skip it
1249 if (!dlgTrackInfo)
1250 return;
1251
1252 // remove the event handlers that we installed just for the move
1253 removeEventHandler(document, "mousemove", dlgTitleMove);
1254 removeEventHandler(document, "mouseup", dlgTitleUp);
1255 removeEventHandler(document, "selectstart", dlgTitleSelect);
1256
1257 // remove the dialog cover division
1258 $(dlgTrackInfo.dlg, "[dialogMoveCover]").style.display = "none";
1259
1260 // done tracking
1261 dlgTrackInfo = null;
1262
1263 // suppress the default handling
1264 preventDefault(ev);
1265 cancelBubble(ev);
1266 return false;
1267 }
1268
1269 /*
1270 * Handle a keystroke in a color button in the main dialog. We'll let
1271 * Enter keystrokes get handled in the <A>, but we'll block these from
1272 * bubbling up to the dialog. This lets us use the keyboard interface to
1273 * select a color button without dismissing the dialog.
1274 */
1275 function colorbuttonKey(desc, ctx)
1276 {
1277 var ele = ctx[0];
1278 var hasDefault = ctx[1];
1279 if (desc.keyName == "Enter" || desc.keyName == "U+0020")
1280 {
1281 openColorPicker(desc.event, ele, hasDefault);
1282 cancelBubble(desc.event);
1283 preventDefault(desc.event);
1284 return false;
1285 }
1286 return true;
1287 }
1288
1289 /*
1290 * Open a color picker
1291 */
1292 var colorPickerBuilt = false;
1293 var colorPickerTarget = null;
1294 function openColorPicker(ev, ele, hasDefault)
1295 {
1296 // get the button and the color picker popup
1297 ele = $(ele);
1298 var cp = $("colorPicker");
1299
1300 // if it's already open, close it
1301 if (cp.style.display == "block")
1302 {
1303 closePopup(cp);
1304 return;
1305 }
1306
1307 // build out the buttons if we haven't already done so
1308 if (!colorPickerBuilt)
1309 {
1310 var colors = ["ff8080", "ffff80", "80ff80", "ff80ff",
1311 "80ffff", "0080ff", "ff80c0", "ff80ff",
1312 "ff0000", "ffff00", "80ff00", "00ff40",
1313 "00ffff", "0080c0", "8080c0", "ff00ff",
1314 "804040", "ff8040", "00ff00", "008080",
1315 "004080", "8080ff", "800040", "ff0080",
1316 "800000", "ff8000", "008000", "008040",
1317 "0000ff", "0000A0", "800080", "8000ff",
1318 "400000", "804000", "004000", "004040",
1319 "000080", "000040", "400040", "400080",
1320 "000000", "808000", "808040", "808080",
1321 "408080", "C0C0C0", "400000", "ffffff"];
1322
1323 // set up the template for each button
1324 var keyTpl = "\"javascript:return @FUNC@"
1325 + "(event,colorBtnKey,['#@COLOR@',this]);\"";
1326 var btnTpl = "<a class=\"colorPickerButton\" href=\"#\" "
1327 + "id=\"colorPickerButton#@I@\" "
1328 + "style=\"background-color:#@COLOR@;\" "
1329 + "onclick=\"javascript:return colorBtnClick("
1330 + "event,'#@COLOR@',this);\" "
1331 + " onkeydown=" + keyTpl.replace(/@FUNC@/m, "$kd")
1332 + " onkeypress=" + keyTpl.replace(/@FUNC@/m, "$kp")
1333 + "></a>";
1334
1335 // build the button array - eight buttons per line
1336 for (var i = 0, s = [] ; i < colors.length ; )
1337 {
1338 // build this line
1339 for (var j = 0, sl = [] ; j < 8 ; ++j, ++i)
1340 {
1341 // build this button and add it to the line list
1342 sl.push(btnTpl
1343 .replace(/@COLOR@/gm, colors[i])
1344 .replace(/@I@/gm, i));
1345 }
1346
1347 // combine the line into a <nobr> and add it to the master list
1348 s.push("<nobr>" + sl.join("") + "</nobr><br>");
1349 }
1350
1351 // add the custom color entry field
1352 s.push("<div><nobr>Custom (rrggbb): <input type=\"text\" size=\"6\" "
1353 + "id=\"colorPickerCustom\" "
1354 + "onkeydown=\"javascript:return $kd(event,colorPickFldKey);\" "
1355 + "onkeypress=\"javascript:return $kp(event,colorPickFldKey);\">"
1356 + "</nobr></div>");
1357
1358 // add the Use Default button
1359 s.push("<div id=\"colorPickerDefault\" class=\"colorPickerDefault\">"
1360 + "<div class=\"off\" "
1361 + "onmouseover=\"javascript:"
1362 + "this.style.borderColor='#ffffff';\" "
1363 + "onmouseout=\"javascript:"
1364 + "this.style.borderColor='transparent';\" "
1365 + "style=\"border: 1px solid transparent;\">"
1366 + "<a href=\"#\" onclick=\"javascript:"
1367 + "return colorDefaultClick(event,this);\">"
1368 + "<img src=\"/webuires/ckbox8pt-off.gif\">Use default color</a>"
1369 + "</div></div>");
1370
1371 // combine the element list into a string and plug it into the
1372 // popup division
1373 cp.innerHTML = s.join("");
1374
1375 // we've now built the color picker
1376 colorPickerBuilt = true;
1377 }
1378
1379 // remember the opener button as the value destination on close
1380 colorPickerTarget = ele;
1381
1382 // move the popup under the opener buton
1383 var rc = getObjectRect(ele);
1384 cp.style.left = rc.x + "px";
1385 cp.style.top = (rc.y + rc.height) + "px";
1386 cp.style.display = "block";
1387 openPopup(ev, cp, null, ele, ele);
1388
1389 // Force the browser to recalculate the layout after digesting its
1390 // internal event queue. IE for one has problems figuring containing
1391 // box sizes on the first pass, but gets it right if we explicitly
1392 // resize the box (even setting it to its current size) later.
1393 setTimeout(function() {
1394 cp.style.width = getObjectRect(cp).width + "px";
1395 }, 1);
1396
1397 // get the current color
1398 var curColor = canonicalizeColor(getStyle(ele, "background-color"));
1399
1400 // set the custom field to the current color
1401 var customFld = $("colorPickerCustom");
1402 customFld.value = curColor.substr(1);
1403
1404 // if there's a button showing the current selected color, focus it
1405 var sel = breadthSearch(cp, function(ele) {
1406 return (ele.nodeName == "A"
1407 && ele.className == "colorPickerButton"
1408 && ele.style.backgroundColor == curColor);
1409 });
1410
1411 // set up the Default button
1412 var dflt = $("colorPicker.colorPickerDefault");
1413 if (hasDefault)
1414 {
1415 dflt.style.display = "block";
1416 checkColorPickerDefault(ele.useDefaultColor);
1417 }
1418 else
1419 dflt.style.display = "none";
1420
1421 // if we have a selection, set focus there; otherwise set focus on
1422 // the custom field
1423 if (sel)
1424 sel.focus();
1425 else
1426 {
1427 customFld.focus();
1428 setSelRangeInEle(customFld);
1429 }
1430 }
1431
1432 /*
1433 * handle a key in the color picker popup background
1434 */
1435 function colorPopupKey(desc)
1436 {
1437 switch (desc.keyName)
1438 {
1439 case "Up":
1440 case "Down":
1441 case "Left":
1442 case "Right":
1443 // if I have focus directly (i.e., it's not in a child),
1444 // move focus to the first button on any arrow key
1445 if (document.activeElement == $("colorPicker"))
1446 $("colorPicker.<A>").focus();
1447 break;
1448 }
1449
1450 // skip default actions on all keys
1451 return false;
1452 }
1453
1454 /*
1455 * Click on a color picker opener button
1456 */
1457 function colorBtnClick(ev, color)
1458 {
1459 // select the color, and de-select "Use Default"
1460 colorPickerApply(color, false);
1461
1462 // close the popup
1463 closePopup();
1464
1465 // don't process the event further
1466 return false;
1467 }
1468
1469 /*
1470 * apply a change to a color picker button
1471 */
1472 function colorPickerApply(color, useDefault)
1473 {
1474 // set the color of the color element
1475 setColorButton(colorPickerTarget, color, useDefault);
1476
1477 // generate an onchange event
1478 sendEvent(colorPickerTarget, createEvent("Event", "change"));
1479 }
1480
1481 /*
1482 * click on the Use Default button in a color picker
1483 */
1484 function colorDefaultClick(ev, ele)
1485 {
1486 // set Use Default and close the popop
1487 colorPickerApply(null, true);
1488 closePopup();
1489 return false;
1490 }
1491
1492 function checkColorPickerDefault(checked)
1493 {
1494 var span = $("colorPicker.colorPickerDefault.<DIV>");
1495 var img = $("colorPicker.colorPickerDefault.<IMG>");
1496 if (checked)
1497 {
1498 span.className = "on";
1499 img.src = "/webuires/ckbox8pt-on.gif";
1500 }
1501 else
1502 {
1503 span.className = "off";
1504 img.src = "/webuires/ckbox8pt-off.gif";
1505 }
1506 }
1507
1508 /*
1509 * handle a key in a color picker button
1510 */
1511 function colorBtnKey(desc, ctx)
1512 {
1513 var color = ctx[0], ele = ctx[1];
1514 var b = null;
1515 var nextButton = function(b, dir)
1516 {
1517 var idx = parseInt(b.id.substr(18));
1518 return $("colorPicker.colorPickerButton#" + (idx + dir));
1519 };
1520 switch (desc.keyName)
1521 {
1522 case "Up":
1523 for (var i = 0, b = ele ; i < 8 && b ; ++i)
1524 b = nextButton(b, -1);
1525 break;
1526
1527 case "Down":
1528 for (var i = 0, b = ele ; i < 8 && b ; ++i)
1529 b = nextButton(b, 1);
1530 break;
1531
1532 case "Left":
1533 b = nextButton(ele, -1);
1534 break;
1535
1536 case "Right":
1537 b = nextButton(ele, 1);
1538 break;
1539
1540 case "U+0020":
1541 case "Enter":
1542 // select the color, and de-select "Use Default"
1543 colorPickerApply(color, false);
1544
1545 // close the popup and swallow the event
1546 closePopup();
1547 cancelBubble(desc.event);
1548 preventDefault(desc.event);
1549 break;
1550
1551 case "U+0009":
1552 // we're on a button, so tab into the field
1553 var fld = $("colorPickerCustom");
1554 fld.focus();
1555 setSelRangeInEle(fld);
1556
1557 // bypass all the normal handling
1558 cancelBubble(desc.event);
1559 preventDefault(desc.event);
1560 return false;
1561 }
1562
1563 // move the focus to the new target, if we found one
1564 if (b)
1565 {
1566 // move focus to the new button, and select its color
1567 b.focus();
1568 $("colorPickerCustom").value = b.style.backgroundColor.substr(1);
1569
1570 // uncheck "Use default"
1571 checkColorPickerDefault(false);
1572 }
1573
1574 // don't bother bubbling the event
1575 return false;
1576 }
1577
1578 /*
1579 * Keystroke in color picker custom color field
1580 */
1581 function colorPickFldKey(desc)
1582 {
1583 switch (desc.keyName)
1584 {
1585 case "Enter":
1586 var v = $("colorPickerCustom").value;
1587 if (v.charAt(0) != '#')
1588 v = '#' + v;
1589 if (v.match(/^#[0-9a-f]{6}$/i))
1590 {
1591 // valid - select the color and de-select "Use Default"
1592 colorPickerApply(v, false);
1593
1594 // close the popup
1595 closePopup();
1596 }
1597 else
1598 {
1599 cancelBubble(desc.event);
1600 alert("Please use the HTML-style hexadecimal RRGGBB format. "
1601 + "For example, for bright red, enter FF0000.");
1602 }
1603
1604 // bypass all the normal handling
1605 cancelBubble(desc.event);
1606 preventDefault(desc.event);
1607 return false;
1608
1609 case "U+0009":
1610 // if the custom color corresponds to a button, tab to the button
1611 var fld = $("colorPickerCustom");
1612 var val = parseColor(fld.value);
1613 var b = breadthSearch($("colorPicker"), function(ele) {
1614 return (ele.nodeName == "A"
1615 && ele.className == "colorPickerButton"
1616 && parseColor(ele.style.backgroundColor) == val);
1617 });
1618 if (b)
1619 {
1620 b.focus();
1621 fld.value = b.style.backgroundColor.substr(1);
1622 }
1623
1624 // bypass all the normal handling
1625 cancelBubble(desc.event);
1626 preventDefault(desc.event);
1627 return false;
1628
1629 default:
1630 // do the default processing for other keys
1631 return true;
1632 }
1633 }
1634
1635 /*
1636 * Click a dialog button
1637 */
1638 function clickDialogButton(n)
1639 {
1640 // get the button info
1641 var b = dialogStack.top().buttons[n];
1642
1643 // call the button function, or just dismiss the dialog if there isn't one
1644 if (b.onclick)
1645 b.onclick();
1646 else
1647 dismissDialog(b);
1648 }
1649
1650 /*
1651 * Dismiss the dialog
1652 */
1653 function dismissDialog(btn)
1654 {
1655 // get the dialog info
1656 var dinfo = dialogStack.top();
1657 var dlg = dinfo.ele;
1658 var bkg = dinfo.bkg;
1659
1660 // if there's not button, it's the close box in the title bar - create
1661 // a pseudo button structure for it
1662 if (!btn)
1663 btn = { name: "(Close Box)", isCancel: true };
1664
1665 // call the dismiss callback, if present
1666 if (dinfo.dismiss && !dinfo.dismiss(dlg, btn))
1667 return;
1668
1669 // remove the dialog from the stack
1670 dialogStack.pop();
1671
1672 // remove focus from any active dialog element
1673 if (document.activeElement)
1674 document.activeElement.blur();
1675
1676 // remove them from the document
1677 document.body.removeChild(dinfo.canvas);
1678 document.body.removeChild(bkg);
1679
1680 // move focus to the default input field in the document
1681 setDefaultFocus();
1682 }
1683
1684 /*
1685 * Dismiss a dialog by ID. If the given dialog is open, we'll cancel it
1686 * and any active child dialogs.
1687 */
1688 function dismissDialogById(id, btn)
1689 {
1690 // scan to see if this dialog is open in the first place
1691 for (var i = 0 ; i < dialogStack.length ; ++i)
1692 {
1693 if (dialogStack[i].id == id)
1694 {
1695 // this is the one - dismiss all nested child dialogs
1696 while (dialogStack.length > i)
1697 dismissDialog(btn);
1698
1699 // no need to look any further
1700 break;
1701 }
1702 }
1703 }
1704
1705 /*
1706 * Set the default focus. If a dialog is active, set focus to the dialog.
1707 * Otherwise set the focus to the default input field in the default child
1708 * window.
1709 */
1710 function setDefaultFocus(desc, fromWin)
1711 {
1712 // if the event is directed to a focus-keeping control, leave focus
1713 // where it is
1714 if (evtKeepsFocus(desc))
1715 return;
1716
1717 // if a dialog is active, set focus there; otherwise refer this to
1718 // the default focusable child window
1719 if (dialogStack.length)
1720 initDialogFocus();
1721 else
1722 setDefaultFocusChild(desc, fromWin);
1723
1724 // If the original event target isn't a control that reads keystrokes,
1725 // buffer the keystroke for the next time we want to read input. This
1726 // ensures that we won't drop keystrokes between command input field
1727 // activations.
1728 bufferKey(desc);
1729 }
1730
1731 // Type-ahead buffer. When we receive keystrokes at the document level,
1732 // and focus isn't in a control that reads keystrokes, we'll buffer the
1733 // keys for future use when a focus-taking control is activated.
1734 //
1735 // The idea is that the IF user interface is "conversational": the UI
1736 // interaction consists primarily of alternating prompts and user
1737 // keyboard inputs. Users become accustomed to this and will anticipate
1738 // that a new command line (or other input reader) will be forthcoming
1739 // shortly after each input is completed, so they'll sometimes start
1740 // typing even before the new command line is visually activated. In
1741 // traditional terminal interfaces, these in-between keystrokes are
1742 // nearly always buffered. Our key buffering scheme here is designed to
1743 // simulate that behavior.
1744 var keybuf = [];
1745 function bufferKey(desc)
1746 {
1747 // don't buffer keystrokes if the server is waiting for an input
1748 // event - we'll instead send the key to the server (later)
1749 if (wantInputEvent)
1750 return;
1751
1752 // if there's no descriptor, there's nothing to save
1753 if (!desc)
1754 return;
1755
1756 // if the key has already been buffered, don't buffer it again
1757 if (desc.keyBufferedInMain)
1758 return;
1759
1760 // discard CRs - IE9 sends CR LF for a newline, but we only want the LF
1761 if (desc.keyCode == 13)
1762 return;
1763
1764 // note that the key has been buffered
1765 desc.keyBufferedInMain = true;
1766
1767 // If the buffer's full, drop the oldest key. The limit is arbitrary;
1768 // the point isn't to conserve memory or anything like that, but simply
1769 // to limit the UI weirdness that can happen if we buffer too many
1770 // keystrokes. The problem is that if there's an extended period where
1771 // the UI is buffering keystrokes rather than reading them, then when we
1772 // do finally get around to activating an input control, the UI can seem
1773 // to be possessed by demons as the huge buffer plays back. Limiting
1774 // the buffer size avoids this - if the buffer's small enough, playback
1775 // will be virtually instantaneous, so no demons. There's really not
1776 // much of a tradeoff here, either, because most users will naturally
1777 // stop typing ahead anyway if the UI is unresponsive for any extended
1778 // period.
1779 if (keybuf.length >= 16)
1780 keybuf.shift();
1781
1782 // make a copy of the key event for buffering, but remove the event
1783 // object, as it might not be valid after the handler returns
1784 var d = desc.copy(false);
1785 d.event = { };
1786
1787 // buffer the event copy
1788 keybuf.push(d);
1789 }
1790
1791
1792 /*
1793 * If the main body should get focus at any point, and gets a keystroke,
1794 * send focus back to the default focus element. This is mostly for the
1795 * sake of dialog focus: we try to keep focus within the dialog by handling
1796 * keyboard events in the dialog itself, but there are odd edge cases where
1797 * key events bypass the dialog handlers and go to the browser's default
1798 * handler, which can set focus into the main body. This catch-all ensures
1799 * that if focus is outside the dialog while the dialog is active, any
1800 * keystrokes will trigger refocusing.
1801 */
1802 function mainBodyKey(desc)
1803 {
1804 // if focus is in the main document body, move it back to the default
1805 // location (usually the command line, but sometimes a dialog object)
1806 if (isFieldKey(desc) && document.activeElement == document.body)
1807 setDefaultFocus(desc, window);
1808
1809 // handle a generic document key
1810 genericDocKey(desc);
1811
1812 // bubble the event
1813 return true;
1814 }
1815
1816 /*
1817 * Handle a key within one of our popup DIVs
1818 */
1819 function popupDivKey(desc)
1820 {
1821 // move focus back to the default location
1822 if (isFieldKey(desc))
1823 setDefaultFocus(desc, window);
1824
1825 // bubble the event
1826 return true;
1827 }
1828
1829 /*
1830 * Handle a key in a dialog
1831 */
1832 function dlgKey(desc, dlg)
1833 {
1834 // Check for explicit shortcut keys defined in the button list - these
1835 // override the default handling. Shortcut keys apply only if the
1836 // current focus element doesn't use the keystroke directly (e.g., if
1837 // focus is in a text field, regular characters go to the field as
1838 // text editing entries.)
1839 var idx, ch = desc.ch ? desc.ch.toUpperCase() : "";
1840 if (!eleKeepsFocus(document.activeElement, desc)
1841 && (idx = dlg.buttons.indexWhich(function(b) {
1842 return b.key && (b.key == ch || b.key == desc.keyName);
1843 })) >= 0)
1844 {
1845 // click this button
1846 clickDialogButton(idx);
1847
1848 // don't process the event any further
1849 cancelBubble(desc.event);
1850 preventDefault(desc.event);
1851 return false;
1852 }
1853
1854 // check the key
1855 switch (desc.keyName)
1856 {
1857 case "Enter":
1858 // ignore this if the focus is in a button or link
1859 var e = document.activeElement;
1860 if ((e.nodeName == "INPUT" && e.type == "submit")
1861 || e.nodeName == "A")
1862 {
1863 // cancel the bubble, but let the default action occur
1864 cancelBubble(desc.event);
1865 return true;
1866 }
1867
1868 // look for a default button
1869 for (var i = 0 ; i < dlg.buttons.length ; ++i)
1870 {
1871 // if this is the default button, click it
1872 if (dlg.buttons[i].isDefault)
1873 {
1874 // click the button
1875 clickDialogButton(i);
1876 break;
1877 }
1878 }
1879
1880 // do no further processing on this key
1881 cancelBubble(desc.event);
1882 preventDefault(desc.event);
1883 return false;
1884
1885 case "U+001B":
1886 // look for a cancel button
1887 for (var i = 0 ; i < dlg.buttons.length ; ++i)
1888 {
1889 // if this is the cancel button, click it
1890 if (dlg.buttons[i].isCancel)
1891 {
1892 // click the cancel button
1893 clickDialogButton(i);
1894 break;
1895 }
1896 }
1897
1898 // do no further processing on this key
1899 cancelBubble(desc.event);
1900 preventDefault(desc.event);
1901 return false;
1902
1903 case "U+0009":
1904 // check immediately after the browser processes the key to see
1905 // if focus has left the dialog, and move it back if so
1906 setTimeout(function() {
1907
1908 // get the current focus and the active dialog
1909 var f = document.activeElement;
1910
1911 // walk up the parent list to see if f is within the dialog
1912 for ( ; f && f != dlg.ele ; f = f.parentNode) ;
1913
1914 // if not, move focus back to the dialog
1915 if (dlg.ele && !f)
1916 dlg.ele.focus();
1917
1918 }, 0);
1919
1920 // allow the default processing to proceed
1921 return true;
1922
1923 default:
1924 // do the normal thing for other keys
1925 return true;
1926 }
1927 }
1928
1929 /* ------------------------------------------------------------------------ */
1930 /*
1931 * Support functions for the TADS.swf Flash object. This is an invisible
1932 * Flash object that we use for certain functionality that we can't get
1933 * directly from the standard browser/javascript APIs. We use this for
1934 * programmatic access only; it doesn't have any visual or UI presence.
1935 *
1936 * Flash is ubiquitous, but it's not universal: we can't count on it being
1937 * available everywhere. Our Flash object is invisible, so there's nothing
1938 * visually missing when Flash isn't available, but we obviously won't have
1939 * access to the API extensions we use it for. We thus have to be careful
1940 * to recover gracefully when the Flash object isn't present: we can use
1941 * defaults, omit the desired functionality, or find some other approach to
1942 * get similar functionality (e.g., proprietary browser features).
1943 *
1944 * We use the Flash object for the following features:
1945 *
1946 * - Sound playback. Flash provides a good set of audio tools, including
1947 * concurrent playback of multiple sounds, support for common audio
1948 * formats, event notifications, volume control, and fades.
1949 *
1950 * - Font enumeration. Flash can give us a list of the fonts installed on
1951 * the system.
1952 */
1953 var TADS_swf = {
1954
1955 // Event coordinator for TADS.swf load completion. The swf object calls
1956 // loaded.fire() from its constructor via the Flash external interface
1957 // (the Flash mechanism that allows Flash scripts to call Javascript on
1958 // the embedding page). This is specified via the "onload" parameter to
1959 // the Flash object loader in the <object> and <embed> tags that embed the
1960 // TADS.swf object, so be sure to specify the "onload" in those tags.
1961 loaded: new AbsEvent(),
1962
1963 // cached font list
1964 fontList: null,
1965
1966 // Wait for the font list to load, then proceed with the callback.
1967 // If the font list is already loaded, this simply invokes the callback
1968 // immediately. If the font list isn't loaded, we'll populate it.
1969 //
1970 // The reason that we have to structure this as a wait-for routine
1971 // with a callback is that we rely on a Flash object to enumerate
1972 // installed fonts, and Flash objects can load asynchronously. We
1973 // can't just assume that our Flash object is ready; we have to await
1974 // a go-ahead signal that it generates when it finished loading.
1975 // The wait-for structure lets us ensure that the Flash object is
1976 // ready before we try to invoke it.
1977 waitForFontList: function(doneFunc)
1978 {
1979 // First, we have to make sure we've loaded the Flash object.
1980 // Flash objects can be loaded asynchronously, so we have to
1981 // await the ready event from Flash before we can proceed.
1982 TADS_swf.loaded.whenDone(function() {
1983
1984 // if we haven't already done so, build the font list
1985 if (!TADS_swf.fontList)
1986 {
1987 // Build the candidate font list. First try the TADS.swf
1988 // embedded Flash object. Flash isn't everywhere (especially
1989 // on mobile devices), so if we don't find it, fall back on
1990 // our canned list of candidate fonts.
1991 var fonts;
1992 try
1993 {
1994 // get the flash object
1995 var ie = navigator.userAgent.indexOf("Microsoft") != -1;
1996 var mobj = (ie ? window["__TADS_swf"] :
1997 document["__TADS_swf"]);
1998
1999 // ask the Flash object for the list of installed fonts
2000 var sfonts = mobj.getFonts();
2001
2002 // Filter the list to keep only the first font of
2003 // each family. Style variations (bold, italic, etc)
2004 // are represented internally on most systems as whole
2005 // separate font objects, but for UI purposes we only
2006 // want to show one list entry per font family.
2007 // Keep only the font names in the final list.
2008 fonts = [];
2009 for (var i = 0 ; i < sfonts.length ; ++i)
2010 {
2011 // if this is a new name, add it to the list
2012 if (sfonts[i].fontStyle == "regular")
2013 fonts.push(sfonts[i].fontName);
2014 }
2015 }
2016 catch (e)
2017 {
2018 // An error occurred; we'll assume that the problem is
2019 // that Flash isn't available. Default to a canned list
2020 // of common fonts. We'll check each entry in a moment
2021 // to see if it's actually installed, so the final list
2022 // will only include fonts that are locally available.
2023 // Of course, it won't necessarily include *all* of the
2024 // available fonts, since we obviously can't include all
2025 // possible fonts in our prefab list. This list is only
2026 // meant to capture the basic set of fonts that most
2027 // operating systems include in their base installs.
2028 // Note that this list is actually a union of common
2029 // fonts from various operating systems, so it's unlikely
2030 // that all of them will be installed on any one machine.
2031 fonts = [
2032 "Arial",
2033 "Arial Black",
2034 "Book Antiqua",
2035 "Charcoal",
2036 "Comic Sans MS",
2037 "Courier",
2038 "Courier New",
2039 "Gadget",
2040 "Geneva",
2041 "Georgia",
2042 "Helvetica",
2043 "Impact",
2044 "Lucida Console",
2045 "Lucida Grande",
2046 "Lucida Sans Unicode",
2047 "Monaco",
2048 "MS Sans Serif",
2049 "MS Serif",
2050 "New York",
2051 "Palatino",
2052 "Palatino Linotype",
2053 "Symbol",
2054 "Tahoma",
2055 "Times",
2056 "Times New Roman",
2057 "Trebuchet MS",
2058 "Verdana",
2059 "Webdings",
2060 "Wingdings",
2061 "Zapf Chancery",
2062 "ZapfChancery",
2063 "Zapf Dingbats"
2064 ];
2065 }
2066
2067 // sort the font list by name (ignoring case)
2068 fonts.sort(function(a, b) {
2069 return a.toLowerCase().localeCompare(b.toLowerCase());
2070 });
2071
2072 // save the list
2073 TADS_swf.fontList = fonts;
2074 }
2075
2076 // the font list is now ready - fire the callback
2077 doneFunc();
2078 });
2079 }
2080 };
2081
2082 /* ------------------------------------------------------------------------ */
2083 /*
2084 * Preferences dialog
2085 */
2086 function showPrefsDialog()
2087 {
2088 showDialog({
2089 id: 'prefs',
2090 title: "Customize Display",
2091 contents: $("prefsDialog"),
2092 buttons: [
2093 { name: "OK", isDefault: true, save: true },
2094 { name: "Cancel", isCancel: true }
2095 ],
2096 init: initPrefsDialog,
2097 dismiss: onClosePrefsDialog
2098 });
2099 }
2100
2101 // List of preference profiles. This is a table of preference objects,
2102 // keyed by profile ID.
2103 var prefProfiles = { };
2104
2105 // Currently selected profile, by ID. Start with a default profile
2106 // that doesn't exist, which will trigger automatic profile creation
2107 // when needed.
2108 var curPrefProfile = 0;
2109
2110 // Next profile ID. This is a high water mark (plus one) of all of the
2111 // profiles we've seen since loading; when we create a new profile, we'll
2112 // assign it this ID and increment this value.
2113 var nextPrefProfile = 1;
2114
2115
2116 // Mapping between dialog elements and preference settings. Each key is
2117 // the ID of a dialog element; the corresponding value explains how to
2118 // map between the dialog element and the style setting.
2119 //
2120 // type: specifies the control type:
2121 //
2122 // "color" specifies a color picker control. The value is in the
2123 // picker's style.backgroundColor property.
2124 //
2125 // "font" specifies a font <select> list.
2126 //
2127 // The default is an input control. For text inputs and selects,
2128 // the value is in the element's "value" property; for checkboxes,
2129 // it's in the "checked" property.
2130 //
2131 // checkbox: a list ["off", "on"] giving the style values that correspond
2132 // to the checkbox states. Applies only to checkbox controls.
2133 //
2134 // selector: the style selector where the setting is stored.
2135 // We ignore case, but otherwise the selector must match the literal
2136 // text in the CSS source. We don't attempt to parse the selectors
2137 // or do any partial matching - we simply look for the identical
2138 // selector text in the style sheet rule list.
2139 //
2140 // Multiple selectors can be specified with commas. We'll look for
2141 // each listed selector separately and set each one to the same list
2142 // of values.
2143 //
2144 // style: the CSS property name for this setting. The style names
2145 // are given in the Javascript naming convention - use 'fontFamily'
2146 // instead of 'font-family', for example.
2147
2148 // parent: ID of the parent item for defaulting. A null value in the
2149 // preference set inherits the given parent value in the set. If
2150 // there's no parent, a null value inherits the corresponding value
2151 // in the game's list of default preference values.
2152 //
2153 var prefsMapper = {
2154 mainFont: {
2155 selector: "body",
2156 style: "fontFamily",
2157 type: "font"
2158 },
2159 mainFontSize: {
2160 selector: "body",
2161 style: "fontSize",
2162 type: "fontsize"
2163 },
2164 mainColor: {
2165 selector: "body",
2166 style: "color",
2167 type: "color"
2168 },
2169 mainBkg: {
2170 selector: "body",
2171 style: "backgroundColor",
2172 type: "color"
2173 },
2174
2175 mainLinkColor: {
2176 selector: "a:link",
2177 style: "color",
2178 type: "color"
2179 },
2180 mainLinkHover: {
2181 selector: "a:hover, a.plain:hover",
2182 style: "color",
2183 type: "color"
2184 },
2185 mainLinkActive: {
2186 selector: "a:active, a:focus, a.plain:active, a.plain:focus",
2187 style: "color",
2188 type: "color"
2189 },
2190
2191 cmdFont: {
2192 selector: ".cmdline, .cmdlineOld",
2193 style: "fontFamily",
2194 type: "font",
2195 parent: "mainFont"
2196 },
2197 cmdFontSize: {
2198 selector: ".cmdline, .cmdlineOld",
2199 style: "fontSize",
2200 type: "fontsize",
2201 parent: "mainFontSize"
2202 },
2203 cmdColor: {
2204 selector: ".cmdline, .cmdlineOld",
2205 style: "color",
2206 type: "color",
2207 parent: "mainColor"
2208 },
2209 cmdBold: {
2210 selector: ".cmdline, .cmdlineOld",
2211 style: "fontWeight",
2212 checkbox: ["normal", "bold"]
2213 },
2214 cmdItalic: {
2215 selector: ".cmdline, .cmdlineOld",
2216 style: "fontStyle",
2217 checkbox: ["normal", "italic"]
2218 },
2219
2220 statusFont: {
2221 selector: "body.statusline",
2222 style: "fontFamily",
2223 type: "font",
2224 parent: "mainFont"
2225 },
2226 statusFontSize: {
2227 selector: "body.statusline",
2228 style: "fontSize",
2229 type: "fontsize",
2230 parent: "mainFontSize"
2231 },
2232 statusColor: {
2233 selector: "body.statusline",
2234 style: "color",
2235 type: "color"
2236 },
2237 statusBkg: {
2238 selector: "body.statusline",
2239 style: "backgroundColor",
2240 type: "color"
2241 },
2242
2243 statusLinkColor: {
2244 selector: "body.statusline a:link",
2245 style: "color",
2246 type: "color"
2247 },
2248 statusLinkHover: {
2249 selector: "body.statusline a:hover, body.statusline a.plain:hover",
2250 style: "color",
2251 type: "color"
2252 },
2253 statusLinkActive: {
2254 selector: "body.statusline a:active,"
2255 + "body.statusline a:focus,"
2256 + "body.statusline a.plain:active,"
2257 + "body.statusline a.plain:focus",
2258 style: "color",
2259 type: "color"
2260 },
2261
2262 serifFont: {
2263 selector: ".serifFont",
2264 style: "fontFamily",
2265 type: "font"
2266 },
2267 serifFontSize: {
2268 selector: ".serifFont",
2269 style: "fontSize",
2270 type: "fontsize",
2271 parent: "mainFontSize"
2272 },
2273
2274 sansFont: {
2275 selector: ".sansFont",
2276 style: "fontFamily",
2277 type: "font"
2278 },
2279 sansFontSize: {
2280 selector: ".sansFont",
2281 style: "fontSize",
2282 type: "fontsize",
2283 parent: "mainFontSize"
2284 },
2285
2286 scriptFont: {
2287 selector: ".scriptFont",
2288 style: "fontFamily",
2289 type: "font"
2290 },
2291 scriptFontSize: {
2292 selector: ".scriptFont",
2293 style: "fontSize",
2294 type: "fontsize",
2295 parent: "mainFontSize"
2296 },
2297
2298 ttFont: {
2299 selector: ".ttFont,tt",
2300 style: "fontFamily",
2301 type: "font"
2302 },
2303 ttFontSize: {
2304 selector: ".ttFont",
2305 style: "fontSize",
2306 type: "fontsize",
2307 parent: "mainFontSize"
2308 }
2309 };
2310
2311 // create a default profile, if required
2312 function initDefProfile()
2313 {
2314 // if there's no current profile, create one
2315 if (!(curPrefProfile in prefProfiles))
2316 {
2317 /* set up an empty profile */
2318 var pro = { profileName: "Default" };
2319 prefsMapper.forEach(function(m, id) { pro[id] = null; });
2320
2321 // add it to the table
2322 curPrefProfile = nextPrefProfile++;
2323 prefProfiles[curPrefProfile] = pro;
2324 }
2325 }
2326
2327 // initialize the preferences dialog on open
2328 function initPrefsDialog(dlg)
2329 {
2330 // initialize the default profile, if necessary
2331 initDefProfile();
2332
2333 // Make a copy of the current preference set. The dialog operates
2334 // on its own copy, so that we don't modify the official copy until
2335 // we save the dialog settings.
2336 dlgProfiles = { };
2337 prefProfiles.forEach(function(pro, id) {
2338 dlgProfiles[id] = pro.copy(false);
2339 });
2340
2341 // set the current profile
2342 dlgCurProfile = curPrefProfile;
2343
2344 // get a list of the profile names, to sort for the <select> list
2345 var proNames = [];
2346 dlgProfiles.forEach(function(pro, id) {
2347 var name = pro.profileName || "Untitled";
2348 proNames.push({ id: id, name: name, sortName: name.toLowerCase() });
2349 });
2350
2351 // sort it by name
2352 proNames.sort(function(a, b) {
2353 return a.sortName.localeCompare(b.sortName);
2354 });
2355
2356 // populate the profile list with the profile names
2357 var sel = $(dlg, "curProfile");
2358 var idx = 0;
2359 proNames.forEach(function(pro) {
2360 var o = new Option(pro.name, pro.id);
2361 try { sel.add(o); } catch (e) { sel.add(o, null); }
2362 });
2363
2364 // select the current item
2365 setSelectByValue(sel, dlgCurProfile);
2366
2367 // set the preferences settings in the dialog
2368 prefsToDlg(dlg, dlgProfiles[dlgCurProfile], true);
2369
2370 // set up onchange event handlers for all controls
2371 breadthSearch(dlg, function(ele) {
2372
2373 // if this is a control with a value, set an onchange handler
2374 if (prefsMapper[ele.id])
2375 ele.onchange = function(ev) { onPrefItemChange(ev, dlg, ele); };
2376
2377 // continue the traversal
2378 return false;
2379 });
2380 }
2381
2382 // dialog copy of the profiles
2383 var dlgProfiles = null;
2384 var dlgCurProfile = null;
2385
2386 // translate profile descriptions from XML sent by the server to our
2387 // in-memory settings list
2388 function xmlToPrefs(prefs)
2389 {
2390 // replace the profile table with the new one
2391 var newPrefs = { };
2392
2393 // run through the list of <profile> children
2394 if (xmlHasChild(prefs, "profile"))
2395 {
2396 var pros = prefs.getElementsByTagName("profile");
2397 for (var i = 0 ; i < pros.length ; ++i)
2398 {
2399 // create a new empty profile, and add it to the master list
2400 // under the given ID
2401 var pro = pros[i];
2402 var tab = { };
2403 var pid = xmlChildText(pro, "id");
2404 newPrefs[pid] = tab;
2405
2406 // if this is a new high-water mark, note it
2407 var pidn = parseInt(pid);
2408 if (pidn && pidn >= nextPrefProfile)
2409 nextPrefProfile = pidn + 1;
2410
2411 // read the <item> elements
2412 var items = pro.getElementsByTagName("item");
2413 for (var j = 0 ; items && j < items.length ; ++j)
2414 {
2415 // retrieve the item ID and value
2416 var item = items[j];
2417 var id = xmlChildText(item, "id");
2418 var val = xmlChildText(item, "value");
2419
2420 // if it's an empty string value, use null
2421 if (val == "")
2422 val = null;
2423
2424 // set the item
2425 tab[id] = val;
2426 }
2427
2428 // if this entry doesn't have a name, give it a default
2429 if (!("profileName" in tab))
2430 tab.profileName = "Untitled";
2431 }
2432 }
2433
2434 // set the current profile ID
2435 var newCur = null;
2436 if (xmlHasChild(prefs, "currentProfile"))
2437 newCur = xmlChildText(prefs, "currentProfile");
2438
2439 // if we have any profiles, and the current profile is defined,
2440 // commit the new settings; otherwise ignore them
2441 if (newPrefs.propCount() > 0 && newCur && newCur in newPrefs)
2442 {
2443 // replace the memory profile set with the newly loaded set
2444 prefProfiles = newPrefs;
2445 curPrefProfile = newCur;
2446
2447 // update the display
2448 prefsToCSS();
2449 }
2450 }
2451
2452 // load a preference set into the live CSS
2453 function prefsToCSS(prefs, win)
2454 {
2455 // create a default profile, if necessary
2456 initDefProfile();
2457
2458 // if the preference set wasn't specified, use the current setting
2459 if (!prefs)
2460 prefs = prefProfiles[curPrefProfile];
2461
2462 // if no window was specified, apply to myself and all children
2463 if (!win)
2464 win = window;
2465
2466 // Build a table of styles to set. Each entry is keyed by the
2467 // selector, converted to all upper-case for matching; each value
2468 // is a list of [property, value] pairs for the selector.
2469 var tab = { };
2470 prefsMapper.forEach(function(m, id)
2471 {
2472 // get the selector
2473 var sels = m.selector.toUpperCase();
2474
2475 // break up the list of selectors in case there are multiples
2476 sels.split(",").forEach(function(sel)
2477 {
2478 // get the table entry for the selector, or add a new one if
2479 // it's not already there
2480 sel = sel.trim();
2481 var e;
2482 if (sel in tab)
2483 e = tab[sel];
2484 else
2485 tab[sel] = e = [];
2486
2487 // add this style and its computed value to the list
2488 e.push([m.style, getPrefVal(prefs, id)]);
2489 });
2490 });
2491
2492 // apply the styles to this window and its children
2493 win.applyCSS(tab);
2494
2495 // recalc the window layout
2496 calcLayout();
2497 }
2498
2499 // load a preference set into the preferences dialog
2500 function prefsToDlg(dlg, prefs, init)
2501 {
2502 // visit all controls in the dialog
2503 breadthSearch(dlg, function(ele)
2504 {
2505 // if this control is in the mapper, set its value
2506 if (ele.id && prefsMapper[ele.id])
2507 prefToControl(ele, prefs, init);
2508
2509 // continue the tree traversal
2510 return false;
2511 });
2512 }
2513
2514 // Set the display value of a control in the preferences dialog based
2515 // on the current value
2516 function prefToControl(ele, prefs, init)
2517 {
2518 // get the element ID and preferences mapper for the item
2519 var id = ele.id, m = prefsMapper[id];
2520
2521 // get the value from the current preference set or defaults
2522 var val = prefs[id];
2523 var defVal = getPrefVal(prefs, id);
2524 if (val == undefined)
2525 val = null;
2526
2527 // note if it's a default, and if so, apply the default
2528 var isDef = (val == null);
2529 if (isDef)
2530 val = defVal;
2531
2532 // set the element's value from 'prefs'
2533 switch (m.type)
2534 {
2535 case "color":
2536 // set the control display if it's changes or we're initialing
2537 if (init
2538 || ele.useDefaultColor != isDef
2539 || ele.style.backgroundColor != val)
2540 setColorButton(ele, val, isDef);
2541 break;
2542
2543 case "font":
2544 case "fontsize":
2545 // set the value in the field
2546 if (isDef)
2547 val = "*" + val;
2548
2549 // set it if it's changed or we're initializing
2550 if (init || ele.value != val)
2551 ele.value = val;
2552 break;
2553
2554 default:
2555 if (m.checkbox)
2556 {
2557 // checkbox - check it if the 'on' value is active
2558 ele.checked = (val == m.checkbox[1]);
2559 }
2560 else if (ele.type == "select-one")
2561 {
2562 // select list - find the value in the option list
2563 var opts = ele.options;
2564 for (var i = 0 ; i < opts.length ; ++i)
2565 {
2566 // if this value matches, select it
2567 if (opts[i].value == val)
2568 {
2569 ele.selectedIndex = i;
2570 break;
2571 }
2572 }
2573 }
2574 else
2575 {
2576 // for anything else, just set the value directly
2577 if (isDef)
2578 val = "*" + val;
2579
2580 // set it if we're initializing or the value changed
2581 if (init || ele.value != val)
2582 ele.value = val;
2583 }
2584 break;
2585 }
2586 }
2587
2588 function setColorButton(ele, color, isDef)
2589 {
2590 ele.useDefaultColor = isDef;
2591 if (color)
2592 {
2593 ele.style.backgroundColor = color;
2594 ele.style.color = contrastColor(color);
2595 }
2596 ele.innerHTML = (isDef ? "*" : "");
2597 }
2598
2599 // Calculate a constrasting color. For most colors we'll just calculate
2600 // the RGB complement, but for middle grays that gives us roughly the
2601 // same color, so we'll simply use black.
2602 function contrastColor(color)
2603 {
2604 // parse the color to an int
2605 color = parseColor(color);
2606
2607 // calculate the inverse of each component
2608 var r = 255 - ((color >> 16) & 0xff);
2609 var g = 255 - ((color >> 8) & 0xff);
2610 var b = 255 - (color & 0xff);
2611
2612 // if the color is near a middle gray, the RGB complement is just
2613 // another middle gray, which isn't very contrasting; black is a
2614 // safe choice in these cases
2615 if (r >= 0x70 && r <= 0x90
2616 && g >= 0x70 && g <= 0x90
2617 && b >= 0x70 && b <= 0x90)
2618 r = g = b = 0;
2619
2620 // generate the result color in #rrggbb format
2621 return unparseCColor(r, g, b);
2622 }
2623
2624 // save the preferences dialog's current settings into the in-memory
2625 // preferences table
2626 function dlgToPrefs(dlg, prefs)
2627 {
2628 // Traverse the dialog DOM tree and save each control value. Note
2629 // that we use the "search" function for the traversal, but we're not
2630 // really doing a search - we just want to traverse the tree for the
2631 // side effects. We can coopt the search function for this purpose
2632 // simply by always returning false from the test callback: the
2633 // search will never find what it's looking for, so it'll traverse
2634 // the entire tree before giving up and returning null.
2635 breadthSearch(dlg, function(ele)
2636 {
2637 // if this item has a mapping, save its value
2638 if (prefsMapper[ele.id])
2639 controlToPref(ele, prefs);
2640
2641 // return false so that we continue the "search"
2642 return false;
2643 });
2644 }
2645
2646 // set the preferences array value for a given control in the dialog
2647 function controlToPref(ele, prefs)
2648 {
2649 // get the mapper
2650 var id = ele.id;
2651 var m = prefsMapper[ele.id];
2652
2653 // figure the value based on the type
2654 var val;
2655 switch (m.type)
2656 {
2657 case "color":
2658 val = ele.useDefaultColor ? null : ele.style.backgroundColor;
2659 break;
2660
2661 case "font":
2662 case "fontsize":
2663 // if it starts with "*", it's a default
2664 val = ele.value;
2665 if (val.charAt(0) == '*')
2666 val = null;
2667 break;
2668
2669 default:
2670 if (m.checkbox)
2671 val = m.checkbox[ele.checked ? 1 : 0];
2672 else
2673 val = ele.value;
2674 break;
2675 }
2676
2677 // save the value
2678 prefs[id] = val;
2679 }
2680
2681 function getPrefVal(prefs, id)
2682 {
2683 // first look at the given preference set, then at the defaults
2684 for (var i = 0 ; i < 2 ; ++i)
2685 {
2686 // get the current set
2687 var s = [prefs, defaultPrefs][i];
2688
2689 // scan up the inheritance tree for this ID
2690 for (var cid = id ; cid ; )
2691 {
2692 // get the mapper entry
2693 var m = prefsMapper[cid];
2694
2695 // if this set has a non-null value for this item, it's the result
2696 var val = s[cid];
2697 if (val != null && val != undefined)
2698 return val;
2699
2700 // get the parent ID
2701 cid = m ? m.parent : null;
2702 }
2703 }
2704
2705 // didn't find it
2706 return null;
2707 }
2708
2709 function onPrefItemChange(ev, dlg, ele)
2710 {
2711 // get the active profile
2712 var profile = dlgProfiles[dlgCurProfile];
2713
2714 // save this control's value in the current preference set
2715 controlToPref(ele, profile);
2716
2717 // refresh all controls to show new inherited defaults as needed
2718 prefsToDlg(dlg, profile, false);
2719 }
2720
2721 function newPrefProfile()
2722 {
2723 // Create a temporary name for the profile of the form "Profile N+1",
2724 // where N is either the maximum of any existing profiles of the form
2725 // "Profile n", otherwise simply the number of existing profiles.
2726 var n = null;
2727 dlgProfiles.forEach(function (pro) {
2728 if (pro.profileName.match(/^\s*profile\s+(\d+)\s*$/i))
2729 {
2730 var m = parseInt(RegExp.$1);
2731 if (n == null || m > n)
2732 n = m;
2733 }
2734 });
2735
2736 // if we didn't find any matching profiles, use the number of profiles
2737 if (n == null)
2738 n = dlgProfiles.propCount();
2739
2740 // generate the name
2741 var initName = "Profile " + (n+1);
2742
2743 // note the preferences dialog object
2744 var prefsDlg = dialogStack.top().ele;
2745
2746 // show the create/rename dialog
2747 createOrRenamePrefProfile("Create Profile", initName, function(newName)
2748 {
2749 // copy the current profile
2750 var newPro = dlgProfiles[dlgCurProfile].copy(false);
2751
2752 // set the name
2753 newPro.profileName = newName;
2754
2755 // make sure the next profile ID is above any existing IDs
2756 dlgProfiles.forEach(function(id) {
2757 id = parseInt(id);
2758 if (nextPrefProfile <= id)
2759 nextPrefProfile = id + 1;
2760 });
2761
2762 // generate a new profile ID and store it in the dialog table
2763 var newID = (nextPrefProfile++).toString();
2764 dlgProfiles[newID] = newPro;
2765
2766 // add it to the profile selector control
2767 var sel = $(prefsDlg, "curProfile");
2768 addSelectOptionSort(sel, newName, newID);
2769
2770 // switch to the new profile
2771 dlgCurProfile = newID;
2772 setSelectByValue(sel, newID);
2773 });
2774 }
2775
2776 function renamePrefProfile()
2777 {
2778 // note the preferences dialog object
2779 var prefsDlg = dialogStack.top().ele;
2780
2781 // run the rename dialog
2782 createOrRenamePrefProfile(
2783 "Rename Profile", dlgProfiles[dlgCurProfile].profileName,
2784 function(newName) {
2785 if (newName != dlgCurProfile)
2786 {
2787 // update the name in the profile table
2788 var pro = dlgProfiles[dlgCurProfile];
2789 pro.profileName = newName;
2790
2791 // update the <select> option in the dialog display
2792 var sel = $(prefsDlg, "curProfile");
2793 var opt = sel.options[sel.selectedIndex];
2794 opt.text = newName;
2795 }
2796 });
2797 }
2798
2799 function createOrRenamePrefProfile(title, initName, setName)
2800 {
2801 // show the dialog
2802 showDialog({
2803 id: 'profileName',
2804 title: title,
2805 contents: "Profile name:<br>"
2806 + "<input type=\"text\" size=\"50\" value=\""
2807 + initName.htmlify() + "\">",
2808 buttons: [{ name: "OK", isDefault: true, save: true },
2809 { name: "Cancel", isCancel: true }],
2810 dimensions: { width: "70ex" },
2811
2812 // on close, add the new profile if they clicked OK
2813 dismiss: function(dlg, btn) {
2814 if (btn && btn.save)
2815 {
2816 // get the new name and trim leading and trailing spaces
2817 var newName = $(dlg, "<INPUT>").value.trim();
2818
2819 // make sure the name is non-empty and unique
2820 var err = null;
2821 if (newName.match(/^\s+$/))
2822 err = "Please enter a name for the new profile.";
2823 else if (newName != initName
2824 && dlgProfiles.propWhich(function(ele, prop) {
2825 return prop.trim().toLowerCase() == newName.toLowerCase();
2826 }))
2827 err = "There's already a profile with this name. "
2828 + "Please choose a different name.";
2829
2830 // if there's an error, show it and return failure
2831 if (err)
2832 {
2833 showDialog({ title: "Profile Name", contents: err });
2834 return false;
2835 }
2836
2837 // the name is valid - tell the caller to save it
2838 setName(newName);
2839 }
2840
2841 // success - close the dialog
2842 return true;
2843 }
2844 });
2845 }
2846
2847 function delPrefProfile()
2848 {
2849 // note the preferences dialog object
2850 var prefsDlg = dialogStack.top().ele;
2851
2852 // don't allow deleting the last profile
2853 if (dlgProfiles.propCount() == 1)
2854 {
2855 $alert("This is the only profile. If you wish to delete this "
2856 + "profile, please create a replacement first.",
2857 "Error");
2858 return;
2859 }
2860
2861 // run the delete confirmation dialog
2862 $confirm("Do you really want to delete the profile \""
2863 + dlgProfiles[dlgCurProfile].profileName + "\"?",
2864 function(del) {
2865 // proceed with the deletion if desired
2866 if (del)
2867 {
2868 // remove this profile from the <select> list
2869 var sel = $(prefsDlg, "curProfile");
2870 var idx = sel.selectedIndex;
2871 sel.remove(idx);
2872
2873 // delete the profile from the dialog globals
2874 delete dlgProfiles[dlgCurProfile];
2875
2876 // arbitrarily select the first remaining item
2877 dlgCurProfile = dlgProfiles.propWhich(
2878 function() { return true; });
2879
2880 // select this in the selector
2881 setSelectByValue(sel, dlgCurProfile);
2882
2883 // display its settings in the dialog
2884 prefsToDlg(prefsDlg, dlgProfiles[dlgCurProfile], true);
2885 }
2886 }, "Delete Profile");
2887 }
2888
2889 function resetPrefProfile()
2890 {
2891 // note the preferences dialog object
2892 var prefsDlg = dialogStack.top().ele;
2893
2894 // confirm
2895 $confirm("This will discard all of your custom settings for this "
2896 + "profile and restore its to the story's default "
2897 + "settings. Are you sure you want to do proceed?",
2898 function(reset) {
2899 if (reset)
2900 {
2901 // get the profile
2902 var pro = dlgProfiles[dlgCurProfile];
2903
2904 // set all of the known preferences to null
2905 prefsMapper.forEach(function(m, id) { pro[id] = null; });
2906
2907 // display the new settings in the dialog
2908 prefsToDlg(prefsDlg, dlgProfiles[dlgCurProfile], true);
2909 }
2910 }, "Reset Profile to Defaults");
2911 }
2912
2913 function onClosePrefsDialog(dlg, btn)
2914 {
2915 // if they clicked OK, save the current settings
2916 if (btn && btn.save)
2917 {
2918 // save the current dialog control settings
2919 dlgToPrefs(dlg, dlgProfiles[dlgCurProfile]);
2920
2921 // save these as the active settings
2922 prefProfiles = dlgProfiles;
2923 curPrefProfile = dlgCurProfile;
2924
2925 // update the browser's live style sheet rules
2926 prefsToCSS();
2927
2928 // build the preference update body to send to the server
2929 var post = [];
2930 post.push("current-profile=" + curPrefProfile);
2931 prefProfiles.forEach(function(pro, proID)
2932 {
2933 pro.forEach(function(val, id) {
2934 post.push(proID + "." + id + "=" + (val ? val : ""));
2935 });
2936 });
2937
2938 // combine it into a CRLF-delimited string
2939 post = post.join("\r\n");
2940
2941 // send the updates to the server
2942 var f = function(req, resp) {
2943 if (xmlHasChild(resp, "error"))
2944 logError("An error occurred saving your preference changes.",
2945 xmlChildText("error"), null);
2946 };
2947 serverRequest("/webui/setPrefs", ServerRequest.Command,
2948 f, post, "text/plain");
2949 }
2950
2951 // allow the dialog to close
2952 return true;
2953 }
2954
2955 function onChangeProfile(ev, sel)
2956 {
2957 // get the active profile
2958 dlgCurProfile = sel.value;
2959
2960 // display its settings in the dialog
2961 prefsToDlg(dialogStack.top().ele, dlgProfiles[dlgCurProfile], true);
2962 }
2963
2964 /* ------------------------------------------------------------------------ */
2965 /*
2966 * File dialog
2967 */
2968
2969 function showFileDialog(desc)
2970 {
2971 // get the file dialog description from the xml
2972 var prompt = xmlChildText(desc, "prompt");
2973 var dlgType = xmlChildText(desc, "dialogType");
2974 var fileType = xmlChildText(desc, "fileType");
2975 var url = xmlChildText(desc, "url");
2976
2977 // show the dialog
2978 showDialog({
2979 id: "inputFile",
2980 title: prompt,
2981 contents: $("fileDialog"),
2982 init: initFileDialog,
2983 fillWidth: true,
2984 url: url,
2985 buttons: [],
2986 dismiss: function(dlg, btn) {
2987 // notify the server that the dialog has been closed
2988 serverRequest("/webui/inputFileDismissed");
2989 return true;
2990 }
2991 });
2992 }
2993
2994 function initFileDialog(dlg, params)
2995 {
2996 var fr = $(dlg, "<IFRAME>");
2997 var frWin = fr.contentWindow || fr.contentDocument.window;
2998 frWin.location = params.url;
2999 }
3000
3001 /* ------------------------------------------------------------------------ */
3002 /*
3003 * Input dialog. This displays a generic message-and-buttons dialog per
3004 * the TADS inputDialog() API.
3005 */
3006 function showInputDialog(desc)
3007 {
3008 // get the dialog parameters
3009 var iconID = parseInt(xmlChildText(desc, "icon"));
3010 var prompt = xmlChildText(desc, "prompt").htmlify().replace(/\n/g, '<br>');
3011 var title = xmlChildText(desc, "title").htmlify();
3012 var defbtn = parseInt(xmlChildText(desc, "defaultButton"));
3013 var cxlbtn = parseInt(xmlChildText(desc, "cancelButton"));
3014 var buttons = xpath(desc, "buttons/button[*]#text").map(function(name, i) {
3015 var key = (name.match(/&(.)/) ? RegExp.$1 : null);
3016 name = name.htmlify().replace(/&amp;(.)/, "<B>$1</B>");
3017 var idx = i + 1;
3018 return {
3019 name: name,
3020 key: key,
3021 isDefault: idx == defbtn,
3022 isCancel: idx == cxlbtn,
3023 buttonIndex: idx
3024 };
3025 });
3026
3027 // select the icon image for the given icon ID
3028 var icons = [null, "dlgIconWarning", "dlgIconInfo",
3029 "dlgIconQuestion", "dlgIconError"];
3030 var icon = "";
3031 if (iconID >= 0 && iconID < icons.length)
3032 icon = icons[iconID];
3033
3034 // if we found an image, wrap it in an <IMG> tag
3035 var img = (icon
3036 ? "<img src=\"/webuires/" + icon
3037 + ".gif\" class=\"inputDialogIcon\">"
3038 : "");
3039
3040 // build the layout table
3041 var cont = "<table class=\"inputDialogTab\">"
3042 + "<tr>"
3043 + "<td>" + img + "</td>"
3044 + "<td class=\"inputDialogPrompt\">" + prompt + "</td>"
3045 + "</tr>"
3046 + "</table>";
3047
3048 // show the dialog
3049 showDialog({
3050 id: "inputDialog",
3051 title: title,
3052 contents: "<div class=\"inputDialog\">" + cont + "</div>",
3053 buttons: buttons,
3054 dismiss: function(dlg, btn) {
3055 var idx = btn.buttonIndex || cxlbtn;
3056 serverRequest("/webui/inputDialog?button=" + idx);
3057 return true;
3058 },
3059 fillWidth: true
3060 });
3061 }
3062
3063 /* ------------------------------------------------------------------------ */
3064 /*
3065 * Upload file dialog. This allows the game server to solicit a file
3066 * upload from the client; we pass along the request to the user through a
3067 * dialog containing an <INPUT TYPE=FILE> field, which allows the user to
3068 * select a local file to upload to the server.
3069 *
3070 * TADS uses file uploads when running in client/server mode without a
3071 * network storage server. In this configuration, the game server doesn't
3072 * have anywhere else to put saved games and other files, so it uses
3073 * uploads and downloads to the client PC. This dialog handles the upload
3074 * side.
3075 */
3076 function showUploadDialog(desc)
3077 {
3078 // get the dialog description
3079 var prompt = xmlChildText(desc, "prompt");
3080
3081 // initialization - fill in the iframe
3082 var init = function(dlg, params)
3083 {
3084 var doc = getIFrameDoc($(dlg, "<IFRAME>"));
3085 doc.open("text/html");
3086 doc.write(
3087 "<html><head><title>File Upload</title>"
3088 + "<link rel=\"stylesheet\" href=\"/webuires/tads.css\">"
3089 + "<link rel=\"stylesheet\" href=\"/webuires/main.css\">"
3090 + "</head>"
3091 + "<body>"
3092 + "<div class=\"dialogWrapper\"><div class=\"dialogContent\">"
3093 + "<form method=\"post\" name=\"uploadDialog\" "
3094 + "enctype=\"multipart/form-data\" "
3095 + "action=\"/webui/uploadFileDialog\" "
3096 + "style=\"padding-top: 2em;\">"
3097 + "Please select a file:"
3098 + "<div style='margin: 1em;'>"
3099 + "<input type=\"file\" size=\"50\" name=\"file\">"
3100 + "</div>"
3101 + "</form>"
3102 + "</div></div>"
3103 + "</body>"
3104 + "</html>");
3105 doc.close();
3106 };
3107
3108 // submit button callback
3109 var submit = function()
3110 {
3111 var doc = getIFrameDoc($(dialogStack.top().ele, "<IFRAME>"));
3112 var form = $(doc.body, "<FORM>");
3113 form.submit();
3114 };
3115
3116 // show the dialog
3117 showDialog({
3118 id: "uploadFile",
3119 init: init,
3120 fillWidth: true,
3121 title: prompt,
3122 contents: $("uploadDialog"),
3123 buttons: [
3124 { name: "OK", isDefault: true, onclick: submit },
3125 { name: "Cancel", isCancel: true }
3126 ],
3127 dismiss: function(dlg, btn) {
3128 serverRequest("/webui/inputFileDismissed");
3129 return true;
3130 }
3131 });
3132 }
3133
3134 /* ------------------------------------------------------------------------ */
3135 /*
3136 * Offer a file for download. When the server wants to offer a file for
3137 * download to the client PC, it sends a request with the server file path
3138 * information, and we in turn offer the file to the user by creating an
3139 * IFRAME with its source set to the downloadable file. This will trigger
3140 * the browser to offer a file download dialog, giving the user a chance to
3141 * decide whether to accept the download and specify where to save it
3142 * locally, or to reject the download by canceling the download dilaog.
3143 *
3144 * This function handles the download portion of the upload/download scheme
3145 * described in the notes about showUploadDialog() above.
3146 */
3147 function addDownloadFrame(fname)
3148 {
3149 // remove any old frame with the same name
3150 removeDownloadFrame(fname);
3151
3152 // create the IFRAME
3153 var fr = document.createElement("IFRAME");
3154 fr.className = "downloadFile";
3155
3156 // set its source to point to the file
3157 fr.src = fname;
3158
3159 // add it to the document
3160 document.body.appendChild(fr);
3161 }
3162
3163 /*
3164 * Remove a downloadable file previously offered. The server removes files
3165 * after we successfully download them, or after a timeout elapses.
3166 */
3167 function removeDownloadFrame(fname)
3168 {
3169 // find the iframe for the download
3170 for (var ele = document.body.firstChild ; ele ; ele = nxt)
3171 {
3172 // remember the next sibling, in case we unlink this one
3173 var nxt = ele.nextSibling;
3174
3175 // if this is an iframe with the given file as the source, remove it
3176 if (ele.nodeName == "IFRAME" && ele.src == fname)
3177 document.body.removeChild(ele);
3178 }
3179 }
3180
3181 /* ------------------------------------------------------------------------ */
3182 /*
3183 * MenuSys menu display - this is the client side implementation of the
3184 * menusys.t module on the server. This displays a dialog box with the
3185 * given list of menu items. Each menu item is a link that sends a command
3186 * to the server to display its submenu or topic.
3187 */
3188 var menuSysLinkCount = 0, menuSysTopicCount = 0, menuSysLastTopic = 0;
3189 function showMenuSys(r)
3190 {
3191 // get the menu title
3192 var title = xmlChildText(r, "title");
3193
3194 // no buttons yet
3195 var buttons = [];
3196
3197 // start out with the menu wrapper div
3198 var s = "<div class=\"menuSys\">";
3199
3200 // presume no specific initial focus
3201 var initFocus = null;
3202
3203 // set up functions for common commands
3204 var prev = function() { serverRequest("/webui/menusys?prev"); };
3205 var up = function() { menuSysArrow(-1); };
3206 var down = function() { menuSysArrow(1); };
3207 var sel = null;
3208
3209 // set up the dialog contents
3210 if (xmlHasChild(r, "close"))
3211 {
3212 // close the menu UI
3213 dismissDialogById("menuSys");
3214 return;
3215 }
3216 else if (xmlHasChild(r, "menuItem"))
3217 {
3218 // this is a list of submenu items - display the menu list
3219 var contents = xmlChild(r, "menuItem");
3220 for (var i = 0 ; i < contents.length ; ++i)
3221 {
3222 var item = xmlNodeText(contents[i]);
3223 var idx = i + 1;
3224 s += "<div class=\"menuSysItem\">"
3225 + "<a href=\"#\" id=\"menuSysLink" + idx
3226 + "\" onclick=\"javascript:menuSysSel(" + idx
3227 + ");return false;\">"
3228 + item + "</a></div>";
3229 }
3230
3231 // 'select' selects the item with focus, if any
3232 sel = function() {
3233 var ae = document.activeElement;
3234 if (ae && ae.id.search(/^menuSysLink(\d+)$/) == 0)
3235 menuSysSel(parseInt(RegExp.$1));
3236 };
3237
3238 // if we navigated from a child item, set the initial focus to
3239 // the child item
3240 if (xmlHasChild(r, "fromChild"))
3241 initFocus = "menuSysLink" + parseInt(xmlChildText(r, "fromChild"));
3242
3243 // note the number of links
3244 menuSysLinkCount = contents.length;
3245
3246 // add up/down arrow handlers
3247 buttons.push({ onclick: up, key: "Up" });
3248 buttons.push({ onclick: up, key: "U+0050" }); // "P"
3249 buttons.push({ onclick: down, key: "Down" });
3250 buttons.push({ onclick: down, key: "U+004E" }); // "N"
3251 }
3252 else if (xmlHasChild(r, "topicItem"))
3253 {
3254 // This is a topic menu - this type of menu is usually used for
3255 // hint lists. We don't immediately display the whole list, but
3256 // instead just display up to the current "last displayed" item.
3257 // We then display more items on demands as the user requests
3258 // them.
3259 s += "<div id=\"menuSysTopicList\">";
3260 var contents = xmlChild(r, "topicItem");
3261 menuSysTopicCount = parseInt(xmlChildText(r, "numItems"));
3262 menuSysLastTopic = contents.length;
3263 for (var i = 0 ; i < contents.length ; ++i)
3264 {
3265 var idx = i + 1;
3266 var item = xmlNodeText(contents[i]);
3267 s += "<div class=\"menuSysItem\" id=\"menuSysTopic" + idx + "\">"
3268 + item
3269 + " [" + idx + "/" + menuSysTopicCount + "]"
3270 + "</div>";
3271 }
3272
3273 // end the topic list div
3274 s += "</div>";
3275
3276 // start the footer with the Next button and "The End" indicator
3277 s += "<div class=\"menuSysTopicFooter\">";
3278
3279 // if there's more to come, add the "next" item
3280 if (menuSysLastTopic < menuSysTopicCount)
3281 s += "<span id=\"menuSysNextButton\">(Press Space or "
3282 + "<a href=\"#\" onclick=\"javascript:menuSysNextTopic();"
3283 + "return false;\">click here</a> to see the next item)"
3284 + "</span>";
3285
3286 // add the "The End" indicator
3287 s += "<span id=\"menuSysTheEnd\""
3288 + (menuSysLastTopic < menuSysTopicCount
3289 ? " style=\"display:none;\"" : "")
3290 + ">[The End]</span>";
3291
3292 // 'select' goes to the next topic
3293 sel = menuSysNextTopic;
3294
3295 // add handlers to show the next topic on space, enter, or arrow down
3296 buttons.push({ onclick: menuSysNextTopic, key: "U+0020" });
3297 buttons.push({ onclick: menuSysNextTopic, key: "Enter" });
3298 buttons.push({ onclick: menuSysNextTopic, key: "Down" });
3299 }
3300 else if (xmlHasChild(r, "longTopic"))
3301 {
3302 // long topic item - limit the height
3303 var winrc = getWindowRect();
3304 var maxht = winrc.height * 0.75;
3305
3306 // add the long topic contents
3307 s += "<div class=\"menuSysLongTopic\" style=\"max-height:"
3308 + maxht + "px;\">"
3309 + xmlChildText(r, "longTopic")
3310 + "</div>";
3311
3312 // add the next and previous chapter buttons, if present
3313 if (xmlHasChild(r, "nextChapter") || xmlHasChild(r, "prevChapter"))
3314 {
3315 s += "<div class=\"menuSysChapterButtons\">";
3316
3317 if (xmlHasChild(r, "prevChapter"))
3318 {
3319 s += "<a href=\"#\" onclick=\"javascript:menuSysGoChapter("
3320 + "'prev');return false;\">&lt; Previous</a>";
3321
3322 up = function() { menuSysGoChapter('prev'); };
3323 buttons.push({ onclick: up, key: "Left" });
3324 buttons.push({ onclick: up, key: "U+0008" });
3325 }
3326
3327 if (xmlHasChild(r, "nextChapter"))
3328 {
3329 s += "<a href=\"#\" onclick=\"javascript:menuSysGoChapter("
3330 + "'next');return false;\">Next: "
3331 + xmlChildText(r, "nextChapter")
3332 + " &gt;</a>";
3333
3334 sel = down = function() { menuSysGoChapter('next'); };
3335 buttons.push({ onclick: down, key: "Right" });
3336 buttons.push({ onclick: down, key: "U+0020" });
3337 }
3338
3339 s += "</div>";
3340 }
3341 }
3342
3343 // close the division wrapper
3344 s += "</div>";
3345
3346 // add a Previous button if this isn't the top-level menu
3347 if (!xmlHasChild(r, "isTop"))
3348 {
3349 // add the Return button
3350 buttons.push({ name: "Return", onclick: prev });
3351
3352 // add backspace and left arrow keys as well; add these at the
3353 // end of the list, so that any key definitions we've already
3354 // added will override these
3355 buttons.push({ onclick: prev, key: "U+0008" });
3356 buttons.push({ onclick: prev, key: "Left" });
3357 }
3358
3359 // add the Close button for all dialog types
3360 buttons.push({ name: "Close", isCancel: true });
3361
3362 // add buttons for key list items
3363 var keylists = xmlChild(r, "keylist");
3364 if (keylists)
3365 {
3366 // the key list entries represent these commands, in order:
3367 // quit, previous, up, down, select
3368 var keyfuncs = [
3369 { isCancel: true, onclick: null },
3370 { isCancel: false, onclick: prev },
3371 { isCancel: false, onclick: up },
3372 { isCancel: false, onclick: down },
3373 { isCancel: false, onclick: sel }
3374 ];
3375
3376 // run through the key list
3377 for (var i = 0 ; i < keylists.length ; ++i)
3378 {
3379 var kf = keyfuncs[i];
3380 var kl = xmlChild(keylists[i], "key");
3381 for (var j = 0 ; j < kl.length ; ++j)
3382 {
3383 // get the key name
3384 var k = xmlNodeText(kl[j]);
3385
3386 // if it's in square brackets, it's a special key name;
3387 // otherwise it's a regular character
3388 if (k.search(/^\[(.*)\]$/) == 0)
3389 {
3390 // special - look up the DOM equivalent
3391 k = DOM3toTADSKey.propWhich(
3392 function(val) { return val == k; });
3393 }
3394 else
3395 {
3396 // ordinary character
3397 k = k.toUpperCase();
3398 }
3399
3400 // if we got the key, set up a button for it; insert it at
3401 // the start of the list so that it overrides any existing
3402 // entry with the same key
3403 if (k && (kf.onclick || kf.isCancel))
3404 {
3405 buttons.unshift(
3406 { onclick: kf.onclick,
3407 isCancel: kf.isCancel,
3408 key: k });
3409 }
3410 }
3411 }
3412 }
3413
3414 // If there's already a menu system dialog showing, remove it. (Use a
3415 // pseudo-button with the 'isNewDlg' property set, so that our dismiss
3416 // handler knows that we're replacing the dialog rather than closing it.
3417 // This tells us not to send a 'close' command to the server to dismiss
3418 // the entire menu interaction.)
3419 dismissDialogById("menuSys", { isCancel: true, isNewDlg: true });
3420
3421 // run the new dialog
3422 showDialog({
3423 id: "menuSys",
3424 fullWidth: true,
3425 title: title,
3426 initFocus: initFocus,
3427 contents: s,
3428 buttons: buttons,
3429 dimensions: { width: "90%" },
3430 dismiss: function(dlg, btn) {
3431 if (!btn.isNewDlg)
3432 serverRequest("/webui/menusys?close");
3433 return true;
3434 }
3435 });
3436 }
3437
3438 function menuSysGoChapter(dir)
3439 {
3440 serverRequest("/webui/menusys?chapter=" + dir);
3441 }
3442
3443 /*
3444 * Handle an arrow in the menu system. This moves the focus up or down in
3445 * the menu list.
3446 */
3447 function menuSysArrow(dir)
3448 {
3449 // find the item with focus
3450 var ele = document.activeElement;
3451
3452 // if it's not one of our items, move to the first or last item
3453 if (ele == null || !ele.id || ele.id.search(/^menuSysLink(\d+)$/) < 0)
3454 {
3455 // select the first element on Down, last element on Up
3456 ele = (dir > 0 ? 1 : menuSysLinkCount);
3457 }
3458 else
3459 {
3460 // we have a focus item - move to the next item
3461 ele = parseInt(RegExp.$1) + dir;
3462 }
3463
3464 // make sure it's in range
3465 if (ele < 1)
3466 ele = menuSysLinkCount;
3467 else if (ele > menuSysLinkCount)
3468 ele = 1;
3469
3470 // select the item
3471 ele = $("menuSysLink" + ele);
3472 if (ele)
3473 ele.focus();
3474 }
3475
3476 /*
3477 * Display the next topic in a topic/hint list
3478 */
3479 function menuSysNextTopic()
3480 {
3481 // if we've displayed all items, we're done
3482 if (menuSysLastTopic >= menuSysTopicCount)
3483 return;
3484
3485 // ask for the next item
3486 serverRequest("/webui/menusys?nextTopic", ServerRequest.Command,
3487 function(req, resp)
3488 {
3489 // get the topic text from the reply
3490 var txt = xmlChildText(resp, "topicItem");
3491 if (txt)
3492 {
3493 // count the additional display item
3494 menuSysLastTopic++;
3495
3496 // set up the topic item
3497 var ele = document.createElement("DIV");
3498 ele.className = "menuSysItem";
3499 ele.id = "menuSysTopic" + menuSysLastTopic;
3500 ele.innerHTML = txt
3501 + " [" + menuSysLastTopic
3502 + "/" + menuSysTopicCount + "]";
3503
3504 // add it to the topic list
3505 $("menuSysTopicList").appendChild(ele);
3506
3507 // if this is the last item, hide the "next" button and show
3508 // the "the end" indicator
3509 if (menuSysLastTopic >= menuSysTopicCount)
3510 {
3511 $("menuSysNextButton").style.display = "none";
3512 $("menuSysTheEnd").style.display = "inline";
3513 }
3514 }
3515 });
3516 }
3517
3518 /*
3519 * Navigate into a given menu item. This sends a command to the server
3520 * telling it to select the given menu. The server will update its menu
3521 * state and send us display instructions for the new menu.
3522 */
3523 function menuSysSel(idx)
3524 {
3525 serverRequest("/webui/menusys?select=" + idx);
3526 }
3527
3528 /* ------------------------------------------------------------------------ */
3529 /*
3530 * Show the page menu. This is typically activated by a button in the
3531 * status line.
3532 */
3533 function showPageMenu(ev, arrow)
3534 {
3535 // get the real event
3536 ev = getEvent(ev);
3537
3538 // get the menu object
3539 var menu = $("pageMenuDiv");
3540
3541 // make sure any past incarnation is closed
3542 closePopup(menu);
3543
3544 // create the shadow div
3545 var sh = document.createElement("DIV");
3546 sh.className = "menuShadow";
3547 document.body.appendChild(sh);
3548 var closer = function() {
3549 document.body.removeChild(sh);
3550 };
3551
3552 // open the menu
3553 menu.style.display = "block";
3554 openPopup(ev, menu, closer, null, arrow);
3555
3556 // move it just under the arrow that opened it
3557 var arc = getObjectRect(arrow);
3558 var mrc = getObjectRect(menu);
3559 mrc.x = arc.x + arc.width - mrc.width;
3560 mrc.y = arc.y + arc.height;
3561 moveObject(menu, mrc.x, mrc.y);
3562
3563 // set up the shadow
3564 sh.style.width = mrc.width + "px";
3565 sh.style.height = mrc.height + "px";
3566 moveObject(sh, mrc.x + 3, mrc.y + 3);
3567 }
3568
3569 function pageMenuClick(item)
3570 {
3571 closePopup($("pageMenuDiv"));
3572 if (item == 'prefs')
3573 {
3574 showPrefsDialog();
3575 }
3576 else if (item == 'errlog')
3577 {
3578 showErrorLog();
3579 }
3580 }
3581
3582 /* ------------------------------------------------------------------------ */
3583 /*
3584 * Screen name setting
3585 */
3586 var screenName = "Host";
3587 function setScreenName(name)
3588 {
3589 serverRequest("/webui/setScreenName?name=" + encodeURIComponent(name));
3590 screenName = name;
3591 }
3592