-
Notifications
You must be signed in to change notification settings - Fork 11
/
glkote.js
2949 lines (2627 loc) · 93 KB
/
glkote.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* GlkOte -- a Javascript display library for IF interfaces
* GlkOte Library: version 2.2.4.
* Designed by Andrew Plotkin <erkyrath@eblong.com>
* <http://eblong.com/zarf/glk/glkote.html>
*
* This Javascript library is copyright 2008-16 by Andrew Plotkin.
* It is distributed under the MIT license; see the "LICENSE" file.
*
* GlkOte is a tool for creating interactive fiction -- and other text-based
* applications -- on a web page. It is a Javascript library which handles
* the mechanics of displaying text, arranging panes of text, and accepting
* text input from the user.
*
* GlkOte is based on the Glk API. However, GlkOte's API is not identical to
* Glk, even allowing for the differences between Javascript and C. GlkOte is
* adapted to the realities of a web application environment -- a thin
* Javascript layer which communicates with a distant server in intermittent
* bursts.
*
* GlkOte can be used from two angles. First, in a purely client-side IF
* application. The (included, optional) glkapi.js file facilitates this; it
* wraps around GlkOte and provides an API that is identical to Glk, as
* closely as Javascript allows. An IF interpreter written in Javascript,
* running entirely within the user's web browser, can use glkapi.js just as
* a C interpreter uses a normal Glk library. Or it could bypass glkapi.js
* and use GlkOte directly.
*
* Alternatively, GlkOte could be used with a Glk library which acts as a
* web service. The RemGlk library (not included) can be used this way.
* In this mode, GlkOte collects user input and sends it to the web service
* as a AJAX request. The service decodes the (JSON-format) input data,
* executes a game turn, and returns the game response as a (JSON-format)
* reply to the request. A proof-of-concept can be found at:
* https://github.com/erkyrath/remote-if-demo
*
* (A few calls, or arguments of calls, are marked "for autosave/autorestore
* only". These exist for the purpose of getting a game displayed in a known
* state, which is rather more complicated than the usual situation of
* letting a game start up and run.)
*
* For full documentation, see the docs.html file in this package.
*/
/* Put everything inside the GlkOte namespace. */
GlkOte = function() {
/* Module global variables */
var game_interface = null;
var dom_context = undefined;
var windowport_id = 'windowport';
var gameport_id = 'gameport';
var generation = 0;
var generation_sent = -1;
var disabled = false;
var loading_visible = null;
var error_visible = false;
var windowdic = null;
var current_metrics = null;
var current_devpixelratio = null;
var currently_focussed = false;
var last_known_focus = 0;
var last_known_paging = 0;
var windows_paging_count = 0;
var graphics_draw_queue = [];
var request_timer = null;
var request_timer_interval = null;
var resize_timer = null;
var retry_timer = null;
var perform_paging = true;
var detect_external_links = false;
var regex_external_links = null;
var debug_out_handler = null;
/* Some handy constants */
/* A non-breaking space character. */
var NBSP = "\xa0";
/* Number of paragraphs to retain in a buffer window's scrollback. */
var max_buffer_length = 200;
/* Size of the scrollbar, give or take some. */
var approx_scroll_width = 20;
/* Margin for how close you have to scroll to end-of-page to kill the
moreprompt. (Really this just counters rounding error.) */
var moreprompt_margin = 2;
/* Some constants for key event native values. (Not including function
keys.) */
var key_codes = {
KEY_BACKSPACE: 8,
KEY_TAB: 9,
KEY_RETURN: 13,
KEY_ESC: 27,
KEY_LEFT: 37,
KEY_UP: 38,
KEY_RIGHT: 39,
KEY_DOWN: 40,
KEY_DELETE: 46,
KEY_HOME: 36,
KEY_END: 35,
KEY_PAGEUP: 33,
KEY_PAGEDOWN: 34,
KEY_INSERT: 45
};
/* All the keys that can be used as line input terminators, and their
native values. */
var terminator_key_names = {
escape : key_codes.KEY_ESC,
func1 : 112, func2 : 113, func3 : 114, func4 : 115, func5 : 116,
func6 : 117, func7 : 118, func8 : 119, func9 : 120, func10 : 121,
func11 : 122, func12 : 123
};
/* The inverse of the above. Maps native values to Glk key names. Set up at
init time. */
var terminator_key_values = {};
/* The transcript-recording feature. If enabled, this sends session
information to an external recording service. */
var recording = false;
var recording_state = null;
var recording_handler = null;
var recording_handler_url = null;
var recording_context = {};
/* An image cache. This maps numbers to Image objects. These are used only
for painting in graphics (canvas) windows.
*/
var image_cache = {};
/* This function becomes GlkOte.init(). The document calls this to begin
the game. The simplest way to do this is to give the <body> tag an
onLoad="GlkOte.init();" attribute.
*/
function glkote_init(iface) {
if (!iface && window.Game)
iface = window.Game;
if (!iface) {
glkote_error('No game interface object has been provided.');
return;
}
if (!iface.accept) {
glkote_error('The game interface object must have an accept() function.');
return;
}
game_interface = iface;
if (!window.jQuery || !jQuery.fn.jquery) {
glkote_error('The jQuery library has not been loaded.');
return;
}
var version = jQuery.fn.jquery.split('.');
if (version.length < 2 || version[0] < 1 || (version[0] == 1 && version[1] < 9)) {
glkote_error('This version of the jQuery library is too old. (Version ' + jQuery.fn.jquery + ' found; 1.9.0 required.)');
return;
}
/* Set up a static table. */
for (var val in terminator_key_names) {
terminator_key_values[terminator_key_names[val]] = val;
}
if (false) {
/* ### test for mobile browser? "'ontouchstart' in document.documentElement"? */
/* Paging doesn't make sense for iphone/android, because you can't
get keystroke events from a window. */
perform_paging = false;
}
/* Object mapping window ID (strings) to window description objects. */
windowdic = {};
if (iface.windowport)
windowport_id = iface.windowport;
if (iface.gameport)
gameport_id = iface.gameport;
var el = $('#'+windowport_id, dom_context);
if (!el.length) {
glkote_error('Cannot find windowport element #'+windowport_id+' in this document.');
return;
}
el.empty();
if (perform_paging)
$(document).on('keypress', evhan_doc_keypress);
$(window).on('resize', evhan_doc_resize);
/* Note the pixel ratio (resolution level; this is greater than 1 for
high-res displays. */
current_devpixelratio = window.devicePixelRatio || 1;
/* We can get callbacks on any *boolean* change in the resolution level.
Not, unfortunately, on all changes. */
if (window.matchMedia) {
window.matchMedia('screen and (min-resolution: 1.5dppx)').addListener(evhan_doc_pixelreschange);
window.matchMedia('screen and (min-resolution: 2dppx)').addListener(evhan_doc_pixelreschange);
window.matchMedia('screen and (min-resolution: 3dppx)').addListener(evhan_doc_pixelreschange);
window.matchMedia('screen and (min-resolution: 4dppx)').addListener(evhan_doc_pixelreschange);
}
/* Figure out the window size and font metrics. */
var res = measure_window();
if (jQuery.type(res) === 'string') {
glkote_error(res);
return;
}
current_metrics = res;
/* Add some elements which will give us notifications if the gameport
size changes. */
create_resize_sensors();
/* Check the options that control whether URL-like strings in the output
are displayed as hyperlinks. */
detect_external_links = iface.detect_external_links;
if (detect_external_links) {
regex_external_links = iface.regex_external_links;
if (!regex_external_links) {
/* Fill in a default regex for matching or finding URLs. */
if (detect_external_links == 'search') {
/* The searching case is hard. This regex is based on John Gruber's
monstrosity, the "web URL only" variant:
http://daringfireball.net/2010/07/improved_regex_for_matching_urls
I cut it down a bit; it will not recognize bare domain names like
"www.eblong.com". I also removed the "(?i)" from the beginning,
because Javascript doesn't handle that syntax. (It's supposed to
make the regex case-insensitive.) Instead, we use the 'i'
second argument to RegExp().
*/
regex_external_links = RegExp('\\b((?:https?://)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:\'".,<>?\u00ab\u00bb\u201c\u201d\u2018\u2019]))', 'i');
}
else {
/* The matching case is much simpler. This matches any string
beginning with "http" or "https". */
regex_external_links = RegExp('^https?:', 'i');
}
}
}
/* Check the options that control transcript recording. */
if (iface.recording_url) {
recording = true;
recording_handler = recording_standard_handler;
recording_handler_url = iface.recording_url;
}
if (iface.recording_handler) {
recording = true;
recording_handler = iface.recording_handler;
recording_handler_url = '(custom handler)';
}
if (recording) {
/* But also check whether the user has opted out by putting "feedback=0"
in the URL query. */
var qparams = get_query_params();
var flag = qparams['feedback'];
if (jQuery.type(flag) != 'undefined' && flag != '1') {
recording = false;
glkote_log('User has opted out of transcript recording.');
}
else {
/* Set up the recording-state object. */
recording_state = {
sessionId: (new Date().getTime())+""+( Math.ceil( Math.random() * 10000 ) ),
input: null, output: null,
timestamp: 0, outtimestamp: 0
}
if (iface.recording_label)
recording_state.label = iface.recording_label;
if (iface.recording_format == 'simple')
recording_state.format = 'simple';
else
recording_state.format = 'glkote';
glkote_log('Transcript recording active: session ' + recording_state.sessionId + ' "' + recording_state.label + '", destination ' + recording_handler_url);
}
}
if (iface.debug_commands) {
var debugmod = window.GiDebug;
if (iface.debug_commands != true)
debugmod = iface.debug_commands;
if (!debugmod) {
glkote_log('The debug_commands option is set, but there is no GiDebug module.');
}
else {
debugmod.init(evhan_debug_command);
debug_out_handler = debugmod.output;
if (iface.debug_console_open)
debugmod.open();
}
}
if (!iface.font_load_delay) {
/* Normal case: start the game (interpreter) immediately. */
send_response('init', null, current_metrics);
}
else {
/* Delay case: wait a tiny interval, then re-check the window metrics
and *then* start the game. We might need to do this if the window
fonts were not cached or loaded with the DOM. (Lectrote, for example,
because of the way it loads font preferences.) */
disabled = true;
defer_func(function() {
disabled = false;
current_metrics = measure_window();
send_response('init', null, current_metrics);
});
}
}
/* Work out various pixel measurements used to compute window sizes:
- the width and height of the windowport
- the width and height of a character in a grid window
- ditto for buffer windows (although this is only approximate, since
buffer window fonts can be non-fixed-width, and styles can have
different point sizes)
- the amount of padding space around buffer and grid window content
This stuff is determined by creating some invisible, offscreen windows
and measuring their dimensions.
*/
function measure_window() {
var metrics = {};
var winsize, line1size, line2size, spansize, canvassize;
/* We assume the gameport is the same size as the windowport, which
is true on all browsers but IE7. Fortunately, on IE7 it's
the windowport size that's wrong -- gameport is the size
we're interested in. */
var gameport = $('#'+gameport_id, dom_context);
if (!gameport.length)
return 'Cannot find gameport element #'+gameport_id+' in this document.';
/* If the HTML file includes an #layouttestpane div, we discard it.
We used to do metrics measurements from a predefined div with
that name. Nowadays, it's sometimes used as a hidden font-preloader. */
$('#layouttestpane', dom_context).remove();
/* Exclude padding and border. */
metrics.width = gameport.width();
metrics.height = gameport.height();
metrics.width = gameport.width();
metrics.height = gameport.height();
/* Create a dummy layout div containing a grid window and a buffer window,
each with two lines of text. */
var layout_test_pane = $('<div>', { 'id':'layout_test_pane' });
layout_test_pane.text('This should not be visible');
layout_test_pane.css({
/* "display:none" would make the pane not render at all, making it
impossible to measure. Instead, make it invisible and offscreen. */
position: 'absolute',
visibility: 'hidden',
left: '-1000px'
});
var line = $('<div>');
line.append($('<span>', {'class': "Style_normal"}).text('12345678'));
var gridwin = $('<div>', {'class': 'WindowFrame GridWindow'});
var gridline1 = line.clone().addClass('GridLine').appendTo(gridwin);
var gridline2 = line.clone().addClass('GridLine').appendTo(gridwin);
var gridspan = gridline1.children('span');
layout_test_pane.append(gridwin);
var bufwin = $('<div>', {'class': 'WindowFrame BufferWindow'});
var bufline1 = line.clone().addClass('BufferLine').appendTo(bufwin);
var bufline2 = line.clone().addClass('BufferLine').appendTo(bufwin);
var bufspan = bufline1.children('span');
layout_test_pane.append(bufwin);
var graphwin = $('<div>', {'class': 'WindowFrame GraphicsWindow'});
var graphcanvas = $('<canvas>');
graphcanvas.attr('width', 64);
graphcanvas.attr('height', 32);
graphwin.append(graphcanvas);
layout_test_pane.append(graphwin);
gameport.append(layout_test_pane);
var get_size = function(el) {
return {
width: el.outerWidth(),
height: el.outerHeight()
};
};
/* Here we will include padding and border. */
winsize = get_size(gridwin);
spansize = get_size(gridspan);
line1size = get_size(gridline1);
line2size = get_size(gridline2);
metrics.gridcharheight = gridline2.position().top - gridline1.position().top;
metrics.gridcharwidth = gridspan.width() / 8;
/* Yes, we can wind up with a non-integer charwidth value. */
/* Find the total margin around the character grid (out to the window's
padding/border). These values include both sides (left+right,
top+bottom). */
metrics.gridmarginx = winsize.width - spansize.width;
metrics.gridmarginy = winsize.height - (line1size.height + line2size.height);
/* Here we will include padding and border. */
winsize = get_size(bufwin);
spansize = get_size(bufspan);
line1size = get_size(bufline1);
line2size = get_size(bufline2);
metrics.buffercharheight = bufline2.position().top - bufline1.position().top;
metrics.buffercharwidth = bufspan.width() / 8;
/* Yes, we can wind up with a non-integer charwidth value. */
/* Again, these values include both sides (left+right, top+bottom). */
metrics.buffermarginx = winsize.width - spansize.width;
metrics.buffermarginy = winsize.height - (line1size.height + line2size.height);
/* Here we will include padding and border. */
winsize = get_size(graphwin);
canvassize = get_size(graphcanvas);
/* Again, these values include both sides (left+right, top+bottom). */
metrics.graphicsmarginx = winsize.width - canvassize.width;
metrics.graphicsmarginy = winsize.height - canvassize.height;
/* Now that we're done measuring, discard the pane. */
layout_test_pane.remove();
/* These values come from the game interface object. */
metrics.outspacingx = 0;
metrics.outspacingy = 0;
metrics.inspacingx = 0;
metrics.inspacingy = 0;
if (game_interface.spacing != undefined) {
metrics.outspacingx = game_interface.spacing;
metrics.outspacingy = game_interface.spacing;
metrics.inspacingx = game_interface.spacing;
metrics.inspacingy = game_interface.spacing;
}
if (game_interface.outspacing != undefined) {
metrics.outspacingx = game_interface.outspacing;
metrics.outspacingy = game_interface.outspacing;
}
if (game_interface.inspacing != undefined) {
metrics.inspacingx = game_interface.inspacing;
metrics.inspacingy = game_interface.inspacing;
}
if (game_interface.inspacingx != undefined)
metrics.inspacingx = game_interface.inspacingx;
if (game_interface.inspacingy != undefined)
metrics.inspacingy = game_interface.inspacingy;
if (game_interface.outspacingx != undefined)
metrics.outspacingx = game_interface.outspacingx;
if (game_interface.outspacingy != undefined)
metrics.outspacingy = game_interface.outspacingy;
return metrics;
}
/* Compare two metrics objects; return whether they're "roughly"
similar. (We only care about window size and some of the font
metrics, because those are the fields likely to change out
from under the library.)
*/
function metrics_match(met1, met2) {
if (met1.width != met2.width)
return false;
if (met1.height != met2.height)
return false;
if (met1.gridcharwidth != met2.gridcharwidth)
return false;
if (met1.gridcharheight != met2.gridcharheight)
return false;
if (met1.buffercharwidth != met2.buffercharwidth)
return false;
if (met1.buffercharheight != met2.buffercharheight)
return false;
return true;
}
/* Create invisible divs in the gameport which will fire events if the
gameport changes size. (For any reason, including document CSS changes.
We need this to detect Lectrote's margin change, for example.)
This code is freely adapted from CSS Element Queries by Marc J. Schmidt.
https://github.com/marcj/css-element-queries
*/
function create_resize_sensors() {
var gameport = $('#'+gameport_id, dom_context);
if (!gameport.length)
return 'Cannot find gameport element #'+gameport_id+' in this document.';
var shrinkel = $('<div>', {
id: 'resize-sensor-shrink'
}).css({
position:'absolute',
left:'0', right:'0', top:'0', bottom:'0',
overflow:'hidden', visibility:'hidden',
'z-index':'-1'
});
shrinkel.append($('<div>', {
id: 'resize-sensor-shrink-child'
}).css({
position:'absolute',
left:'0', right:'0',
width:'200%', height:'200%'
}));
var expandel = $('<div>', {
id: 'resize-sensor-expand'
}).css({
position:'absolute',
left:'0', right:'0', top:'0', bottom:'0',
overflow:'hidden', visibility:'hidden',
'z-index':'-1'
});
expandel.append($('<div>', {
id: 'resize-sensor-expand-child'
}).css({
position:'absolute',
left:'0', right:'0'
}));
var shrinkdom = shrinkel.get(0);
var expanddom = expandel.get(0);
var expandchilddom = expanddom.childNodes[0];
var reset = function() {
shrinkdom.scrollLeft = 100000;
shrinkdom.scrollTop = 100000;
expandchilddom.style.width = '100000px';
expandchilddom.style.height = '100000px';
expanddom.scrollLeft = 100000;
expanddom.scrollTop = 100000;
}
gameport.append(shrinkel);
gameport.append(expandel);
reset();
var evhan = function(ev) {
evhan_doc_resize(ev);
reset();
}
/* These events fire copiously when the window is being resized.
This is one reason evhan_doc_resize() has debouncing logic. */
shrinkel.on('scroll', evhan);
expandel.on('scroll', evhan);
}
/* This function becomes GlkOte.update(). The game calls this to update
the screen state. The argument includes all the information about new
windows, new text, and new input requests -- everything necessary to
construct a new display state for the user.
*/
function glkote_update(arg) {
hide_loading();
/* This field is *only* for the autorestore case, and only on the very
first update. It contains additional information (from save_allstate)
which helps recreate the display. */
var autorestore = null;
if (arg.autorestore && generation == 0)
autorestore = arg.autorestore;
delete arg.autorestore; /* keep it out of the recording */
if (recording) {
recording_send(arg);
}
if (arg.debugoutput && debug_out_handler) {
debug_out_handler(arg.debugoutput);
}
if (arg.type == 'error') {
glkote_error(arg.message);
return;
}
if (arg.type == 'pass') {
return;
}
if (arg.type == 'retry') {
if (!retry_timer) {
glkote_log('Event has timed out; will retry...');
show_loading();
retry_timer = delay_func(2, retry_update);
}
else {
glkote_log('Event has timed out, but a retry is already queued!');
}
return;
}
if (arg.type != 'update') {
glkote_log('Ignoring unknown message type ' + arg.type + '.');
return;
}
if (arg.gen == generation) {
/* Nothing has changed. */
glkote_log('Ignoring repeated generation number: ' + generation);
return;
}
if (arg.gen < generation) {
/* This update belongs in the past. */
glkote_log('Ignoring out-of-order generation number: got ' + arg.gen + ', currently at ' + generation);
return;
}
generation = arg.gen;
/* Un-disable the UI, if it was previously disabled. */
if (disabled) {
jQuery.each(windowdic, function(winid, win) {
if (win.inputel) {
win.inputel.prop('disabled', false);
}
});
disabled = false;
}
/* Perform the updates, in a most particular order. */
if (arg.input != null)
accept_inputcancel(arg.input);
if (arg.windows != null)
accept_windowset(arg.windows);
if (arg.content != null)
accept_contentset(arg.content);
if (arg.input != null)
accept_inputset(arg.input);
/* Note that a timer value of null is different from undefined. */
if (arg.timer !== undefined)
accept_timerrequest(arg.timer);
if (arg.specialinput != null)
accept_specialinput(arg.specialinput);
/* Any buffer windows that have changed need to be scrolled down.
Then, we take the opportunity to update topunseen. (If a buffer
window hasn't changed, topunseen hasn't changed.) */
jQuery.each(windowdic, function(winid, win) {
if (win.type == 'buffer' && win.needscroll) {
/* needscroll is true if the window has accumulated any content or
an input field in this update cycle. needspaging is true if
the window has any unviewed content from *last* cycle; we set
it now if any new content remains unviewed after the first
obligatory scrolldown.
(If perform_paging is false, we forget about needspaging and
just always scroll to the bottom.) */
win.needscroll = false;
if (!win.needspaging) {
var frameel = win.frameel;
if (!perform_paging) {
/* Scroll all the way down. Note that scrollHeight is not a jQuery
property; we have to go to the raw DOM to get it. */
frameel.scrollTop(frameel.get(0).scrollHeight);
win.needspaging = false;
}
else {
/* Scroll the unseen content to the top. */
frameel.scrollTop(win.topunseen - current_metrics.buffercharheight);
/* Compute the new topunseen value. */
win.pagefrommark = win.topunseen;
var frameheight = frameel.outerHeight();
var realbottom = buffer_last_line_top_offset(win);
var newtopunseen = frameel.scrollTop() + frameheight;
if (newtopunseen > realbottom)
newtopunseen = realbottom;
if (win.topunseen < newtopunseen)
win.topunseen = newtopunseen;
/* The scroll-down has not touched needspaging, because it is
currently false. Let's see if it should be true. */
if (frameel.scrollTop() + frameheight + moreprompt_margin >= frameel.get(0).scrollHeight) {
win.needspaging = false;
}
else {
win.needspaging = true;
}
}
/* Add or remove the more prompt and previous mark, based on the
new needspaging flag. Note that the more-prompt will be
removed when the user scrolls down; but the prev-mark
stays until we get back here. */
var moreel = $('#win'+win.id+'_moreprompt', dom_context);
var prevel = $('#win'+win.id+'_prevmark', dom_context);
if (!win.needspaging) {
if (moreel.length)
moreel.remove();
if (prevel.length)
prevel.remove();
}
else {
if (!moreel.length) {
moreel = $('<div>',
{ id: 'win'+win.id+'_moreprompt', 'class': 'MorePrompt' } );
moreel.append('More');
/* 20 pixels is a cheap approximation of a scrollbar-width. */
var morex = win.coords.right + approx_scroll_width;
var morey = win.coords.bottom;
moreel.css({ bottom:morey+'px', right:morex+'px' });
$('#'+windowport_id, dom_context).append(moreel);
}
if (!prevel.length) {
prevel = $('<div>',
{ id: 'win'+win.id+'_prevmark', 'class': 'PreviousMark' } );
frameel.prepend(prevel);
}
prevel.css('top', (win.pagefrommark+'px'));
}
}
}
});
/* Set windows_paging_count. (But don't set the focus -- we'll do that
momentarily.) */
readjust_paging_focus(false);
/* Disable everything, if that was requested (or if this is a special
input cycle). */
disabled = false;
if (arg.disable || arg.specialinput) {
disabled = true;
jQuery.each(windowdic, function(winid, win) {
if (win.inputel) {
win.inputel.prop('disabled', true);
}
});
}
/* Figure out which window to set the focus to. (But not if the UI is
disabled. We also skip this if there's paging to be done, because
focussing might autoscroll and we want to trap keystrokes for
paging anyhow.) */
var newinputwin = 0;
if (!disabled && !windows_paging_count) {
jQuery.each(windowdic, function(winid, win) {
if (win.input) {
if (!newinputwin || win.id == last_known_focus)
newinputwin = win.id;
}
});
}
if (newinputwin) {
/* MSIE is weird about when you can call focus(). The input element
has probably just been added to the DOM, and MSIE balks at
giving it the focus right away. So we defer the call until
after the javascript context has yielded control to the browser. */
var focusfunc = function() {
var win = windowdic[newinputwin];
if (win.inputel) {
win.inputel.focus();
}
};
defer_func(focusfunc);
}
if (autorestore) {
if (autorestore.history) {
jQuery.each(autorestore.history, function(winid, ls) {
win = windowdic[winid];
if (win != null) {
win.history = ls.slice(0);
win.historypos = win.history.length;
}
});
}
if (autorestore.defcolor) {
jQuery.each(autorestore.defcolor, function(winid, val) {
win = windowdic[winid];
if (win != null) {
win.defcolor = val;
}
});
}
/* For the case of autorestore (only), we short-circuit the paging
mechanism and assume the player has already seen all the text. */
jQuery.each(windowdic, function(winid, win) {
if (win.type == 'buffer') {
window_scroll_to_bottom(win);
}
});
if (!(autorestore.metrics
&& autorestore.metrics.width == current_metrics.width
&& autorestore.metrics.height == current_metrics.height)) {
/* The window metrics don't match what's recorded in the
autosave. Trigger a synthetic resize event. */
current_metrics.width += 2;
evhan_doc_resize();
}
}
/* Done with the update. Exit and wait for the next input event. */
}
/* Handle all the window changes. The argument lists all windows that
should be open. Any unlisted windows, therefore, get closed.
Note that if there are no changes to the window state, this function
will not be called. This is different from calling this function with
an empty argument object (which would mean "close all windows").
*/
function accept_windowset(arg) {
jQuery.each(windowdic, function(winid, win) { win.inplace = false; });
jQuery.map(arg, accept_one_window);
/* Close any windows not mentioned in the argument. */
var closewins = jQuery.map(windowdic, function(win, winid) {
if (!win.inplace)
return win;
});
jQuery.map(closewins, close_one_window);
}
/* Handle the update for a single window. Open it if it doesn't already
exist; set its size and position, if those need to be changed.
*/
function accept_one_window(arg) {
var frameel, win;
if (!arg) {
return;
}
win = windowdic[arg.id];
if (win == null) {
/* The window must be created. */
win = { id: arg.id, type: arg.type, rock: arg.rock };
windowdic[arg.id] = win;
var typeclass;
if (win.type == 'grid')
typeclass = 'GridWindow';
if (win.type == 'buffer')
typeclass = 'BufferWindow';
if (win.type == 'graphics')
typeclass = 'GraphicsWindow';
var rockclass = 'WindowRock_' + arg.rock;
frameel = $('<div>',
{ id: 'window'+arg.id,
'class': 'WindowFrame ' + typeclass + ' ' + rockclass });
frameel.data('winid', arg.id);
frameel.on('mousedown', arg.id, evhan_window_mousedown);
if (perform_paging && win.type == 'buffer')
frameel.on('scroll', arg.id, evhan_window_scroll);
if (win.type == 'grid' || win.type == 'graphics')
frameel.on('click', win.id, evhan_input_mouse_click);
if (win.type == 'buffer')
frameel.attr({
'aria-live':'polite',
'aria-atomic':'false',
'aria-relevant':'additions' });
win.frameel = frameel;
win.gridheight = 0;
win.gridwidth = 0;
win.input = null;
win.inputel = null;
win.terminators = {};
win.reqhyperlink = false;
win.reqmouse = false;
win.needscroll = false;
win.needspaging = false;
win.topunseen = 0;
win.pagefrommark = 0;
win.coords = { left:null, top:null, right:null, bottom:null };
win.history = new Array();
win.historypos = 0;
$('#'+windowport_id, dom_context).append(frameel);
}
else {
frameel = win.frameel;
if (win.type != arg.type)
glkote_error('Window ' + arg.id + ' was created with type ' + win.type + ', but now is described as type ' + arg.type);
}
win.inplace = true;
if (win.type == 'grid') {
/* Make sure we have the correct number of GridLine divs. */
var ix;
if (arg.gridheight > win.gridheight) {
for (ix=win.gridheight; ix<arg.gridheight; ix++) {
var el = $('<div>',
{ id: 'win'+win.id+'_ln'+ix, 'class': 'GridLine' });
el.append(NBSP);
win.frameel.append(el);
}
}
if (arg.gridheight < win.gridheight) {
for (ix=arg.gridheight; ix<win.gridheight; ix++) {
var el = $('#win'+win.id+'_ln'+ix, dom_context);
if (el.length)
el.remove();
}
}
win.gridheight = arg.gridheight;
win.gridwidth = arg.gridwidth;
}
if (win.type == 'buffer') {
/* Don't need anything? */
}
if (win.type == 'graphics') {
var el = $('#win'+win.id+'_canvas', dom_context);
if (!el.length) {
win.graphwidth = arg.graphwidth;
win.graphheight = arg.graphheight;
win.defcolor = '#FFF';
el = $('<canvas>',
{ id: 'win'+win.id+'_canvas' });
/* The pixel-ratio code here should work correctly on Chrome and
Safari, on screens of any pixel-ratio. I followed
http://www.html5rocks.com/en/tutorials/canvas/hidpi/ .
*/
win.backpixelratio = 1;
var canvas = el.get(0);
var ctx = canvas_get_2dcontext(el);
if (ctx) {
/* This property is still namespaced as of 2016. */
win.backpixelratio = ctx.webkitBackingStorePixelRatio
|| ctx.mozBackingStorePixelRatio
|| ctx.msBackingStorePixelRatio
|| ctx.oBackingStorePixelRatio
|| ctx.backingStorePixelRatio
|| 1;
}
win.scaleratio = current_devpixelratio / win.backpixelratio;
//glkote_log('### created canvas with scale ' + win.scaleratio + ' (device ' + current_devpixelratio + ' / backstore ' + win.backpixelratio + ')');
el.attr('width', win.graphwidth * win.scaleratio);
el.attr('height', win.graphheight * win.scaleratio);
el.css('width', (win.graphwidth + 'px'));
el.css('height', (win.graphheight + 'px'));
win.frameel.css('background-color', win.defcolor);
if (ctx) {
/* Set scale to win.scaleratio */
ctx.setTransform(win.scaleratio, 0, 0, win.scaleratio, 0, 0);
}
win.frameel.append(el);
}
else {
if (win.graphwidth != arg.graphwidth || win.graphheight != arg.graphheight) {
win.graphwidth = arg.graphwidth;
win.graphheight = arg.graphheight;
el.attr('width', win.graphwidth * win.scaleratio);
el.attr('height', win.graphheight * win.scaleratio);
el.css('width', (win.graphwidth + 'px'));
el.css('height', (win.graphheight + 'px'));
/* Clear to the default color, as if for a "fill" command. */
var ctx = canvas_get_2dcontext(el);
if (ctx) {
ctx.setTransform(win.scaleratio, 0, 0, win.scaleratio, 0, 0);
ctx.fillStyle = win.defcolor;
ctx.fillRect(0, 0, win.graphwidth, win.graphheight);
ctx.fillStyle = '#000000';
}
win.frameel.css('background-color', win.defcolor);
/* We have to trigger a redraw event for this window. But we can't do
that from inside the accept handler. We'll set up a deferred
function call. */
var funcarg = win.id;
defer_func(function() { send_window_redraw(funcarg); });
}
}
}
/* The trick is that left/right/top/bottom are measured to the outside
of the border, but width/height are measured from the inside of the
border. (Measured by the browser's DOM methods, I mean.) */
var styledic;
if (0 /*###Prototype.Browser.IE*/) {
/* Actually this method works in Safari also, but in Firefox the buffer
windows are too narrow by a scrollbar-width. So we don't use it
generally. */
var width = arg.width;
var height = arg.height;
if (arg.type == 'grid') {
width -= current_metrics.gridmarginx;
height -= current_metrics.gridmarginy;
}
if (arg.type == 'buffer') {
width -= current_metrics.buffermarginx;
height -= current_metrics.buffermarginy;
}
if (width < 0)
width = 0;
if (height < 0)
height = 0;