Debian Codegraph @

terps/tads/tads3/lib/adv3/browser.t

raw
1 #charset "us-ascii"
2
3 /*
4 * Copyright (c) 2000, 2006 Michael J. Roberts. All Rights Reserved.
5 *
6 * TADS 3 Library - browser (Web UI) input/output manager
7 *
8 * This module defines the low-level functions for handling input and
9 * output via the Web UI.
10 *
11 * The functions in this module are designed primarily for internal use
12 * within the library itself. Games should use the higher level objects
13 * and functions defined in input.t and output.t instead of directly
14 * calling the functions defined here. The reason for separating these
15 * functions is to make the UI selection pluggable, so that the same game
16 * can be compiled for either the traditional UI or the Web UI simply by
17 * plugging in the correct i/o module.
18 */
19
20 /* include the library header */
21 #include "adv3.h"
22
23
24 /* ------------------------------------------------------------------------ */
25 /*
26 * Browser globals
27 */
28 transient browserGlobals: object
29 /* the HTTPServer object for the browser UI session */
30 httpServer = nil
31
32 /*
33 * Log file handle. For a LogTypeTranscript file, this is a
34 * LogConsole object; for other types, it's a regular file handle.
35 */
36 logFile = nil
37
38 /* logging type (LogTypeXxx from tadsio.h, or nil if not logging) */
39 logFileType = nil
40 ;
41
42 /* ------------------------------------------------------------------------ */
43 /*
44 * Initialize the user interface. The library calls this once at the
45 * start of the interpreter session to set up the UI. For the Web UI, we
46 * create the HTTP server and send connection instructions to the client.
47 */
48 initUI()
49 {
50 /*
51 * Set up the HTTP server. Listen on the launch address, which is
52 * the address that the client used to reach the external Web server
53 * that launched the interpreter. For local stand-alone launches,
54 * the launch address is nil, so the HTTP server will listen on
55 * localhost, which is just what we need in order to connect to the
56 * local UI.
57 */
58 local srv = browserGlobals.httpServer = new HTTPServer(
59 getLaunchHostAddr(), nil, 1024*1024);
60
61 /* send connection instructions to the client */
62 webSession.connectUI(srv);
63 }
64
65 /*
66 * Initialize the display. We call this when we first enter the
67 * interpreter, and again at each RESTART, to set up the main game
68 * window's initial layout. We set up the conventional IF screen layout,
69 * with the status line across the top and the transcript/command window
70 * filling the rest of the display.
71 */
72 initDisplay()
73 {
74 /* set up the command window and status line */
75 webMainWin.createFrame(commandWin, 'command',
76 '0, statusline.bottom, 100%, 100%');
77 webMainWin.createFrame(statuslineBanner, 'statusline',
78 '0, 0, 100%, content.height');
79
80 /* capture the title string */
81 local title = mainOutputStream.captureOutput(
82 {: gameMain.setGameTitle() });
83
84 /* parse out the contents of the <title> tag */
85 if (rexSearch('<nocase>[<]title[>](.*)[<]/title[>]', title))
86 title = rexGroup(1)[3];
87
88 /* initialize the statusline window object */
89 statuslineBanner.init();
90 statusLine.statusDispMode = StatusModeBrowser;
91
92 /* set the title */
93 webMainWin.setTitle(title);
94
95 /* get the session parameters from the arguments */
96 local arg = libGlobal.getCommandSwitch('-gameid=');
97 if (arg != nil && arg != '')
98 webSession.launcherGameID = arg;
99
100 arg = libGlobal.getCommandSwitch('-storagesid=');
101 if (arg != nil && arg != '')
102 webSession.storageSID = arg;
103
104 arg = libGlobal.getCommandSwitch('-username=');
105 if (arg != nil && arg != '')
106 webSession.launcherUsername = arg;
107 }
108
109 /*
110 * Shut down the user interface. The library calls this when the game is
111 * about to terminate.
112 */
113 terminateUI()
114 {
115 /* if we have an HTTP server, shut it down */
116 if (browserGlobals.httpServer != nil)
117 {
118 /* flush our windows */
119 webMainWin.flushWin();
120 commandWin.sendWinEvent('<scrollToBottom/>');
121
122 /* end any scripting */
123 aioSetLogFile(nil, LogTypeTranscript);
124 aioSetLogFile(nil, LogTypeCommand);
125
126 /*
127 * keep running for a few more minutes, to give clients a chance
128 * to perform final tasks like downloading log files
129 */
130 ClientSession.shutdownWait(5*60*1000);
131
132 /* send the shutdown message */
133 eventPage.sendEvent('<shutdown/>');
134
135 /* wait a short time for clients to process the shutdown event */
136 ClientSession.shutdownWait(5*1000);
137
138 /* shut down the http server */
139 browserGlobals.httpServer.shutdown(true);
140 }
141 }
142
143 /* ------------------------------------------------------------------------ */
144 /*
145 * Check to see if we're in HTML mode
146 */
147 checkHtmlMode()
148 {
149 /*
150 * The web UI is always in HTML mode. This is regardless of the
151 * interpreter class, because that only tells us about the
152 * interpreter's own native UI. The actual user interface in Web UI
153 * mode runs in a separate Web browser app, which is inherently HTML
154 * capable.
155 */
156 return true;
157 }
158
159 /* ------------------------------------------------------------------------ */
160 /*
161 * Write text to the main game window
162 */
163 aioSay(txt)
164 {
165 /* write the text to the main command window */
166 commandWin.write(txt);
167
168 /* if we're logging a full transcript, write the text */
169 if (browserGlobals.logFileType == LogTypeTranscript)
170 browserGlobals.logFile.writeToStream(txt);
171 }
172
173 /* ------------------------------------------------------------------------ */
174 /*
175 * Is a script file active?
176 */
177 readingScript()
178 {
179 return setScriptFile(ScriptReqGetStatus) != nil;
180 }
181
182 /*
183 * Is an event script active?
184 */
185 readingEventScript()
186 {
187 local s = setScriptFile(ScriptReqGetStatus);
188 return (s != nil && (s & ScriptFileEvent) != 0);
189 }
190
191 /* ------------------------------------------------------------------------ */
192 /*
193 * Get a line of input from the keyboard, with timeout
194 */
195 aioInputLineTimeout(timeout)
196 {
197 /* check for script input */
198 local scriptMode = setScriptFile(ScriptReqGetStatus);
199 if (scriptMode != nil)
200 {
201 /* we're in a script, so use the regular input line reader */
202 local e = inputLineTimeout(timeout);
203
204 /*
205 * If it's not an end-of-file indication, return the event. An
206 * EOF means that there are no more events in the script, so
207 * return to reading from the live client UI.
208 */
209 if (e[1] != InEvtEof)
210 {
211 /* echo the input if we're not in quiet mode */
212 if (e[1] == InEvtLine && !(scriptMode & ScriptFileQuiet))
213 aioSay(e[2].htmlify() + '\n');
214
215 /* log and return the event */
216 return aioLogInputEvent(e);
217 }
218 }
219
220 /*
221 * read an input line event from the main command window, log it, and
222 * return it
223 */
224 return aioLogInputEvent(commandWin.getInputLine(timeout));
225 }
226
227 /*
228 * Cancel a suspended input line
229 */
230 aioInputLineCancel(reset)
231 {
232 /* cancel the input line in the command window */
233 commandWin.cancelInputLine(reset);
234 }
235
236
237 /* ------------------------------------------------------------------------ */
238 /*
239 * Read an input event
240 */
241 aioInputEvent(timeout)
242 {
243 /* check for script input */
244 if (readingEventScript())
245 {
246 /* we're in a script, so use the regular input line reader */
247 local e = inputEvent(timeout);
248
249 /*
250 * If it's not an end-of-file indication, return the event. An
251 * EOF means that there are no more events in the script, so
252 * return to reading from the live client UI.
253 */
254 if (e[1] != InEvtEof)
255 return aioLogInputEvent(e);
256 }
257
258 /* read an event from the main command window, log it, and return it */
259 return aioLogInputEvent(webMainWin.getInputEvent(timeout));
260 }
261
262
263 /* ------------------------------------------------------------------------ */
264 /*
265 * Show a "More" prompt
266 */
267 aioMorePrompt()
268 {
269 /* show a More prompt in the main command window */
270 commandWin.showMorePrompt();
271 }
272
273 /* ------------------------------------------------------------------------ */
274 /*
275 * Clear the screen
276 */
277 aioClearScreen()
278 {
279 /* clear the main transcript window */
280 commandWin.clearWindow();
281 }
282
283
284 /* ------------------------------------------------------------------------ */
285 /*
286 * Show a file selector dialog
287 */
288 aioInputFile(prompt, dialogType, fileType, flags)
289 {
290 /*
291 * First, try reading from the local console. Even though we're
292 * using the Web UI, there are two special cases where the input will
293 * come from the local (server-side) console instead of from the
294 * browser UI:
295 *
296 * 1. We're reading from an event script. In this case, regardless
297 * of the UI mode, the interpreter reads from a server-side file and
298 * parses the results into an inputFile() result, bypassing any UI
299 * interaction.
300 *
301 * 2. We're running in the Web UI's local stand-alone configuration,
302 * where the browser is actually an integrated window within the
303 * interpreter. This configuration simulates the traditional UI by
304 * running everything locally - the client and server are running on
305 * the same machine, so there's really no distinction between
306 * client-side and server-side. Because everything's local, files
307 * are local, so we want to display traditional local file selector
308 * dialogs. The stand-alone interpreter does this for us via the
309 * standard inputFile() function when it detects this configuration.
310 *
311 * If neither of these special cases apply, inputFile() will return
312 * an error to let us know that it can't show a file dialog in the
313 * current configuration, so we'll continue on to showing the dialog
314 * on the client side via the Web UI.
315 */
316 local f = inputFile(prompt, dialogType, fileType, flags);
317
318 /* if that failed, forget the result */
319 if (f[1] == InFileFailure)
320 f = nil;
321
322 /* if we got a file, check for warnings */
323 if (f != nil && f.length() >= 4 && f[4] != nil)
324 {
325 /* keep going until we get a definitive answer */
326 for (local done = nil ; !done ; )
327 {
328 /* show the warning dialog */
329 local d = webMainWin.getInputDialog(
330 InDlgIconWarning,
331 libMessages.inputFileScriptWarning(f[4], f[2]),
332 libMessages.inputFileScriptWarningButtons, 1, 3);
333
334 /* check the result */
335 switch (d)
336 {
337 case 0:
338 case 3:
339 /* dialog error or Cancel Script - stop the script */
340 setScriptFile(nil);
341
342 /* return a Cancel result */
343 return [InFileCancel];
344
345 case 1:
346 /* "Yes" - proceed */
347 done = true;
348 break;
349
350 case 2:
351 /* Choose New File button - show a file dialog */
352 local fNew = webMainWin.getInputFile(
353 prompt, dialogType, fileType, flags);
354
355 switch (fNew[1])
356 {
357 case InFileSuccess:
358 /* success - use the new file, and we're done */
359 f = fNew;
360 done = true;
361 break;
362
363 case InFileCancel:
364 /* cancel - repeat the prompt */
365 break;
366
367 case InFileFailure:
368 /* dialog error - cancel the script */
369 setScriptFile(nil);
370 return [InFileCancel];
371 }
372 }
373 }
374 }
375
376 /*
377 * if we didn't get a result from a script or from the local console,
378 * tell the client UI to display its file dialog
379 */
380 if (f == nil)
381 f = webMainWin.getInputFile(prompt, dialogType, fileType, flags);
382
383 /* log a synthetic <file> event, if applicable */
384 aioLogInputEvent(
385 ['<file>',
386 f[1] != InFileSuccess ? '' :
387 dataType(f[2]) == TypeObject && !f[2].ofKind(FileName) ? 't' :
388 f[2]]);
389
390 /* return the file information */
391 return f;
392 }
393
394 /* ------------------------------------------------------------------------ */
395 /*
396 * Show an input dialog
397 */
398 aioInputDialog(icon, prompt, buttons, defaultButton, cancelButton)
399 {
400 /* check for script input */
401 local d = nil;
402 if (readingEventScript())
403 {
404 /* we're in a script, so use the regular dialog event reader */
405 d = inputDialog(icon, prompt, buttons, defaultButton, cancelButton);
406
407 /* if it failed, forget the result */
408 if (d == 0)
409 d = nil;
410 }
411
412 /* if we didn't get script input, show the dialog via the client UI */
413 if (d == nil)
414 d = webMainWin.getInputDialog(icon, prompt, buttons,
415 defaultButton, cancelButton);
416
417 /* log a synthetic <dialog> event, if applicable */
418 aioLogInputEvent(['<dialog>', d]);
419
420 /* return the result */
421 return d;
422 }
423
424
425 /* ------------------------------------------------------------------------ */
426 /*
427 * Set/remove the output logging file
428 */
429 aioSetLogFile(fname, typ = LogTypeTranscript)
430 {
431 /* if there's currently a log file open, close it */
432 local log = browserGlobals.logFile;
433 if (log != nil)
434 {
435 switch (browserGlobals.logFileType)
436 {
437 case LogTypeTranscript:
438 /* for a transcript, we have a log console as the handle */
439 log.closeConsole();
440 break;
441
442 default:
443 /* for other types, we have a regular file handle */
444 try
445 {
446 log.closeFile();
447 }
448 catch (Exception exc)
449 {
450 /* ignore errors, as we have no way to return them */
451 }
452 break;
453 }
454
455 /* we've closed the handle, so forget it */
456 log = nil;
457 }
458
459 /* presume success */
460 local ok = true;
461
462 /* if there's a filename, create a new console for this file */
463 if (fname != nil)
464 {
465 /* create the output handle according to the type */
466 switch (typ)
467 {
468 case LogTypeTranscript:
469 /*
470 * full transcript - create a log console, which will do the
471 * standard output formatting for us
472 */
473 log = new LogConsole(fname, nil, 80);
474 break;
475
476 case LogTypeCommand:
477 case LogTypeScript:
478 /* for other types, create an ordinary text file */
479 try
480 {
481 /* open the log file */
482 log = File.openTextFile(fname, FileAccessWrite, nil);
483
484 /* for an event script, write the <eventscript> opener */
485 if (typ == LogTypeScript)
486 log.writeFile('<eventscript>\n');
487 }
488 catch (Exception exc)
489 {
490 /* if anything went wrong, we have no log file */
491 log = nil;
492 }
493 break;
494
495 default:
496 throw RuntimeError.newRuntimeError(2306, 'bad log file type');
497 }
498
499 /* we failed if the log handle is nil */
500 if (log == nil)
501 {
502 ok = nil;
503 typ = nil;
504 }
505 }
506 else
507 {
508 /* no longer logging */
509 typ = nil;
510 }
511
512 /* remember the new handle and log type */
513 browserGlobals.logFile = log;
514 browserGlobals.logFileType = typ;
515
516 /* return the success/failure indicator */
517 return ok;
518 }
519
520 /*
521 * Log an input event. We call this internally from each of the event
522 * input routines to add the event to any event or command log we're
523 * creating.
524 */
525 aioLogInputEvent(evt)
526 {
527 /* if the system is maintaining its own input log, write it there */
528 logInputEvent(evt);
529
530 /* get the script globals */
531 local ltyp = browserGlobals.logFileType;
532 local log = browserGlobals.logFile;
533
534 /* get the basic event parameters */
535 local evtType = evt[1];
536 local param = (evt.length() > 1 ? evt[2] : nil);
537
538 /* format the event based on the event type */
539 switch (ltyp)
540 {
541 case LogTypeTranscript:
542 /* transcript - echo command line input */
543 if (evt[1] == InEvtLine)
544 log.writeToStream(evt[2].htmlify() + '\n');
545 break;
546
547 case LogTypeCommand:
548 /* command script - write command inputs only */
549 if (evt[1] == InEvtLine)
550 log.writeFile('>' + evt[2] + '\n');
551 break;
552
553 case LogTypeScript:
554 /* event script - write all event types */
555 switch (evtType)
556 {
557 case InEvtKey:
558 log.writeFile('<key>' + evtCharForScript(param));
559 break;
560
561 case InEvtTimeout:
562 log.writeFile('<timeout>' + param);
563 break;
564
565 case InEvtHref:
566 log.writeFile('<href>' + param);
567 break;
568
569 case InEvtNoTimeout:
570 log.writeFile('<notimeout>');
571 break;
572
573 case InEvtEof:
574 log.writeFile('<eof>');
575 break;
576
577 case InEvtLine:
578 log.writeFile('<line>' + param);
579 break;
580
581 case InEvtSysCommand:
582 log.writeFile('<command>' + param);
583 break;
584
585 case InEvtEndQuietScript:
586 log.writeFile('<endqs>');
587 break;
588
589 default:
590 /* if it's a string value, it's the literal event tag */
591 if (dataType(evtType) == TypeSString)
592 log.writeFile(evtType + param);
593 break;
594 }
595
596 /* add a newline at the end of the event line */
597 log.writeFile('\n');
598 break;
599 }
600
601 /*
602 * return the event, so that the caller can conveniently return it
603 * after logging it
604 */
605 return evt;
606 }
607
608 /*
609 * Get an InEvtKey event parameter in suitable format for script file
610 * output. This returns the key as it appears in the event, except that
611 * ASCII control characters are translated to '[ctrl-X]'.
612 */
613 evtCharForScript(c)
614 {
615 if (c.toUnicode(1) < 32)
616 {
617 /* it's a control character - return the [ctrl-X] sequence */
618 return '[ctrl-<<makeString(c.toUnicode(1) + 64)>>]';
619 }
620 else
621 {
622 /* return everything else as it appears in the event descriptor */
623 return c;
624 }
625 }
626
627
628 /* ------------------------------------------------------------------------ */
629 /*
630 * Generate a string to show hyperlinked text. The browser UI is always
631 * in HTML mode, so we unconditionally generate the hyperlink.
632 *
633 * If the display text is included, we'll generate the entire link,
634 * including the <A HREF> tag, the hyperlinked text contents, and the
635 * </A> end tag. If the text is omitted, we'll simply generate the <A
636 * HREF> tag itself, leaving it to the caller to display the text and the
637 * </A>.
638 *
639 * The optional 'flags' is a combination of AHREF_xxx flags indicating
640 * any special properties of the hyperlink.
641 */
642 aHref(href, txt?, title?, flags = 0)
643 {
644 /* figure extra properties, based on the flags */
645 local props = '';
646 if (flags & AHREF_Plain)
647 props += 'class="plain" ';
648
649 /* generate the <A HREF>, text, and </A>, as applicable */
650 return '<a <<props>> href="<<href.findReplace('"', '%22')>>"<<
651 (title != nil
652 ? ' title="' + title.findReplace('"', '&#34;') + '"'
653 : '')
654 >> onclick="javascript:return gamehref(event,\'<<
655 href.findReplace(['\'', '"'],
656 ['\\\'', '\'+String.fromCharCode(34)+\''])
657 >>\', \'main.command\', this);"><.a><<
658 (txt != nil ? txt + '<./a></a>' : '')>>';
659 }
660
661 /* ------------------------------------------------------------------------ */
662 /*
663 * Generate a string to show hyperlinked text, with alternate text if
664 * we're not in HTML mode. The browser UI is always in HTML mode, so we
665 * unconditionally generate the hyperlink.
666 */
667 aHrefAlt(href, linkedText, altText, title?)
668 {
669 return aHref(href, linkedText, title);
670 }
671
672 /* ------------------------------------------------------------------------ */
673 /*
674 * The standard main command window.
675 */
676 transient commandWin: WebCommandWin
677 ;
678
679
680 /* ------------------------------------------------------------------------ */
681 /*
682 * Generate HTML to wrap the left/right portions of the status line. The
683 * basic status line has three stages: stage 0 precedes the left portion,
684 * stage 1 comes between the left and right portions, and stage 2 follows
685 * the right portion. If we're listing exits, we get two more stages:
686 * stage 3 precedes the exit listing, stage 4 follows it.
687 */
688 statusHTML(stage)
689 {
690 switch(stage)
691 {
692 case 0:
693 /* start the left-aligned portion */
694 return '<div class="statusleft">';
695
696 case 1:
697 /* close the left portion, and start the right-aligned portion */
698 return '</div><div class="statusright">';
699
700 case 2:
701 /*
702 * Close the right portion, and break clear of the floating
703 * sections. The break is necessary to make sure that the
704 * contents of the two sections count in the window height; some
705 * browsers don't include floating boxes in the content height,
706 * so we need to manually extend the main vertical box's height
707 * past the floating sections.
708 */
709 return '</div><div class="statusStrut"></div>';
710
711 case 3:
712 case 4:
713 /* before/after exit listing - we have nothing to add here */
714 return '';
715
716 default:
717 return '';
718 }
719 }
720
721 /* ------------------------------------------------------------------------ */
722 /*
723 * Web Banner Window. This is designed as a *partial* drop-in
724 * replacement for the BannerWindow class, using Web UI windows as
725 * implemented in the core TADS javascript client.
726 *
727 * This class is designed to be mixed with a WebWindow subclass.
728 *
729 * This isn't a complete replacement for BannerWindow, because the layout
730 * model for the Web UI is different from the banner window model (the
731 * Web UI model is better and more flexible). This class implements the
732 * parts of the BannerWindow API related to the stream-oriented output to
733 * the window, so you shouldn't have to change anything that writes HTML
734 * text to the window. However, you will have to rework code that sets
735 * up the window's layout to use the Web UI model.
736 */
737 class WebBannerWin: OutputStreamWindow
738 /*
739 * Initialize. Call this when first displaying the window in the UI.
740 */
741 init()
742 {
743 /* set up our output stream */
744 createOutputStream();
745 }
746
747 /* create our output stream subclass */
748 createOutputStreamObj()
749 {
750 return new transient WebWinOutputStream(self);
751 }
752
753 /* flush output */
754 flushBanner()
755 {
756 flushWin();
757 }
758
759 /* write text */
760 writeToBanner(txt)
761 {
762 outputStream_.writeToStream(txt);
763 }
764
765 /*
766 * Banner window size settings. We simply ignore these; callers must
767 * rework their layout logic for the Web UI, since the javascript
768 * layout system is so different.
769 */
770 setSize(siz, units, advisory) { }
771 sizeToContents() { }
772 ;
773
774 /*
775 * Output stream for web banner windows
776 */
777 class WebWinOutputStream: OutputStream
778 /* construct */
779 construct(win)
780 {
781 /* do the base class construction */
782 inherited();
783
784 /* save our window */
785 win_ = win;
786 }
787
788 /* ignore preinit - we're always created dynamically */
789 execute() { }
790
791 /* write to the underlying window */
792 writeFromStream(txt)
793 {
794 /* add the text to the window */
795 win_.write(txt);
796 }
797
798 /* our status line window */
799 win_ = nil
800 ;
801
802 /* ------------------------------------------------------------------------ */
803 /*
804 * The basic status line window. The "banner" in the name is historical,
805 * because the traditional console UI implements the status line as a
806 * banner window. We don't actually have banner windows in the Web UI;
807 * we use iframes instead. But we keep the name to make it easier to
808 * port games written for the traditional UI to the Web UI.
809 */
810 transient statuslineBanner: WebStatusWin, WebBannerWin
811 ;
812