Debian Codegraph @

terps/tads/tads3/lib/webui.t

raw
1 #charset "us-ascii"
2
3 /*
4 * Copyright (c) 2010 Michael J. Roberts. All Rights Reserved.
5 *
6 * This module defines some useful helper functions for implementing a
7 * TADS game with a Web-based user interface.
8 */
9
10 #include <tads.h>
11 #include <tadsnet.h>
12 #include <httpsrv.h>
13 #include <httpreq.h>
14 #include <strbuf.h>
15 #include <file.h>
16
17 /* ------------------------------------------------------------------------ */
18 /*
19 * write a message to the system debug log
20 */
21 #define DbgMsg(msg) t3DebugTrace(T3DebugLog, msg)
22
23
24 /* ------------------------------------------------------------------------ */
25 /*
26 * Session timeout settings. Times are in milliseconds.
27 */
28
29 /*
30 * Housekeeping interval. We'll wait at least this long between
31 * housekeeping passes.
32 */
33 #define HousekeepingInterval 15000
34
35 /*
36 * Session startup timeout. When we first start up, we'll give our first
37 * client this long to establish a connection. If we don't hear anything
38 * from a client within this interval, we'll assume that the client
39 * exited before it had a chance to set up its first connection, so we'll
40 * terminate the server.
41 */
42 #define SessionStartupTimeout 90000
43
44 /*
45 * Ongoing session timeout. After we've received our first connection,
46 * we'll terminate the server if we go this long without any active
47 * connections.
48 */
49 #define SessionTimeout 120000
50
51 /*
52 * Event request timeout. After an event request from a client has been
53 * sitting in the queue for longer than this limit, we'll send a "keep
54 * alive" reply to let the client know that we're still here. The client
55 * will just turn around and send a new request. This periodic handshake
56 * lets the client know we're still alive, and vice versa.
57 */
58 #define EventRequestTimeout 90000
59
60 /*
61 * Client session timeout. If we haven't seen a request from a given
62 * client within this interval, we'll assume that the client has
63 * disconnected, and we'll drop the client session state on this end.
64 */
65 #define ClientSessionTimeout 60000
66
67
68
69 /* ------------------------------------------------------------------------ */
70 /*
71 * Some handy Vector extensions
72 */
73 modify Vector
74 push(ele) { append(ele); }
75 pop() { return getAndRemove(length()); }
76 shift() { return getAndRemove(1); }
77
78 getAndRemove(idx)
79 {
80 /* get the element */
81 local ret = self[idx];
82
83 /* remove it */
84 removeElementAt(idx);
85
86 /* return the popped element */
87 return ret;
88 }
89
90 clear()
91 {
92 if (length() > 0)
93 removeRange(1, length());
94 }
95 ;
96
97 /* ------------------------------------------------------------------------ */
98 /*
99 * HTTPRequest extensions
100 */
101 modify HTTPRequest
102 /*
103 * Send a reply, catching "socket disconnect" exceptions. In most
104 * cases, server objects will want to use this method rather than the
105 * native sendReply() so that they won't have to handle disconnect
106 * exceptions manually.
107 *
108 * Disconnect exceptions are common with HTTP: the protocol is
109 * stateless by design, so clients can close their sockets at any
110 * time. Most modern browsers use HTTP 1.1, which allows the client
111 * to maintain an open socket indefinitely and reuse it serially for
112 * multiple requests, but browsers tend to close these reusable
113 * sockets after a few minutes of inactivity.
114 *
115 * When this routine encounters a disconnected socket, it deletes the
116 * client session record for the request, and then otherwise ignores
117 * the error. This generally makes the client's socket management
118 * transparent to the server, since if the client is still running
119 * they'll just connect again with a new socket and retry any lost
120 * requests.
121 */
122 sendReplyCatch(reply, contType?, stat?, headers?)
123 {
124 /* catch any errors */
125 try
126 {
127 /* try sending the reply */
128 sendReply(reply, contType, stat, headers);
129 }
130 catch (SocketDisconnectException sde)
131 {
132 /* notify the associated client session of the disconnect */
133 local client = ClientSession.find(self);
134 if (client != nil)
135 client.checkDisconnect();
136 }
137 }
138 ;
139
140 /* ------------------------------------------------------------------------ */
141 /*
142 * Web UI Session object. This keeps track of miscellaneous items
143 * associated with the game session.
144 */
145 transient webSession: object
146 /*
147 * Get the full URL to the given resource.
148 */
149 getFullUrl(resname)
150 {
151 return 'http://<<server.getAddress()>>:<<
152 server.getPortNum()>><<resname>>';
153 }
154
155 /*
156 * Connect to the UI. By default, we ask the webMainWin object to
157 * establish a connection, and we save the server object internally
158 * for future reference.
159 */
160 connectUI(srv)
161 {
162 /* connect the UI to the main window object */
163 webMainWin.connectUI(srv);
164
165 /* save a reference to the server object */
166 server = srv;
167
168 /*
169 * set the zero point for the connection time - for timeout
170 * purposes, the countdown starts now, since we obviously can't
171 * have a connection before this point
172 */
173 lastClientTime = getTime(GetTimeTicks);
174 }
175
176 /*
177 * The session key. This identifies the server as a whole, and is
178 * essentially an authentication mechanism that lets clients prove
179 * they got our address from an authorized source (rather than just
180 * stumbling across it via a port scan, say). Clients must hand this
181 * to us on each request, either via a URL query parameter or via a
182 * cookie. The normal setup (via WebResourceInit) is for the client
183 * to send us the key as a URL parameter on the initial request, at
184 * which point we'll pass it back as a set-cookie, removing the need
185 * for the client to include the key in subsequent URLs.
186 *
187 * The key is just a random number that's long enough that an
188 * interloper couldn't hope to guess it. We generate this on the
189 * first evaluation, and it remains fixed at that point for as long
190 * as we're running.
191 */
192 sessionKey = (sessionKey = generateRandomKey())
193
194 /*
195 * The collaborative session key. This is a secondary session key
196 * that allows additional users to connect to the session for
197 * collaborative play.
198 */
199 collabKey = (collabKey = generateRandomKey())
200
201 /*
202 * Validate a session key sent from the client
203 */
204 validateKey(req, query)
205 {
206 /* get the key, either from the query string or from a cookie */
207 local rkey = query['TADS_session'];
208 if (rkey == nil)
209 rkey = req.getCookie('TADS_session');
210
211 /* if there's no key, it's an error */
212 if (rkey == nil)
213 {
214 /* no key -> bad request */
215 req.sendReply(400);
216 return nil;
217 }
218
219 /* the key has to match either the main key or the collab key */
220 if (rkey != sessionKey && rkey != collabKey)
221 {
222 /* invalid key -> forbidden */
223 req.sendReply(403);
224 return nil;
225 }
226
227 /* the session key is valid */
228 return true;
229 }
230
231 /*
232 * The launcher's game ID. This is the ID passed from the web server
233 * that launched the game, to let us know how the game is identified
234 * in the launcher database. This is typically an IFDB TUID string.
235 */
236 launcherGameID = nil
237
238 /*
239 * The launcher's user name. This is passed from the web server that
240 * launched the game, to let us know the host user's screen name. We
241 * use this as the user's default screen name in multi-user games.
242 */
243 launcherUsername = 'Host'
244
245 /*
246 * The primary storage server session ID, for the user who launched
247 * the server. If the user who launched the game logged in to a
248 * cloud storage server, this is the session ID that we use to
249 * transact business with the server on behalf of this logged-in
250 * user. This token identifies and authenticates the user, but it's
251 * ephemeral and it's only valid for the current game server session,
252 * so it's not quite like a password. This is the session for the
253 * launch user only; if other collaborative users join, they can get
254 * their own session IDs that will allow them to store files under
255 * their own private user folders on the server.
256 */
257 storageSID = nil
258
259 /*
260 * Get the collaborative player launch URL. This is a URL that the
261 * host can send to other players who wish to join the session as
262 * collaborative users.
263 */
264 getCollabUrl()
265 {
266 /* return the main window URL */
267 return webSession.getFullUrl(
268 '<<webMainWin.vpath>>?TADS_session=<<collabKey>>');
269 }
270
271 /* list of active client sessions (ClientSession objects) */
272 clientSessions = static new transient Vector()
273
274 /* add a client session */
275 addClient(s)
276 {
277 clientSessions.append(s);
278 lastClientTime = getTime(GetTimeTicks);
279 everHadClient = true;
280 }
281
282 /* remove a client session */
283 removeClient(s)
284 {
285 clientSessions.removeElement(s);
286 lastClientTime = getTime(GetTimeTicks);
287 }
288
289 /* the HTTPServer object running our web session */
290 server = nil
291
292 /*
293 * Run housekeeping tasks. The network event processor calls this
294 * periodically to let us perform background cleanup tasks. Returns
295 * the system tick time of the next housekeeping run.
296 */
297 housekeeping()
298 {
299 /*
300 * if it hasn't been long enough yet since the last housekeeping
301 * run, skip this
302 */
303 if (getTime(GetTimeTicks) < hkTime)
304 return hkTime;
305
306 /* send keep-alives and check for dead client sessions */
307 clientSessions.forEach(function(s)
308 {
309 /* send keep-alives to aged-out event requests */
310 s.sendKeepAlive();
311
312 /* check to see if the client has disconnected */
313 s.checkDisconnect();
314 });
315
316 /* if there are no client sessions, check for server termination */
317 if (clientSessions.length() == 0)
318 {
319 /*
320 * There are no clients connected. If we've exceeded the
321 * maximum interval for running without a client, shut down
322 * the server. Use the initial connection time limit if
323 * we've never had a client, otherwise use the ongoing idle
324 * time limit.
325 */
326 local limit = everHadClient
327 ? SessionTimeout : SessionStartupTimeout;
328
329 if (getTime(GetTimeTicks) > lastClientTime + limit)
330 {
331 /* no clients - shut down */
332 throw new QuittingException();
333 }
334 }
335 else
336 {
337 /* we have a session as of right now */
338 lastClientTime = getTime(GetTimeTicks);
339 }
340
341 /* update the housekeeping timer */
342 return hkTime = getTime(GetTimeTicks) + HousekeepingInterval;
343 }
344
345 /* system time (ms ticks) of next scheduled housekeeping pass */
346 hkTime = 0
347
348 /* the last time we noticed that we had a client connected */
349 lastClientTime = 0
350
351 /* have we ever had a client connection? */
352 everHadClient = nil
353 ;
354
355 /*
356 * Generate a random key. This returns a 128-bit random number as a hex
357 * string. This is designed for ephemeral identifiers, such as session
358 * keys.
359 */
360 generateRandomKey()
361 {
362 /* generate a long random hex string */
363 return rand('xxxxxxxx%-xxxx%-xxxx%-xxxxxxxxxxxx%-xxxx');
364 }
365
366 /* ------------------------------------------------------------------------ */
367 /*
368 * Client session. This represents a connection to one browser (or other
369 * client application). Each browser client is a separate session, so we
370 * create one instance of this class per connected browser. Note that
371 * browser instances don't necessarily represent different users - a
372 * single user could open multiple browser windows on the same server.
373 *
374 * We identify each browser instance via a session cookie, which we
375 * establish when the client connects. The browser sends the cookie with
376 * each subsequent request, allowing us to tie the request to the browser
377 * session we previously set up.
378 */
379 class ClientSession: object
380 construct(skey, ssid)
381 {
382 /* remember my session key and storage server SID */
383 storageSID = ssid;
384
385 /* note if we're a secondary (collaborative play) user */
386 isPrimary = (skey == webSession.sessionKey);
387
388 /* add me to the master list of sessions */
389 webSession.addClient(self);
390
391 /* note our last activity time */
392 updateEventTime();
393
394 /* create a UI preferences object */
395 uiPrefs = new WebUIPrefs(self);
396 }
397
398 /* the UI preferences object for this session */
399 uiPrefs = nil
400
401 /*
402 * The client's "screen name" - this is the user-visible name that
403 * we'll show other users to identify commands and chat messages
404 * entered by this client.
405 */
406 screenName = ''
407
408 /* set the default screen name for a client */
409 setDefaultScreenName()
410 {
411 /*
412 * If this is the primary, the name is the launching user's
413 * screen name. If not, it's 'Guest N', where N is the number of
414 * guest connections we have.
415 */
416 screenName = (isPrimary ? webSession.launcherUsername :
417 'Guest <<webSession.clientSessions.countWhich(
418 {x: !x.isPrimary})>>');
419 }
420
421 /* the client's IFDB user ID (a "TUID"), if logged in to IFDB */
422 ifdbTuid = nil
423
424 /* the list of pending event requests from this client */
425 pendingReqs = perInstance(new Vector())
426
427 /*
428 * The client's event queue. When a server-to-client event occurs,
429 * we post it to each current client's queue. When the client sends
430 * a get-event request, we satisfy it out of this queue.
431 */
432 pendingEvts = perInstance(new Vector())
433
434 /*
435 * The client session key. This identifies the client across
436 * requests. We send this to the client as a cookie when they
437 * connect, so we get it back on each request.
438 */
439 clientKey = perInstance(generateRandomKey())
440
441 /*
442 * The storage server session key for the user connected to this
443 * session, if any. We can have multiple users logged in to the game
444 * in collaborative play mode, each with their own separate storage
445 * server session. This allows each user to have their own private
446 * preference settings, saved games, etc.
447 */
448 storageSID = nil
449
450 /*
451 * Am I the primary player? This is true if the player connected
452 * using the primary session key. Collaborative players join through
453 * the separate collaborative session key.
454 */
455 isPrimary = nil
456
457 /*
458 * Is this session alive? When we detect that the client has
459 * disconnected, we'll set this to nil. When waiting for a client in
460 * a modal event loop, this can be used to terminate the wait if the
461 * client disconnects.
462 */
463 isAlive = true
464
465 /*
466 * Last request time, in system ticks (ms). We use this to determine
467 * how long it's been since we've heard from the client, for timeout
468 * purposes. This is updated any time we receive a command or event
469 * request from the client, and each time we successfully send an
470 * event reply.
471 */
472 lastEventTime = 0
473
474 /* update the last event time for this client */
475 updateEventTime() { lastEventTime = getTime(GetTimeTicks); }
476
477 /* class method: broadcast an event message to all connected clients */
478 broadcastEvent(msg)
479 {
480 /* send the event to each client in our active list */
481 webSession.clientSessions.forEach({ c: c.sendEvent(msg) });
482 }
483
484 /* send an event to this client */
485 sendEvent(msg)
486 {
487 /* enqueue the event, then match it to a request if possible */
488 pendingEvts.push(msg);
489 processQueues();
490 }
491
492 /* receive an event request from the client */
493 requestEvent(req)
494 {
495 /* enqueue the request, then match it to an event if possible */
496 pendingReqs.push(new ClientEventRequest(req));
497 processQueues();
498 }
499
500 /* flush outstanding events for this client */
501 flushEvents()
502 {
503 /* discard any queued events */
504 pendingEvts.clear();
505
506 /* send no-op replies to any pending event requests */
507 while (pendingReqs.length() > 0)
508 {
509 /* pull out the first request */
510 local req = pendingReqs.shift();
511
512 /*
513 * Send a reply. Ignore any errors: the client probably
514 * canceled their side of the socket already, so we'll
515 * probably get a socket error sending the reply. Since
516 * we're just canceling the request anyway, this is fine.
517 */
518 try
519 {
520 /* send a no-op reply */
521 req.req.sendReply('<?xml version="1.0"?><noOp></noOp>',
522 'text/xml', 200);
523
524 /* update the successful communications time */
525 updateEventTime();
526 }
527 catch (Exception exc)
528 {
529 /*
530 * ignore errors - the client probably canceled their
531 * side of the socket already, so we'll probably fail
532 * sending the reply
533 */
534 }
535 }
536 }
537
538 /*
539 * Send a keep-alive reply to each pending request from this client
540 * that's been waiting for longer than the timeout interval.
541 *
542 * Javascript clients in principle will wait indefinitely for an
543 * XmlHttpRequest to complete, but in practice browsers tend to set
544 * fairly long but finite time limits. If the time limit is exceeded
545 * for a request, the client will fail the request with an error. To
546 * prevent this, our main event loop (processNetRequests)
547 * periodically calls this routine if no other events have occurred
548 * recently. We'll clear out the pending event request queue for
549 * each client by sending a no-op reply to each event. This tells
550 * the client that the server is still alive and connected but has
551 * nothing new to report.
552 */
553 sendKeepAlive()
554 {
555 /*
556 * Send no-op replies to any requests that have been in the queue
557 * for longer than the maximum event wait interval. New requests
558 * are added to the end of the queue, so the first item in the
559 * queue is the oldest.
560 */
561 local t = getTime(GetTimeTicks);
562 while (pendingReqs.length() > 0 && t >= pendingReqs[1].reqTimeout)
563 {
564 /* pull out the oldest request */
565 local req = pendingReqs.shift();
566
567 try
568 {
569 /* send a no-op reply */
570 req.req.sendReply(
571 '<?xml version="1.0"?><event><keepAlive/></event>',
572 'text/xml', 200,
573 ['Cache-control: no-store, no-cache, '
574 + 'must-revalidate, post-check=0, pre-check=0',
575 'Pragma: no-cache',
576 'Expires: Mon, 26 Jul 1997 05:00:00 GMT']);
577
578 /* successful communications, so note the last up time */
579 updateEventTime();
580 }
581 catch (Exception exc)
582 {
583 /* couldn't send the reply - consider disconnecting */
584 checkDisconnect();
585 }
586 }
587 }
588
589 /* broadcast a downloadable file to all clients */
590 broadcastDownload(desc)
591 {
592 /* add the download to all clients */
593 webSession.clientSessions.forEach({c: c.addDownload(desc)});
594 }
595
596 /* add a download to this client */
597 addDownload(desc)
598 {
599 /* add the download to the table */
600 downloads[desc.resName] = desc;
601 }
602
603 /*
604 * Cancel a downloadable file. Removes the file from the download
605 * list and notifies the client that the file is no longer available.
606 */
607 cancelDownload(desc)
608 {
609 /* remove the file from our table */
610 downloads.removeElement(desc.resName);
611
612 /* tell the client that the file is no longer available */
613 webMainWin.sendWinEventTo(
614 '<cancelDownload><<desc.resPath.htmlify()>></cancelDownload>',
615 self);
616 }
617
618 /* this client's list of downloadable temporary files */
619 downloads = perInstance(new LookupTable())
620
621 /* get a list of all of my downloadable files */
622 allDownloads() { return downloads.valsToList(); }
623
624 /* process the request and response queues */
625 processQueues()
626 {
627 /* keep going as long as we have requests and responses to pair up */
628 while (pendingReqs.length() > 0 && pendingEvts.length() > 0)
629 {
630 /* pull the first element out of each list */
631 local req = pendingReqs.shift();
632 local evt = pendingEvts[1];
633
634 /*
635 * Answer the request with the event. Since this is an API
636 * request masquerading as a page view, we need to generate a
637 * live reply to each new request to the same virtual
638 * resource path. So, include some headers to tell the
639 * browser and any proxies not to cache the reply.
640 */
641 try
642 {
643 /* send the reply */
644 req.req.sendReply(
645 evt, 'text/xml', 200,
646 ['Cache-control: no-store, no-cache, '
647 + 'must-revalidate, post-check=0, pre-check=0',
648 'Pragma: no-cache',
649 'Expires: Mon, 26 Jul 1997 05:00:00 GMT']);
650
651 /* we've successfully sent the event - discard it */
652 pendingEvts.shift();
653
654 /* update the successful communications time */
655 updateEventTime();
656 }
657 catch (SocketDisconnectException sde)
658 {
659 /* the socket has been disconnected - consider disconnecting */
660 checkDisconnect();
661 }
662 catch (Exception exc)
663 {
664 /*
665 * Ignore other errors, since we can just turn around and
666 * send the event again in response to the next event
667 * request from the client - no information will be lost,
668 * since we still have the event in the queue.
669 */
670 }
671 }
672 }
673
674 /* wait for the queues to empty in preparation for shutting down */
675 shutdownWait(timeout)
676 {
677 /* process network requests until all clients disconnect */
678 processNetRequests({: webSession.clientSessions.length() == 0 },
679 timeout);
680 }
681
682 /*
683 * Check to see if the client is still alive. If the client has no
684 * pending event requests, and we haven't heard from the client in
685 * more than the client session timeout interval, assume the client
686 * is no longer connected and kill the session object.
687 *
688 * This should be called whenever a sending a reply to a request
689 * fails with a Socket Disconnect exception. We also run this
690 * periodically during routine housekeeping to check for clients that
691 * haven't even bothered to send a request.
692 */
693 checkDisconnect()
694 {
695 /* if we don't have any pending requests, kill the session */
696 if (pendingReqs.length() == 0
697 && getTime(GetTimeTicks) >= lastEventTime + ClientSessionTimeout)
698 {
699 /* remove the client session from our master list */
700 webSession.removeClient(self);
701
702 /* the session is now dead */
703 isAlive = nil;
704 }
705 }
706
707 /*
708 * Class method: forcibly disconnect all clients. This simply
709 * deletes the list of active clients and deletes any pending events
710 * in their queues. This doesn't actually terminate their network
711 * connections, but simply clears out any pending work for each
712 * client that we've initiated on the server side.
713 */
714 disconnectAll()
715 {
716 /* delete all pending events for each client */
717 webSession.clientSessions.forEach({ s: s.pendingReqs.clear() });
718
719 /* delete the client list */
720 webSession.clientSessions.clear();
721 }
722
723 /*
724 * Class method: Find a client session, given the session key or an
725 * HTTPRequest object.
726 */
727 find(key)
728 {
729 /*
730 * if the key is given as an HTTPRequest, find the key by URL
731 * parameter or cookie
732 */
733 if (dataType(key) == TypeObject && key.ofKind(HTTPRequest))
734 {
735 /* get the request */
736 local req = key;
737
738 /* try the URL parameters and cookies */
739 if ((key = req.getQueryParam('TADS_client')) == nil
740 && (key = req.getCookie('TADS_client')) == nil)
741 {
742 /* there's no client key, so there's no client */
743 return nil;
744 }
745 }
746
747 /* find the client that matches the key string */
748 return webSession.clientSessions.valWhich({ x: x.clientKey == key });
749 }
750
751 /*
752 * Get the primary session. This is the session for the original
753 * initiating user (the "host" in a multi-user game).
754 */
755 getPrimary()
756 {
757 /* scan for a session with the host session key */
758 return webSession.clientSessions.valWhich({ x: x.isPrimary });
759 }
760 ;
761
762 /* ------------------------------------------------------------------------ */
763 /*
764 * Client event request. Each client session object keeps a queue of
765 * pending event requests, representing incoming "GET /webui/getEvent"
766 * requests that have yet to be answered.
767 */
768 class ClientEventRequest: object
769 construct(req)
770 {
771 self.req = req;
772 reqTimeout = getTime(GetTimeTicks) + EventRequestTimeout;
773 }
774
775 /* the underlying HTTPRequest object */
776 req = nil
777
778 /*
779 * The system time (ms ticks) when the request times out. If we
780 * don't have an actual event to send in response by this time, the
781 * housekeeper will generate a no-op reply just to let the client
782 * know that we're still here.
783 */
784 reqTimeout = 0
785 ;
786
787
788
789 /* ------------------------------------------------------------------------ */
790 /*
791 * A WebResource is a virtual file accessible via the HTTP server. Each
792 * resource object has a path, which can be given as a simple string that
793 * must be matched exactly, or as a RexPattern object with a regular
794 * expression to be matched. Each object also has a "processRequest"
795 * method, which the server invokes to answer the request when the path
796 * is matched.
797 */
798 class WebResource: object
799 /*
800 * The virtual path to the resource. This is the apparent URL path
801 * to this resource, as seen by the client.
802 *
803 * URL paths follow the Unix file system conventions in terms of
804 * format, but don't confuse the virtual path with an actual file
805 * system path. The vpath doesn't have anything to do with the disk
806 * file system on the server machine or anywhere else. That's why we
807 * call it "virtual" - it's merely the apparent location, from the
808 * client's perspective.
809 *
810 * When the server receives a request from the client, it looks at
811 * the URL sent by the client to determine which WebResource object
812 * should handle the request. The server does this by matching the
813 * resource path portion of the URL to the virtual path of each
814 * WebResource, until it finds a WebResource that matches. The
815 * resource path in the URL is the part of the URL following the
816 * domain, and continuing up to but not including any "?" query
817 * parameters. The resource path always starts with a slash "/".
818 * For example, for the URL "http://192.168.1.15/test/path?param=1",
819 * the resource path would be "/test/path".
820 *
821 * The virtual path can be given as a string or as a RexPattern. If
822 * it's a string, a URL resource path must match the virtual path
823 * exactly, including upper/lower case. If the virtual path is given
824 * as a RexPattern, the URL resource path will be matched to the
825 * pattern with the usual regular expression rules.
826 */
827 vpath = ''
828
829 /*
830 * Process the request. This is invoked when we determine that this
831 * is the highest priority resource object matching the request.
832 * 'req' is the HTTPRequest object; 'query' is the parsed query data
833 * as returned by req.parseQuery(). The query information is
834 * provided for convenience, in case the result depends on the query
835 * parameters.
836 */
837 processRequest(req, query)
838 {
839 /* by default, just send an empty HTML page */
840 req.sendReply('<html><title>TADS</title></html>', 'text/html', 200);
841 }
842
843 /*
844 * The priority of this resource. If the path is given as a regular
845 * expression, a given request might match more than one resource.
846 * In such cases, the matching resource with the highest priority is
847 * the one that's actually used to process the request.
848 */
849 priority = 100
850
851 /*
852 * The group this resource is part of. This is the object that
853 * "contains" the resource, via its 'contents' property; any object
854 * will work here, since it's just a place to put the contents list
855 * for the resource group.
856 *
857 * By default, we put all resources into the mainWebGroup object.
858 *
859 * The point of the group is to allow different servers to use
860 * different sets of resources, or to allow one server to use
861 * different resource sets under different circumstances. When a
862 * server processes a request, it does so by looking through the
863 * 'contents' list for a group of its choice.
864 */
865 group = mainWebGroup
866
867 /*
868 * Determine if this resource matches the given request. 'query' is
869 * the parsed query from the request, as returned by
870 * req.parseQuery(). 'req' is the HTTPRequest object representing
871 * the request; you can use this to extract more information from the
872 * request, such as cookies or the client's network address.
873 *
874 * This method returns true if the request matches this resource, nil
875 * if not.
876 *
877 * You can override this to specify more complex matching rules than
878 * you could achieve just by specifying the path string or
879 * RexPattern. For example, you could make the request conditional
880 * on the time of day, past request history, cookies in the request,
881 * parameters, etc.
882 */
883 matchRequest(query, req)
884 {
885 /* get the query path */
886 local qpath = query[1];
887
888 /* by default, we match GET */
889 local verb = req.getVerb().toUpper();
890 if (verb != 'GET' && verb != 'POST')
891 return nil;
892
893 /* if the virtual path a string, simply match the string exactly */
894 if (dataType(vpath) == TypeSString)
895 return vpath == qpath;
896
897 /* if it's a regular expression, match the pattern */
898 if (dataType(vpath) == TypeObject && vpath.ofKind(RexPattern))
899 return rexMatch(vpath, qpath) != nil;
900
901 /* we can't match other path types */
902 return nil;
903 }
904
905 /*
906 * Send a generic request acknowledgment or reply. This wraps the
907 * given XML fragment in an XML document with the root type given by
908 * the last element in our path name. If the 'xml' value is omitted,
909 * we send "<ok/>" by default.
910 */
911 sendAck(req, xml = '<ok/>')
912 {
913 /*
914 * Figure the XML document root element. If we have a non-empty
915 * path, use the last element of the path (as delimited by '/'
916 * characters). Otherwise, use a default root of <reply>.
917 */
918 local root = 'reply';
919 if (dataType(vpath) == TypeSString
920 && vpath.length() > 0
921 && rexSearch(vpath, '/([^/]+)$') != nil)
922 root = rexGroup(1)[3];
923
924 /* send the reply, wrapping the fragment in a proper XML document */
925 sendXML(req, root, xml);
926 }
927
928 /*
929 * Send an XML reply. This wraps the given XML fragment in an XML
930 * document with the given root element.
931 */
932 sendXML(req, root, xml)
933 {
934 req.sendReply('<?xml version="1.0"?>\<<<root>>><<xml>></<<root>>>',
935 'text/xml', 200);
936 }
937 ;
938
939 /* ------------------------------------------------------------------------ */
940 /*
941 * A resource file request handler. This handles a request by sending
942 * the contents of the resource file matching the given name.
943 *
944 * To expose a bundled game resource as a Web object that the client can
945 * access and download via HTTP, simply create an instance of this class,
946 * and set the virtual path (the vpath property) to the resource name.
947 * See coverArtResource below for an example - that object creates a URL
948 * for the Cover Art image so that the browser can download and display
949 * it.
950 *
951 * You can expose *all* bundled resources in the entire game simply by
952 * creating an object like this:
953 *
954 *. WebResourceResFile
955 *. vpath = static new RexPattern('/')
956 *. ;
957 *
958 * That creates a URL mapping that matches *any* URL path that
959 * corresponds to a bundled resource name. The library intentionally
960 * doesn't provide an object like this by default, as a security measure;
961 * the default configuration as a rule tries to err on the side of
962 * caution, and in this case the cautious thing to do is to hide
963 * everything by default. There's really no system-level security risk
964 * in exposing all resources, since the only files available as resources
965 * are files you explicitly bundle into the build anyway; but even so,
966 * some resources might be for internal use within the game, so we don't
967 * want to just assume that everything should be downloadable.
968 *
969 * You can also expose resources on a directory-by-directory basis,
970 * simply by specifying a longer path prefix:
971 *
972 *. WebResourceResFile
973 *. vpath = static new RexPattern('/graphics/')
974 *. ;
975 *
976 * Again, the library doesn't define anything like this by default, since
977 * we don't want to impose any assumptions about how your resources are
978 * organized.
979 */
980 class WebResourceResFile: WebResource
981 /*
982 * Match a request. A resource file resource matches if we match the
983 * virtual path setting for the resource, and the requested resource
984 * file exists.
985 */
986 matchRequest(query, req)
987 {
988 return inherited(query, req) && resExists(processName(query[1]));
989 }
990
991 /* process the request: send the resource file's contents */
992 processRequest(req, query)
993 {
994 /* get the local resource name */
995 local name = processName(query[1]);
996
997 /* get the filename suffix (extension) */
998 local ext = nil;
999 if (rexSearch('%.([^.]+)$', name) != nil)
1000 ext = rexGroup(1)[3];
1001
1002 local fp = nil;
1003 try
1004 {
1005 /* open the file in the appropriate mode */
1006 if (isTextFile(name))
1007 fp = File.openTextResource(name);
1008 else
1009 fp = File.openRawResource(name);
1010 }
1011 catch (FileException exc)
1012 {
1013 /* send a 404 error */
1014 req.sendReply(404);
1015 return;
1016 }
1017
1018 /*
1019 * If the file suffix implies a particular mime type, set it.
1020 * There are some media types that are significant to browsers,
1021 * but which the HTTPRequest object can't infer based on the
1022 * contents, so as a fallback infer the media type from the
1023 * filename suffix if possible.
1024 */
1025 local mimeType = browserExtToMime[ext];
1026
1027 /*
1028 * Send the file's contents. Since resource files can be large
1029 * (e.g., images or audio files), send the reply asynchronously
1030 * so that we don't block other requests while the file is being
1031 * downloaded. Browsers typically download multimedia resources
1032 * in background threads so that the UI remains responsive during
1033 * large downloads, so we have to be prepared to handle these
1034 * overlapped requests while a download proceeds.
1035 */
1036 req.sendReplyAsync(fp, mimeType);
1037
1038 /* done with the file */
1039 fp.closeFile();
1040 }
1041
1042 /* extension to MIME type map for important browser file types */
1043 browserExtToMime = static [
1044 'css' -> 'text/css',
1045 'js' -> 'text/javascript'
1046 ]
1047
1048 /*
1049 * Process the name. This takes the path string from the query, and
1050 * returns the resource file name to look for. By default, we simply
1051 * return the same name specified by the client, minus the leading
1052 * '/' (since resource paths are always relative).
1053 */
1054 processName(n) { return n.substr(2); }
1055
1056 /*
1057 * Determine if the given file is a text file or a binary file. By
1058 * default, we base the determination solely on the filename suffix,
1059 * checking the extension against a list of common file types.
1060 */
1061 isTextFile(fname)
1062 {
1063 /* get the extension */
1064 if (rexMatch('.*%.([^.]+)$', fname) != nil)
1065 {
1066 /* pull out the extension */
1067 local ext = rexGroup(1)[3].toLower();
1068
1069 /*
1070 * check against common binary types - if it's not there,
1071 * assume it's text
1072 */
1073 return (binaryExts.indexOf(ext) == nil);
1074 }
1075 else
1076 {
1077 /* no extension - assume binary */
1078 return nil;
1079 }
1080 }
1081
1082 /* table of common binary file extensions */
1083 binaryExts = ['jpg', 'jpeg', 'png', 'mng', 'bmp', 'gif',
1084 'mpg', 'mp3', 'mid', 'ogg', 'wav',
1085 'pdf', 'doc', 'docx', 'swf',
1086 'dat', 'sav', 'bin', 'gam', 't3', 't3v'];
1087 ;
1088
1089 /*
1090 * The resource handler for our standard library resources. All of the
1091 * library resources are in the /webuires resource folder. This exposes
1092 * everything in that folder as a downloadable Web object.
1093 */
1094 webuiResources: WebResourceResFile
1095 vpath = static new RexPattern('/webuires/')
1096 ;
1097
1098 /* the special cover art resource */
1099 coverArtResource: WebResourceResFile
1100 vpath = static new RexPattern('/%.system/CoverArt%.(jpg|png)$')
1101 ;
1102
1103 /*
1104 * Session initializer resource. This is a mix-in class designed to be
1105 * used for a special resource that initializes the session. Mix this
1106 * with a WebResource class to set up the initializer. When you connect
1107 * to the client via connectWebUI(), point the client to this resource.
1108 *
1109 * There are two elements to setting up the session. First, we need to
1110 * set the program session key as a cookie. The client obtains this from
1111 * the registration mechanism, whose purpose is to launch the game
1112 * program and send the connection information back to the client. The
1113 * client sends this to us in the form of a URL parameter, TADS_session.
1114 * This key is essentially for authentication, to make sure that the
1115 * client that we're talking to is actually the client that launched the
1116 * program: only that client would be able to get the key, because we
1117 * invent it and send it to the registrar, and the registrar only sends
1118 * it back to the client session it's already established on its end.
1119 * This prevents port scanners from finding our open port and trying to
1120 * crawl our "site" or otherwise access our services.
1121 *
1122 * The second setup element is to create a client session key. Whereas
1123 * the program session key is for our entire service, the client session
1124 * key is specific to this one connection. If the user opens two browser
1125 * windows on this server, each browser needs its own separate client
1126 * session so that we can tell the traffic apart. The client session key
1127 * is simply another random key we generate, and again we pass it back to
1128 * the client in a cookie.
1129 *
1130 * The reason we set cookies for both of these session keys is that it
1131 * lets the client pass the information back to us on subsequent requests
1132 * without having to encode another parameter in every URL. We set
1133 * session cookies in both cases; the program session is for
1134 * authentication purposes and so we don't want it to be stored or
1135 * shared, and the client session key is explicitly to identify this one
1136 * browser session, so it obviously shouldn't be shared across browser
1137 * instances or sessions.
1138 *
1139 * Note that instances should always provide a string (as opposed to a
1140 * regular expression) for the virtual path (the 'vpath' property). We
1141 * have to send the path to the browser UI as part of the connection
1142 * information, so we need a string we can send rather than a pattern to
1143 * match.
1144 */
1145 class WebResourceInit: object
1146 /*
1147 * Connect to the client. The program should call this after
1148 * creating its HTTPServer object, which you pass here as 'srv'.
1149 * This establishes the client UI connection, generating the path to
1150 * the start page.
1151 */
1152 connectUI(srv)
1153 {
1154 /*
1155 * point the client to our start page, adding the session key as
1156 * a query parameter
1157 */
1158 connectWebUI(srv, '<<vpath>>?TADS_session=<<webSession.sessionKey>>');
1159 }
1160
1161 /*
1162 * Process the request. This sets up the program and client session
1163 * keys as cookies.
1164 */
1165 processRequest(req, query)
1166 {
1167 /* get the session parameter from the query */
1168 local skey = query['TADS_session'];
1169
1170 /* set the session cookie in the reply */
1171 if (skey)
1172 req.setCookie('TADS_session', '<<skey>>; path=/;');
1173
1174 /* check for a client session */
1175 local ckey = req.getCookie('TADS_client');
1176 if (ckey == nil || ClientSession.find(ckey) == nil)
1177 {
1178 /*
1179 * There's no client session ID cookie, or the ID is invalid
1180 * or has expired. Create a new client session.
1181 */
1182
1183 /* get the storage server session ID key from the request */
1184 local ssid = query['storagesid'];
1185
1186 /* get the user name */
1187 local uname = query['username'];
1188
1189 /*
1190 * if there's no storage server session, and they're
1191 * connecting under the primary server session key, use the
1192 * primary user's storage server session
1193 */
1194 if (ssid == nil && skey == webSession.sessionKey)
1195 ssid = webSession.storageSID;
1196
1197 /* create the new session object */
1198 local client = new transient ClientSession(skey, ssid);
1199
1200 /* if there's a user name, set it in the session */
1201 if (uname != nil)
1202 client.screenName = uname;
1203 else
1204 client.setDefaultScreenName();
1205
1206 /* send the client session ID to the browser as a cookie */
1207 req.setCookie('TADS_client', '<<client.clientKey>>; path=/;');
1208
1209 /* if this is a guest, alert everyone to the new connection */
1210 if (!client.isPrimary)
1211 webMainWin.postSyntheticEvent('newGuest', client.screenName);
1212 }
1213
1214 /* go return the underlying resource */
1215 inherited(req, query);
1216 }
1217
1218 /* the HTPTServer for communicating with the client */
1219 server = nil
1220 ;
1221
1222 /* ------------------------------------------------------------------------ */
1223 /*
1224 * A WebResourceGroup is a container for WebResource objects. When a
1225 * server receives a request, it looks in its group list to find the
1226 * resource object that will handle the request.
1227 */
1228 class WebResourceGroup: object
1229 /*
1230 * Should this group handle the given request? By default, we say
1231 * yes if the server that received the request is associated with
1232 * this group via the group's 'server' property.
1233 */
1234 isGroupFor(req)
1235 {
1236 /* get the request's server object */
1237 local srv = req.getServer();
1238
1239 /*
1240 * if this server matches our 'server' property, or is in the
1241 * list of servers if 'server' is a list, we're the group for the
1242 * request
1243 */
1244 return (srv == server
1245 || (dataType(server) == TypeList
1246 && server.indexOf(srv) != nil));
1247 }
1248
1249 /*
1250 * The priority of the group, relative to other groups. If the same
1251 * server matches multiple groups, this allows you to designate which
1252 * group has precedence. A higher value means higher priority.
1253 */
1254 priority = 100
1255
1256 /*
1257 * The HTTPServer object or objects this group is associated with.
1258 * The general event processor uses this to route a request to the
1259 * appropriate resource group, by finding the group that's associated
1260 * with the server that received the request.
1261 *
1262 * To associate a group with multiple servers, make this a list.
1263 */
1264 server = nil
1265
1266 /* the WebResource objects in the group */
1267 contents = []
1268
1269 /*
1270 * Process a request. This looks for the highest priority matching
1271 * resource in the group, then hands the request to that resource for
1272 * processing.
1273 */
1274 processRequest(req)
1275 {
1276 /* parse the query */
1277 local query = req.parseQuery();
1278
1279 /*
1280 * Check for the session ID. The session ID is required either
1281 * in a URL parameter or in a cookie. If it's not present,
1282 * reject the request with a "403 Forbidden" error, since the
1283 * session is essentially an authentication token to tell us that
1284 * the client is in fact the same user that launched the game.
1285 */
1286 if (!webSession.validateKey(req, query))
1287 return;
1288
1289 /*
1290 * Search our list for the first resource that matches this
1291 * request. The list is initialized in descending priority
1292 * order, so the first match we find will be the one with the
1293 * highest priority.
1294 */
1295 local match = contents.valWhich({res: res.matchRequest(query, req)});
1296
1297 /* if we found a match, process it; otherwise return a 404 error */
1298 if (match != nil)
1299 match.processRequest(req, query);
1300 else
1301 req.sendReply(404);
1302 }
1303
1304 /* class property: list of all WebResourceGroup objects */
1305 all = []
1306 ;
1307
1308 /* ------------------------------------------------------------------------ */
1309 /*
1310 * The default web resource group. This is the default container for
1311 * WebResource objects.
1312 */
1313 mainWebGroup: WebResourceGroup
1314 /* the default group matches any server, but with low priority */
1315 isGroupFor(req) { return true; }
1316 priority = 1
1317 ;
1318
1319 /* ------------------------------------------------------------------------ */
1320 /*
1321 * At startup, put each WebResource object into the contents list for its
1322 * group.
1323 */
1324 PreinitObject
1325 execute()
1326 {
1327 /* build the contents list for each resource group */
1328 forEachInstance(WebResource, function(obj) {
1329
1330 /* get the group object for the resource */
1331 local g = obj.group;
1332
1333 /* if the group doesn't have a contents list yet, create one */
1334 if (g.contents == nil)
1335 g.contents = [];
1336
1337 /* add this resource to the contents list */
1338 g.contents += obj;
1339 });
1340
1341 /* sort each group's contents list in priority order */
1342 forEachInstance(WebResourceGroup, function(obj) {
1343
1344 /* sort the group's contents list */
1345 obj.contents = obj.contents.sort(
1346 SortDesc, { a, b: a.priority - b.priority });
1347
1348 /* add this group to the master list of groups */
1349 WebResourceGroup.all += obj;
1350 });
1351
1352 /* sort the groups in descending order of priority */
1353 WebResourceGroup.all = WebResourceGroup.all.sort(
1354 SortDesc, { a, b: a.priority - b.priority });
1355 }
1356 ;
1357
1358 /* ------------------------------------------------------------------------ */
1359 /*
1360 * Guest connection request. This enables "switchboard" applications on
1361 * remote servers that keep track of multi-user game sessions, to show
1362 * users available sessions and connect new users to those sessions.
1363 *
1364 * The first step in setting up a switchboard is for the game server to
1365 * register itself with the switchboard by sending a request on startup.
1366 * That part is external to us - that's not handled within the game
1367 * program but rather within the web server script that launches the
1368 * game. Here, then, we simply assume that this work is already done.
1369 *
1370 * The second step is that the switchboard needs to check back with the
1371 * game server from time to time to see if it's still alive - essentially
1372 * a "ping" operation. We handle that here: if we respond to the
1373 * request, we're obviously still alive.
1374 *
1375 * The third step is that we need to send the switchboard a URL that lets
1376 * secondary users ("guests") connect to the game session. We handle
1377 * that here as well: our reply body is the client connection URL.
1378 */
1379 guestConnectPage: WebResource
1380 vpath = '/webui/guestConnect'
1381 processRequest(req, query)
1382 {
1383 /* send the collaborative connection URL */
1384 req.sendReply(webSession.getCollabUrl(), 'text/plain', 200);
1385 }
1386 ;
1387
1388 /* ------------------------------------------------------------------------ */
1389 /*
1390 * getEvent request. This is the mechanism we use to "send" events to
1391 * the client. The client sends a getEvent request to us, and we simply
1392 * put it in a queue - we don't send back any response immediately. As
1393 * soon as we want to send an event to the client, we go through the
1394 * queue of pending getEvent requests, and reply to each one with the
1395 * event we want to send.
1396 */
1397 eventPage: WebResource
1398 vpath = '/webui/getEvent'
1399 processRequest(req, query)
1400 {
1401 /* find the client */
1402 local c = ClientSession.find(req);
1403
1404 /* if we found the client session object, send it the request */
1405 if (c != nil)
1406 c.requestEvent(req);
1407 else
1408 req.sendReply(400);
1409 }
1410
1411 /* broadcast an event message to each client */
1412 sendEvent(msg)
1413 {
1414 /* build the full XML message */
1415 msg = '<?xml version="1.0"?><event><<msg>></event>';
1416
1417 /* send it to each client */
1418 ClientSession.broadcastEvent(msg);
1419 }
1420
1421 /* send an event to a particular client */
1422 sendEventTo(msg, client)
1423 {
1424 /* build the full XML message */
1425 msg = '<?xml version="1.0"?><event><<msg>></event>';
1426
1427 /* send it to the given client */
1428 client.sendEvent(msg);
1429 }
1430 ;
1431
1432 /*
1433 * Flush events. This cancels any pending event requests for the client.
1434 * The client can use this after being reloaded to flush any outstanding
1435 * event requests from a past incarnation of the page.
1436 */
1437 flushEventsPage: WebResource
1438 vpath = '/webui/flushEvents'
1439 processRequest(req, query)
1440 {
1441 /* find the client */
1442 local c = ClientSession.find(req);
1443
1444 /* if we found the client, send it the flush request */
1445 if (c != nil)
1446 c.flushEvents();
1447
1448 /*
1449 * acknowledge the request; it's okay if we didn't find the
1450 * client session, since this just means there are no events to
1451 * flush for this client
1452 */
1453 sendAck(req);
1454 }
1455 ;
1456
1457 /*
1458 * getState request. The web page can send this to get a full accounting
1459 * of the current state of the UI. It does this automatically when first
1460 * loaded, and again when the user manually refreshes the page.
1461 *
1462 * We handle this by asking the main window to generate its state.
1463 */
1464 uiStatePage: WebResource
1465 vpath = '/webui/getState'
1466 processRequest(req, query)
1467 {
1468 /* get the window making the request */
1469 local w = webMainWin.winFromPath(query['window']);
1470 local client = ClientSession.find(req);
1471
1472 /* if we found the window, send the reply */
1473 if (w)
1474 {
1475 /* send the uiState reply for the window */
1476 sendXML(req, 'uiState', w.getState(client));
1477 }
1478 else
1479 {
1480 /* no window - send an error reply */
1481 req.sendReply(406);
1482 }
1483 }
1484 ;
1485
1486 /* ------------------------------------------------------------------------ */
1487 /*
1488 * Process network requests. Continues until doneFunc() returns true, or
1489 * a timeout or error occurs. If we return because doneFunc() returned
1490 * true, we'll return nil. Otherwise, we'll return the NetEvent that
1491 * terminated the wait.
1492 */
1493 processNetRequests(doneFunc, timeout?)
1494 {
1495 /* if there's a timeout, figure the ending time */
1496 local endTime = (timeout != nil ? getTime(GetTimeTicks) + timeout : nil);
1497
1498 /* keep going until the 'done' function returns true */
1499 while (doneFunc == nil || !doneFunc())
1500 {
1501 try
1502 {
1503 /* get the next housekeeping time */
1504 local hkTime = webSession.hkTime;
1505
1506 /*
1507 * figure the time to the next timeout - stop at the caller's
1508 * ending time, or the next housekeeping time, whichever is
1509 * sooner
1510 */
1511 local tf = (endTime != nil && endTime < hkTime ? endTime : hkTime);
1512
1513 /* figure the time remaining to the next timeout */
1514 local dt = max(0, tf - getTime(GetTimeTicks));
1515
1516 /*
1517 * Flush any pending output. If we're waiting for user
1518 * input, this ensures that the last output is visible in the
1519 * UI while we await the next user action.
1520 */
1521 flushOutput();
1522
1523 /* get the next network event */
1524 local evt = getNetEvent(dt);
1525
1526 /* see what we have */
1527 switch (evt.evType)
1528 {
1529 case NetEvRequest:
1530 /*
1531 * This is an incoming network request from a client.
1532 * Check the protocol type of the request object.
1533 */
1534 if (evt.evRequest.ofKind(HTTPRequest))
1535 {
1536 /*
1537 * HTTP request - process it through the appropriate
1538 * web resource group. First, find the group that
1539 * wants to handle the request.
1540 */
1541 local req = evt.evRequest;
1542 local group = WebResourceGroup.all.valWhich(
1543 { g: g.isGroupFor(req) });
1544
1545 /*
1546 * if there's a client associated with the request,
1547 * update its last activity time
1548 */
1549 local client = ClientSession.find(req);
1550 if (client != nil)
1551 client.updateEventTime();
1552
1553 /* if we found a group, let it handle the request */
1554 if (group != nil)
1555 {
1556 try
1557 {
1558 /* send the request to the group for processing */
1559 group.processRequest(req);
1560 }
1561 catch (Exception exc)
1562 {
1563 /*
1564 * Unhandled exception - something went wrong
1565 * in the server, so the appropriate reply is
1566 * 500 Internal Server Error. Send the
1567 * exception message with the reply.
1568 */
1569 local msg =
1570 'Unhandled exception processing request: '
1571 + exc.getExceptionMessage().specialsToText();
1572 req.sendReply(msg, 'text/plain', 500);
1573 }
1574 }
1575 else
1576 {
1577 /* no group - send back a 404 error */
1578 req.sendReply(404);
1579 }
1580 }
1581 break;
1582
1583 case NetEvTimeout:
1584 /*
1585 * Timeout. Always try running housekeeping on a
1586 * timeout; the housekeeper will ignore this unless the
1587 * time has actually come.
1588 */
1589 hkTime = webSession.housekeeping();
1590
1591 /*
1592 * Check for a caller timeout. If the caller's end time
1593 * has arrived, pass the timeout back to the caller as a
1594 * timeout event.
1595 */
1596 if (endTime != nil && getTime(GetTimeTicks) >= endTime)
1597 return evt;
1598
1599 /*
1600 * it wasn't a caller timeout, so it must have been an
1601 * internal housekeeping timeout, which we just handled;
1602 * simply continue looping
1603 */
1604 break;
1605
1606 case NetEvUIClose:
1607 /*
1608 * UI Closed. This tells us that the user has manually
1609 * closed the UI window. This only happens in the local
1610 * stand-alone configuration, where the "browser" is an
1611 * integrated part of the interpreter application,
1612 * simulating the traditional TADS interpreter setup
1613 * where the whole program is a single application
1614 * running on one machine. In this setup, closing the UI
1615 * window should dismiss the whole application, since
1616 * that's the convention on virtually all GUIs.
1617 */
1618
1619 /* disconnect all clients */
1620 ClientSession.disconnectAll();
1621
1622 /* quit by signaling a "quit game" event */
1623 throw new QuittingException();
1624 }
1625 }
1626 catch (SocketDisconnectException sdx)
1627 {
1628 /* the client has closed its connection; ignore this */
1629 }
1630 }
1631
1632 /* indicate that the 'done' condition was triggered */
1633 return nil;
1634 }
1635
1636 /* ------------------------------------------------------------------------ */
1637 /*
1638 * Web Window tracker. This is a game object that controls and remembers
1639 * the state of a "window" in the browser user interface. By "window",
1640 * we basically mean an HTML page, which might reside at the top level of
1641 * the browser itself, or inside an IFRAME element within an enclosing
1642 * page.
1643 *
1644 * Each WebWindow class corresponds to a particular HTML page that we
1645 * serve the client. The HTML page is the expression of the window in
1646 * the browser, and the WebWindow object is the expression of the same
1647 * information in the game program. The two are different facets of the
1648 * same conceptual UI object. The reason we need the two separate
1649 * expressions is that the server controls everything, but the client has
1650 * to do the actual display work, and the two parts of the program speak
1651 * different languages - the server is TADS, and the client is HTML.
1652 *
1653 * The WebWindow object on the server lets us easily reconstruct the UI
1654 * state in a newly opened browser window, or when the user performs a
1655 * page refresh. This object's job is to send information to the client
1656 * on demand that allows the client to display the page in its current
1657 * state.
1658 *
1659 * Note that a given WebWindow/HTML page combination can be used more
1660 * than once within the same UI. The pages defined in the library are
1661 * designed to be generic and reusable, so you might use the same window
1662 * class more than once for different purposes within the UI. The
1663 * library pages can also be subclassed, by subclassing the WebWindow
1664 * object and creating a customized copy of the corresponding HTML page
1665 * resource.
1666 */
1667 class WebWindow: WebResourceResFile
1668 /*
1669 * The URL path to the window's HTML definition file, as seen by the
1670 * browser. For the pre-defined library window types, we expose the
1671 * HTML file in the root of the URL namespace - e.g., "/main.htm".
1672 * The files are actually stored in the /webuires folder, but we
1673 * expose them to the browser as though they were in the root folder
1674 * to make embedded object references on the pages simpler. The
1675 * browser figures the path to an embedded object relative to the
1676 * containing page, so by placing the containing page in the root
1677 * folder, embedded object paths don't have to worry about
1678 * referencing parent folders.
1679 */
1680 vpath = nil
1681
1682 /*
1683 * The window's actual source location, as a resource path. A given
1684 * WebWindow subclass corresponds to a particular HMTL page, since
1685 * the class and the page are facets of the same conceptual object
1686 * (one facet is the browser expression, the other is the game
1687 * program expression).
1688 */
1689 src = nil
1690
1691 /* process a request path referencing me into my actual resource path */
1692 processName(n) { return src; }
1693
1694 /*
1695 * Resolve a window path name. For container windows, this should
1696 * search the sub-windows for the given path. By default, we match
1697 * simply if the path matches our name.
1698 */
1699 winFromPath(path)
1700 {
1701 return path == name ? self : nil;
1702 }
1703
1704 /*
1705 * Flush the window. This sends any buffered text to the UI.
1706 */
1707 flushWin() { }
1708
1709 /*
1710 * Write text to the window. Subclasses with stream-oriented APIs
1711 * must override this.
1712 */
1713 write(txt) { }
1714
1715 /*
1716 * Clear the window. Subclasses must override this.
1717 */
1718 clearWindow() { }
1719
1720 /*
1721 * Get the window's current state. This returns a string containing
1722 * an XML fragment that describes the state of the window. This
1723 * information is sent to the HTML page when the browser asks for the
1724 * current layout state when first loaded or when the page is
1725 * refreshed. The XML format for each subclass is specific to the
1726 * Javascript on the class's HTML page.
1727 */
1728 getState(client) { return ''; }
1729
1730 /* send an event related to this window to all clients */
1731 sendWinEvent(evt)
1732 {
1733 /*
1734 * send the event message, adding a <window> parameter to
1735 * identify the source
1736 */
1737 eventPage.sendEvent('<window><<pathName>></window><<evt>>');
1738 }
1739
1740 /* send a window event to a specific client */
1741 sendWinEventTo(evt, client)
1742 {
1743 eventPage.sendEventTo('<window><<pathName>></window><<evt>>', client);
1744 }
1745
1746 /* specialsToHtml context */
1747 sthCtx = perInstance(new SpecialsToHtmlState())
1748
1749 /* the name of this window */
1750 name = nil
1751
1752 /* the full path name of this window, in "win.sub.sub" format */
1753 pathName = nil
1754 ;
1755
1756 /* ------------------------------------------------------------------------ */
1757 /*
1758 * Layout Window. This is a specialized Web Window tracker for our
1759 * layout page type, which is displayed using the resource file
1760 * webuires/layout.htm. This page is designed as a container of more
1761 * specialized sub-window pages; its job is to divide up the window space
1762 * into IFRAME elements that display the sub-windows, and to manage the
1763 * geometry of the IFRAMEs.
1764 *
1765 * The layout page is primarily designed to be the top-level page of the
1766 * web UI. The idea is to set up a layout page as the navigation URL for
1767 * the browser, so the layout page fills the browser window. You then
1768 * arrange your functional windows within the layout page - a command
1769 * window, a status line window, etc. This arrangement is similar to
1770 * banner window in HTML TADS, but IFRAMEs are considerably more
1771 * flexible; for example, they don't have to tile the main window, and
1772 * you can size them in the full range of units CSS provides.
1773 *
1774 * Layout windows aren't limited to the top level, though. Since you can
1775 * put any HTML page within an IFRAME, you can put another layout window
1776 * within an IFRAME, to further subdivide the space inside the IFRAME.
1777 */
1778 class WebLayoutWindow: WebWindow
1779 /*
1780 * Resolve a window path name
1781 */
1782 winFromPath(path)
1783 {
1784 /* get the first element and the rest of the path */
1785 local idx = path.find('.');
1786 if (idx == nil)
1787 idx = path.length() + 1;
1788
1789 /* pull out the first element and the rest */
1790 local head = path.substr(1, idx - 1);
1791 local tail = path.substr(idx + 1);
1792
1793 /* if the first element doesn't match our name, it's not a match */
1794 if (head != name)
1795 return nil;
1796
1797 /* if that's the end of the path, we have our match */
1798 if (tail == '')
1799 return self;
1800
1801 /* match the rest of the path against our children */
1802 foreach (local w in frames)
1803 {
1804 local match = w[1].winFromPath(tail);
1805 if (match != nil)
1806 return match;
1807 }
1808
1809 /* no match */
1810 return nil;
1811 }
1812
1813 /*
1814 * Create a new window within the layout. This creates an IFRAME in
1815 * the browser, laid out according to the 'pos' argument, and
1816 * displays the given window object within the frame.
1817 *
1818 * If the window already exists, this updates the window with the new
1819 * layout settings.
1820 *
1821 * 'win' is a WebWindow object that will be displayed within the
1822 * IFRAME. This method automatically loads the HTML resource from
1823 * the WebWindow into the new IFRAME.
1824 *
1825 * 'name' is the name of the window. Each window within a layout
1826 * must have a distinct name. This allows you to refer to the
1827 * dimensions of other windows in 'pos' parameters. The name should
1828 * be alphanumeric.
1829 *
1830 * 'pos' is the layout position for the new frame. This is a string
1831 * in this format: 'left, top, width, height', where 'left' is the
1832 * horizontal position of the top left corner, 'top' is the vertical
1833 * position of the top left corner, 'width' is the width of the
1834 * window, and 'height' is the height. Each element can be specified
1835 * as a Javascript-style arithmetic expression. Within the
1836 * expression, you can use a mix of any of the following:
1837 *
1838 *. 123 - a number, representing a number of pixels on the display
1839 *. 5em - 5 'em' units, relative to the main BODY font in the window
1840 *. 5en - 5 'en' units in the main BODY font
1841 *. 5ex - 5 'ex' units in the main BODY font
1842 *. window.width - the width in pixels of the enclosing window
1843 *. window.height - the height in pixels of the enclosing window
1844 *. 50% - percentage of the width or height of the enclosing window
1845 *. content.width - the width in pixels of the contents of the frame
1846 *. content.height - the height in pixels of the contents of the frame
1847 *. x.left - horizontal coordinate of leftmost edge of window 'x'
1848 *. x.right - horizontal coordinate of rightmost edge of window 'x'
1849 *. x.top - vertical coordinate of top edge of window 'x'
1850 *. x.bottom - vertical coordinate of bottom edge of window 'x'
1851 *. x.width - width in pixels of window 'x'
1852 *. x.height - height in pixels of window 'x'
1853 *
1854 * The "window" dimensions refer to the *enclosing* window. If this
1855 * layout window is the main page of the UI, this is simply the
1856 * browser window itself. For a layout window nested within another
1857 * frame, this is the enclosing frame.
1858 *
1859 * Percentage units apply to the enclosing window. When a percentage
1860 * is used in the 'left' or 'width' slot, it applies to the width of
1861 * the enclosing window; in the 'top' or 'height' slot, it applies to
1862 * the height.
1863 *
1864 * The "content" dimensions refer to the contents of the frame we're
1865 * creating. This is the size of the contents as actually laid out
1866 * in the browser.
1867 *
1868 * "x.left" and so on refer to the dimensions of other frames *within
1869 * this same layout window*. 'x' is the name of another window
1870 * within the same layout, as specified by the 'name' argument given
1871 * when the window was created.
1872 */
1873 createFrame(win, name, pos)
1874 {
1875 /* set the window's internal name to its full path name */
1876 win.name = name;
1877 win.pathName = self.name + '.' + name;
1878
1879 /* add the window to our list */
1880 frames[name] = [win, pos];
1881
1882 /* notify the UI */
1883 sendWinEvent('<subwin>'
1884 + '<name><<name>></name>'
1885 + '<pos><<pos>></pos>'
1886 + '<src><<win.vpath.htmlify()>></src>'
1887 + '</subwin>');
1888 }
1889
1890 /*
1891 * Flush this window. For a layout window, we simply flush each
1892 * child window.
1893 */
1894 flushWin()
1895 {
1896 /* flush each child window */
1897 frames.forEach({w: w[1].flushWin()});
1898 }
1899
1900 /*
1901 * Get the state.
1902 */
1903 getState(client)
1904 {
1905 /* build an XML fragment describing the list of frames */
1906 local s = '';
1907 frames.forEachAssoc(function(name, info) {
1908 s += '<subwin><name><<name>></name>'
1909 + '<pos><<info[2]>></pos>'
1910 + '<src><<info[1].vpath.htmlify()>></src>'
1911 + '</subwin>';
1912 });
1913
1914 /* return the completed state object */
1915 return s;
1916 }
1917
1918 /*
1919 * The table of active frames within this layout. This table is
1920 * keyed by window name; each entry is a list of [win, pos], where
1921 * 'win' is the WebWindow object for the window, and 'pos' is its
1922 * position parameter.
1923 */
1924 frames = perInstance(new LookupTable(16, 32))
1925
1926 /* my virtual path and the actual resource file location */
1927 vpath = '/layoutwin.htm'
1928 src = 'webuires/layoutwin.htm'
1929 ;
1930
1931 /* ------------------------------------------------------------------------ */
1932 /*
1933 * Command Window. This object keeps track of the state of command
1934 * window within the web UI.
1935 */
1936 class WebCommandWin: WebWindow
1937 /*
1938 * Write to the window
1939 */
1940 write(txt)
1941 {
1942 /* add the text to the output buffer */
1943 outbuf.append(txt);
1944 }
1945
1946 /*
1947 * Flush the buffers
1948 */
1949 flushWin()
1950 {
1951 /* get the current output buffer */
1952 local txt = toString(outbuf).specialsToHtml(sthCtx);
1953
1954 /* add it to the state buffer (text since last input) */
1955 textbuf.append(txt);
1956
1957 /* send the text to the client via an event */
1958 sendWinEvent('<say><<txt.htmlify()>></say>');
1959
1960 /* we've now processed the pending output buffer */
1961 outbuf.deleteChars(1);
1962 }
1963
1964 /*
1965 * Read a line of input in this window. Blocks until the reply is
1966 * received. Returns nil on timeout.
1967 */
1968 getInputLine(timeout?)
1969 {
1970 /* flush buffered output */
1971 flushWin();
1972
1973 /* clear out the last input */
1974 lastInput = nil;
1975 lastInputClient = nil;
1976 lastInputReady = nil;
1977
1978 /* set the UI state */
1979 mode = 'inputLine';
1980 isInputOpen = true;
1981
1982 /* send the inputLine event to the client */
1983 sendWinEvent('<inputLine/>');
1984
1985 /* process network events until we get our input or we time out */
1986 processNetRequests(
1987 {: lastInputReady || webMainWin.syntheticEventReady() },
1988 timeout);
1989
1990 /* move the current textbuf contents to the scrollback list */
1991 textbufToScrollback(lastInput);
1992
1993 /* back to 'working' mode */
1994 mode = 'working';
1995
1996 /* check the result */
1997 if (lastInput != nil)
1998 {
1999 /* we got a reply - mark the input line as closed in the UI */
2000 isInputOpen = nil;
2001
2002 /* reset to the start of the line in the output context */
2003 sthCtx.resetLine();
2004
2005 /* remember the source of the command */
2006 webMainWin.curCmdClient = lastInputClient;
2007
2008 /* return the Line Input event */
2009 return [InEvtLine, lastInput];
2010 }
2011 else if (webMainWin.syntheticEventReady())
2012 {
2013 /* there's a synthetic event available - return it */
2014 return webMainWin.getSyntheticEvent();
2015 }
2016 else
2017 {
2018 /* we didn't get a reply, so we timed out */
2019 return [InEvtTimeout, ''];
2020 }
2021 }
2022
2023 /*
2024 * Cancel an input line that was interrupted by a timeout
2025 */
2026 cancelInputLine(reset)
2027 {
2028 /* if the input line is open, send the cancel event */
2029 if (isInputOpen)
2030 {
2031 /* send the cancel event to the client */
2032 sendWinEvent('<cancelInputLine reset="<<
2033 reset ? 'yes' : 'no'>>" />');
2034
2035 /* the input line is closed */
2036 isInputOpen = nil;
2037
2038 /* reset to the start of the line in the output context */
2039 sthCtx.resetLine();
2040 }
2041 }
2042
2043 /*
2044 * Get the state of this command window
2045 */
2046 getState(client)
2047 {
2048 return '<mode><<mode>></mode><scrollback>'
2049 + scrollback.join()
2050 + '<sbitem><text><<toString(textbuf).htmlify()>></text></sbitem>'
2051 + '</scrollback>';
2052 }
2053
2054 /*
2055 * Receive input from the client
2056 */
2057 receiveInput(req, query)
2058 {
2059 /* remember the text */
2060 lastInput = query['txt'];
2061
2062 /* remember the source of the input */
2063 lastInputClient = ClientSession.find(req);
2064
2065 /* set the input-ready flag so we exit the modal input loop */
2066 lastInputReady = true;
2067
2068 /* get the user who entered the command */
2069 local user = (lastInputClient != nil
2070 ? lastInputClient.screenName : '');
2071
2072 /* tell any other windows listening in about the new input */
2073 sendWinEvent('<closeInputLine>'
2074 + (lastInput != nil ?
2075 '<text><<lastInput.htmlify()>></text>' : '')
2076 + '<user><<user.htmlify()>></user>'
2077 + '</closeInputLine>');
2078
2079 /* reset to the start of the line in the output context */
2080 sthCtx.resetLine();
2081 }
2082
2083 /*
2084 * Clear the window
2085 */
2086 clearWindow()
2087 {
2088 /* flush the output buffer */
2089 flushWin();
2090
2091 /*
2092 * clear the transcript - if the user refreshes the browser
2093 * window, we want to show a blank window
2094 */
2095 textbuf.deleteChars(1);
2096 scrollback.clear();
2097
2098 /* send a clear window event */
2099 sendWinEvent('<clearWindow/>');
2100
2101 /* reset to the start of the line in the output context */
2102 sthCtx.resetLine();
2103 }
2104
2105 /*
2106 * Move the current text buffer contents to the scrollback list. If
2107 * this would make the scrollback list exceed the limit, we'll drop
2108 * the oldest item.
2109 *
2110 * 'cmd' is the command line text of the last input. We include this
2111 * in the srollback list with special tagging so that the UI can
2112 * display it in a custom style, if it wants.
2113 */
2114 textbufToScrollback(cmd)
2115 {
2116 /* get the current buffer, tagged as a <text> entry in the list */
2117 local t = '<text><<toString(textbuf).htmlify()>></text>';
2118
2119 /* add the command line tagged as <input> */
2120 if (cmd != nil)
2121 t += '<input><<cmd.htmlify()>></input>';
2122
2123 /* add the buffer to the scrollback list */
2124 scrollback.append('<sbitem><<t>></sbitem>');
2125
2126 /* if this pushes us past the limit, drop the oldest item */
2127 if (scrollback.length() > scrollbackLimit)
2128 scrollback.shift();
2129
2130 /* clear text buffer */
2131 textbuf.deleteChars(1);
2132 }
2133
2134 /*
2135 * Show a "More" prompt
2136 */
2137 showMorePrompt()
2138 {
2139 /* flush the output buffer */
2140 flushWin();
2141
2142 /* send a "More" prompt event to the UI */
2143 sendWinEvent('<morePrompt/>');
2144 mode = 'morePrompt';
2145 moreMode = true;
2146
2147 /* process events until More mode is done */
2148 processNetRequests({: !moreMode });
2149
2150 /* return the default mode */
2151 mode = 'working';
2152 }
2153
2154 /*
2155 * receive notification from the client that the user has responded
2156 * to the More prompt, ending the pause
2157 */
2158 endMoreMode()
2159 {
2160 /* no longer in More mode */
2161 moreMode = nil;
2162 }
2163
2164 /* main window text buffer since last input read */
2165 textbuf = perInstance(new StringBuffer(4096))
2166
2167 /*
2168 * Scrollback list. After each input, we add the contents of
2169 * 'textbuf' to this list. If this pushes the list past the limit,
2170 * we drop the oldest item. This is used to reconstruct a reasonable
2171 * amount of scrollback history when a new client connects, or when
2172 * an existing client refreshes the page.
2173 */
2174 scrollback = perInstance(new Vector())
2175
2176 /*
2177 * The scrollback limit, as a number of command inputs. Each input
2178 * interaction adds one item to the scrollback list. When the number
2179 * of items in the list exceeds the limit set here, we drop the
2180 * oldest item.
2181 */
2182 scrollbackLimit = 10
2183
2184 /* pending output buffer, since last flush */
2185 outbuf = perInstance(new StringBuffer(4096))
2186
2187 /* the text of the last input line we received from the client */
2188 lastInput = nil
2189
2190 /* is input ready? */
2191 lastInputReady = nil
2192
2193 /* client session who sent the last input line */
2194 lastInputClient = nil
2195
2196 /*
2197 * Is an input line open? This is true between sending an
2198 * <inputLine> event and either getting a reply, or explicitly
2199 * sending a close or cancel event.
2200 */
2201 isInputOpen = nil
2202
2203 /* flag: we're in More mode */
2204 moreMode = nil
2205
2206 /*
2207 * Current UI mode. This is 'working' if the program is running and
2208 * in the process of computing and/or generating output; 'inputLine'
2209 * if we're waiting for the user to enter a line of input;
2210 * 'morePrompt' if we're showing a "More" prompt.
2211 */
2212 mode = 'working'
2213
2214 /* my virtual path, and the actual resource file location */
2215 vpath = '/cmdwin.htm'
2216 src = 'webuires/cmdwin.htm'
2217 ;
2218
2219 /*
2220 * input-line event page
2221 */
2222 inputLinePage: WebResource
2223 vpath = '/webui/inputLine'
2224 processRequest(req, query)
2225 {
2226 /* find the window */
2227 local w = webMainWin.winFromPath(query['window']);
2228
2229 /* dispatch to the window if we found it */
2230 if (w != nil)
2231 {
2232 /* send the input to the window */
2233 w.receiveInput(req, query);
2234
2235 /* acknowledge the request */
2236 sendAck(req);
2237 }
2238 else
2239 req.sendReply(406);
2240 }
2241 ;
2242
2243 /*
2244 * "More" prompt done event page
2245 */
2246 morePromptDonePage: WebResource
2247 vpath = '/webui/morePromptDone'
2248 processRequest(req, query)
2249 {
2250 /* find the target winodw */
2251 local w = webMainWin.winFromPath(query['window']);
2252 if (w != nil)
2253 {
2254 /* release More mode in the server window */
2255 w.endMoreMode();
2256
2257 /* acknowledge the request */
2258 sendAck(req);
2259 }
2260 else
2261 req.sendReply(406);
2262 }
2263 ;
2264
2265
2266 /* ------------------------------------------------------------------------ */
2267 /*
2268 * Set Preferences command
2269 */
2270 setPrefsPage: WebResource
2271 vpath = '/webui/setPrefs'
2272 processRequest(req, query)
2273 {
2274 /* get the request body */
2275 local f = req.getBody();
2276 if (f == nil)
2277 {
2278 errorReply(req, 'Error saving preferences: no data received');
2279 return;
2280 }
2281 else if (f == 'overflow')
2282 {
2283 errorReply(req, 'Error saving preferences: message too large');
2284 return;
2285 }
2286
2287 /* get the client session for the request */
2288 local cli = ClientSession.find(req);
2289 if (cli == nil)
2290 {
2291 errorReply(req, 'Error saving preferences: missing session');
2292 return;
2293 }
2294
2295 /* process the file through the profile reader */
2296 cli.uiPrefs.readSettings(f);
2297
2298 /* save the updated settings */
2299 cli.uiPrefs.saveSettings();
2300
2301 /* done with the file */
2302 f.closeFile();
2303
2304 /* done - acknowledge the request */
2305 sendAck(req);
2306 }
2307
2308 /* send an error as the reply to a request, formatted into XML */
2309 errorReply(req, msg)
2310 {
2311 sendXML(req, 'reply', '<error><<msg.htmlify()>></error>');
2312 }
2313 ;
2314
2315 /*
2316 * UI Settings list. This represents a named UI settings profile in the
2317 * Web UI. A profile is a list of name/value pairs.
2318 *
2319 * Most of the name keys are style IDs defined in the javascript for on
2320 * the UI side - see main.js. These style IDs are arbitrary keys we
2321 * define to identify UI elements - "mainFont" for the main font name,
2322 * "statusBkg" for the status-line window's background color, etc. Each
2323 * style ID generally corresponds to a dialog control widget in the
2324 * preferences dialog in the javascript UI, and also corresponds to one
2325 * or more CSS style selectors. The mapping from style ID to CSS is
2326 * defined in the UI javascript (see prefsMapper in main.js).
2327 *
2328 * The non-style key "profileName" is the user-visible name of this
2329 * profile. Internally, we refer to profiles using ID values, which are
2330 * arbitrary identifiers generated by the UI when it creates a new
2331 * profile (it currently uses integer keys).
2332 */
2333 class WebUIProfile: object
2334 construct(id)
2335 {
2336 self.profileID = id;
2337 self.settings = new LookupTable();
2338 }
2339
2340 /* set a preference item in the profile */
2341 setItem(id, val)
2342 {
2343 settings[id] = val;
2344 }
2345
2346 /* call a callback for each style: func(id, val) */
2347 forEach(func)
2348 {
2349 settings.forEachAssoc(func);
2350 }
2351
2352 /* internal ID of the profile */
2353 profileID = ''
2354
2355 /* table of style value strings, keyed by style ID */
2356 settings = nil
2357 ;
2358
2359 /*
2360 * Web UI preferences. This object contains the in-memory version of the
2361 * display style preferences file.
2362 *
2363 * Each client session has its own copy of this object, because each
2364 * client can be associated with a different user, and each user has
2365 * their own preferences file.
2366 */
2367 class WebUIPrefs: object
2368 construct(c)
2369 {
2370 /* remember our client session object */
2371 clientSession = c;
2372
2373 /* load the initial settings from the user's config file */
2374 loadSettings();
2375 }
2376
2377 /* read the settings file */
2378 loadSettings()
2379 {
2380 /* open the preferences file; do nothing if that fails */
2381 local f = openSettingsFile(FileAccessRead);
2382 if (f == nil)
2383 return;
2384
2385 /* read the settings from the file */
2386 readSettings(f);
2387
2388 /* done with the file */
2389 f.closeFile();
2390 }
2391
2392 /* read settings from a file */
2393 readSettings(f)
2394 {
2395 /* set up our table of profiles */
2396 local pros = profileTab = new LookupTable();
2397
2398 /* we don't have a current profile selection yet */
2399 curProfile = nil;
2400
2401 /* read the file */
2402 for (;;)
2403 {
2404 /* read the next line */
2405 local l = f.readFile();
2406 if (l == nil)
2407 break;
2408
2409 /* if it's a valid line, process it */
2410 if (rexMatch(curProPat, l) != nil)
2411 {
2412 /* current profile setting */
2413 curProfile = rexGroup(1)[3];
2414 }
2415 else if (rexMatch(proItemPat, l) != nil)
2416 {
2417 /* style item definition - pull out the parts */
2418 local proid = rexGroup(1)[3];
2419 local key = rexGroup(2)[3];
2420 local val = rexGroup(3)[3];
2421
2422 /* if the profile isn't in the table yet, add it */
2423 local pro = pros[proid];
2424 if (pro == nil)
2425 pros[proid] = pro = new WebUIProfile(proid);
2426
2427 /* add this item to the table */
2428 pro.setItem(key, val);
2429 }
2430 }
2431 }
2432
2433 /* current profile ID pattern - current-profile:xxx */
2434 curProPat = static new RexPattern('current-profile=([^\n]*)\n?$')
2435
2436 /* setting ID pattern for profile items - nnn.xxx=yyy */
2437 proItemPat = static new RexPattern('([^.]+)%.([^=]+)=([^\n]*)\n?$')
2438
2439 /* save the current settings to the user's config file */
2440 saveSettings()
2441 {
2442 /* if there's no profile table, there's nothing to write */
2443 if (profileTab == nil)
2444 return;
2445
2446 try
2447 {
2448 /* open the preferences file; do nothing if that fails */
2449 local f = openSettingsFile(FileAccessWrite);
2450 if (f == nil)
2451 return;
2452
2453 /* write the current profile ID */
2454 f.writeFile('current-profile=<<curProfile>>\n');
2455
2456 /* write the profiles */
2457 profileTab.forEachAssoc(function(id, pro)
2458 {
2459 /* write each element of this profile */
2460 pro.forEach(function(key, val)
2461 {
2462 /* write this profile item */
2463 f.writeFile('<<id>>.<<key>>=<<val>>\n');
2464 });
2465 });
2466
2467 /* done with the file */
2468 f.closeFile();
2469 }
2470 catch (Exception e)
2471 {
2472 /*
2473 * couldn't save the file; this isn't fatal, so just log an
2474 * error event
2475 */
2476 webMainWin.postSyntheticEvent(
2477 'logError', 'An error occurred saving your setting changes.
2478 (Details: <<e.getExceptionMessage()>>)');
2479 }
2480 }
2481
2482 /* open the settings file */
2483 openSettingsFile(access)
2484 {
2485 /* get the filename; abort if we don't have a file */
2486 local name = getSettingsFile();
2487 if (name == nil)
2488 return nil;
2489
2490 /* open the file */
2491 try
2492 {
2493 /* open the file and return the handle */
2494 return File.openTextFile(name, access, 'ascii');
2495 }
2496 catch (Exception exc)
2497 {
2498 /* failed to open the file */
2499 return nil;
2500 }
2501 }
2502
2503 /* get the settings file path */
2504 getSettingsFile()
2505 {
2506 /* if we're in local stand-alone mode, use the local Web UI file */
2507 if (getLaunchHostAddr() == nil)
2508 return WebUIPrefsFile;
2509
2510 /* if there's a storage server session, the file is on the server */
2511 if (clientSession.storageSID != nil)
2512 return '~<<clientSession.storageSID>>/special/2';
2513
2514 /*
2515 * We're in client/server mode, but there's no storage server.
2516 * In this mode, we don't have any server-side location to store
2517 * files, so we can't save or restore the configuration.
2518 */
2519 return nil;
2520 }
2521
2522 /* get the current settings as XML, to send to the web UI */
2523 getXML()
2524 {
2525 /* if there's no profile table, there are no settings to return */
2526 if (profileTab == nil)
2527 return '';
2528
2529 /* create a buffer for the results */
2530 local s = new StringBuffer();
2531
2532 /* add the current profile */
2533 s.append('<currentProfile><<curProfile>></currentProfile>');
2534
2535 /* add each profile's contents */
2536 profileTab.forEachAssoc(function(id, pro)
2537 {
2538 /* open this profile section */
2539 s.append('<profile><id><<id>></id>');
2540
2541 /* add each style element */
2542 pro.forEach(function(id, val) {
2543 s.append('<item>'
2544 + '<id><<id.htmlify()>></id>'
2545 + '<value><<val.htmlify()>></value>'
2546 + '</item>');
2547 });
2548
2549 /* close this profile's section */
2550 s.append('</profile>');
2551 });
2552
2553 /* return the result as an XML string */
2554 return toString(s);
2555 }
2556
2557 /* the client session for this preference list */
2558 clientSession = nil
2559
2560 /*
2561 * profile table - this is a LookupTable of WebUIProfile objects
2562 * keyed by profile name
2563 */
2564 profileTab = nil
2565
2566 /* current active profile selected by the user */
2567 curProfile = nil
2568 ;
2569
2570
2571 /* ------------------------------------------------------------------------ */
2572 /*
2573 * Status line window
2574 */
2575 class WebStatusWin: WebWindow
2576 /* my request path and actual resource path */
2577 vpath = '/statwin.htm'
2578 src = 'webuires/statwin.htm'
2579
2580 /*
2581 * Set the room and score/turns portions of the status line. This
2582 * sets the left side of the status line to the 'room' text (which
2583 * can contain HTML markups), and the right side to the the
2584 * score/turns values, if present. If the turn counter is omitted
2585 * but the score value is present, we'll just show the score value;
2586 * otherwise we'll format these as "score/turns". If no score value
2587 * is present, we'll leave the right side blank.
2588 */
2589 setStatus(room, score?, turns?)
2590 {
2591 /* set up the room text in the left portion */
2592 local msg = '<div class="statusleft"><<room>></div>';
2593
2594 /*
2595 * format the right side: 'score/turns', 'score', or empty,
2596 * depending on what the caller specified
2597 */
2598 local rt = (score != nil ? toString(score) : '')
2599 + (turns != nil ? '/' + turns : '');
2600
2601 /* if there's a right side, wrap it with right alignment */
2602 if (rt != '')
2603 msg += '<div class="statusright"><<rt>></div>';
2604
2605 /*
2606 * our left/right divisions are floats, which some browsers don't
2607 * count against the container size; so add a clear:all division
2608 * to make sure we count the height properly
2609 */
2610 msg += '<div style="clear: both;"></div>';
2611
2612 /* set the text */
2613 setStatusText(msg);
2614 }
2615
2616 /*
2617 * Set the text of the status line. This sets the entire status
2618 * window to the given HTML text, without any additional formatting.
2619 */
2620 setStatusText(msg)
2621 {
2622 /* setting new text, so reset the stream context */
2623 sthCtx.resetState();
2624
2625 /* set the new text */
2626 txt_.deleteChars(1);
2627 txt_.append(msg.specialsToHtml(sthCtx));
2628
2629 /* note that we have new text to send to the UI */
2630 deltas_ = true;
2631 }
2632
2633 /* add text to the status line */
2634 write(msg)
2635 {
2636 /* add the text */
2637 txt_.append(msg.specialsToHtml(sthCtx));
2638
2639 /* note that we have new text to send to the UI */
2640 deltas_ = true;
2641 }
2642
2643 /* clear the window */
2644 clearWindow()
2645 {
2646 setStatusText('');
2647 }
2648
2649 /* flush pending text to the window */
2650 flushWin()
2651 {
2652 /* if we have any deltas since the last flush, send changes */
2653 if (deltas_)
2654 {
2655 /*
2656 * Send a set-text event, along with a resize. The resize
2657 * ensures that the status line adjusts to the current
2658 * content size, assuming the window is using automatic
2659 * content-height sizing.
2660 */
2661 sendWinEvent(
2662 '<text><<toString(txt_).htmlify()>></text><resize/>');
2663
2664 /* reset the deltas counter */
2665 deltas_ = nil;
2666 }
2667 }
2668
2669 /*
2670 * Refigure the window size. The status line is generally set up to
2671 * be automatically sized to its contents, which requires that we
2672 * tell the UI when it's time to recalculate the layout to reflect
2673 * the current contents after a change.
2674 */
2675 resize() { sendWinEvent('<resize/>'); }
2676
2677 /* get the current state to send to the browser */
2678 getState(client)
2679 {
2680 return '<text><<toString(txt_).htmlify()>></text>';
2681 }
2682
2683 /* do we have any deltas since the last flush? */
2684 deltas_ = nil
2685
2686 /* the current status message */
2687 txt_ = perInstance(new StringBuffer(512))
2688 ;
2689
2690 /* ------------------------------------------------------------------------ */
2691 /*
2692 * The standard "main window" of our user interface. This is the game
2693 * object that represents the default initial HTML page that the player's
2694 * web browser connects to. We build this out of three base classes:
2695 *
2696 * - WebResourceInit, because this is the starting page that the browser
2697 * initially connects to. This class does the initial handshaking to set
2698 * up the session.
2699 *
2700 * - WebResourceResFile, because we store the HTML for the page in a
2701 * resource file. This class does the work of sending the resource
2702 * file's contents to the browser.
2703 *
2704 * - WebLayoutWindow, because the default main page is also a layout
2705 * window, which is basically a container for IFRAME elements where we
2706 * plug in the sub-windows that make up the game's user interface.
2707 *
2708 * Games can customize the front page in any way they like. If you want
2709 * to customize the HTML of the main page, you can substitute a different
2710 * HTML (.htm) file, and change the processName() method to return the
2711 * name of that file. If you want to use something other than a layout
2712 * window as the front page, you can simply replace this whole class.
2713 */
2714 transient webMainWin: WebResourceInit, WebLayoutWindow, WebResourceResFile
2715 /*
2716 * match the webuires directory path as the URL path, but map this to
2717 * main.htm as the underlying resource name
2718 */
2719 vpath = '/'
2720 processName(n) { return 'webuires/main.htm'; }
2721
2722 /* the top window is always called "main" */
2723 name = 'main'
2724 pathName = 'main'
2725
2726 /* the window title */
2727 title = 'TADS'
2728
2729 /* set the window title */
2730 setTitle(title)
2731 {
2732 /* remember the title */
2733 self.title = title;
2734
2735 /* update the browser */
2736 sendWinEvent('<setTitle><<title.htmlify()>></setTitle>');
2737 }
2738
2739 /*
2740 * Client session for current command line input. Certain modal
2741 * interactions, such as file dialogs, are directed only to the
2742 * client that initiated the current command.
2743 */
2744 curCmdClient = nil
2745
2746 /* get the state */
2747 getState(client)
2748 {
2749 /* get the inherited layout state */
2750 local s = inherited(client);
2751
2752 /* add the preference settings */
2753 s += '<prefs><<client.uiPrefs.getXML()>></prefs>';
2754
2755 /* add the window title */
2756 s += '<title><<title.htmlify()>></title>';
2757
2758 /* add the input event, input file, and input dialog states */
2759 s += inputEventState;
2760 s += inputDialogState;
2761 s += menuSysState;
2762
2763 /* if this is the command client, include the file dialog state */
2764 if (client == curCmdClient)
2765 s += fileDialogState;
2766
2767 /* add the downloadable file list */
2768 s += client.allDownloads().mapAll(
2769 { x: x.isReady
2770 ? '<offerDownload><<x.resPath.htmlify()>></offerDownload>'
2771 : '' }
2772 ).join();
2773
2774 /* return the result */
2775 return s;
2776 }
2777
2778 /* wait for an input event */
2779 getInputEvent(timeout)
2780 {
2781 /* flush buffered output */
2782 flushWin();
2783
2784 /* send the get-event request to the client */
2785 inputEventState = '<getInputEvent/>';
2786 inputEventResult = nil;
2787 sendWinEvent(inputEventState);
2788
2789 /* process network events until we get an input event */
2790 processNetRequests({: inputEventResult != nil }, timeout);
2791
2792 /* check what happened */
2793 if (inputEventResult)
2794 {
2795 /* we got an input event - return it */
2796 return inputEventResult;
2797 }
2798 else
2799 {
2800 /*
2801 * There's no result, so we timed out. Tell the UI to cancel
2802 * the input event mode.
2803 */
2804 inputEventState = '';
2805 sendWinEvent('<cancelInputEvent/>');
2806
2807 /* return a timeout event */
2808 return [InEvtTimeout];
2809 }
2810 }
2811
2812 /* receive an input event */
2813 receiveInputEvent(req, query)
2814 {
2815 local typ = query['type'];
2816 local param = query['param'];
2817
2818 switch (typ)
2819 {
2820 case 'key':
2821 inputEventResult = [InEvtKey, param];
2822 break;
2823
2824 case 'href':
2825 inputEventResult = [InEvtHref, param];
2826 break;
2827
2828 default:
2829 inputEventResult = [InEvtEof];
2830 break;
2831 }
2832 }
2833
2834 /* show the file selector dialog */
2835 getInputFile(prompt, dialogType, fileType, flags)
2836 {
2837 /* mappings from FileTypeXxx to storage manager type codes */
2838 local typeMap = [
2839 FileTypeLog -> 'log',
2840 FileTypeData -> 'dat',
2841 FileTypeCmd -> 'cmd',
2842 FileTypeText -> 'txt',
2843 FileTypeBin -> 'bin',
2844 FileTypeT3Image -> 't3',
2845 FileTypeT3Save -> 't3v',
2846 * -> '*'];
2847
2848 /* get the storage server session for the command client */
2849 local sid = curCmdClient.storageSID;
2850
2851 /*
2852 * If we have a session, get the URL to the storage server file
2853 * selection dialog. Note that we don't specify the session in
2854 * the URL, since the storage server separately maintains the
2855 * session with the client via a cookie.
2856 */
2857 local url = nil;
2858 if (sid != nil)
2859 url = getNetStorageURL(
2860 'fileDialog?filetype=<<typeMap[fileType]>>'
2861 + '&dlgtype=<<dialogType == InFileOpen ? 'open' : 'save'>>'
2862 + '&prompt=<<prompt.urlEncode()>>'
2863 + '&ret=<<webSession.getFullUrl('/webui/inputFile')>>');
2864
2865 /*
2866 * if there's no storage server, try using a client PC upload or
2867 * download
2868 */
2869 if (url == nil)
2870 return getInputFileFromClient(prompt, dialogType, fileType, flags);
2871
2872 /*
2873 * set up the file dialog state description (store it in a
2874 * property, so that we can send it again as part of a state
2875 * request if the client window is reloaded from scratch)
2876 */
2877 fileDialogState =
2878 '<fileDialog>'
2879 + '<prompt><<prompt.htmlify()>></prompt>'
2880 + '<dialogType><<dialogType == InFileOpen
2881 ? 'open' : 'save'>></dialogType>'
2882 + '<fileType><<typeMap[fileType]>></fileType>'
2883 + '<url><<url.htmlify()>></url>'
2884 + '</fileDialog>';
2885
2886 /*
2887 * Presume that the dialog will be canceled. If the user clicks
2888 * the close box on the dialog, the dialog will be dismissed
2889 * without ever sending us a result. This counts as a
2890 * cancellation, so it's the default result.
2891 */
2892 fileDialogResult = [InFileCancel];
2893
2894 /* send the request to the current command client */
2895 sendWinEventTo(fileDialogState, curCmdClient);
2896
2897 /* process network events until the dialog is dismissed */
2898 processNetRequests(
2899 {: fileDialogState == '' || !curCmdClient.isAlive });
2900
2901 /* return the dialog result */
2902 return fileDialogResult;
2903 }
2904
2905 /*
2906 * Get an input file from the client PC. We'll attempt to upload or
2907 * download a file from/to the client PC, using a local temporary
2908 * file for the actual file operations. This is a special form of
2909 * the input file dialog that we use when we're not connected to a
2910 * storage server.
2911 */
2912 getInputFileFromClient(prompt, dialogType, fileType, flags)
2913 {
2914 /* use the appropriate procedure for Open vs Save */
2915 if (dialogType == InFileOpen)
2916 {
2917 /*
2918 * Opening an existing file. Show a dialog asking the user
2919 * to select a file to upload. If the user uploads a file,
2920 * we'll use the local temp file created by the upload as the
2921 * result of the input dialog.
2922 */
2923 fileDialogState =
2924 '<uploadFileDialog>'
2925 + '<prompt><<prompt.htmlify()>></prompt>'
2926 + '</uploadFileDialog>';
2927
2928 /* presume the user will cancel the dialog */
2929 fileDialogResult = [InFileCancel];
2930
2931 /* send the request to the UI */
2932 sendWinEventTo(fileDialogState, curCmdClient);
2933
2934 /* process network events until the dialog is dismissed */
2935 processNetRequests(
2936 {: fileDialogState == '' || !curCmdClient.isAlive });
2937
2938 /* return the file dialog result */
2939 return fileDialogResult;
2940 }
2941 else if (dialogType == InFileSave)
2942 {
2943 /*
2944 * Saving to a new file. The caller is asking the user to
2945 * choose a name for a file that the caller *intends* to
2946 * create, but hasn't yet created. HTTP can only do a
2947 * download as a transaction, though - we can offer an
2948 * existing file to the user to download, and the user will
2949 * choose the location for the download as part of that
2950 * transaction. We don't have that file yet because the
2951 * standard protocol is to ask the user for the name first,
2952 * then write the selected file.
2953 *
2954 * So, we have to play a little game. We don't ask the user
2955 * to save anything right now, because there's no file to
2956 * offer for download yet. Instead, we silently generate a
2957 * local temporary file name and return that to our caller.
2958 * Our caller will create the temp file and write its data.
2959 *
2960 * The trick is that we wrap this temp file name in a
2961 * DownloadTempFile object. When the caller finishes
2962 * writing, it will call closeFile() on the temp file. The
2963 * system will pass that along to use by calling closeFile()
2964 * on our DownloadTempFile object. At that point, we'll have
2965 * a completed temporary file, so we'll pop up a download box
2966 * at that point offering the file for download to the user.
2967 * The user can then select a local file on the client side,
2968 * and we'll send the temporary file's contents as the
2969 * download to store in the client file.
2970 */
2971 return [InFileSuccess,
2972 tempFileDownloadPage.addFile(fileType, curCmdClient)];
2973 }
2974 else
2975 {
2976 /* unknown dialog type */
2977 return [InFileFailure];
2978 }
2979 }
2980
2981 /*
2982 * Offer a file for download to the client. 'file' is a
2983 * DownloadTempFile object previously created by a call to
2984 * inputFile().
2985 */
2986 offerDownload(file)
2987 {
2988 /*
2989 * send the "offer download" event to the client - the client
2990 * will display an iframe with the file as an "attachment", which
2991 * will trigger the browser to offer it as a download
2992 */
2993 sendWinEventTo(
2994 '<offerDownload><<file.resPath.htmlify()>></offerDownload>',
2995 curCmdClient);
2996 }
2997
2998 /* receive a file selection from the file selector dialog */
2999 receiveFileSelection(req, query)
3000 {
3001 /* get the filename from the query */
3002 local f = query['file'];
3003 local desc = query['desc'];
3004 local cancel = (query['cancel'] != nil);
3005 local err = query['error'];
3006
3007 /*
3008 * Set the file dialog result list. This uses the same format as
3009 * the native inputFile() routine: the first element is the
3010 * status code (Success, Failure, Cancel); on success, the second
3011 * element is the filename string. We add two bits of
3012 */
3013 if (err != nil)
3014 fileDialogResult = [InFileFailure, err];
3015 else if (cancel || f == nil || f == '')
3016 fileDialogResult = [InFileCancel];
3017 else
3018 {
3019 /* we got a filename - add the SID prefix if necessary */
3020 if (rexMatch('~[^/]+/', f) == nil)
3021 f = '~<<curCmdClient.storageSID>>/<<f>>';
3022
3023 /* success - return the filename */
3024 fileDialogResult = [InFileSuccess, f];
3025
3026 /* if there's a description string, return that as well */
3027 if (desc != nil)
3028 fileDialogResult += desc;
3029 }
3030 }
3031
3032 /* receive notification that the file dialog has been closed */
3033 inputFileDismissed()
3034 {
3035 /* clear the file dialog state */
3036 fileDialogState = '';
3037 }
3038
3039 /* receive a file upload from the file upload dialog */
3040 receiveFileUpload(req, query)
3041 {
3042 /* get the file from the request */
3043 local fields = req.getFormFields(), file;
3044 if (fields == 'overflow')
3045 {
3046 /* error */
3047 fileDialogResult = [InFileFailure, libMessages.webUploadTooBig];
3048 }
3049 else if (fields != nil && (file = fields['file']) != nil)
3050 {
3051 /* got it - save the contents to a local temporary file */
3052 local tmpfile = new TemporaryFile();
3053 local fpTmp = nil;
3054 try
3055 {
3056 /* open the temp file */
3057 fpTmp = File.openRawFile(tmpfile, FileAccessWrite);
3058
3059 /* make sure the input file is in raw binary mode */
3060 local fpIn = file.file;
3061 fpIn.setFileMode(FileModeRaw);
3062
3063 /* copy the contents */
3064 fpTmp.writeBytes(fpIn);
3065
3066 /* close the temp file */
3067 fpTmp.closeFile();
3068
3069 /*
3070 * Set the dialog result to the temp file. The system
3071 * will automatically delete the underlying file system
3072 * object when the garbage collector deletes the
3073 * TemporaryFile.
3074 */
3075 fileDialogResult = [InFileSuccess, tmpfile];
3076 }
3077 catch (Exception exc)
3078 {
3079 /* error - the dialog failed */
3080 fileDialogResult = [InFileFailure, exc.getExceptionMessage()];
3081
3082 /* close and delete the temporary file */
3083 if (fpTmp != nil)
3084 fpTmp.closeFile();
3085 if (tmpfile != nil)
3086 tmpfile.deleteFile();
3087 }
3088 }
3089 else
3090 {
3091 /* no file - consider it a cancellation */
3092 fileDialogResult = [InFileCancel];
3093 }
3094
3095 /* the dialog is dismissed */
3096 fileDialogState = '';
3097 }
3098
3099 /* show a generic inputDialog dialog */
3100 getInputDialog(icon, prompt, buttons, defaultButton, cancelButton)
3101 {
3102 /*
3103 * if one of the standard button sets was selected, turn it into
3104 * a list of localized button names
3105 */
3106 switch (buttons)
3107 {
3108 case InDlgOk:
3109 buttons = [libMessages.dlgButtonOk];
3110 break;
3111
3112 case InDlgOkCancel:
3113 buttons = [libMessages.dlgButtonOk, libMessages.dlgButtonCancel];
3114 break;
3115
3116 case InDlgYesNo:
3117 buttons = [libMessages.dlgButtonYes, libMessages.dlgButtonNo];
3118 break;
3119
3120 case InDlgYesNoCancel:
3121 buttons = [libMessages.dlgButtonYes, libMessages.dlgButtonNo,
3122 libMessages.dlgButtonCancel];
3123 break;
3124 }
3125
3126 /* get a suitable localized title corresponding to the icon tyep */
3127 local title = [InDlgIconNone -> libMessages.dlgTitleNone,
3128 InDlgIconWarning -> libMessages.dlgTitleWarning,
3129 InDlgIconInfo -> libMessages.dlgTitleInfo,
3130 InDlgIconQuestion -> libMessages.dlgTitleQuestion,
3131 InDlgIconError -> libMessages.dlgTitleError][icon];
3132
3133 /* build the dialog xml description */
3134 inputDialogState =
3135 '<inputDialog>'
3136 + '<icon><<icon>></icon>'
3137 + '<title><<title>></title>'
3138 + '<prompt><<prompt.htmlify>></prompt>'
3139 + '<buttons>'
3140 + buttons.mapAll({b: '<button><<b.htmlify()>></button>'})
3141 .join('')
3142 + '</buttons>'
3143 + '<defaultButton><<defaultButton>></defaultButton>'
3144 + '<cancelButton><<cancelButton>></cancelButton>'
3145 + '</inputDialog>';
3146
3147 /* send the request to the client */
3148 inputDialogResult = nil;
3149 sendWinEvent(inputDialogState);
3150
3151 /* process network events until we get an answer */
3152 processNetRequests({: inputDialogResult != nil });
3153
3154 /* return the dialog result */
3155 return inputDialogResult;
3156 }
3157
3158 /* receive a selection from the input dialog */
3159 receiveInputDialog(req, query)
3160 {
3161 /* note the result button */
3162 inputDialogResult = toInteger(query['button']);
3163
3164 /* if we didn't get a valid button index, select button 1 */
3165 if (inputDialogResult == 0)
3166 inputDialogResult = 1;
3167
3168 /* the dialog is no longer open */
3169 inputDialogState = '';
3170 }
3171
3172 /*
3173 * Post a synthetic event. A synthetic event looks like a regular UI
3174 * or network event, but is generated internally instead of being
3175 * delivered from the underlying browser or network subsystems.
3176 *
3177 * 'id' is a string giving the event type. The remaining parameters
3178 * are up to each event type to define.
3179 */
3180 postSyntheticEvent(id, [params])
3181 {
3182 /* add it to the synthetic event queue */
3183 synthEventQueue.append([id] + params);
3184 }
3185
3186 /* is a synthetic event ready? */
3187 syntheticEventReady() { return synthEventQueue.length() > 0; }
3188
3189 /* pull the next synthetic event from the queue */
3190 getSyntheticEvent() { return synthEventQueue.shift(); }
3191
3192 /*
3193 * file dialog state - this is the XML describing the currently open
3194 * file dialog; if the dialog isn't open, this is an empty string
3195 */
3196 fileDialogState = ''
3197
3198 /*
3199 * file dialog result - this is a result list using the same format
3200 * as the native inputFile() function
3201 */
3202 fileDialogResult = nil
3203
3204 /*
3205 * input dialog state - this is the XML describing an input dialog
3206 * while a dialog is running, or an empty string if not
3207 */
3208 inputDialogState = ''
3209
3210 /* input dialog result - this is the button number the user selected */
3211 inputDialogResult = nil
3212
3213 /* input event state */
3214 inputEventState = ''
3215
3216 /* input event result */
3217 inputEventResult = nil
3218
3219 /* menuSys state - menu system state (maintained by the menu module) */
3220 menuSysState = ''
3221
3222 /*
3223 * Synthetic event queue. This is a vector of synthetic events, set
3224 * up in the [type, params...] format that the system inputEvent()
3225 * function and related functions use. The 'type' code for a
3226 * synthetic evente is a string instead of the numeric identifier
3227 * that the system functions use.
3228 */
3229 synthEventQueue = static new transient Vector()
3230 ;
3231
3232 /* ------------------------------------------------------------------------ */
3233 /*
3234 * Temporary file download page. This page serves temporary files
3235 * created via inputFile() as HTTP downloads to the client.
3236 */
3237 transient tempFileDownloadPage: WebResource
3238 vpath = static new RexPattern('/clienttmp/')
3239 processRequest(req, query)
3240 {
3241 /*
3242 * look up the file - the key in our table is the ID string after
3243 * the /clienttmp/ path prefix
3244 */
3245 local id = query[1].substr(12);
3246 local client = ClientSession.find(req);
3247 local desc = client.downloads[id];
3248
3249 /* check for cancellation */
3250 if (query['cancel'] != nil)
3251 {
3252 /*
3253 * acknowledge the request - do this before we cancel the
3254 * file, since removing the file will remove the link that
3255 * fired this request (the order probably isn't a big deal
3256 * one way or the other, and we probably can't really control
3257 * it anyway as the browser might process the ack and the
3258 * event out of order, but just in case)
3259 */
3260 sendAck(req);
3261
3262 /* if we found the descriptor, cancel it */
3263 if (desc != nil)
3264 client.cancelDownload(desc);
3265
3266 /* done */
3267 return;
3268 }
3269
3270 /* if we didn't find it, return failure */
3271 if (desc == nil)
3272 {
3273 req.sendReply(404);
3274 return;
3275 }
3276
3277 /* open the file */
3278 local fp = nil;
3279 try
3280 {
3281 fp = File.openRawFile(desc.tempFileName, FileAccessRead);
3282 }
3283 catch (Exception exc)
3284 {
3285 /* couldn't send the file - send a 404 */
3286 req.sendReply(404);
3287 return;
3288 }
3289
3290 /* set up the download file headers */
3291 local headers = [
3292 'Content-Disposition: attachment; filename=<<desc.resName>>'
3293 ];
3294
3295 try
3296 {
3297 /* send the file's contents */
3298 req.sendReply(fp, desc.mimeType, 200, headers);
3299 }
3300 catch (Exception exc)
3301 {
3302 /* ignore errors */
3303 }
3304
3305 /* done with the file */
3306 fp.closeFile();
3307
3308 /*
3309 * We've at least tried sending the file, so remove it from the
3310 * download list. This was just a temp file, so there's no need
3311 * to keep it around even if we ran into an error sending it; if
3312 * the send failed, the user can just repeat the operation that
3313 * generated the file.
3314 */
3315 client.cancelDownload(desc);
3316 }
3317
3318 /* add a file to our list of downloadable files */
3319 addFile(fileType, client)
3320 {
3321 /*
3322 * Generate a server-side name template based on the file type.
3323 * The name doesn't matter to us, but browsers will display it to
3324 * the user, and many browsers use the server-side name as the
3325 * default name for the newly downloaded file in the "Save File"
3326 * dialog. Many browsers also use the suffix to determine the
3327 * file type, ignoring any Content-Type headers.
3328 */
3329 local tpl = [FileTypeLog -> 'Script#.txt',
3330 FileTypeData -> 'File#.dat',
3331 FileTypeCmd -> 'Command#.txt',
3332 FileTypeText -> 'File#.txt',
3333 FileTypeBin -> 'File#.bin',
3334 FileTypeT3Image -> 'Story#.t3',
3335 FileTypeT3Save -> 'Save#.t3v',
3336 * -> 'File#'][fileType];
3337
3338 /* figure the mime type based on the file type */
3339 local mimeType = [FileTypeLog -> 'text/plain',
3340 FileTypeCmd -> 'text/plain',
3341 FileTypeT3Image -> 'application/x-t3vm-image',
3342 FileTypeT3Save -> 'application/x-t3vm-state',
3343 * -> 'application/octet-stream'][fileType];
3344
3345 /* replace the '#' in the template with the next ID value */
3346 tpl = tpl.findReplace('#', toString(nextID++));
3347
3348 /* create a new table entry */
3349 local desc = new DownloadTempFile(tpl, mimeType);
3350
3351 /* add this download to each client */
3352 client.addDownload(desc);
3353
3354 /* return the descriptor */
3355 return desc;
3356 }
3357
3358 /* next available ID */
3359 nextID = 1
3360 ;
3361
3362 /*
3363 * Downloadable temporary file descriptor. We create this object when
3364 * the program calls inputFile() to ask for a writable file. This lets
3365 * the caller create and write a temporary file on the server side; when
3366 * the caller is done with the file, we'll offer the file for download to
3367 * the client through the UI.
3368 */
3369 class DownloadTempFile: object
3370 construct(res, mimeType)
3371 {
3372 tempFileName = new TemporaryFile();
3373 resName = res;
3374 resPath = '/clienttmp/<<res>>';
3375 timeCreated = getTime(GetTimeTicks);
3376 self.mimeType = mimeType;
3377 }
3378
3379 /*
3380 * File spec interface. This allows the DownloadTempFile to be used as
3381 * though it were a filename string.
3382 *
3383 * When the object is passed to one of the File.open methods, or to
3384 * saveGame(), setScriptFile(), etc., the system will call our
3385 * getFilename() method to determine the actual underlying file.
3386 * We'll return our temporary file object.
3387 *
3388 * When the underlying file is closed, the system calls our
3389 * closeFile() method to notify us.
3390 */
3391 getFilename() { return tempFileName; }
3392 closeFile()
3393 {
3394 /* mark the file as ready for download */
3395 isReady = true;
3396
3397 /* offering the file to the client as an HTTP download */
3398 webMainWin.offerDownload(self);
3399 }
3400
3401 /* TemporaryFile object for the local temp file */
3402 tempFileName = nil
3403
3404 /* root resource name, and full resource path */
3405 resName = nil
3406 resPath = nil
3407
3408 /* MIME type */
3409 mimeType = nil
3410
3411 /* creation timestamp, as a system tick count value */
3412 timeCreated = 0
3413
3414 /* is the file ready for download? */
3415 isReady = nil
3416
3417 /* this is a web temp file */
3418 isWebTempFile = true
3419 ;
3420
3421 /* ------------------------------------------------------------------------ */
3422 /*
3423 * Input event page. The client javascript does a GET on this resource
3424 * to send us an input event.
3425 */
3426 inputEventPage: WebResource
3427 vpath = '/webui/inputEvent'
3428 processRequest(req, query)
3429 {
3430 /* send the event to the main window object */
3431 webMainWin.receiveInputEvent(req, query);
3432
3433 /* acknowledge the request */
3434 sendAck(req);
3435 }
3436 ;
3437
3438 /* ------------------------------------------------------------------------ */
3439 /*
3440 * Input dialog event page. The web UI sends a GET to this page when the
3441 * user selects a button in an input dialog.
3442 */
3443 inputDialogPage: WebResource
3444 vpath = '/webui/inputDialog'
3445 processRequest(req, query)
3446 {
3447 /* send the event to the main window */
3448 webMainWin.receiveInputDialog(req, query);
3449
3450 /* acknowledge the request */
3451 sendAck(req);
3452 }
3453 ;
3454
3455 /* ------------------------------------------------------------------------ */
3456 /*
3457 * File dialog event page. This page is used by the IFDB Storage Server
3458 * file dialog to return information to the game UI. The IFDB dialog
3459 * page can't itself perform scripting actions on the enclosing dialog
3460 * frame, since it's being served from a different domain - browsers
3461 * prohibit cross-domain scripting for security reasons. The IFDB dialog
3462 * must therefore navigate back to a page within the game server domain
3463 * in order to return information through scripting. This is that page:
3464 * when the IFDB page is ready to return information, it navigates its
3465 * frame to this page, passing the return values in the request
3466 * parameters. Since this page is served by the game server, within the
3467 * game server domain, the browser allows it to use scripting actions on
3468 * its enclosing frame. We finish the job by dismissing the dialog in
3469 * the UI.
3470 */
3471 inputFilePage: WebResource
3472 vpath = '/webui/inputFile'
3473 processRequest(req, query)
3474 {
3475 /* set the file selection in the main window */
3476 webMainWin.receiveFileSelection(req, query);
3477
3478 /*
3479 * We have our response, so dismiss the file dialog. Do this by
3480 * sending back a page with script instructions to close the
3481 * containing dialog window.
3482 */
3483 req.sendReply(
3484 '<html><body>'
3485 + '<script type="text/javascript">'
3486 + 'window.parent.dismissDialogById("inputFile");'
3487 + '</script>'
3488 + '</body></html>');
3489 }
3490 ;
3491
3492 /*
3493 * Cancel the input dialog. This is called from the UI directly to
3494 * cancel the file selection, when the user closes the dialog through the
3495 * enclosing main page UI rather than from within the dialog. This is
3496 * useful if the dialog page fails to load, for example.
3497 *
3498 * Note: the upload file dialog also uses this. The upload dialog is
3499 * basically a variation on the regular input file dialog.
3500 */
3501 inputFileCancel: WebResource
3502 vpath = '/webui/inputFileDismissed'
3503 processRequest(req, query)
3504 {
3505 /* note that the dialog has been dismissed */
3506 webMainWin.inputFileDismissed();
3507
3508 /* acknowledge the request */
3509 sendAck(req);
3510 }
3511 ;
3512
3513 /*
3514 * Receive results from the input file dialog
3515 */
3516 uploadFilePage: WebResource
3517 vpath = '/webui/uploadFileDialog'
3518 processRequest(req, query)
3519 {
3520 /* send the request to the main window */
3521 webMainWin.receiveFileUpload(req, query);
3522
3523 /* send back a script to dismiss the dialog */
3524 req.sendReply(
3525 '<html><body>'
3526 + '<script type="text/javascript">'
3527 + 'window.parent.dismissDialogById("uploadFile");'
3528 + '</script>'
3529 + '</body></html>');
3530 }
3531 ;
3532
3533 /* ------------------------------------------------------------------------ */
3534 /*
3535 * Receive the client's screen name setting
3536 */
3537 setScreenNamePage: WebResource
3538 vpath = '/webui/setScreenName'
3539 processRequest(req, query)
3540 {
3541 /* set the name in the client session */
3542 local cli = ClientSession.find(req);
3543 if (cli != nil)
3544 cli.screenName = query['name'];
3545
3546 /* acknowledge the request */
3547 sendAck(req);
3548 }
3549 ;
3550