-
Notifications
You must be signed in to change notification settings - Fork 0
/
screen.cpp
3483 lines (2985 loc) · 103 KB
/
screen.cpp
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
// Copyright 2010-2021 Chris Spiegel.
//
// This file is part of Bocfel.
//
// Bocfel is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License, version
// 2 or 3, as published by the Free Software Foundation.
//
// Bocfel is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Bocfel. If not, see <http://www.gnu.org/licenses/>.
#include <algorithm>
#include <array>
#include <bitset>
#include <cstdarg>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <functional>
#include <initializer_list>
#include <iostream>
#include <iterator>
#include <list>
#include <memory>
#include <new>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#ifdef ZTERP_GLK
extern "C" {
#include <glk.h>
}
#ifdef ZERP_GLK_WINGLK
// rpcndr.h, eventually included via WinGlk.h, defines a type “byte”
// which conflicts with the “byte” from memory.h. Temporarily redefine
// it to avoid a compile error.
#define byte rpc_byte
// Windows Glk puts non-standard declarations (specifically for this
// file, those guarded by GLK_MODULE_GARGLKTEXT) in WinGlk.h, so include
// it to get color/style extensions.
#include <WinGlk.h>
#undef byte
#endif
#endif
#include "screen.h"
#include "branch.h"
#include "dict.h"
#include "iff.h"
#include "io.h"
#include "memory.h"
#include "meta.h"
#include "objects.h"
#include "osdep.h"
#include "process.h"
#include "sound.h"
#include "stack.h"
#include "stash.h"
#include "types.h"
#include "unicode.h"
#include "util.h"
#include "zterp.h"
// Somewhat ugly hack to get around the fact that some Glk functions may
// not exist. These function calls should all be guarded (e.g.
// if (have_unicode), with have_unicode being set iff GLK_MODULE_UNICODE
// is defined) so they will never be called if the Glk implementation
// being used does not support them, but they must at least exist to
// prevent link errors.
#ifdef ZTERP_GLK
#ifndef GLK_MODULE_UNICODE
#define glk_put_char_uni(...) die("bug %s:%d: glk_put_char_uni() called with no unicode", __FILE__, __LINE__)
#define glk_put_char_stream_uni(...) die("bug %s:%d: glk_put_char_stream_uni() called with no unicode", __FILE__, __LINE__)
#define glk_request_char_event_uni(...) die("bug %s:%d: glk_request_char_event_uni() called with no unicode", __FILE__, __LINE__)
#define glk_request_line_event_uni(...) die("bug %s:%d: glk_request_line_event_uni() called with no unicode", __FILE__, __LINE__)
#endif
#ifndef GLK_MODULE_LINE_ECHO
#define glk_set_echo_line_event(...) die("bug: %s %d: glk_set_echo_line_event() called with no line echo", __FILE__, __LINE__)
#endif
#endif
// Flag describing whether the header bit meaning “fixed font” is set.
static bool header_fixed_font;
// This variable stores whether Unicode is supported by the current Glk
// implementation, which determines whether Unicode or Latin-1 Glk
// functions are used. In addition, for both Glk and non-Glk versions,
// this affects the behavior of @check_unicode. In non-Glk versions,
// this is always true.
static bool have_unicode;
struct Window {
Style style;
Color fg_color = Color(), bg_color = Color();
enum class Font { Query, Normal, Picture, Character, Fixed } font = Font::Normal;
#ifdef ZTERP_GLK
winid_t id = nullptr;
long x = 0, y = 0; // Only meaningful for window 1
bool has_echo = false;
#endif
};
static std::array<Window, 8> windows;
static Window *mainwin = &windows[0], *curwin = &windows[0];
#ifdef ZTERP_GLK
// This represents a line of input from Glk; if the global variable
// “have_unicode” is true, then the “unicode” member is used; otherwise,
// “latin1”.
struct Line {
union {
std::array<char, 256> latin1;
std::array<glui32, 256> unicode;
};
glui32 len;
};
static Window *upperwin = &windows[1];
static Window statuswin;
static long upper_window_height = 0;
static long upper_window_width = 0;
static winid_t errorwin;
#endif
// In all versions but 6, styles and colors are global and stored in
// mainwin. For V6, they’re tracked per window and thus stored in each
// individual window. For convenience, this macro returns the “style
// window” for any version.
static Window *style_window()
{
return zversion == 6 ? curwin : mainwin;
}
// Output stream bits.
enum {
STREAM_SCREEN = 1,
STREAM_TRANS = 2,
STREAM_MEMORY = 3,
STREAM_SCRIPT = 4,
};
static std::bitset<5> streams;
static std::unique_ptr<IO> scriptio, transio, perstransio;
class StreamTables {
public:
void push(uint16_t addr) {
ZASSERT(m_tables.size() < MAX_STREAM_TABLES, "too many stream tables");
m_tables.emplace_back(addr);
}
void pop() {
if (!m_tables.empty()) {
m_tables.pop_back();
}
}
void write(uint16_t c) {
ZASSERT(!m_tables.empty(), "invalid stream table");
m_tables.back().write(c);
}
size_t size() const {
return m_tables.size();
}
void clear() {
m_tables.clear();
}
private:
static constexpr size_t MAX_STREAM_TABLES = 16;
class Table {
public:
explicit Table(uint16_t addr) : m_addr(addr) {
user_store_word(m_addr, 0);
}
Table(const Table &) = delete;
Table &operator=(const Table &) = delete;
~Table() {
user_store_word(m_addr, m_idx - 2);
if (zversion == 6) {
store_word(0x30, m_idx - 2);
}
}
void write(uint8_t c) {
user_store_byte(m_addr + m_idx++, c);
}
private:
uint16_t m_addr;
uint16_t m_idx = 2;
};
std::list<Table> m_tables;
};
static StreamTables stream_tables;
static int istream = ISTREAM_KEYBOARD;
static std::unique_ptr<IO> istreamio;
struct Input {
enum class Type { Char, Line } type;
// ZSCII value of key read for @read_char.
uint8_t key;
// Unicode line of chars read for @read.
std::array<uint16_t, 256> line;
uint8_t maxlen;
uint8_t len;
uint8_t preloaded;
// Character used to terminate input. If terminating keys are not
// supported by the Glk implementation being used (or if Glk is not
// used at all) this will be ZSCII_NEWLINE; or in the case of
// cancellation, 0.
uint8_t term;
};
// Convert a 15-bit color to a 24-bit color.
uint32_t screen_convert_color(uint16_t color)
{
// Map 5-bit color values to 8-bit.
const uint32_t table[] = {
0x00, 0x08, 0x10, 0x19, 0x21, 0x29, 0x31, 0x3a,
0x42, 0x4a, 0x52, 0x5a, 0x63, 0x6b, 0x73, 0x7b,
0x84, 0x8c, 0x94, 0x9c, 0xa5, 0xad, 0xb5, 0xbd,
0xc5, 0xce, 0xd6, 0xde, 0xe6, 0xef, 0xf7, 0xff
};
return table[(color >> 0) & 0x1f] << 16 |
table[(color >> 5) & 0x1f] << 8 |
table[(color >> 10) & 0x1f] << 0;
}
#ifdef GLK_MODULE_GARGLKTEXT
static glui32 zcolor_map[] = {
static_cast<glui32>(zcolor_Current),
static_cast<glui32>(zcolor_Default),
0x000000, // Black
0xef0000, // Red
0x00d600, // Green
0xefef00, // Yellow
0x006bb5, // Blue
0xff00ff, // Magenta
0x00efef, // Cyan
0xffffff, // White
0xb5b5b5, // Light grey
0x8c8c8c, // Medium grey
0x5a5a5a, // Dark grey
};
void update_color(int which, unsigned long color)
{
if (which < 2 || which > 12) {
return;
}
zcolor_map[which] = color;
}
// Provide descriptive aliases for Gargoyle styles.
enum {
GStyleBoldItalicFixed = style_Note,
GStyleBoldItalic = style_Alert,
GStyleBoldFixed = style_User1,
GStyleItalicFixed = style_User2,
GStyleBold = style_Subheader,
GStyleItalic = style_Emphasized,
GStyleFixed = style_Preformatted,
};
static int gargoyle_style(const Style &style)
{
if (style.test(STYLE_BOLD) && style.test(STYLE_ITALIC) && style.test(STYLE_FIXED)) {
return GStyleBoldItalicFixed;
} else if (style.test(STYLE_BOLD) && style.test(STYLE_ITALIC)) {
return GStyleBoldItalic;
} else if (style.test(STYLE_BOLD) && style.test(STYLE_FIXED)) {
return GStyleBoldFixed;
} else if (style.test(STYLE_ITALIC) && style.test(STYLE_FIXED)) {
return GStyleItalicFixed;
} else if (style.test(STYLE_BOLD)) {
return GStyleBold;
} else if (style.test(STYLE_ITALIC)) {
return GStyleItalic;
} else if (style.test(STYLE_FIXED)) {
return GStyleFixed;
}
return style_Normal;
}
static glui32 gargoyle_color(const Color &color)
{
switch (color.mode) {
case Color::Mode::ANSI:
return zcolor_map[color.value];
case Color::Mode::True:
return screen_convert_color(color.value);
}
return zcolor_Current;
}
#endif
#ifdef ZTERP_GLK
// These functions make it so that code elsewhere needn’t check have_unicode before printing.
static void xglk_put_char(uint16_t c)
{
if (!have_unicode) {
glk_put_char(unicode_to_latin1[c]);
} else {
glk_put_char_uni(c);
}
}
static void xglk_put_char_stream(strid_t s, uint32_t c)
{
if (!have_unicode) {
glk_put_char_stream(s, unicode_to_latin1[c]);
} else {
glk_put_char_stream_uni(s, c);
}
}
#endif
static void set_window_style(const Window *win)
{
#ifdef ZTERP_GLK
auto style = win->style;
if (curwin->id == nullptr) {
return;
}
#ifdef GLK_MODULE_GARGLKTEXT
if (curwin->font == Window::Font::Fixed || header_fixed_font) {
style.set(STYLE_FIXED);
}
if (options.disable_fixed) {
style.reset(STYLE_FIXED);
}
glk_set_style(gargoyle_style(style));
garglk_set_reversevideo(style.test(STYLE_REVERSE));
garglk_set_zcolors(gargoyle_color(win->fg_color), gargoyle_color(win->bg_color));
#else
// Yes, there are three ways to indicate that a fixed-width font should be used.
bool use_fixed_font = style.test(STYLE_FIXED) || curwin->font == Window::Font::Fixed || header_fixed_font;
// Glk can’t mix other styles with fixed-width, but the upper window
// is always fixed, so if it is selected, there is no need to
// explicitly request it here. In addition, the user can disable
// fixed-width fonts or tell Bocfel to assume that the output font is
// already fixed (e.g. in an xterm); in either case, there is no need
// to request a fixed font.
// This means that another style can also be applied if applicable.
if (use_fixed_font && !options.disable_fixed && !options.assume_fixed && curwin != upperwin) {
glk_set_style(style_Preformatted);
return;
}
// According to standard 1.1, if mixed styles aren’t available, the
// priority is Fixed, Italic, Bold, Reverse.
if (style.test(STYLE_ITALIC)) {
glk_set_style(style_Emphasized);
} else if (style.test(STYLE_BOLD)) {
glk_set_style(style_Subheader);
} else if (style.test(STYLE_REVERSE)) {
glk_set_style(style_Alert);
} else {
glk_set_style(style_Normal);
}
#endif
#else
zterp_os_set_style(win->style, win->fg_color, win->bg_color);
#endif
}
static void set_current_style()
{
set_window_style(style_window());
}
// The following implements a circular buffer to track the state of the
// screen so that recent history can be stored in save files for
// playback on restore.
constexpr size_t HISTORY_SIZE = 2000;
class History {
public:
struct Entry {
// Suppress a dubious shadow warning (see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=55776)
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wshadow"
#endif
// These values are part of the Bfhs chunk so must remain stable.
enum class Type {
Style = 0,
FGColor = 1,
BGColor = 2,
InputStart = 3,
InputEnd = 4,
Char = 5,
} type;
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
union Contents {
Color color;
uint8_t style;
uint32_t c;
Contents() : c(0) { }
explicit Contents(Color color_) : color(color_) { }
explicit Contents(uint8_t style_) : style(style_) { }
explicit Contents(uint32_t c_) : c(c_) { }
} contents;
explicit Entry(Type type_) : type(type_) { }
Entry(Type type_, const Color &color) : type(type_), contents(color) { }
Entry(Type type_, uint8_t style) : type(type_), contents(style) { }
Entry(Type type_, uint32_t c) : type(type_), contents(c) { }
static Entry style(uint8_t style) {
return {Type::Style, style};
}
static Entry color(Type color_type, const Color &color) {
return {color_type, color};
}
static Entry character(uint32_t c) {
return {Type::Char, c};
}
};
std::deque<Entry>::size_type size() {
return m_entries.size();
}
void add_style() {
auto style = mainwin->style;
if (mainwin->font == Window::Font::Fixed || header_fixed_font) {
style.set(STYLE_FIXED);
}
add(Entry::style(style.to_ulong()));
}
void add_fg_color(const Color &color) {
add(Entry::color(Entry::Type::FGColor, color));
}
void add_bg_color(const Color &color) {
add(Entry::color(Entry::Type::BGColor, color));
}
void add_input(const uint16_t *string, size_t len) {
add(Entry(Entry::Type::InputStart));
for (size_t i = 0; i < len; i++) {
add(Entry::character(string[i]));
}
add(Entry::character(UNICODE_LINEFEED));
add(Entry(Entry::Type::InputEnd));
}
void add_input_start() {
add(Entry(Entry::Type::InputStart));
}
void add_input_end() {
add(Entry(Entry::Type::InputEnd));
}
void add_char(uint32_t c) {
add(Entry::character(c));
}
const std::deque<Entry> &entries() {
return m_entries;
}
private:
void add(const Entry &entry) {
while (m_entries.size() >= HISTORY_SIZE) {
m_entries.pop_front();
}
m_entries.push_back(entry);
}
std::deque<Entry> m_entries;
};
static History history;
void screen_set_header_bit(bool set)
{
if (set != header_fixed_font) {
header_fixed_font = set;
history.add_style();
set_current_style();
}
}
static void transcribe(uint32_t c)
{
if (streams.test(STREAM_TRANS)) {
transio->putc(c);
}
if (perstransio != nullptr) {
perstransio->putc(c);
}
}
// Print out a character. The character is in “c” and is either Unicode
// or ZSCII; if the former, “unicode” is true. This is meant for any
// output produced by the game, as opposed to output produced by the
// interpreter, which should use Glk (or standard I/O) calls only, to
// avoid interacting with the Z-machine’s streams: interpreter-provided
// output should not be considered part of a transcript, nor should it
// be included in the memory stream.
static void put_char_base(uint16_t c, bool unicode)
{
if (c == 0) {
return;
}
if (streams.test(STREAM_MEMORY)) {
// When writing to memory, ZSCII should always be used (§7.5.3).
if (unicode) {
c = unicode_to_zscii_q[c];
}
stream_tables.write(c);
} else {
// For screen and transcription, always prefer Unicode.
if (!unicode) {
c = zscii_to_unicode[c];
}
if (c != 0) {
uint8_t zscii = 0;
// §16 makes no mention of what a newline in font 3 should map to.
// Other interpreters that implement font 3 assume it stays a
// newline, and this makes the most sense, so don’t do any
// translation in that case.
if (curwin->font == Window::Font::Character && !options.disable_graphics_font && c != UNICODE_LINEFEED) {
zscii = unicode_to_zscii[c];
// These four characters have a “built-in” reverse video (see §16).
if (zscii >= 123 && zscii <= 126) {
style_window()->style.flip(STYLE_REVERSE);
set_current_style();
}
c = zscii_to_font3[zscii];
}
#ifdef ZTERP_GLK
if (streams.test(STREAM_SCREEN) && curwin->id != nullptr) {
if (curwin == upperwin) {
// Interpreters seem to have differing ideas about what
// happens when the cursor reaches the end of a line in the
// upper window. Some wrap, some let it run off the edge (or,
// at least, stop the text at the edge). The standard, from
// what I can see, says nothing on this issue. Follow Windows
// Frotz and don’t wrap.
if (c == UNICODE_LINEFEED) {
if (upperwin->y < upper_window_height) {
// Glk wraps, so printing a newline when the cursor has
// already reached the edge of the screen will produce two
// newlines.
if (upperwin->x < upper_window_width) {
xglk_put_char(c);
}
// Even if a newline isn’t explicitly printed here
// (because the cursor is at the edge), setting
// upperwin->x to 0 will cause the next character to be on
// the next line because the text will have wrapped.
upperwin->x = 0;
upperwin->y++;
}
} else if (upperwin->x < upper_window_width && upperwin->y < upper_window_height) {
upperwin->x++;
xglk_put_char(c);
}
} else {
xglk_put_char(c);
}
}
#else
if (streams.test(STREAM_SCREEN) && curwin == mainwin) {
#ifdef ZTERP_DOS
// DOS doesn’t support Unicode, but instead uses code
// page 437. Special-case non-Glk DOS here, by writing
// bytes (not UTF-8 characters) from code page 437.
IO::standard_out().write8(unicode_to_437(c));
#else
IO::standard_out().putc(c);
#endif
}
#endif
if (curwin == mainwin) {
// Don’t check streams here: for quote boxes (which are in the
// upper window, and thus not transcribed), both Infocom and
// Inform games turn off the screen stream and write a duplicate
// copy of the quote, so it appears in a transcript (if any is
// occurring). In short, assume that if a game is writing text
// with the screen stream turned off, it’s doing so with the
// expectation that it appear in a transcript, which means it also
// ought to appear in the history.
history.add_char(c);
transcribe(c);
}
// If the reverse video bit was flipped (for the character font), flip it back.
if (zscii >= 123 && zscii <= 126) {
style_window()->style.flip(STYLE_REVERSE);
set_current_style();
}
}
}
}
static void put_char_u(uint16_t c)
{
put_char_base(c, true);
}
void put_char(uint8_t c)
{
put_char_base(c, false);
}
// Print a C string (UTF-8) directly to the main window. This is meant
// to print text from the interpreter, not the game. Text will also be
// written to any transcripts which are active, as well as to the
// history buffer. For convenience, carriage returns are ignored under
// the assumption that they are coming from a Windows text stream.
void screen_print(const std::string &s)
{
auto io = std::make_unique<IO>(std::vector<uint8_t>(s.begin(), s.end()), IO::Mode::ReadOnly);
#ifdef ZTERP_GLK
strid_t stream = glk_window_get_stream(mainwin->id);
#endif
for (long c = io->getc(false); c != -1; c = io->getc(false)) {
if (c != UNICODE_CARRIAGE_RETURN) {
transcribe(c);
history.add_char(c);
#ifdef ZTERP_GLK
xglk_put_char_stream(stream, c);
#endif
}
}
#ifndef ZTERP_GLK
std::cout << s;
#endif
}
void screen_printf(const char *fmt, ...)
{
std::va_list ap;
std::string message;
va_start(ap, fmt);
message = vstring(fmt, ap);
va_end(ap);
screen_print(message);
}
void screen_puts(const std::string &s)
{
screen_print(s);
screen_print("\n");
}
void show_message(const char *fmt, ...)
{
std::va_list ap;
std::string message;
va_start(ap, fmt);
message = vstring(fmt, ap);
va_end(ap);
#ifdef ZTERP_GLK
static glui32 error_lines = 0;
if (errorwin != nullptr) {
glui32 w, h;
// Allow multiple messages to stack, but force at least 5 lines to
// always be visible in the main window. This is less than perfect
// because it assumes that each message will be less than the width
// of the screen, but it’s not a huge deal, really; even if the
// lines are too long, at least Gargoyle and glktermw are graceful
// enough.
glk_window_get_size(mainwin->id, &w, &h);
if (h > 5) {
glk_window_set_arrangement(glk_window_get_parent(errorwin), winmethod_Below | winmethod_Fixed, ++error_lines, errorwin);
}
glk_put_char_stream(glk_window_get_stream(errorwin), LATIN1_LINEFEED);
} else {
errorwin = glk_window_open(mainwin->id, winmethod_Below | winmethod_Fixed, error_lines = 2, wintype_TextBuffer, 0);
}
// If windows are not supported (e.g. in cheapglk or no Glk), messages
// will not get displayed. If this is the case, print to the main
// window.
strid_t stream;
if (errorwin != nullptr) {
stream = glk_window_get_stream(errorwin);
glk_set_style_stream(stream, style_Alert);
} else {
stream = glk_window_get_stream(mainwin->id);
message = "\n[" + message + "]\n";
}
for (size_t i = 0; message[i] != 0; i++) {
xglk_put_char_stream(stream, char_to_unicode(message[i]));
}
#else
{
std::cout << "\n[" << message << "]\n";
}
#endif
}
void screen_message_prompt(const std::string &message)
{
screen_puts(message);
if (curwin == mainwin) {
screen_print("\n>");
}
}
// See §7.
// This returns true if the stream was successfully selected.
// Deselecting a stream is always successful.
bool output_stream(int16_t number, uint16_t table)
{
ZASSERT(std::labs(number) <= (zversion >= 3 ? 4 : 2), "invalid output stream selected: %ld", static_cast<long>(number));
if (number == 0) {
return true;
} else if (number > 0) {
streams.set(number);
} else if (number < 0) {
if (number != -3 || stream_tables.size() == 1) {
streams.reset(-number);
}
}
if (number == 2) {
store_word(0x10, word(0x10) | FLAGS2_TRANSCRIPT);
if (transio == nullptr) {
try {
transio = std::make_unique<IO>(options.transcript_name.get(), options.overwrite_transcript ? IO::Mode::WriteOnly : IO::Mode::Append, IO::Purpose::Transcript);
} catch (const IO::OpenError &) {
store_word(0x10, word(0x10) & ~FLAGS2_TRANSCRIPT);
streams.reset(STREAM_TRANS);
warning("unable to open the transcript");
}
}
} else if (number == -2) {
store_word(0x10, word(0x10) & ~FLAGS2_TRANSCRIPT);
}
if (number == 3) {
stream_tables.push(table);
} else if (number == -3) {
stream_tables.pop();
}
if (number == 4) {
if (scriptio == nullptr) {
try {
scriptio = std::make_unique<IO>(options.record_name.get(), IO::Mode::WriteOnly, IO::Purpose::Input);
} catch (const IO::OpenError &) {
streams.reset(STREAM_SCRIPT);
warning("unable to open the script");
}
}
}
// XXX V6 has even more handling
return number < 0 || streams.test(number);
}
void zoutput_stream()
{
output_stream(as_signed(zargs[0]), zargs[1]);
}
// See §10.
// This returns true if the stream was successfully selected.
bool input_stream(int which)
{
istream = which;
if (istream == ISTREAM_KEYBOARD) {
istreamio.reset();
} else if (istream == ISTREAM_FILE) {
if (istreamio == nullptr) {
try {
istreamio = std::make_unique<IO>(options.replay_name.get(), IO::Mode::ReadOnly, IO::Purpose::Input);
} catch (const IO::OpenError &) {
warning("unable to open the command script");
istream = ISTREAM_KEYBOARD;
}
}
} else {
ZASSERT(false, "invalid input stream: %d", istream);
}
return istream == which;
}
void zinput_stream()
{
input_stream(zargs[0]);
}
// This does not even pretend to understand V6 windows.
static void set_current_window(Window *window)
{
curwin = window;
#ifdef ZTERP_GLK
if (curwin == upperwin && upperwin->id != nullptr) {
upperwin->x = upperwin->y = 0;
glk_window_move_cursor(upperwin->id, 0, 0);
}
glk_set_window(curwin->id);
#endif
set_current_style();
}
// Find and validate a window. If window is -3 and the story is V6,
// return the current window.
static Window *find_window(uint16_t window)
{
int16_t w = as_signed(window);
ZASSERT(zversion == 6 ? w == -3 || (w >= 0 && w < 8) : w == 0 || w == 1, "invalid window selected: %d", w);
if (w == -3) {
return curwin;
}
return &windows[w];
}
#ifdef ZTERP_GLK
static void perform_upper_window_resize(long new_height)
{
glui32 actual_height;
glk_window_set_arrangement(glk_window_get_parent(upperwin->id), winmethod_Above | winmethod_Fixed, new_height, upperwin->id);
upper_window_height = new_height;
// Glk might resize the window to a smaller height than was requested,
// so track the actual height, not the requested height.
glk_window_get_size(upperwin->id, nullptr, &actual_height);
if (actual_height != upper_window_height) {
// This message probably won’t be seen in a window since the upper
// window is likely covering everything, but try anyway.
show_message("Unable to fulfill window size request: wanted %ld, got %lu", new_height, static_cast<unsigned long>(actual_height));
upper_window_height = actual_height;
}
}
// When resizing the upper window, the screen’s contents should not
// change (§8.6.1); however, the way windows are handled with Glk makes
// this slightly impossible. When an Inform game tries to display
// something with “box”, it expands the upper window, displays the quote
// box, and immediately shrinks the window down again. This is a
// problem under Glk because the window immediately disappears. Other
// games, such as Bureaucracy, expect the upper window to shrink as soon
// as it has been requested. Thus the following system is used:
//
// If a request is made to shrink the upper window, it is granted
// immediately if there has been user input since the last window resize
// request. If there has not been user input, the request is delayed
// until after the next user input is read.
static long delayed_window_shrink = -1;
static bool saw_input;
static void update_delayed()
{
if (delayed_window_shrink != -1 && upperwin->id != nullptr) {
perform_upper_window_resize(delayed_window_shrink);
delayed_window_shrink = -1;
}
}
static void clear_window(Window *window)
{
if (window->id == nullptr) {
return;
}
glk_window_clear(window->id);
window->x = window->y = 0;
}
#endif
static void resize_upper_window(long nlines, bool from_game)
{
#ifdef ZTERP_GLK
if (upperwin->id == nullptr) {
return;
}
long previous_height = upper_window_height;
if (from_game) {
delayed_window_shrink = nlines;
if (upper_window_height <= nlines || saw_input) {
update_delayed();
}
saw_input = false;
// §8.6.1.1.2
if (zversion == 3) {
clear_window(upperwin);
}
} else {
perform_upper_window_resize(nlines);
}
// If the window is being created, or if it’s shrinking and the cursor
// is no longer inside the window, move the cursor to the origin.
if (previous_height == 0 || upperwin->y >= nlines) {
upperwin->x = upperwin->y = 0;
if (nlines > 0) {
glk_window_move_cursor(upperwin->id, 0, 0);
}
}
// As in a few other areas, changing the upper window causes reverse
// video to be deactivated, so reapply the current style.
set_current_style();
#endif
}
void close_upper_window()
{
// The upper window is never destroyed; rather, when it’s closed, it
// shrinks to zero height.
resize_upper_window(0, true);
#ifdef ZTERP_GLK
delayed_window_shrink = -1;
saw_input = false;
#endif
set_current_window(mainwin);
}
void get_screen_size(unsigned int &width, unsigned int &height)
{
#ifdef ZTERP_GLK
glui32 w, h;