Debian Codegraph @

terps/bocfel/screen.cpp

raw symbols SCIP
1 // Copyright 2010-2025 Chris Spiegel.
2 //
3 // SPDX-License-Identifier: MIT
4
5 #include <algorithm>
6 #include <array>
7 #include <bitset>
8 #include <cmath>
9 #include <cstdarg>
10 #include <cstdlib>
11 #include <cstring>
12 #include <deque>
13 #include <functional>
14 #include <initializer_list>
15 #include <iomanip>
16 #include <iostream>
17 #include <iterator>
18 #include <limits>
19 #include <list>
20 #include <map>
21 #include <memory>
22 #include <new>
23 #include <set>
24 #include <sstream>
25 #include <stdexcept>
26 #include <string>
27 #include <unordered_map>
28 #include <unordered_set>
29 #include <utility>
30 #include <vector>
31
32 #ifdef ZTERP_GLK
33 extern "C" {
34 #include <glk.h>
35 }
36
37 #if defined(GLK_MODULE_IMAGE) && defined(ZTERP_GLK_BLORB) && !defined(ZTERP_NO_V6)
38 #define ZTERP_GLK_GRAPHICS
39
40 extern "C" {
41 #include <gi_blorb.h>
42 }
43 #endif
44
45 #ifdef ZTERP_GLK_WINGLK
46 // rpcndr.h, eventually included via WinGlk.h, defines a type “byte”
47 // which conflicts with the “byte” from memory.h. Temporarily redefine
48 // it to avoid a compile error.
49 #define byte rpc_byte
50 // Windows Glk puts non-standard declarations (specifically for this
51 // file, those guarded by GLK_MODULE_GARGLKTEXT) in WinGlk.h, so include
52 // it to get color/style extensions.
53 #include <WinGlk.h>
54 #undef byte
55 #endif
56 #endif
57
58 #include "screen.h"
59 #include "branch.h"
60 #include "dict.h"
61 #include "iff.h"
62 #include "io.h"
63 #include "memory.h"
64 #include "meta.h"
65 #include "objects.h"
66 #include "options.h"
67 #include "osdep.h"
68 #include "process.h"
69 #include "sound.h"
70 #include "stack.h"
71 #include "stash.h"
72 #include "types.h"
73 #include "unicode.h"
74 #include "util.h"
75 #include "zterp.h"
76
77 #ifdef __DJGPP__
78 // For some reason, DJGPP does not expose std::round. Manually defining
79 // std::round like this violates the C++ standard, but since it’s only
80 // for DJGPP and is known to work with it, this beats compile failure.
81 namespace std {
82 double round(double x) {
83 return ::round(x);
84 }
85 }
86 #endif
87
88 // Somewhat ugly hack to get around the fact that some Glk functions may
89 // not exist. These function calls should all be guarded (e.g.
90 // if (have_unicode), with have_unicode being set iff GLK_MODULE_UNICODE
91 // is defined) so they will never be called if the Glk implementation
92 // being used does not support them, but they must at least exist to
93 // prevent link errors.
94 #ifdef ZTERP_GLK
95 #ifndef GLK_MODULE_UNICODE
96 #define glk_put_char_uni(...) die("bug %s:%d: glk_put_char_uni() called with no unicode", __FILE__, __LINE__)
97 #define glk_put_char_stream_uni(...) die("bug %s:%d: glk_put_char_stream_uni() called with no unicode", __FILE__, __LINE__)
98 #define glk_request_char_event_uni(...) die("bug %s:%d: glk_request_char_event_uni() called with no unicode", __FILE__, __LINE__)
99 #define glk_request_line_event_uni(...) die("bug %s:%d: glk_request_line_event_uni() called with no unicode", __FILE__, __LINE__)
100 #endif
101 #endif
102
103 // Flag describing whether the header bit meaning “fixed font” is set.
104 static bool header_fixed_font;
105
106 // This variable stores whether Unicode is supported by the current Glk
107 // implementation, which determines whether Unicode or Latin-1 Glk
108 // functions are used. In addition, for both Glk and non-Glk versions,
109 // this affects the behavior of @check_unicode. In non-Glk versions,
110 // this is always true.
111 static bool have_unicode;
112
113 struct Window {
114 Style style;
115 Color fg_color = Color(), bg_color = Color();
116
117 enum class Font { Query, Normal, Picture, Character, Fixed } font = Font::Normal;
118
119 #ifdef ZTERP_GLK
120 winid_t id = nullptr;
121 // In general these are only meaningful for window 1, except that
122 // Arthur uses them in window 2 as well.
123 uint16_t x = 0, y = 0;
124 bool has_echo = false;
125 #endif
126 };
127
128 static std::array<Window, 8> windows;
129 static Window *mainwin = &windows[0], *curwin = &windows[0];
130 #ifdef ZTERP_GLK
131 // This represents a line of input from Glk; if the global variable
132 // “have_unicode” is true, then the “unicode” member is used; otherwise,
133 // “latin1”.
134 struct Line {
135 union {
136 std::array<char, 256> latin1;
137 std::array<glui32, 256> unicode;
138 };
139 glui32 len;
140 };
141
142 static Window *upperwin = &windows[1];
143 static Window statuswin;
144 static uint16_t upper_window_height = 0;
145 static uint16_t upper_window_width = 0;
146 static winid_t errorwin;
147
148 enum class WindowRock : glui32 {
149 None = 0,
150 MainWin = 1,
151 UpperWin = 2,
152 // windows[2-7] are going to be copies of mainwin if they are used at all
153 StatusWin = 3,
154 ErrorWin = 4,
155 // graphics windows are not currently managed by this scheme
156 };
157
158 void screen_recover_glk_windows()
159 {
160 glui32 tmpwid, tmphgt;
161
162 statuswin.id = nullptr;
163 errorwin = nullptr;
164 for (auto &win : windows) {
165 win.id = nullptr;
166 }
167
168 glui32 rock = 0;
169 for (auto win = glk_window_iterate(nullptr, &rock); win != nullptr; win = glk_window_iterate(win, &rock)) {
170 switch (static_cast<WindowRock>(rock)) {
171 case WindowRock::None:
172 break;
173 case WindowRock::MainWin:
174 mainwin->id = win;
175 break;
176 case WindowRock::UpperWin:
177 upperwin->id = win;
178 glk_window_get_size(upperwin->id, &tmpwid, &tmphgt);
179 upper_window_width = tmpwid;
180 upper_window_height = tmphgt;
181 break;
182 case WindowRock::StatusWin:
183 statuswin.id = win;
184 break;
185 case WindowRock::ErrorWin:
186 errorwin = win;
187 break;
188 }
189 }
190
191 ZASSERT(mainwin->id != nullptr, "no main window after recovery");
192
193 // Redirect windows 2-7 -- see note in init_screen().
194 if (options.redirect_v6_windows) {
195 for (int i = 2; i < 8; i++) {
196 windows[i].id = windows[0].id;
197 }
198 }
199 }
200
201 #ifdef ZTERP_GLK_GRAPHICS
202 // Arthur uses window 2 for the larger upper window (room graphics,
203 // inventory, etc). Graphics are intercepted and drawn separately with
204 // GraphicsWindow (using Glk’s graphics window). For text mode, use a
205 // separate Glk text buffer, since Glk doesn’t support the kind of mixed
206 // graphics and text V6 needs; but if you give Arthur a text buffer
207 // window as window 2, it just generally works, when in text mode
208 // (inventory, score, room description).
209 static Window *arthurwin = &windows[2];
210
211 static double aspect_scale() {
212 return options.aspect_correction ? 1.2 : 1.0;
213 }
214
215 #ifndef GLK_MODULE_GARGLKWINSIZE
216 // For scaling V6 graphics, the window width and height are needed, but
217 // really what’s needed is the main window width and height so that
218 // scaling can be done with things like margins taken into account.
219 // Gargoyle provides an extension for this, but for Glk implementations
220 // that do not, temporarily create a graphics window that’s as large as
221 // possible, and measure it. This isn’t perfect, but works well enough.
222 static glui32 full_window_width = -1, full_window_height = -1;
223
224 static void find_window_size(winid_t split)
225 {
226 auto gwin = glk_window_open(split, winmethod_Above | winmethod_Proportional, 100, wintype_Graphics, 0);
227 if (gwin != nullptr) {
228 glk_window_get_size(gwin, &full_window_width, &full_window_height);
229 glk_window_close(gwin, nullptr);
230 }
231 }
232 #endif
233
234 // Glk’s window/graphics model is not suitable for V6’s graphics.
235 // However, since Infocom produced only 4 V6 games, it’s possible to
236 // special-case their graphics calls to at least approximate a proper
237 // apperance, which Bocfel does. In addition to Infocom games, Colin
238 // Davies’ ports of Brian Howarth’s Mysterious Adventure games are
239 // supported as well.
240 //
241 // For most games, graphics tend to be drawn in a window on top, and
242 // text below it, which is implemented here by opening a graphics window
243 // above other windows, and resizing it as necessary. For Journey, the
244 // dedicated graphics window is on the left side.
245 //
246 // To deal with different target machines, Infocom’s graphics
247 // formats included what they called invisible pictures, which were
248 // coordinates showing where to draw pictures. Different target machines
249 // were given different invisible pictures, presumably based on the
250 // target resolution. Kevin Bracey created Blorb files based on the
251 // MS-DOS releases, which had a 320x200 target resolution.
252 //
253 // But different Infocom games dealt with graphics slightly differently.
254 //
255 // Zork Zero: Generally uses invisible pictures to determine where to
256 // draw things. The invisible pictures effectively instruct Zork Zero to
257 // draw into a 320x200 region, and it does so correctly, regardless of
258 // the actual size of the window: Zork Zero doesn’t generally care about
259 // the window size since it “knows” the size is 320x200 based on the
260 // invisible pictures. Drawing calls are intercepted and scaled up (or
261 // down) to the actual window size, and no further work is necessary.
262 // Zork Zero writes text on top of its graphics, which Glk does not
263 // support at all (graphics windows don’t support text, and text windows
264 // don’t support drawing at arbitrary locations). In these cases, the
265 // text will generally be in the window below the graphics. It looks a
266 // little odd, but works well enough. Zork Zero also has marginal
267 // images, which do use the window size to determine where to place
268 // them, but Bocfel ignores all the intricate setup for marginal
269 // pictures, and instead just “knows” which images are marginal, and
270 // instructs Glk to draw them in the margins, which it directly
271 // supports.
272 //
273 // Shogun: Most graphics in Shogun are marginal graphics, and as with
274 // Zork Zero, are hard coded to be drawn in the margins via Glk calls.
275 // The Shogun maze does use the upper graphics window, and again as with
276 // Zork Zero, it generally works using invisible pictures, resulting in
277 // proper calculations. There is one small hack needed to get an offset
278 // right, but otherwise the game’s coordinates are used.
279 //
280 // Journey: This makes a lot more use of the actual screen size to draw.
281 // The problem there is that the Glk screen size will likely be some
282 // value which is nowhere near the 320x200 that Journey is expecting. As
283 // a result, the handling of graphics is more invasive. Graphics in
284 // Journey are pictures drawn in a left-hand window that illustrate the
285 // current scene, but in some cases, these include overlaid images (what
286 // Infocom called “stamps”): in the cave, near the beginning, for
287 // example, is a covered pool. Journey draws the image of a covered
288 // pool. When you pick up the cover, Journey draws an image of a pool of
289 // water in exactly the same place the cover is. The pool image is a
290 // stamp, drawn in precisely the right location to hide the cover. To
291 // handle all this, Bocfel effectively takes over all image drawing. A
292 // graphics window on the left side, taking up 3/8 of the screen, is
293 // created. When Journey draws a background image, Bocfel ignores its
294 // coordinates, and draws it centered in this left-hand window. When
295 // Journey draws a stamp, Bocfel also ignores the coordinates. Instead,
296 // it has a table of where all the stamps are supposed to be drawn,
297 // since they are always in a fixed location. Journey should be able to
298 // calculate stamp locations, but since Bocfel doesn’t properly track
299 // windows (yet), it gets the values wrong. As with Shogun, if window
300 // tracking is eventually properly supported, this table of stamp sizes
301 // may become obsolete, but for now it works fine.
302 //
303 // Arthur: Arthur has two main graphics modes: either showing a picture
304 // of the current location, or a map. Arthur uses invisible images for
305 // the map, and draws it correctly with no aid needed (apart from a
306 // fixed offset as with Shogun’s maze). However, the location pictures
307 // make a lot of use of the actual window size, which doesn’t currently
308 // work. Since these images are always drawn in the same place, it’s
309 // trivial to plot them directly. Arthur also uses stamps like Journey,
310 // and like in Journey, these stamps’ locations are looked up in a
311 // table. Ultimately, as with all other games, it’d be nice to remove
312 // the hard coding and allow the game to calculate everything, but for
313 // now, this works.
314 //
315 // Mysterious Adventures games are generally straightforward in that
316 // each room has a static image which is displayed in the top window.
317 // However, the Z-machine versions of the games also have an image which
318 // serves as a separator, or border, between the upper part of the
319 // window (containing the image and description/exits/items) and the
320 // lower part, which contains the input and parser messages. Bocfel
321 // creates a second graphics window for this border, so that the
322 // appearance is generally faithful to the original intent.
323 static enum class Hack {
324 None,
325 Arthur,
326 ZorkZero,
327 Shogun,
328 Journey,
329 MysteriousAdventures,
330 } hack = Hack::None;
331
332 struct ImageSize {
333 double width;
334 double height;
335 };
336
337 struct ImageGeometry {
338 ImageGeometry(double x_, double y_) : x(x_), y(y_) {}
339 double x;
340 double y;
341 };
342
343 class GraphicsWindow {
344 public:
345 enum class Type {
346 None,
347 ArthurIntro,
348 ArthurBanner,
349 ArthurMap,
350 ArthurDemon,
351 ZorkZeroBorder,
352 ZorkZero320,
353 ZorkZeroGame,
354 ShogunTitle,
355 ShogunNormal,
356 ShogunMaze,
357 Mysterious,
358 MysteriousSeparator,
359 };
360
361 enum class Border {
362 Left,
363 Right,
364 };
365
366 bool create();
367 bool resize(Type type);
368 void destroy();
369 void clear();
370 void draw(glui32 pic, const ImageGeometry &geom, glui32 w, glui32 h) const;
371 void draw_border(Type type, Border border, glui32 pic) const;
372 void draw_shogun_borders() const;
373 glui32 get_window_width() const;
374
375 winid_t id() const { return m_id; }
376 Type type() const { return m_type; }
377 double ratio() const { return m_ratio; }
378
379 private:
380 winid_t m_id = nullptr;
381 winid_t m_left_border = nullptr;
382 winid_t m_right_border = nullptr;
383 Type m_type = Type::None;
384 double m_ratio = 0.0;
385 double m_base_width = 0.0;
386 glui32 m_width = 0;
387 };
388
389 // The “main” graphics window: this is use for the banner/map in Arthur,
390 // the maze in Shogun, the banner/map in Zork Zero, and the room images
391 // in Mysterious Adventures.
392 static GraphicsWindow graphics_window;
393
394 // Arthur, Shogun, and Zork Zero all have roughly the same layout, with
395 // graphics on top and text on the bottom. Journey has a different
396 // enough layout that it’s not worth trying to shoehorn it into the
397 // GraphicsWindow class.
398 static winid_t journey_window;
399 static glui32 journey_screen_width;
400
401 // Mysterious Adventures have an image separating the “upper window”
402 // (graphics plus location info) from the main text window. For the main
403 // graphics window, use the common graphics_window, but dedicate a
404 // special window for the separator.
405 static GraphicsWindow mysterious_separator;
406
407 // Mysterious Adventures games always start up with two images: the
408 // Mysterious Adventures logo, and the game title. These are displayed
409 // one right after the other, so if they were placed in the graphics
410 // window, the game title would always immediately overwrite the
411 // Mysterious Adventures logo. To avoid this, the graphics window isn’t
412 // opened until after these images are displayed; but these images are
413 // always the last two in the Blorb, and there are different numbers of
414 // images for different games, so the image IDs aren‘t the same across
415 // games. We could map game IDs to image IDs, but it’s simpler to just
416 // count the total number of images and use that.
417 static glui32 mysterious_max_image;
418
419 static constexpr glui32 SHOGUN_MAZE_BLOCK_WIDTH = 7;
420 static constexpr glui32 SHOGUN_MAZE_BLOCK_HEIGHT = 7;
421 #endif
422 #endif
423
424 // In all versions but 6, styles and colors are global and stored in
425 // mainwin. For V6, they’re tracked per window and thus stored in each
426 // individual window. For convenience, this macro returns the “style
427 // window” for any version.
428 static Window *style_window()
429 {
430 return zversion == 6 ? curwin : mainwin;
431 }
432
433 static std::bitset<5> streams;
434 static std::unique_ptr<IO> scriptio, transio, perstransio;
435
436 #ifdef ZTERP_GLK_UNIX
437
438 void screen_clean_up_glk_streams()
439 {
440 // transio may or may not be a Glk stream, but it’s safest to clean
441 // it up.
442 transio = nullptr;
443 }
444
445 #endif
446
447 #ifdef ZTERP_GLK
448
449 void screen_recover_glk_streams()
450 {
451 transio = nullptr;
452 streams.reset(OSTREAM_TRANSCRIPT);
453
454 glui32 rock = 0;
455 for (auto str = glk_stream_iterate(nullptr, &rock); str != nullptr; str = glk_stream_iterate(str, &rock)) {
456 switch (static_cast<StreamRock>(rock)) {
457 case StreamRock::None:
458 break;
459 case StreamRock::TranscriptStream:
460 transio = std::make_unique<IO>(IO::Mode::Append, IO::Purpose::Transcript, str);
461 streams.set(OSTREAM_TRANSCRIPT);
462 break;
463 default:
464 break;
465 }
466 }
467 }
468
469 #endif
470
471 class StreamTables {
472 public:
473 void push(uint16_t addr, bool formatted) {
474 ZASSERT(m_tables.size() < MAX_STREAM_TABLES, "too many stream tables");
475 m_tables.emplace_back(addr, formatted);
476 }
477
478 void pop() {
479 if (!m_tables.empty()) {
480 m_tables.pop_back();
481 }
482 }
483
484 void write(uint16_t c) {
485 ZASSERT(!m_tables.empty(), "invalid stream table");
486 m_tables.back().write(c);
487 }
488
489 size_t size() const {
490 return m_tables.size();
491 }
492
493 void clear() {
494 m_tables.clear();
495 }
496
497 private:
498 static constexpr size_t MAX_STREAM_TABLES = 16;
499 class Table {
500 public:
501 explicit Table(uint16_t addr, bool formatted) :
502 m_addr(addr),
503 m_formatted(formatted)
504 {
505 user_store_word(m_addr, 0);
506 }
507
508 Table(const Table &) = delete;
509 Table &operator=(const Table &) = delete;
510
511 ~Table() {
512 user_store_word(m_addr, m_idx - 2);
513
514 if (m_formatted) {
515 user_store_word(m_addr + m_idx, 0);
516 }
517
518 if (zversion == 6) {
519 store_word(0x30, m_idx - 2);
520 }
521 }
522
523 void write(uint8_t c) {
524 user_store_byte(m_addr + m_idx++, c);
525 }
526
527 private:
528 uint16_t m_addr;
529 bool m_formatted;
530 uint16_t m_idx = 2;
531 };
532
533 std::list<Table> m_tables;
534 };
535
536 static StreamTables stream_tables;
537
538 static int istream = ISTREAM_KEYBOARD;
539 static std::unique_ptr<IO> istreamio;
540
541 struct Input {
542 enum class Type { Char, Line } type;
543
544 // ZSCII value of key read for @read_char.
545 uint8_t key;
546
547 // Unicode line of chars read for @read.
548 std::array<uint16_t, 256> line;
549 uint8_t maxlen;
550 uint8_t len;
551 uint8_t preloaded;
552
553 // Character used to terminate input. If terminating keys are not
554 // supported by the Glk implementation being used (or if Glk is not
555 // used at all) this will be ZSCII_NEWLINE; or in the case of
556 // cancellation, 0.
557 uint8_t term;
558 };
559
560 // Convert a 15-bit color to a 24-bit color.
561 uint32_t screen_convert_color(uint16_t color)
562 {
563 // Map 5-bit color values to 8-bit.
564 const uint32_t table[] = {
565 0x00, 0x08, 0x10, 0x19, 0x21, 0x29, 0x31, 0x3a,
566 0x42, 0x4a, 0x52, 0x5a, 0x63, 0x6b, 0x73, 0x7b,
567 0x84, 0x8c, 0x94, 0x9c, 0xa5, 0xad, 0xb5, 0xbd,
568 0xc5, 0xce, 0xd6, 0xde, 0xe6, 0xef, 0xf7, 0xff
569 };
570
571 return table[(color >> 0) & 0x1f] << 16 |
572 table[(color >> 5) & 0x1f] << 8 |
573 table[(color >> 10) & 0x1f] << 0;
574 }
575
576 #ifdef GLK_MODULE_GARGLKTEXT
577 static glui32 zcolor_map[] = {
578 static_cast<glui32>(zcolor_Current),
579 static_cast<glui32>(zcolor_Default),
580
581 0x000000, // Black
582 0xef0000, // Red
583 0x00d600, // Green
584 0xefef00, // Yellow
585 0x006bb5, // Blue
586 0xff00ff, // Magenta
587 0x00efef, // Cyan
588 0xffffff, // White
589 0xb5b5b5, // Light grey
590 0x8c8c8c, // Medium grey
591 0x5a5a5a, // Dark grey
592 };
593
594 void update_color(int which, unsigned long color)
595 {
596 if (which < 2 || which > 12) {
597 return;
598 }
599
600 zcolor_map[which] = color;
601 }
602
603 // Provide descriptive aliases for Gargoyle styles.
604 enum {
605 GStyleBoldItalicFixed = style_Note,
606 GStyleBoldItalic = style_Alert,
607 GStyleBoldFixed = style_User1,
608 GStyleItalicFixed = style_User2,
609 GStyleBold = style_Subheader,
610 GStyleItalic = style_Emphasized,
611 GStyleFixed = style_Preformatted,
612 };
613
614 static int gargoyle_style(const Style &style)
615 {
616 if (style.test(STYLE_BOLD) && style.test(STYLE_ITALIC) && style.test(STYLE_FIXED)) {
617 return GStyleBoldItalicFixed;
618 } else if (style.test(STYLE_BOLD) && style.test(STYLE_ITALIC)) {
619 return GStyleBoldItalic;
620 } else if (style.test(STYLE_BOLD) && style.test(STYLE_FIXED)) {
621 return GStyleBoldFixed;
622 } else if (style.test(STYLE_ITALIC) && style.test(STYLE_FIXED)) {
623 return GStyleItalicFixed;
624 } else if (style.test(STYLE_BOLD)) {
625 return GStyleBold;
626 } else if (style.test(STYLE_ITALIC)) {
627 return GStyleItalic;
628 } else if (style.test(STYLE_FIXED)) {
629 return GStyleFixed;
630 }
631
632 return style_Normal;
633 }
634
635 static glui32 gargoyle_color(const Color &color)
636 {
637 switch (color.mode) {
638 case Color::Mode::ANSI:
639 return zcolor_map[color.value];
640 case Color::Mode::True:
641 return screen_convert_color(color.value);
642 }
643
644 return zcolor_Current;
645 }
646 #endif
647
648 #ifdef ZTERP_GLK
649 // These functions make it so that code elsewhere needn’t check have_unicode before printing.
650 static void xglk_put_char(uint16_t c)
651 {
652 if (!have_unicode) {
653 glk_put_char(c > 255 ? LATIN1_QUESTIONMARK : c);
654 } else {
655 glk_put_char_uni(c);
656 }
657 }
658
659 static void xglk_put_char_stream(strid_t s, uint32_t c)
660 {
661 if (!have_unicode) {
662 glk_put_char_stream(s, c > 255 ? LATIN1_QUESTIONMARK : c);
663 } else {
664 glk_put_char_stream_uni(s, c);
665 }
666 }
667 #endif
668
669 static bool set_force_fixed = false;
670
671 static void set_window_style(const Window *win)
672 {
673 #ifdef ZTERP_GLK
674 auto style = win->style;
675 if (curwin->id == nullptr) {
676 return;
677 }
678
679 #ifdef GLK_MODULE_GARGLKTEXT
680 if (curwin->font == Window::Font::Fixed || header_fixed_font) {
681 style.set(STYLE_FIXED);
682 }
683
684 if (curwin == mainwin && set_force_fixed) {
685 style.set(STYLE_FIXED);
686 }
687
688 if (options.disable_fixed) {
689 style.reset(STYLE_FIXED);
690 }
691
692 glk_set_style(gargoyle_style(style));
693
694 garglk_set_reversevideo(style.test(STYLE_REVERSE));
695
696 // Colors are per-window in V6, but global in V5.
697 if (zversion == 6) {
698 garglk_set_zcolors(gargoyle_color(win->fg_color), gargoyle_color(win->bg_color));
699 } else {
700 garglk_set_zcolors_stream(glk_window_get_stream(mainwin->id), gargoyle_color(win->fg_color), gargoyle_color(win->bg_color));
701 if (upperwin->id != nullptr) {
702 garglk_set_zcolors_stream(glk_window_get_stream(upperwin->id), gargoyle_color(win->fg_color), gargoyle_color(win->bg_color));
703 }
704 }
705 #else
706 // Yes, there are three ways to indicate that a fixed-width font should be used.
707 bool use_fixed_font = style.test(STYLE_FIXED) || curwin->font == Window::Font::Fixed || header_fixed_font;
708
709 if (curwin == mainwin && set_force_fixed) {
710 use_fixed_font = true;
711 }
712
713 // Glk can’t mix other styles with fixed-width, but the upper window
714 // is always fixed, so if it is selected, there is no need to
715 // explicitly request it here. In addition, the user can disable
716 // fixed-width fonts or tell Bocfel to assume that the output font is
717 // already fixed (e.g. in an xterm); in either case, there is no need
718 // to request a fixed font.
719 // This means that another style can also be applied if applicable.
720 if (use_fixed_font && !options.disable_fixed && !options.assume_fixed && curwin != upperwin) {
721 glk_set_style(style_Preformatted);
722 return;
723 }
724
725 // According to standard 1.1, if mixed styles aren’t available, the
726 // priority is Fixed, Italic, Bold, Reverse.
727 if (style.test(STYLE_ITALIC)) {
728 glk_set_style(style_Emphasized);
729 } else if (style.test(STYLE_BOLD)) {
730 glk_set_style(style_Subheader);
731 } else if (style.test(STYLE_REVERSE)) {
732 glk_set_style(style_Alert);
733 } else {
734 glk_set_style(style_Normal);
735 }
736 #endif
737 #else
738 zterp_os_set_style(win->style, win->fg_color, win->bg_color);
739 #endif
740 }
741
742 bool screen_toggle_force_fixed()
743 {
744 set_force_fixed = !set_force_fixed;
745 set_window_style(mainwin);
746 return set_force_fixed;
747 }
748
749 static void set_current_style()
750 {
751 set_window_style(style_window());
752 }
753
754 // The following implements a circular buffer to track the state of the
755 // screen so that recent history can be stored in save files for
756 // playback on restore.
757 static constexpr size_t HISTORY_SIZE = 2000;
758
759 class History {
760 public:
761 struct Entry {
762 // Suppress a dubious shadow warning (see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=55776)
763 #ifdef __GNUC__
764 #pragma GCC diagnostic push
765 #pragma GCC diagnostic ignored "-Wshadow"
766 #endif
767 // These values are part of the Bfhs chunk so must remain stable.
768 enum class Type {
769 Style = 0,
770 FGColor = 1,
771 BGColor = 2,
772 InputStart = 3,
773 InputEnd = 4,
774 Char = 5,
775 } type;
776 #ifdef __GNUC__
777 #pragma GCC diagnostic pop
778 #endif
779
780 union Contents {
781 Color color;
782 uint8_t style;
783 uint32_t c;
784
785 Contents() : c(0) { }
786 explicit Contents(Color color_) : color(color_) { }
787 explicit Contents(uint8_t style_) : style(style_) { }
788 explicit Contents(uint32_t c_) : c(c_) { }
789 } contents;
790
791 explicit Entry(Type type_) : type(type_) { }
792 Entry(Type type_, const Color &color) : type(type_), contents(color) { }
793 Entry(Type type_, uint8_t style) : type(type_), contents(style) { }
794 Entry(Type type_, uint32_t c) : type(type_), contents(c) { }
795
796 static Entry style(uint8_t style) {
797 return {Type::Style, style};
798 }
799
800 static Entry color(Type color_type, const Color &color) {
801 return {color_type, color};
802 }
803
804 static Entry character(uint32_t c) {
805 return {Type::Char, c};
806 }
807 };
808
809 std::deque<Entry>::size_type size() const {
810 return m_entries.size();
811 }
812
813 void add_style() {
814 auto style = mainwin->style;
815
816 if (mainwin->font == Window::Font::Fixed || header_fixed_font) {
817 style.set(STYLE_FIXED);
818 }
819
820 add(Entry::style(style.to_ulong()));
821 }
822
823 void add_fg_color(const Color &color) {
824 add(Entry::color(Entry::Type::FGColor, color));
825 }
826
827 void add_bg_color(const Color &color) {
828 add(Entry::color(Entry::Type::BGColor, color));
829 }
830
831 void add_input(const uint16_t *string, size_t len) {
832 add(Entry(Entry::Type::InputStart));
833
834 for (size_t i = 0; i < len; i++) {
835 add(Entry::character(string[i]));
836 }
837
838 add(Entry::character(UNICODE_LINEFEED));
839 add(Entry(Entry::Type::InputEnd));
840 }
841
842 void add_input_start() {
843 add(Entry(Entry::Type::InputStart));
844 }
845
846 void add_input_end() {
847 add(Entry(Entry::Type::InputEnd));
848 }
849
850 void add_char(uint32_t c) {
851 add(Entry::character(c));
852 }
853
854 const std::deque<Entry> &entries() const {
855 return m_entries;
856 }
857
858 private:
859 void add(const Entry &entry) {
860 while (m_entries.size() >= HISTORY_SIZE) {
861 m_entries.pop_front();
862 }
863
864 m_entries.push_back(entry);
865 }
866
867 std::deque<Entry> m_entries;
868 };
869
870 static History history;
871
872 void screen_set_header_bit(bool set)
873 {
874 if (set != header_fixed_font) {
875 header_fixed_font = set;
876 history.add_style();
877 set_current_style();
878 }
879 }
880
881 static void transcribe(uint32_t c)
882 {
883 if (streams.test(OSTREAM_TRANSCRIPT)) {
884 transio->putc(c);
885 }
886
887 if (perstransio != nullptr) {
888 perstransio->putc(c);
889 }
890 }
891
892 // Print out a character. The character is in “c” and is either Unicode
893 // or ZSCII; if the former, “unicode” is true. This is meant for any
894 // output produced by the game, as opposed to output produced by the
895 // interpreter, which should use Glk (or standard I/O) calls only, to
896 // avoid interacting with the Z-machine’s streams: interpreter-provided
897 // output should not be considered part of a transcript, nor should it
898 // be included in the memory stream.
899 static void put_char_base(uint16_t c, bool unicode)
900 {
901 if (c == 0) {
902 return;
903 }
904
905 if (streams.test(OSTREAM_MEMORY)) {
906 // When writing to memory, ZSCII should always be used (§7.5.3).
907 if (unicode) {
908 c = unicode_to_zscii_q[c];
909 }
910
911 stream_tables.write(c);
912 } else {
913 // For screen and transcription, always prefer Unicode.
914 if (!unicode) {
915 // Tab (9) and sentence space (11) are defined for output
916 // only in V6 (§3.8.2.3 and §3.8.2.4), but Zork I writes out
917 // a tab, when you read the FCD#3 guidebook. In the DOS
918 // interpreter, this prints out a bullet (CP-437 character
919 // 9); on Apple ][ and C64 it prints nothing; and on
920 // Macintosh and Amiga it prints a space. This was clearly
921 // not intentional, and looks to be a vestige from at least
922 // 1977 MDL Zork, which used tabs to center the guidebook’s
923 // title. Odds are mainframe Zork just printed the tabs out
924 // directly and it worked, and nobody noticed any issues as
925 // it was ported to ZIL. In any case, ignore these ZSCII
926 // characters when not on V6.
927 if (zversion != 6 && (c == 9 || c == 11)) {
928 return;
929 }
930
931 c = zscii_to_unicode[c];
932 }
933
934 if (c != 0) {
935 uint8_t zscii = 0;
936
937 // §16 makes no mention of what a newline in font 3 should map to.
938 // Other interpreters that implement font 3 assume it stays a
939 // newline, and this makes the most sense, so don’t do any
940 // translation in that case.
941 if (curwin->font == Window::Font::Character && !options.disable_graphics_font && c != UNICODE_LINEFEED) {
942 zscii = unicode_to_zscii[c];
943
944 // These four characters have a “built-in” reverse video (see §16).
945 if (zscii >= 123 && zscii <= 126) {
946 style_window()->style.flip(STYLE_REVERSE);
947 set_current_style();
948 }
949
950 c = zscii_to_font3[zscii];
951 }
952 #ifdef ZTERP_GLK
953 if (streams.test(OSTREAM_SCREEN) && curwin->id != nullptr) {
954 if (curwin == upperwin) {
955 // Interpreters seem to have differing ideas about what
956 // happens when the cursor reaches the end of a line in the
957 // upper window. Some wrap, some let it run off the edge (or,
958 // at least, stop the text at the edge). The standard, from
959 // what I can see, says nothing on this issue. Follow Windows
960 // Frotz and don’t wrap.
961
962 if (c == UNICODE_LINEFEED) {
963 if (upperwin->y < upper_window_height) {
964 // Glk wraps, so printing a newline when the cursor has
965 // already reached the edge of the screen will produce two
966 // newlines.
967 if (upperwin->x < upper_window_width) {
968 xglk_put_char(c);
969 }
970
971 // Even if a newline isn’t explicitly printed here
972 // (because the cursor is at the edge), setting
973 // upperwin->x to 0 will cause the next character to be on
974 // the next line because the text will have wrapped.
975 upperwin->x = 0;
976 upperwin->y++;
977 }
978 } else if (upperwin->x < upper_window_width && upperwin->y < upper_window_height) {
979 upperwin->x++;
980 xglk_put_char(c);
981 }
982 #ifdef ZTERP_GLK_GRAPHICS
983 } else if (hack == Hack::Arthur && curwin == arthurwin && arthurwin->id != nullptr) {
984 // In “room description” mode, this should perform
985 // line breaking, but it currently does not.
986 glui32 w;
987 glk_window_get_size(arthurwin->id, &w, nullptr);
988 if (c == UNICODE_LINEFEED || curwin->x == w) {
989 curwin->x = 0;
990 curwin->y++;
991 } else {
992 curwin->x++;
993 }
994 xglk_put_char(c);
995 #endif
996 } else {
997 xglk_put_char(c);
998 }
999 }
1000 #else
1001 if (streams.test(OSTREAM_SCREEN) && curwin == mainwin) {
1002 #ifdef ZTERP_OS_DOS
1003 // DOS doesn’t support Unicode, but instead uses code
1004 // page 437. Special-case non-Glk DOS here, by writing
1005 // bytes (not UTF-8 characters) from code page 437.
1006 IO::standard_out().write8(unicode_to_437(c));
1007 #else
1008 IO::standard_out().putc(c);
1009 #endif
1010 }
1011 #endif
1012
1013 if (curwin == mainwin) {
1014 // Don’t check streams here: for quote boxes (which are in the
1015 // upper window, and thus not transcribed), both Infocom and
1016 // Inform games turn off the screen stream and write a duplicate
1017 // copy of the quote, so it appears in a transcript (if any is
1018 // occurring). In short, assume that if a game is writing text
1019 // with the screen stream turned off, it’s doing so with the
1020 // expectation that it appear in a transcript, which means it also
1021 // ought to appear in the history.
1022 history.add_char(c);
1023
1024 transcribe(c);
1025 }
1026
1027 // If the reverse video bit was flipped (for the character font), flip it back.
1028 if (zscii >= 123 && zscii <= 126) {
1029 style_window()->style.flip(STYLE_REVERSE);
1030 set_current_style();
1031 }
1032 }
1033 }
1034 }
1035
1036 static void put_char_u(uint16_t c)
1037 {
1038 put_char_base(c, true);
1039 }
1040
1041 void put_char(uint8_t c)
1042 {
1043 put_char_base(c, false);
1044 }
1045
1046 // Glk doesn’t allow control characters (apart from newline) to be
1047 // written (§2.2). In most cases this isn’t a problem, but there are a
1048 // couple of places where user-provided strings need to be printed out
1049 // (/shownotes and history replay), which means we have no control over
1050 // whether those contain control characters. In circumstances where
1051 // possibly-uncontrolled input is being sent to Glk, it is passed
1052 // through here first, which converts invalid characters to hex escape
1053 // sequences.
1054 //
1055 // Since there’s really no need to allow user-provided control
1056 // characters to be written out, this happens in non-Glk mode as well,
1057 // including for transcripts and history.
1058 static std::vector<uint32_t> cleanse_control(uint32_t c)
1059 {
1060 std::vector<uint32_t> ret;
1061 if (c == 10 || (c >= 32 && c <= 126) || c >= 160) {
1062 ret.push_back(c);
1063 } else {
1064 std::ostringstream ss;
1065 ss << "\\x" << std::setw(2) << std::setfill('0') << std::hex << c;
1066 for (const auto esc : ss.str()) {
1067 ret.push_back(esc);
1068 }
1069 }
1070
1071 return ret;
1072 }
1073
1074 // Print a string directly to the main window. This is meant to print
1075 // text from the interpreter, not the game. Text will also be written to
1076 // any transcripts which are active, as well as to the history buffer.
1077 // For convenience, carriage returns are ignored under the assumption
1078 // that they are coming from a Windows text stream.
1079 //
1080 // This string should be UTF-8 encoded. If it’s not, invalid sequences
1081 // will be represented as the Unicode replacement character.
1082 void screen_print(const std::string &s)
1083 {
1084 auto io = std::make_unique<IO>(std::vector<uint8_t>(s.begin(), s.end()), IO::Mode::ReadOnly);
1085 #ifdef ZTERP_GLK
1086 strid_t stream = glk_window_get_stream(mainwin->id);
1087 #endif
1088 for (long c = io->getc(false); c != -1; c = io->getc(false)) {
1089 if (c != UNICODE_CARRIAGE_RETURN) {
1090 for (const auto clean : cleanse_control(c)) {
1091 transcribe(clean);
1092 history.add_char(clean);
1093 #ifdef ZTERP_GLK
1094 xglk_put_char_stream(stream, clean);
1095 #else
1096 IO::standard_out().putc(clean);
1097 #endif
1098 }
1099 }
1100 }
1101 }
1102
1103 // Print a Unicode character directly to the main window. This is the
1104 // single-character analog of screen_print().
1105 void screen_putc(uint32_t c)
1106 {
1107 transcribe(c);
1108 history.add_char(c);
1109 #ifdef ZTERP_GLK
1110 xglk_put_char_stream(glk_window_get_stream(mainwin->id), c);
1111 #else
1112 IO::standard_out().putc(c);
1113 #endif
1114 }
1115
1116 void screen_printf(const char *fmt, ...)
1117 {
1118 std::va_list ap;
1119 std::string message;
1120
1121 va_start(ap, fmt);
1122 message = vstring(fmt, ap);
1123 va_end(ap);
1124
1125 screen_print(message);
1126 }
1127
1128 void screen_puts(const std::string &s)
1129 {
1130 screen_print(s);
1131 screen_print("\n");
1132 }
1133
1134 void show_message(const char *fmt, ...)
1135 {
1136 std::va_list ap;
1137 std::string message;
1138
1139 va_start(ap, fmt);
1140 message = vstring(fmt, ap);
1141 va_end(ap);
1142
1143 #ifdef ZTERP_GLK
1144 static glui32 error_lines = 0;
1145
1146 if (errorwin != nullptr) {
1147 glui32 w, h;
1148
1149 // Allow multiple messages to stack, but force at least 5 lines to
1150 // always be visible in the main window. This is less than perfect
1151 // because it assumes that each message will be less than the width
1152 // of the screen, but it’s not a huge deal, really; even if the
1153 // lines are too long, at least Gargoyle and glktermw are graceful
1154 // enough.
1155 glk_window_get_size(mainwin->id, &w, &h);
1156
1157 if (h > 5) {
1158 glk_window_set_arrangement(glk_window_get_parent(errorwin), winmethod_Below | winmethod_Fixed, ++error_lines, errorwin);
1159 }
1160
1161 glk_put_char_stream(glk_window_get_stream(errorwin), LATIN1_LINEFEED);
1162 } else {
1163 errorwin = glk_window_open(mainwin->id, winmethod_Below | winmethod_Fixed, error_lines = 2, wintype_TextBuffer, static_cast<glui32>(WindowRock::ErrorWin));
1164 }
1165
1166 // If windows are not supported (e.g. in cheapglk or no Glk), messages
1167 // will not get displayed. If this is the case, print to the main
1168 // window.
1169 strid_t stream;
1170 if (errorwin != nullptr) {
1171 stream = glk_window_get_stream(errorwin);
1172 glk_set_style_stream(stream, style_Alert);
1173 } else {
1174 stream = glk_window_get_stream(mainwin->id);
1175 message = "\n[" + message + "]\n";
1176 }
1177
1178 for (size_t i = 0; message[i] != 0; i++) {
1179 xglk_put_char_stream(stream, char_to_unicode(message[i]));
1180 }
1181 #else
1182 {
1183 std::cout << "\n[" << message << "]\n";
1184 }
1185 #endif
1186 }
1187
1188 void screen_message_prompt(const std::string &message)
1189 {
1190 screen_puts(message);
1191 if (curwin == mainwin) {
1192 screen_print("\n>");
1193 }
1194 }
1195
1196 // See §7.
1197 // This returns true if the stream was successfully selected.
1198 // Deselecting a stream is always successful.
1199 static bool output_stream(int16_t number, uint16_t table, bool formatted)
1200 {
1201 ZASSERT(std::labs(number) <= (zversion >= 3 ? 4 : 2), "invalid output stream selected: %ld", static_cast<long>(number));
1202
1203 if (number == 0) {
1204 return true;
1205 } else if (number > 0) {
1206 streams.set(number);
1207 } else if (number < 0) {
1208 if (number != -3 || stream_tables.size() == 1) {
1209 streams.reset(-number);
1210 }
1211 }
1212
1213 if (number == 2) {
1214 store_word(0x10, word(0x10) | FLAGS2_TRANSCRIPT);
1215 if (transio == nullptr) {
1216 try {
1217 // If autosave_librarystate, we open this as a Glk stream so
1218 // that it will be part of the librarystate.
1219 transio = std::make_unique<IO>(options.transcript_name.get(), options.overwrite_transcript ? IO::Mode::WriteOnly : IO::Mode::Append, IO::Purpose::Transcript, options.autosave_librarystate ? StreamRock::TranscriptStream : StreamRock::None);
1220 } catch (const IO::OpenError &) {
1221 store_word(0x10, word(0x10) & ~FLAGS2_TRANSCRIPT);
1222 streams.reset(OSTREAM_TRANSCRIPT);
1223 warning("unable to open the transcript");
1224 }
1225 }
1226 } else if (number == -2) {
1227 store_word(0x10, word(0x10) & ~FLAGS2_TRANSCRIPT);
1228 // If autosave_librarystate, we close the stream. (Keeping it open in
1229 // the background is unnecessary work.)
1230 if (options.transcript_name != nullptr && options.autosave_librarystate) {
1231 transio = nullptr;
1232 }
1233 }
1234
1235 if (number == 3) {
1236 stream_tables.push(table, formatted);
1237 } else if (number == -3) {
1238 stream_tables.pop();
1239 }
1240
1241 if (number == 4) {
1242 if (scriptio == nullptr) {
1243 try {
1244 scriptio = std::make_unique<IO>(options.record_name.get(), IO::Mode::WriteOnly, IO::Purpose::Input);
1245 } catch (const IO::OpenError &) {
1246 streams.reset(OSTREAM_RECORD);
1247 warning("unable to open the script");
1248 }
1249 }
1250 }
1251 // XXX V6 has even more handling
1252
1253 return number < 0 || streams.test(number);
1254 }
1255
1256 bool output_stream(int16_t number, uint16_t table)
1257 {
1258 return output_stream(number, table, false);
1259 }
1260
1261 void zoutput_stream()
1262 {
1263 output_stream(as_signed(zargs[0]), zargs[1], znargs > 2);
1264 }
1265
1266 // See §10.
1267 // This returns true if the stream was successfully selected.
1268 bool input_stream(int which)
1269 {
1270 istream = which;
1271
1272 if (istream == ISTREAM_KEYBOARD) {
1273 istreamio.reset();
1274 } else if (istream == ISTREAM_FILE) {
1275 if (istreamio == nullptr) {
1276 try {
1277 istreamio = std::make_unique<IO>(options.replay_name.get(), IO::Mode::ReadOnly, IO::Purpose::Input);
1278 } catch (const IO::OpenError &) {
1279 warning("unable to open the command script");
1280 istream = ISTREAM_KEYBOARD;
1281 }
1282 }
1283 } else {
1284 ZASSERT(false, "invalid input stream: %d", istream);
1285 }
1286
1287 return istream == which;
1288 }
1289
1290 void zinput_stream()
1291 {
1292 input_stream(zargs[0]);
1293 }
1294
1295 // This does not even pretend to understand V6 windows.
1296 static void set_current_window(Window *window)
1297 {
1298 curwin = window;
1299
1300 #ifdef ZTERP_GLK
1301 if (curwin == upperwin && upperwin->id != nullptr) {
1302 upperwin->x = upperwin->y = 0;
1303 // V3 (§8.6.1) and V4/V5 (§8.7.2) require the cursor to be moved
1304 // to the origin when the upper window is selected, but V6 doesn’t.
1305 if (zversion != 6) {
1306 glk_window_move_cursor(upperwin->id, 0, 0);
1307 }
1308 }
1309
1310 glk_set_window(curwin->id);
1311 #endif
1312
1313 set_current_style();
1314 }
1315
1316 // Find and validate a window. If window is -3 and the story is V6,
1317 // return the current window.
1318 static Window *find_window(uint16_t window)
1319 {
1320 int16_t w = as_signed(window);
1321
1322 ZASSERT(zversion == 6 ? w == -3 || (w >= 0 && w < 8) : w == 0 || w == 1, "invalid window selected: %d", w);
1323
1324 if (w == -3) {
1325 return curwin;
1326 }
1327
1328 return &windows[w];
1329 }
1330
1331 #ifdef ZTERP_GLK
1332 static void perform_upper_window_resize(glui32 new_height)
1333 {
1334 glui32 actual_height;
1335
1336 auto location = is_game(Game::Journey) ?
1337 winmethod_Below :
1338 winmethod_Above;
1339
1340 glk_window_set_arrangement(glk_window_get_parent(upperwin->id), location | winmethod_Fixed, new_height, upperwin->id);
1341 upper_window_height = new_height;
1342
1343 // Glk might resize the window to a smaller height than was requested,
1344 // so track the actual height, not the requested height.
1345 glk_window_get_size(upperwin->id, nullptr, &actual_height);
1346 if (actual_height != upper_window_height) {
1347 // This message probably won’t be seen in a window since the upper
1348 // window is likely covering everything, but try anyway.
1349 show_message("Unable to fulfill window size request: wanted %lu, got %lu", static_cast<unsigned long>(new_height), static_cast<unsigned long>(actual_height));
1350 upper_window_height = actual_height;
1351 }
1352 }
1353
1354 // When resizing the upper window, the screen’s contents should not
1355 // change (§8.6.1); however, the way windows are handled with Glk makes
1356 // this slightly impossible. When an Inform game tries to display
1357 // something with “box”, it expands the upper window, displays the quote
1358 // box, and immediately shrinks the window down again. This is a
1359 // problem under Glk because the window immediately disappears. Other
1360 // games, such as Bureaucracy, expect the upper window to shrink as soon
1361 // as it has been requested. Thus the following system is used:
1362 //
1363 // If a request is made to shrink the upper window, it is granted
1364 // immediately if there has been user input since the last window resize
1365 // request. If there has not been user input, the request is delayed
1366 // until after the next user input is read.
1367 static long delayed_window_shrink = -1;
1368 static bool saw_input;
1369
1370 static void update_delayed()
1371 {
1372 if (delayed_window_shrink != -1 && upperwin->id != nullptr) {
1373 perform_upper_window_resize(delayed_window_shrink);
1374 delayed_window_shrink = -1;
1375 }
1376 }
1377
1378 static void clear_window(Window *window)
1379 {
1380 if (window->id == nullptr) {
1381 return;
1382 }
1383
1384 glk_window_clear(window->id);
1385
1386 window->x = window->y = 0;
1387 }
1388 #endif
1389
1390 static void resize_upper_window(uint32_t nlines, bool from_game)
1391 {
1392 #ifdef ZTERP_GLK
1393 if (upperwin->id == nullptr) {
1394 return;
1395 }
1396
1397 glui32 previous_height = upper_window_height;
1398
1399 if (from_game) {
1400 delayed_window_shrink = nlines;
1401 if (upper_window_height <= nlines || saw_input) {
1402 update_delayed();
1403 }
1404 saw_input = false;
1405
1406 // §8.6.1.1.2
1407 if (zversion == 3) {
1408 clear_window(upperwin);
1409 }
1410 } else {
1411 perform_upper_window_resize(nlines);
1412 }
1413
1414 // If the window is being created, or if it’s shrinking and the cursor
1415 // is no longer inside the window, move the cursor to the origin.
1416 if (previous_height == 0 || upperwin->y >= nlines) {
1417 upperwin->x = upperwin->y = 0;
1418 if (nlines > 0) {
1419 glk_window_move_cursor(upperwin->id, 0, 0);
1420 }
1421 }
1422
1423 // As in a few other areas, changing the upper window causes reverse
1424 // video to be deactivated, so reapply the current style.
1425 set_current_style();
1426 #endif
1427 }
1428
1429 void close_upper_window()
1430 {
1431 // The upper window is never destroyed; rather, when it’s closed, it
1432 // shrinks to zero height.
1433 resize_upper_window(0, true);
1434
1435 #ifdef ZTERP_GLK
1436 delayed_window_shrink = -1;
1437 saw_input = false;
1438 #endif
1439
1440 set_current_window(mainwin);
1441 }
1442
1443 void get_screen_size(unsigned int &width, unsigned int &height)
1444 {
1445 #ifdef ZTERP_GLK
1446 glui32 w, h;
1447
1448 // The main window can be proportional, and if so, its width is not
1449 // generally useful because games tend to care about width with a
1450 // fixed font. If a status window is available, or if an upper window
1451 // is available, use that to calculate the width, because these
1452 // windows will have a fixed-width font. The height is the combined
1453 // height of all windows.
1454 glk_window_get_size(mainwin->id, &w, &h);
1455 height = h;
1456 if (statuswin.id != nullptr) {
1457 glk_window_get_size(statuswin.id, &w, &h);
1458 height += h;
1459 }
1460 if (upperwin->id != nullptr) {
1461 glk_window_get_size(upperwin->id, &w, &h);
1462 height += h;
1463 }
1464 width = w;
1465 #else
1466 std::tie(width, height) = zterp_os_get_screen_size();
1467 #endif
1468
1469 // XGlk does not report the size of textbuffer windows, and
1470 // zterp_os_get_screen_size() may not be able to get the screen
1471 // size, so use reasonable defaults in those cases.
1472 if (width == 0) {
1473 width = 80;
1474 }
1475 if (height == 0) {
1476 height = 24;
1477 }
1478
1479 // Terrible hack: Because V6 is not properly supported, the window to
1480 // which Journey writes its story is completely covered up by window
1481 // 1. For the same reason, only the bottom 6 lines of window 1 are
1482 // actually useful, even though the game expands it to cover the whole
1483 // screen. By pretending that the screen height is only 6, the main
1484 // window, where text is actually sent, becomes visible.
1485 if (is_game(Game::Journey) && height > 6) {
1486 height = 6;
1487 }
1488 }
1489
1490 #ifdef ZTERP_GLK
1491 #ifdef GLK_MODULE_LINE_TERMINATORS
1492 static std::vector<glui32> term_keys;
1493 #endif
1494 static bool term_mouse = false;
1495
1496 static void term_keys_reset()
1497 {
1498 #ifdef GLK_MODULE_LINE_TERMINATORS
1499 term_keys.clear();
1500 #endif
1501 term_mouse = false;
1502 }
1503
1504 static void insert_key(uint32_t key)
1505 {
1506 #ifdef GLK_MODULE_LINE_TERMINATORS
1507 term_keys.push_back(key);
1508 #endif
1509 }
1510
1511 static void term_keys_add(uint8_t key)
1512 {
1513 switch (key) {
1514 case ZSCII_UP: insert_key(keycode_Up); break;
1515 case ZSCII_DOWN: insert_key(keycode_Down); break;
1516 case ZSCII_LEFT: insert_key(keycode_Left); break;
1517 case ZSCII_RIGHT: insert_key(keycode_Right); break;
1518 case ZSCII_F1: insert_key(keycode_Func1); break;
1519 case ZSCII_F2: insert_key(keycode_Func2); break;
1520 case ZSCII_F3: insert_key(keycode_Func3); break;
1521 case ZSCII_F4: insert_key(keycode_Func4); break;
1522 case ZSCII_F5: insert_key(keycode_Func5); break;
1523 case ZSCII_F6: insert_key(keycode_Func6); break;
1524 case ZSCII_F7: insert_key(keycode_Func7); break;
1525 case ZSCII_F8: insert_key(keycode_Func8); break;
1526 case ZSCII_F9: insert_key(keycode_Func9); break;
1527 case ZSCII_F10: insert_key(keycode_Func10); break;
1528 case ZSCII_F11: insert_key(keycode_Func11); break;
1529 case ZSCII_F12: insert_key(keycode_Func12); break;
1530
1531 // Keypad 0–9 should be here, but Glk doesn’t support that.
1532 case ZSCII_KEY0: case ZSCII_KEY1: case ZSCII_KEY2: case ZSCII_KEY3:
1533 case ZSCII_KEY4: case ZSCII_KEY5: case ZSCII_KEY6: case ZSCII_KEY7:
1534 case ZSCII_KEY8: case ZSCII_KEY9:
1535 break;
1536
1537 case ZSCII_CLICK_SINGLE:
1538 term_mouse = true;
1539 break;
1540
1541 case ZSCII_CLICK_MENU: case ZSCII_CLICK_DOUBLE:
1542 break;
1543
1544 case 255:
1545 for (int i = 129; i <= 154; i++) {
1546 term_keys_add(i);
1547 }
1548 for (int i = 252; i <= 254; i++) {
1549 term_keys_add(i);
1550 }
1551 break;
1552
1553 default:
1554 break;
1555 }
1556 }
1557
1558 // Look in the terminating characters table (if any) and reset the
1559 // current state of terminating characters appropriately.
1560 static void check_terminators()
1561 {
1562 if (header.terminating_characters_table != 0) {
1563 term_keys_reset();
1564
1565 for (uint32_t addr = header.terminating_characters_table; user_byte(addr) != 0; addr++) {
1566 term_keys_add(user_byte(addr));
1567 }
1568 }
1569 }
1570 #endif
1571
1572 // Decode and print a zcode string at address “addr”. This can be
1573 // called recursively thanks to abbreviations; the initial call should
1574 // have “in_abbr” set to false.
1575 // Each time a character is decoded, it is passed to the function
1576 // “outc”.
1577 static int print_zcode(uint32_t addr, bool in_abbr, void (*outc)(uint8_t))
1578 {
1579 enum class TenBit { None, Start, Half } tenbit = TenBit::None;
1580 int abbrev = 0, shift = 0;
1581 int c, lastc = 0; // initialize to appease g++
1582 uint16_t w;
1583 uint32_t counter = addr;
1584 int current_alphabet = 0;
1585
1586 do {
1587 ZASSERT(counter < memory_size - 1, "string (@0x%lx) runs beyond the end of memory", static_cast<unsigned long>(addr));
1588
1589 w = word(counter);
1590
1591 for (int i : {10, 5, 0}) {
1592 c = (w >> i) & 0x1f;
1593
1594 if (tenbit == TenBit::Start) {
1595 lastc = c;
1596 tenbit = TenBit::Half;
1597 } else if (tenbit == TenBit::Half) {
1598 outc((lastc << 5) | c);
1599 tenbit = TenBit::None;
1600 } else if (abbrev != 0) {
1601 uint32_t new_addr = user_word(header.abbr + 64 * (abbrev - 1) + 2 * c);
1602
1603 // new_addr is a word address, so multiply by 2
1604 print_zcode(new_addr * 2, true, outc);
1605
1606 abbrev = 0;
1607 } else {
1608 switch (c) {
1609 case 0:
1610 outc(ZSCII_SPACE);
1611 shift = 0;
1612 break;
1613 case 1:
1614 if (zversion == 1) {
1615 outc(ZSCII_NEWLINE);
1616 shift = 0;
1617 break;
1618 }
1619 // fallthrough
1620 case 2: case 3:
1621 if (zversion >= 3 || (zversion == 2 && c == 1)) {
1622 ZASSERT(!in_abbr, "abbreviation being used recursively");
1623 abbrev = c;
1624 shift = 0;
1625 } else {
1626 shift = c - 1;
1627 }
1628 break;
1629 case 4: case 5:
1630 if (zversion <= 2) {
1631 current_alphabet = (current_alphabet + (c - 3)) % 3;
1632 shift = 0;
1633 } else {
1634 shift = c - 3;
1635 }
1636 break;
1637 case 6:
1638 if (zversion <= 2) {
1639 shift = (current_alphabet + shift) % 3;
1640 }
1641
1642 if (shift == 2) {
1643 shift = 0;
1644 tenbit = TenBit::Start;
1645 break;
1646 }
1647 // fallthrough
1648 default:
1649 if (zversion <= 2 && c != 6) {
1650 shift = (current_alphabet + shift) % 3;
1651 }
1652
1653 outc(atable[(26 * shift) + (c - 6)]);
1654 shift = 0;
1655 break;
1656 }
1657 }
1658 }
1659
1660 counter += 2;
1661 } while ((w & 0x8000) == 0);
1662
1663 return counter - addr;
1664 }
1665
1666 // Prints the string at addr “addr”.
1667 //
1668 // Returns the number of bytes the string took up. “outc” is passed as
1669 // the character-print function to print_zcode(); if it is null,
1670 // put_char is used.
1671 int print_handler(uint32_t addr, void (*outc)(uint8_t))
1672 {
1673 return print_zcode(addr, false, outc != nullptr ? outc : put_char);
1674 }
1675
1676 void zprint()
1677 {
1678 pc += print_handler(pc, nullptr);
1679 }
1680
1681 void znew_line()
1682 {
1683 put_char(ZSCII_NEWLINE);
1684 }
1685
1686 void zprint_ret()
1687 {
1688 zprint();
1689 znew_line();
1690 zrtrue();
1691 }
1692
1693 #ifdef ZTERP_GLK_GRAPHICS
1694 bool GraphicsWindow::create()
1695 {
1696 if (m_id == nullptr) {
1697 m_id = glk_window_open(mainwin->id, winmethod_Above | winmethod_Fixed, 0, wintype_Graphics, 0);
1698 }
1699
1700 return m_id != nullptr;
1701 }
1702
1703 bool GraphicsWindow::resize(Type type)
1704 {
1705 if (m_id == nullptr) {
1706 return false;
1707 }
1708
1709 if (type == m_type) {
1710 return true;
1711 }
1712
1713 glk_window_clear(m_id);
1714
1715 try {
1716 auto window_width = get_window_width();
1717 if (window_width == 0) {
1718 return false;
1719 }
1720
1721 // The images for Zork Zero games (Tower of Bozbar, Peggleboz,
1722 // Snarfem, and Double Fanucci) are 320x200, but the bottom ≅83
1723 // pixels are a box intended to hold all the text on the screen;
1724 // and since Glk doesn’t support text in graphics windows, the
1725 // text will go below the entire image. That’s a complete waste
1726 // of space and requires a tall window to fit both the original
1727 // 320x200 (or 320x240 in aspect-correct mode) image, as well as
1728 // all the text. So instead, pretend the image is 320x117,
1729 // preventing the bottom 83 pixels from appearing.
1730 static const std::unordered_map<GraphicsWindow::Type, ImageSize, EnumClassHash> window_sizes = {
1731 {GraphicsWindow::Type::ArthurIntro, {292, 196}},
1732 {GraphicsWindow::Type::ArthurBanner, {314, 84}},
1733 {GraphicsWindow::Type::ArthurMap, {320, 96}},
1734 {GraphicsWindow::Type::ArthurDemon, {254, 164}},
1735 {GraphicsWindow::Type::ZorkZeroBorder, {320, 39}},
1736 {GraphicsWindow::Type::ZorkZero320, {320, 200}},
1737 {GraphicsWindow::Type::ZorkZeroGame, {320, 117}},
1738 {GraphicsWindow::Type::ShogunTitle, {320, 200}},
1739 {GraphicsWindow::Type::ShogunNormal, {320, 0}},
1740 {GraphicsWindow::Type::ShogunMaze, {274, 140}},
1741 {GraphicsWindow::Type::Mysterious, {512, 208}},
1742 {GraphicsWindow::Type::MysteriousSeparator, {512, 16}},
1743 };
1744
1745 const auto &size = window_sizes.at(type);
1746
1747 m_ratio = std::min(window_width / size.width, options.v6_hack_max_scale);
1748 m_width = window_width;
1749 m_base_width = size.width;
1750
1751 glk_window_set_arrangement(glk_window_get_parent(m_id), winmethod_Above | winmethod_Fixed, std::round(size.height * m_ratio * aspect_scale()), m_id);
1752 } catch (const std::out_of_range &) {
1753 return false;
1754 }
1755
1756 if (m_id == nullptr) {
1757 return false;
1758 }
1759
1760 if (options.v6_borders) {
1761 if (m_left_border != nullptr) {
1762 glk_window_close(m_left_border, nullptr);
1763 m_left_border = nullptr;
1764 }
1765
1766 if (m_right_border != nullptr) {
1767 glk_window_close(m_right_border, nullptr);
1768 m_right_border = nullptr;
1769 }
1770
1771 if (type == Type::ZorkZeroBorder ||
1772 type == Type::ArthurBanner ||
1773 type == Type::ShogunNormal ||
1774 type == Type::ShogunMaze)
1775 {
1776 int left, right;
1777
1778 // Zork Zero border images vary in widths (from 36 to 43
1779 // pixels for the left border, and 36 to 42 for the right);
1780 // to simplify things, create each border window as the max
1781 // possible size for that side. For Arthur, the staffs are
1782 // always 2 pixels wide, and for Shogun, the decorations are
1783 // always 23 pixels wide.
1784 if (type == Type::ZorkZeroBorder) {
1785 left = 43;
1786 right = 42;
1787 } else if (type == Type::ArthurBanner) {
1788 left = right = 2;
1789 } else {
1790 left = right = 23;
1791 }
1792
1793 m_left_border = glk_window_open(glk_window_get_parent(mainwin->id), winmethod_Left | winmethod_Fixed, left * ratio(), wintype_Graphics, 0);
1794 if (m_left_border != nullptr) {
1795 m_right_border = glk_window_open(glk_window_get_parent(mainwin->id), winmethod_Right | winmethod_Fixed, right * ratio(), wintype_Graphics, 0);
1796 if (m_right_border == nullptr) {
1797 glk_window_close(m_left_border, nullptr);
1798 m_left_border = nullptr;
1799 }
1800 }
1801
1802 if (upperwin->id != nullptr) {
1803 glui32 w;
1804 glk_window_get_size(upperwin->id, &w, nullptr);
1805 upper_window_width = w;
1806 }
1807 }
1808 }
1809
1810 m_type = type;
1811
1812 return true;
1813 }
1814
1815 void GraphicsWindow::destroy()
1816 {
1817 if (m_id != nullptr) {
1818 m_type = Type::None;
1819 glk_window_clear(m_id);
1820 glk_window_set_arrangement(glk_window_get_parent(m_id), winmethod_Above | winmethod_Fixed, 0, m_id);
1821 }
1822
1823 if (m_left_border != nullptr) {
1824 glk_window_close(m_left_border, nullptr);
1825 m_left_border = nullptr;
1826 }
1827
1828 if (m_right_border != nullptr) {
1829 glk_window_close(m_right_border, nullptr);
1830 m_right_border = nullptr;
1831 }
1832 }
1833
1834 void GraphicsWindow::clear()
1835 {
1836 if (m_id != nullptr) {
1837 glk_window_clear(m_id);
1838 }
1839 }
1840
1841 glui32 GraphicsWindow::get_window_width() const
1842 {
1843 winid_t parent = m_id != nullptr ? m_id : mainwin->id;
1844 winid_t win = glk_window_open(parent, winmethod_Above | winmethod_Fixed, 0, wintype_Graphics, 0);
1845
1846 if (win == nullptr) {
1847 return 0;
1848 }
1849
1850 glui32 width;
1851 glk_window_get_size(win, &width, nullptr);
1852
1853 glk_window_close(win, nullptr);
1854
1855 return width;
1856 }
1857
1858 static bool zorkzero_has_border()
1859 {
1860 // Whether in bordered or borderless mode (controlled by the MODE
1861 // game command) is tracked via a global variable, which differs for
1862 // each version of Zork Zero.
1863 static const std::unordered_map<std::string, uint8_t> gvars = {
1864 {"296-881019", 0x9f},
1865 {"366-890323", 0x7f},
1866 {"383-890602", 0x82},
1867 {"393-890714", 0x83},
1868 };
1869
1870 try {
1871 return variable(gvars.at(get_story_id()) + 0x10) != 0;
1872 } catch (const std::out_of_range &) {
1873 return false;
1874 }
1875 }
1876
1877 struct JourneyStamp {
1878 glui32 background;
1879 ImageGeometry geom;
1880 };
1881
1882 static void close_journey_window()
1883 {
1884 if (journey_window != nullptr) {
1885 glk_window_close(journey_window, nullptr);
1886 journey_window = nullptr;
1887 }
1888 }
1889
1890 // This duplicates some code from draw_journey(), but it may not be
1891 // worth pulling it out since the code is just different enough to make
1892 // that annoying.
1893 static void draw_journey_stamp(glui32 pic, glui32 w, glui32 h, const JourneyStamp &stamp)
1894 {
1895 glui32 width = journey_screen_width * 0.375;
1896
1897 glui32 gwin_width, gwin_height;
1898 glk_window_get_size(journey_window, &gwin_width, &gwin_height);
1899
1900 double multiplier = width / 120.0;
1901
1902 glui32 base_background_width, base_background_height;
1903 glk_image_get_info(stamp.background, &base_background_width, &base_background_height);
1904
1905 double background_width = std::round(base_background_width * multiplier);
1906 double background_height = std::round(base_background_height * multiplier * aspect_scale());
1907
1908 double x = (stamp.geom.x * multiplier) + ((gwin_width - background_width) / 2.0);
1909 double y = (stamp.geom.y * multiplier * aspect_scale()) + ((gwin_height - background_height) / 2.0);
1910
1911 glk_image_draw_scaled(journey_window, pic, std::round(x), std::round(y), std::round(w * multiplier), std::round(h * multiplier * aspect_scale()));
1912 }
1913
1914 static bool draw_journey_background(glui32 pic, glui32 w, glui32 h)
1915 {
1916 journey_screen_width = graphics_window.get_window_width();
1917 if (journey_screen_width == 0) {
1918 return false;
1919 }
1920
1921 glui32 width = journey_screen_width * 0.375;
1922
1923 // Try to somewhat match the bars in the menu area.
1924 int border_width = 1;
1925 if (options.int_number == 2 || options.int_number == 6 || options.int_number == 9 || options.int_number == 10) {
1926 border_width = 10;
1927 }
1928
1929 if (journey_window == nullptr) {
1930 journey_window = glk_window_open(mainwin->id, winmethod_Left | winmethod_Fixed, width + border_width, wintype_Graphics, 0);
1931 if (journey_window == nullptr) {
1932 return false;
1933 }
1934 }
1935
1936 glui32 gwin_width, gwin_height;
1937 glk_window_get_size(journey_window, &gwin_width, &gwin_height);
1938
1939 // The widest image is 119 pixels so scale everything based on that.
1940 double multiplier = width / 120.0;
1941
1942 double image_width = std::round(w * multiplier);
1943 double image_height = std::round(h * multiplier * aspect_scale());
1944
1945 double x = (gwin_width - image_width) / 2.0;
1946 double y = (gwin_height - image_height) / 2.0;
1947
1948 glk_image_draw_scaled(journey_window, pic, std::round(x), std::round(y), std::round(w * multiplier), std::round(h * multiplier * aspect_scale()));
1949
1950 glui32 color;
1951 if (!glk_style_measure(mainwin->id, style_Normal, stylehint_TextColor, &color)) {
1952 color = 0xe7e8e9;
1953 }
1954
1955 glk_window_fill_rect(journey_window, color, width, 0, border_width, gwin_height);
1956
1957 return true;
1958 }
1959
1960 static bool draw_journey(glui32 pic, glui32 w, glui32 h)
1961 {
1962 if (hack != Hack::Journey) {
1963 return false;
1964 }
1965
1966 static const std::unordered_map<glui32, JourneyStamp> journey_stamps = {
1967 {6, JourneyStamp{5, ImageGeometry(0, 32)}},
1968 {8, JourneyStamp{7, ImageGeometry(0, 4)}},
1969 {12, JourneyStamp{11, ImageGeometry(23, 74)}},
1970 {21, JourneyStamp{20, ImageGeometry(0, 21)}},
1971 {46, JourneyStamp{7, ImageGeometry(0, 0)}},
1972 {81, JourneyStamp{80, ImageGeometry(0, 12)}},
1973 {82, JourneyStamp{84, ImageGeometry(0, 0)}},
1974 {85, JourneyStamp{84, ImageGeometry(0, 0)}},
1975 {88, JourneyStamp{87, ImageGeometry(0, 0)}},
1976 {91, JourneyStamp{90, ImageGeometry(0, 39)}},
1977 {101, JourneyStamp{100, ImageGeometry(0, 0)}},
1978 {115, JourneyStamp{114, ImageGeometry(49, 0)}},
1979 {129, JourneyStamp{128, ImageGeometry(1, 0)}},
1980 {139, JourneyStamp{138, ImageGeometry(0, 0)}},
1981 {141, JourneyStamp{140, ImageGeometry(0, 92)}},
1982 {145, JourneyStamp{144, ImageGeometry(26, 80)}},
1983 {147, JourneyStamp{146, ImageGeometry(0, 87)}},
1984 {158, JourneyStamp{157, ImageGeometry(33, 74)}},
1985 };
1986
1987 try {
1988 const auto &stamp = journey_stamps.at(pic);
1989 draw_journey_stamp(pic, w, h, stamp);
1990 return true;
1991 } catch (const std::out_of_range &) {
1992 }
1993
1994 close_journey_window();
1995
1996 // This is the title; ignore it here to allow zdraw_picture() to
1997 // draw it inline in the main window.
1998 if (pic == 160) {
1999 return false;
2000 }
2001
2002 return draw_journey_background(pic, w, h);
2003 }
2004
2005 static bool draw_shogun(glui32 pic, glui32 w, glui32 h, glui32 x, glui32 y)
2006 {
2007 if (hack != Hack::Shogun) {
2008 return false;
2009 }
2010
2011 if (pic == 1) {
2012 if (!graphics_window.resize(GraphicsWindow::Type::ShogunTitle)) {
2013 return false;
2014 }
2015 graphics_window.draw(1, ImageGeometry{0, 0}, w, h);
2016 return true;
2017 }
2018
2019 // Different releases of Shogun did the borders differently, as in
2020 // Zork Zero: DOS split them up, and Blorbs are for DOS, so whenever
2021 // a drawing request comes in for the left border, unconditionally
2022 // draw the right as well. 59 is the right border, requested only
2023 // when the interpreter and game file are both DOS; ignore such
2024 // requests because it will have already been drawn by
2025 // graphics_window.draw_shogun_borders().
2026 if (pic == 3) {
2027 if (!graphics_window.resize(GraphicsWindow::Type::ShogunNormal)) {
2028 return false;
2029 }
2030 graphics_window.draw_shogun_borders();
2031 return true;
2032 } else if (pic == 59) {
2033 return true;
2034 }
2035
2036 // Shogun calculates coordinates (for the maze) correctly.
2037 if (pic >= 38 && pic <= 44) {
2038 if (!graphics_window.resize(GraphicsWindow::Type::ShogunMaze)) {
2039 return false;
2040 }
2041 graphics_window.draw_shogun_borders();
2042
2043 // The maze itself is offset one block from the background (so
2044 // it’s centered), but to calculate this, it uses the maze
2045 // window size, which isn’t currently tracked by Bocfel, so its
2046 // calculating is incorrect. However, since we know the
2047 // invisible picture size (7x7), it’s simple enough to manually
2048 // add this to the offsets for the maze pieces. Eventually, if
2049 // window sizes are properly tracked, this should not be
2050 // necessary.
2051 x--;
2052 y--;
2053 if (pic != 44) {
2054 x += SHOGUN_MAZE_BLOCK_WIDTH;
2055 y += SHOGUN_MAZE_BLOCK_HEIGHT;
2056 }
2057
2058 ImageGeometry geom(x, y);
2059 graphics_window.draw(pic, geom, w, h);
2060 return true;
2061 }
2062
2063 return false;
2064 }
2065
2066 static bool draw_mysterious(glui32 pic, glui32 w, glui32 h, double x, double y)
2067 {
2068 if (hack != Hack::MysteriousAdventures ||
2069 mysterious_max_image == 0 ||
2070 pic > (mysterious_max_image - 3))
2071 {
2072 return false;
2073 }
2074
2075 if (!graphics_window.resize(GraphicsWindow::Type::Mysterious)) {
2076 return false;
2077 }
2078
2079 // Delay creation till here, to ensure the upper window is created
2080 // first, so this comes _below_ the upper window.
2081 if (mysterious_separator.create() && mysterious_separator.resize(GraphicsWindow::Type::MysteriousSeparator)) {
2082 glui32 sepw, seph;
2083 if (pic == mysterious_max_image - 3 && glk_image_get_info(mysterious_max_image - 3, &sepw, &seph)) {
2084 ImageGeometry geom{0, 0};
2085 mysterious_separator.draw(mysterious_max_image - 3, geom, sepw, seph);
2086
2087 return true;
2088 }
2089 }
2090
2091 ImageGeometry geom{0, 0};
2092 graphics_window.draw(pic, geom, w, h);
2093
2094 return true;
2095 }
2096 #endif
2097
2098 void zerase_window()
2099 {
2100 #ifdef ZTERP_GLK
2101 switch (as_signed(zargs[0])) {
2102 case -2:
2103 for (auto &window : windows) {
2104 clear_window(&window);
2105 }
2106 break;
2107 case -1:
2108 close_upper_window();
2109 #ifdef ZTERP_GLK_GRAPHICS
2110 graphics_window.destroy();
2111 #endif
2112 // fallthrough
2113 case 0:
2114 // 8.7.3.2.1 says V5+ should have the cursor set to 1, 1 of the
2115 // erased window; V4 the lower window goes bottom left, the upper
2116 // to 1, 1. Glk doesn’t give control over the cursor when
2117 // clearing, and that doesn’t really seem to be an issue; so just
2118 // call glk_window_clear().
2119 clear_window(mainwin);
2120
2121 break;
2122 case 1:
2123 clear_window(upperwin);
2124 break;
2125 case 2:
2126 #ifdef ZTERP_GLK_GRAPHICS
2127 // In Arthur, the banner/map window is 2, which is represented
2128 // by the graphics window.
2129 if (hack == Hack::Arthur) {
2130 graphics_window.clear();
2131 if (arthurwin->id != nullptr) {
2132 glk_window_clear(arthurwin->id);
2133 }
2134 }
2135 break;
2136 #endif
2137 default:
2138 break;
2139 }
2140
2141 // glk_window_clear() kills reverse video in Gargoyle. Reapply style.
2142 set_current_style();
2143 #endif
2144 }
2145
2146 void zerase_line()
2147 {
2148 #ifdef ZTERP_GLK
2149 #ifdef ZTERP_GLK_GRAPHICS
2150 // Selectively handle @erase_line for version 6 games.
2151 if (hack == Hack::Journey && curwin == upperwin && upperwin->id != nullptr && zargs[0] > 1) {
2152 for (glui32 i = upperwin->x; i < std::min<glui32>(upper_window_width, curwin->x + (zargs[0] - 1)); i++) {
2153 xglk_put_char(UNICODE_SPACE);
2154 }
2155
2156 glk_window_move_cursor(curwin->id, curwin->x, curwin->y);
2157
2158 return;
2159 } else if (hack == Hack::Arthur && curwin == arthurwin && arthurwin->id != nullptr && zargs[0] > 0) {
2160 glui32 window_width;
2161 glk_window_get_size(arthurwin->id, &window_width, nullptr);
2162 auto erase_end = zargs[0] == 1 ? window_width : curwin->x + (zargs[0] - 1);
2163 auto *stream = glk_window_get_stream(arthurwin->id);
2164 for (glui32 i = curwin->x; i < std::min(window_width, erase_end); i++) {
2165 glk_put_char_stream(stream, ' ');
2166 }
2167
2168 glk_window_move_cursor(curwin->id, curwin->x, curwin->y);
2169
2170 return;
2171 }
2172 #endif
2173
2174 // XXX V6 does pixel handling here.
2175 if (zargs[0] != 1 || curwin != upperwin || upperwin->id == nullptr) {
2176 return;
2177 }
2178
2179 for (uint16_t i = upperwin->x; i < upper_window_width; i++) {
2180 xglk_put_char(UNICODE_SPACE);
2181 }
2182
2183 glk_window_move_cursor(upperwin->id, upperwin->x, upperwin->y);
2184 #endif
2185 }
2186
2187 // XXX This is more complex in V6 and needs to be updated when V6 windowing is implemented.
2188 static void set_cursor(uint16_t y, uint16_t x)
2189 {
2190 #ifdef ZTERP_GLK
2191 // All the windows in V6 can have their cursor positioned; if full
2192 // V6 ever comes about this should be fixed. For now just hardcode
2193 // some Arthur handling: with Arthur, the cursor can be set in
2194 // either the upper window (as normal) or window 2; window 2 is the
2195 // window used for text/graphics above the game, e.g. room images,
2196 // map, inventory, etc.
2197 #ifdef ZTERP_GLK_GRAPHICS
2198 if ((hack == Hack::Arthur && curwin != upperwin && curwin != arthurwin) ||
2199 (hack != Hack::Arthur && curwin != upperwin))
2200 {
2201 #else
2202 if (curwin != upperwin) {
2203 #endif
2204 return;
2205 }
2206
2207 // -1 and -2 are V6 only, but at least Zracer passes -1 (or it’s
2208 // trying to position the cursor to line 65535; unlikely!)
2209 if (as_signed(y) == -1 || as_signed(y) == -2) {
2210 return;
2211 }
2212
2213 // §8.7.2.3 says 1,1 is the top-left, but at least one program (Paint
2214 // and Corners) uses @set_cursor 0 0 to go to the top-left; so
2215 // special-case it.
2216 if (y == 0) {
2217 y = 1;
2218 }
2219
2220 // This handles 0, but also takes care of working around a bug in Inform’s
2221 // “box” statement, which causes “x” to be negative if the box’s text is
2222 // wider than the screen.
2223 if (as_signed(x) < 1) {
2224 x = 1;
2225 }
2226
2227 // This is actually illegal, but some games (e.g. Beyond Zork) expect it to work.
2228 if (curwin == upperwin && y > upper_window_height) {
2229 resize_upper_window(y, true);
2230 }
2231
2232 #ifdef ZTERP_GLK_GRAPHICS
2233 auto *cursorwin = (hack == Hack::Arthur && curwin == arthurwin) ? curwin : upperwin;
2234 #else
2235 auto *cursorwin = upperwin;
2236 #endif
2237
2238 if (cursorwin->id != nullptr) {
2239 cursorwin->x = x - 1;
2240 cursorwin->y = y - 1;
2241
2242 glk_window_move_cursor(cursorwin->id, x - 1, y - 1);
2243 }
2244 #endif
2245 }
2246
2247 void zset_cursor()
2248 {
2249 #ifdef ZTERP_GLK_GRAPHICS
2250 if (hack == Hack::MysteriousAdventures) {
2251 zargs[0] -= 180;
2252 }
2253 #endif
2254
2255 set_cursor(zargs[0], zargs[1]);
2256 }
2257
2258 void zget_cursor()
2259 {
2260 #ifdef ZTERP_GLK
2261 user_store_word(zargs[0] + 0, upperwin->y + 1);
2262 user_store_word(zargs[0] + 2, upperwin->x + 1);
2263 #else
2264 user_store_word(zargs[0] + 0, 1);
2265 user_store_word(zargs[0] + 2, 1);
2266 #endif
2267 }
2268
2269 static bool prepare_color_opcode(int16_t &fg, int16_t &bg, Window *&win)
2270 {
2271 // Glk (apart from Gargoyle) has no color support.
2272 #if !defined(ZTERP_GLK) || defined(GLK_MODULE_GARGLKTEXT)
2273 if (options.disable_color) {
2274 return false;
2275 }
2276
2277 fg = as_signed(zargs[0]);
2278 bg = as_signed(zargs[1]);
2279 win = znargs == 3 ? find_window(zargs[2]) : style_window();
2280
2281 return true;
2282 #else
2283 return false;
2284 #endif
2285 }
2286
2287 void zset_colour()
2288 {
2289 int16_t fg, bg;
2290 Window *win;
2291
2292 if (prepare_color_opcode(fg, bg, win)) {
2293 // XXX -1 is a valid color in V6.
2294 if (fg >= 1 && fg <= 12) {
2295 win->fg_color = Color(Color::Mode::ANSI, fg);
2296 }
2297 if (bg >= 1 && bg <= 12) {
2298 win->bg_color = Color(Color::Mode::ANSI, bg);
2299 }
2300
2301 if (win == mainwin) {
2302 history.add_fg_color(win->fg_color);
2303 history.add_bg_color(win->bg_color);
2304 }
2305
2306 set_current_style();
2307 }
2308 }
2309
2310 void zset_true_colour()
2311 {
2312 int16_t fg, bg;
2313 Window *win;
2314
2315 if (prepare_color_opcode(fg, bg, win)) {
2316 if (fg >= 0) {
2317 win->fg_color = Color(Color::Mode::True, fg);
2318 } else if (fg == -1) {
2319 win->fg_color = Color();
2320 }
2321
2322 if (bg >= 0) {
2323 win->bg_color = Color(Color::Mode::True, bg);
2324 } else if (bg == -1) {
2325 win->bg_color = Color();
2326 }
2327
2328 if (win == mainwin) {
2329 history.add_fg_color(win->fg_color);
2330 history.add_bg_color(win->bg_color);
2331 }
2332
2333 set_current_style();
2334 }
2335 }
2336
2337 // V6 has per-window styles, but all others have a global style; in this
2338 // case, track styles via the main window.
2339 void zset_text_style()
2340 {
2341 // A style of 0 means all others go off.
2342 if (zargs[0] == 0) {
2343 style_window()->style.reset();
2344 } else if (zargs[0] < 16) {
2345 style_window()->style |= zargs[0];
2346 }
2347
2348 if (style_window() == mainwin) {
2349 history.add_style();
2350 }
2351
2352 set_current_style();
2353 }
2354
2355 static bool is_valid_font(Window::Font font)
2356 {
2357 return font == Window::Font::Normal ||
2358 (font == Window::Font::Character && !options.disable_graphics_font) ||
2359 (font == Window::Font::Fixed && !options.disable_fixed);
2360 }
2361
2362 void zset_font()
2363 {
2364 Window *win = curwin;
2365
2366 if (zversion == 6 && znargs == 2 && as_signed(zargs[1]) != -3) {
2367 ZASSERT(zargs[1] < 8, "invalid window selected: %d", as_signed(zargs[1]));
2368 win = &windows[zargs[1]];
2369 }
2370
2371 if (static_cast<Window::Font>(zargs[0]) == Window::Font::Query) {
2372 store(static_cast<uint16_t>(win->font));
2373 } else if (is_valid_font(static_cast<Window::Font>(zargs[0]))) {
2374 store(static_cast<uint16_t>(win->font));
2375 win->font = static_cast<Window::Font>(zargs[0]);
2376 set_current_style();
2377 if (win == mainwin) {
2378 history.add_style();
2379 }
2380 } else {
2381 store(0);
2382 }
2383 }
2384
2385 void zprint_table()
2386 {
2387 uint16_t text = zargs[0], width = zargs[1], height = zargs[2], skip = zargs[3];
2388 uint16_t n = 0;
2389
2390 #ifdef ZTERP_GLK
2391 uint16_t start = 0; // initialize to appease g++
2392
2393 if (curwin == upperwin) {
2394 start = upperwin->x + 1;
2395 }
2396 #endif
2397
2398 if (znargs < 3) {
2399 height = 1;
2400 }
2401 if (znargs < 4) {
2402 skip = 0;
2403 }
2404
2405 for (uint16_t i = 0; i < height; i++) {
2406 for (uint16_t j = 0; j < width; j++) {
2407 put_char(user_byte(text + n++));
2408 }
2409
2410 if (i + 1 != height) {
2411 n += skip;
2412 #ifdef ZTERP_GLK
2413 if (curwin == upperwin) {
2414 set_cursor(upperwin->y + 2, start);
2415 } else
2416 #endif
2417 {
2418 put_char(ZSCII_NEWLINE);
2419 }
2420 }
2421 }
2422 }
2423
2424 void zprint_char()
2425 {
2426 put_char(zargs[0]);
2427 }
2428
2429 void zprint_num()
2430 {
2431 for (const auto &c : std::to_string(as_signed(zargs[0]))) {
2432 put_char(c);
2433 }
2434 }
2435
2436 void zprint_addr()
2437 {
2438 print_handler(zargs[0], nullptr);
2439 }
2440
2441 void zprint_paddr()
2442 {
2443 print_handler(unpack_string(zargs[0]), nullptr);
2444 }
2445
2446 // XXX This is more complex in V6 and needs to be updated when V6 windowing is implemented.
2447 void zsplit_window()
2448 {
2449 #ifdef ZTERP_GLK_GRAPHICS
2450 if (hack == Hack::MysteriousAdventures) {
2451 zargs[0] = 3;
2452 }
2453 #endif
2454
2455 if (zargs[0] == 0) {
2456 close_upper_window();
2457 } else {
2458 resize_upper_window(zargs[0], true);
2459 }
2460 }
2461
2462 void zset_window()
2463 {
2464 set_current_window(find_window(zargs[0]));
2465 }
2466
2467 #ifdef ZTERP_GLK
2468 static void window_change()
2469 {
2470 #ifdef ZTERP_GLK_GRAPHICS
2471 auto current_type = graphics_window.type();
2472
2473 graphics_window.destroy();
2474 close_journey_window();
2475 mysterious_separator.destroy();
2476 #endif
2477
2478 // When a textgrid (the upper window) in Gargoyle is rearranged, it
2479 // forgets about reverse video settings, so reapply any styles to the
2480 // current window (it doesn’t hurt if the window is a textbuffer). If
2481 // the current window is not the upper window that’s OK, because
2482 // set_current_style() is called when a @set_window is requested.
2483 set_current_style();
2484
2485 #if defined(ZTERP_GLK_GRAPHICS) && !defined(GLK_MODULE_GARGLKWINSIZE)
2486 find_window_size(mainwin->id);
2487 #endif
2488
2489 // Shogun won’t redraw its borders on resize, so do it here. Ideally
2490 // this would occur above instead of closing the borders, but the
2491 // call to find_window_size(mainwin->id) needs to find the size of
2492 // the main window _without_ borders, so it’s sandwiched between the
2493 // “destroy” and “draw” calls.
2494 #ifdef ZTERP_GLK_GRAPHICS
2495 if (hack == Hack::Shogun) {
2496 graphics_window.resize(current_type);
2497 graphics_window.draw_shogun_borders();
2498 }
2499 #endif
2500
2501 // Track the new size of the upper window.
2502 if (zversion >= 3 && upperwin->id != nullptr) {
2503 glui32 w, h;
2504
2505 glk_window_get_size(upperwin->id, &w, &h);
2506
2507 upper_window_width = w;
2508
2509 resize_upper_window(h, false);
2510 }
2511
2512 // §8.4
2513 // Only 0x20 and 0x21 are mentioned; what of 0x22 and 0x24? Zoom and
2514 // Windows Frotz both update the V5 header entries, so do that here,
2515 // too.
2516 //
2517 // Also, no version restrictions are given, but assume V4+ per §11.1.
2518 if (zversion >= 4) {
2519 unsigned width, height;
2520
2521 get_screen_size(width, height);
2522
2523 store_byte(0x20, height > 254 ? 254 : height);
2524 store_byte(0x21, width > 255 ? 255 : width);
2525
2526 if (zversion >= 5) {
2527 store_word(0x22, width > UINT16_MAX ? UINT16_MAX : width);
2528 store_word(0x24, height > UINT16_MAX ? UINT16_MAX : height);
2529 }
2530 } else {
2531 zshow_status();
2532 }
2533 }
2534 #endif
2535
2536 #ifdef ZTERP_GLK
2537 static bool timer_running;
2538
2539 static void start_timer(uint16_t n)
2540 {
2541 if (!timer_available()) {
2542 return;
2543 }
2544
2545 if (timer_running) {
2546 die("nested timers unsupported");
2547 }
2548 glk_request_timer_events(n * 100);
2549 timer_running = true;
2550 }
2551
2552 static void stop_timer()
2553 {
2554 if (!timer_available()) {
2555 return;
2556 }
2557
2558 glk_request_timer_events(0);
2559 timer_running = false;
2560 }
2561
2562 static void request_char()
2563 {
2564 if (have_unicode) {
2565 glk_request_char_event_uni(curwin->id);
2566 } else {
2567 glk_request_char_event(curwin->id);
2568 }
2569 }
2570
2571 static void request_line(Line &line, glui32 maxlen)
2572 {
2573 // If the game has specified any line terminators, enable them.
2574 #ifdef GLK_MODULE_LINE_TERMINATORS
2575 if (glk_gestalt(gestalt_LineTerminators, 0)) {
2576 glk_set_terminators_line_event(curwin->id, term_keys.data(), term_keys.size());
2577 }
2578 #endif
2579
2580 if (have_unicode) {
2581 glk_request_line_event_uni(curwin->id, line.unicode.data(), maxlen, line.len);
2582 } else {
2583 glk_request_line_event(curwin->id, line.latin1.data(), maxlen, line.len);
2584 }
2585 }
2586
2587 // If an interrupt is called, cancel any pending read events. They will
2588 // be restarted after the interrupt returns. If this was a line input
2589 // event, “line” will be updated with the length of the input that had
2590 // been entered at the time of cancellation.
2591 static void cancel_read_events(const Window *window, Line &line)
2592 {
2593 event_t ev;
2594
2595 glk_cancel_char_event(window->id);
2596 glk_cancel_line_event(window->id, &ev);
2597 if (upperwin->id != nullptr) {
2598 glk_cancel_mouse_event(upperwin->id);
2599 }
2600
2601 // If the pending read was a line input, set the line length to the
2602 // amount read before cancellation (this will already have been
2603 // stored in the line struct by Glk).
2604 if (ev.type == evtype_LineInput) {
2605 line.len = ev.val1;
2606 }
2607 }
2608
2609 // This is a wrapper around internal_call() which handles screen-related
2610 // issues: input events are canceled (in case the interrupt routine
2611 // calls input functions) and the window is restored if the interrupt
2612 // changes it. The value from the internal call is returned. This does
2613 // not restart the canceled read events.
2614 static uint16_t handle_interrupt(uint16_t addr, Line *line)
2615 {
2616 Window *saved = curwin;
2617
2618 if (line != nullptr) {
2619 cancel_read_events(curwin, *line);
2620 }
2621
2622 uint16_t ret = internal_call(addr);
2623
2624 // It’s possible for an interrupt to switch windows; if it does,
2625 // simply switch back. This is the easiest way to deal with an
2626 // undefined bit of the Z-machine.
2627 if (curwin != saved) {
2628 set_current_window(saved);
2629 }
2630
2631 return ret;
2632 }
2633
2634 // Request mouse events in all supported windows, which is to say the
2635 // upper window (if it exists) and the graphics window (if it exists).
2636 static void request_mouse_events()
2637 {
2638 if (upperwin->id != nullptr) {
2639 glk_request_mouse_event(upperwin->id);
2640 }
2641
2642 #ifdef ZTERP_GLK_GRAPHICS
2643 if (graphics_window.id() != nullptr) {
2644 glk_request_mouse_event(graphics_window.id());
2645 }
2646 #endif
2647 }
2648
2649 // All read events are canceled during an interrupt, but after an
2650 // interrupt returns, it’s possible that the read should be restarted,
2651 // so this function does that.
2652 static void restart_read_events(Line &line, const Input &input, bool enable_mouse)
2653 {
2654 switch (input.type) {
2655 case Input::Type::Char:
2656 request_char();
2657 break;
2658 case Input::Type::Line:
2659 request_line(line, input.maxlen);
2660 break;
2661 }
2662
2663 if (enable_mouse) {
2664 request_mouse_events();
2665 }
2666 }
2667 #endif
2668
2669 #ifdef ZTERP_GLK
2670 void screen_flush()
2671 {
2672 event_t ev;
2673
2674 glk_select_poll(&ev);
2675 switch (ev.type) {
2676 case evtype_None:
2677 break;
2678 case evtype_Arrange:
2679 window_change();
2680 break;
2681 #ifdef GLK_MODULE_SOUND2
2682 case evtype_SoundNotify: {
2683 sound_stopped(ev.val2);
2684 uint16_t sound_routine = sound_get_routine(ev.val2);
2685 if (sound_routine != 0) {
2686 handle_interrupt(sound_routine, nullptr);
2687 }
2688 break;
2689 }
2690 #endif
2691 default:
2692 // No other events should arrive. Timers are only started in
2693 // get_input() and are stopped before that function returns.
2694 // Input events will not happen with glk_select_poll(), and no
2695 // other event type is expected to be raised.
2696 break;
2697 }
2698 }
2699 #else
2700 void screen_flush()
2701 {
2702 }
2703 #endif
2704
2705 template <typename T>
2706 static bool special_zscii(T c)
2707 {
2708 return c > 129 && c < 154;
2709 }
2710
2711 // This is called when input stream 1 (read from file) is selected. If
2712 // it succefully reads a character/line from the file, it fills the
2713 // struct at “input” with the appropriate information and returns true.
2714 // If it fails to read (likely due to EOF) then it sets the input stream
2715 // back to the keyboard and returns false.
2716 static bool istream_read_from_file(Input &input)
2717 {
2718 if (input.type == Input::Type::Char) {
2719 long c;
2720
2721 // If there are carriage returns in the input, this is almost
2722 // certainly a command script from a Windows system being run on a
2723 // non-Windows system, so ignore them.
2724 do {
2725 c = istreamio->getc(true);
2726 } while (c == UNICODE_CARRIAGE_RETURN);
2727
2728 if (c == -1) {
2729 input_stream(ISTREAM_KEYBOARD);
2730 return false;
2731 }
2732
2733 // Don’t translate special ZSCII characters (cursor keys, function keys, keypad).
2734 if (special_zscii(c)) {
2735 input.key = c;
2736 } else {
2737 input.key = unicode_to_zscii_q[c];
2738 }
2739 } else {
2740 std::vector<uint16_t> line;
2741
2742 try {
2743 line = istreamio->readline();
2744 } catch (const IO::EndOfFile &) {
2745 input_stream(ISTREAM_KEYBOARD);
2746 return false;
2747 }
2748
2749 // As above, ignore carriage returns.
2750 if (!line.empty() && line.back() == UNICODE_CARRIAGE_RETURN) {
2751 line.pop_back();
2752 }
2753
2754 if (line.size() > input.maxlen) {
2755 line.resize(input.maxlen);
2756 }
2757
2758 input.len = line.size();
2759
2760 #ifdef ZTERP_GLK
2761 if (curwin->id != nullptr) {
2762 glk_set_style(style_Input);
2763 for (const auto &c : line) {
2764 xglk_put_char(c);
2765 }
2766 xglk_put_char(UNICODE_LINEFEED);
2767 set_current_style();
2768 }
2769 #else
2770 for (const auto &c : line) {
2771 IO::standard_out().putc(c);
2772 }
2773 IO::standard_out().putc(UNICODE_LINEFEED);
2774 #endif
2775
2776 std::copy(line.begin(), line.end(), input.line.begin());
2777 }
2778
2779 #ifdef ZTERP_GLK
2780 // It’s possible that output is buffered, meaning that until
2781 // glk_select() is called, output will not be displayed. When reading
2782 // from a command-script, flush on each command so that output is
2783 // visible while the script is being replayed.
2784 screen_flush();
2785
2786 saw_input = true;
2787 #endif
2788
2789 return true;
2790 }
2791
2792 #ifdef GLK_MODULE_LINE_TERMINATORS
2793 // Glk returns terminating characters as keycode_*, but we need them as
2794 // ZSCII. This should only ever be called with values that are matched
2795 // in the switch, because those are the only ones that Glk was told are
2796 // terminating characters. In the event that another keycode comes
2797 // through, though, treat it as Enter.
2798 static uint8_t zscii_from_glk(glui32 key)
2799 {
2800 switch (key) {
2801 case keycode_Up: return ZSCII_UP;
2802 case keycode_Down: return ZSCII_DOWN;
2803 case keycode_Left: return ZSCII_LEFT;
2804 case keycode_Right: return ZSCII_RIGHT;
2805 case keycode_Func1: return ZSCII_F1;
2806 case keycode_Func2: return ZSCII_F2;
2807 case keycode_Func3: return ZSCII_F3;
2808 case keycode_Func4: return ZSCII_F4;
2809 case keycode_Func5: return ZSCII_F5;
2810 case keycode_Func6: return ZSCII_F6;
2811 case keycode_Func7: return ZSCII_F7;
2812 case keycode_Func8: return ZSCII_F8;
2813 case keycode_Func9: return ZSCII_F9;
2814 case keycode_Func10: return ZSCII_F10;
2815 case keycode_Func11: return ZSCII_F11;
2816 case keycode_Func12: return ZSCII_F12;
2817 }
2818
2819 return ZSCII_NEWLINE;
2820 }
2821 #endif
2822
2823 // Attempt to read input from the user. The input type can be either a
2824 // single character or a full line. If “timer” is not zero, a timer is
2825 // started that fires off every “timer” tenths of a second (if the value
2826 // is 1, it will timeout 10 times a second, etc.). Each time the timer
2827 // times out the routine at address “routine” is called. If the routine
2828 // returns true, the input is canceled.
2829 //
2830 // The function returns true if input was stored, false if there was a
2831 // cancellation as described above.
2832 static bool get_input(uint16_t timer, uint16_t routine, Input &input)
2833 {
2834 // If either of these is zero, no timeout should happen.
2835 if (timer == 0) {
2836 routine = 0;
2837 }
2838 if (routine == 0) {
2839 timer = 0;
2840 }
2841
2842 // Flush all streams when input is requested.
2843 #ifndef ZTERP_GLK
2844 IO::standard_out().flush();
2845 #endif
2846 if (scriptio != nullptr) {
2847 scriptio->flush();
2848 }
2849 if (transio != nullptr) {
2850 transio->flush();
2851 }
2852 if (perstransio != nullptr) {
2853 perstransio->flush();
2854 }
2855
2856 // Update the status of line terminators.
2857 #ifdef ZTERP_GLK
2858 check_terminators();
2859 #endif
2860
2861 // Generally speaking, newline will be the reason the line input
2862 // stopped, so set it by default. It will be overridden where
2863 // necessary.
2864 input.term = ZSCII_NEWLINE;
2865
2866 if (istream == ISTREAM_FILE && istream_read_from_file(input)) {
2867 #ifdef ZTERP_GLK
2868 saw_input = true;
2869 #endif
2870 return true;
2871 }
2872 #ifdef ZTERP_GLK
2873 enum class InputStatus { Waiting, Received, Canceled } status = InputStatus::Waiting;
2874 Line line;
2875 Window *saved = nullptr;
2876 // Mouse support is turned on if the game requests it via Flags2
2877 // and, for @read, if it adds single click to the list of
2878 // terminating keys.
2879 bool enable_mouse = mouse_available() &&
2880 ((input.type == Input::Type::Char) ||
2881 (input.type == Input::Type::Line && term_mouse));
2882
2883 // In V6, input might be requested on an unsupported window. If so,
2884 // switch to the main window temporarily.
2885 if (curwin->id == nullptr) {
2886 saved = curwin;
2887 curwin = mainwin;
2888 glk_set_window(curwin->id);
2889 }
2890
2891 if (enable_mouse) {
2892 request_mouse_events();
2893 }
2894
2895 switch (input.type) {
2896 case Input::Type::Char:
2897 request_char();
2898 break;
2899 case Input::Type::Line:
2900 #ifdef ZTERP_GLK_GRAPHICS
2901 // When in borderless mode, there’s no direct way to detect when
2902 // the game is finished with a 320x200/Game window, so infer
2903 // it from line input being requested.
2904 if (hack == Hack::ZorkZero &&
2905 !zorkzero_has_border() &&
2906 (graphics_window.type() == GraphicsWindow::Type::ZorkZero320 || graphics_window.type() == GraphicsWindow::Type::ZorkZeroGame))
2907 {
2908 graphics_window.destroy();
2909 }
2910 #endif
2911 line.len = input.preloaded;
2912 for (int i = 0; i < input.preloaded; i++) {
2913 if (have_unicode) {
2914 line.unicode[i] = input.line[i];
2915 } else {
2916 line.latin1 [i] = input.line[i] > 255 ? LATIN1_QUESTIONMARK : input.line[i];
2917 }
2918 }
2919
2920 request_line(line, input.maxlen);
2921 break;
2922 }
2923
2924 if (timer != 0) {
2925 start_timer(timer);
2926 }
2927
2928 while (status == InputStatus::Waiting) {
2929 event_t ev;
2930
2931 glk_select(&ev);
2932
2933 switch (ev.type) {
2934 case evtype_Arrange:
2935 window_change();
2936 break;
2937
2938 case evtype_Timer:
2939 // Per Glk, timer events shouldn’t arrive after a call to
2940 // glk_request_timer_events(0), but at least GlkOte/RemGlk
2941 // can send such events, and the fix there may be a lot more
2942 // difficult than simply ignoring spurious events here, so
2943 // do that.
2944 if (timer == 0) {
2945 break;
2946 }
2947
2948 stop_timer();
2949
2950 if (handle_interrupt(routine, &line) != 0) {
2951 status = InputStatus::Canceled;
2952 input.term = 0;
2953 } else {
2954 restart_read_events(line, input, enable_mouse);
2955 start_timer(timer);
2956 }
2957
2958 break;
2959
2960 case evtype_CharInput:
2961 ZASSERT(input.type == Input::Type::Char, "got unexpected evtype_CharInput");
2962 ZASSERT(ev.win == curwin->id, "got evtype_CharInput on unexpected window");
2963
2964 status = InputStatus::Received;
2965
2966 // As far as the Standard is concerned, there is no difference in
2967 // behavior for @read_char between versions 4 and 5, as §10.7.1 claims
2968 // that all characters defined for input can be returned by @read_char.
2969 // However, according to Infocom’s EZIP documentation, “keys which do
2970 // not have a single ASCII value are ignored,” with the exception that
2971 // up, down, left, and right map to 14, 13, 11, and 7, respectively.
2972 // From looking at V4 games’ source code, it seems like only Bureaucracy
2973 // makes use of these codes, and then only partially. Since the down
2974 // arrow maps to 13, it is indistinguishable from ENTER. Bureaucracy
2975 // treats 14 like ^, meaning “back up a field”. The other arrows aren’t
2976 // handled specifically, but what Bureaucracy does with all characters
2977 // it doesn’t handle specifically is print them out. In the DOS version
2978 // of Bureaucracy, hitting the left arrow inserts a mars symbol (which
2979 // is what code page 437 uses to represent value 11). Hitting the right
2980 // arrow results in a beep since 7 is the bell in ASCII. Up and down
2981 // work as expected, but left and right appear to have just been ignored
2982 // and untested. On the Apple II, up and down work, but left and right
2983 // cause nothing to be printed. However, Bureaucracy does advance its
2984 // cursor location when the arrows are hit (as it does with every
2985 // character), which causes interesting behavior: hit the right arrow a
2986 // couple of times and then hit backspace: the cursor will jump to the
2987 // right first due to the fact that the cursor position was advanced
2988 // without anything actually being printed. This can’t be anything but a
2989 // bug.
2990 //
2991 // At any rate, given how haphazard the arrow keys act under V4, they
2992 // are just completely ignored here. This does no harm for Bureaucracy,
2993 // since ENTER and ^ can be used. In fact, all input which is not also
2994 // defined for output (save for BACKSPACE, given that Bureaucracy
2995 // properly handles it) is ignored. As a result, Bureaucracy will not
2996 // accidentally print out invalid values (since only valid values will
2997 // be read). This violates both the Standard (since that allows all
2998 // values defined for input) and the EZIP documentation (since that
2999 // mandates ASCII only), but hopefully provides the best experience
3000 // overall: Unicode values are allowed, but Bureaucracy no longer tries
3001 // to print out invalid characters.
3002 //
3003 // Note that if function keys are supported in V4, Bureaucracy will pass
3004 // them along to @print_char, even though they’re not valid for output,
3005 // so ignoring things provides better results than following the
3006 // Standard.
3007 if (zversion == 4) {
3008 switch (ev.val1) {
3009 case keycode_Delete: input.key = ZSCII_DELETE; break;
3010 case keycode_Return: input.key = ZSCII_NEWLINE; break;
3011
3012 default:
3013 input.key = ZSCII_QUESTIONMARK;
3014 if (ev.val1 >= 32 && ev.val1 <= 126) {
3015 input.key = ev.val1;
3016 } else if (ev.val1 < UINT16_MAX) {
3017 uint8_t c = unicode_to_zscii[ev.val1];
3018
3019 if (c != 0) {
3020 input.key = c;
3021 }
3022 } else if (ev.val1 > 0xffffffff - keycode_MAXVAL) {
3023 status = InputStatus::Waiting;
3024 request_char();
3025 }
3026 }
3027 } else {
3028 switch (ev.val1) {
3029 case keycode_Delete: input.key = ZSCII_DELETE; break;
3030 case keycode_Return: input.key = ZSCII_NEWLINE; break;
3031 case keycode_Escape: input.key = ZSCII_ESCAPE; break;
3032 case keycode_Up: input.key = ZSCII_UP; break;
3033 case keycode_Down: input.key = ZSCII_DOWN; break;
3034 case keycode_Left: input.key = ZSCII_LEFT; break;
3035 case keycode_Right: input.key = ZSCII_RIGHT; break;
3036 case keycode_Func1: input.key = ZSCII_F1; break;
3037 case keycode_Func2: input.key = ZSCII_F2; break;
3038 case keycode_Func3: input.key = ZSCII_F3; break;
3039 case keycode_Func4: input.key = ZSCII_F4; break;
3040 case keycode_Func5: input.key = ZSCII_F5; break;
3041 case keycode_Func6: input.key = ZSCII_F6; break;
3042 case keycode_Func7: input.key = ZSCII_F7; break;
3043 case keycode_Func8: input.key = ZSCII_F8; break;
3044 case keycode_Func9: input.key = ZSCII_F9; break;
3045 case keycode_Func10: input.key = ZSCII_F10; break;
3046 case keycode_Func11: input.key = ZSCII_F11; break;
3047 case keycode_Func12: input.key = ZSCII_F12; break;
3048
3049 default:
3050 input.key = ZSCII_QUESTIONMARK;
3051
3052 if (ev.val1 <= UINT16_MAX) {
3053 uint8_t c = unicode_to_zscii[ev.val1];
3054
3055 if (c != 0) {
3056 input.key = c;
3057 }
3058 }
3059
3060 break;
3061 }
3062 }
3063
3064 break;
3065
3066 case evtype_LineInput:
3067 ZASSERT(input.type == Input::Type::Line, "got unexpected evtype_LineInput");
3068 ZASSERT(ev.win == curwin->id, "got evtype_LineInput on unexpected window");
3069 line.len = ev.val1;
3070 #ifdef GLK_MODULE_LINE_TERMINATORS
3071 if (zversion >= 5 && ev.val2 != 0) {
3072 input.term = zscii_from_glk(ev.val2);
3073 }
3074 #endif
3075 status = InputStatus::Received;
3076 break;
3077 case evtype_MouseInput:
3078 if (ev.win == upperwin->id) {
3079 #ifdef ZTERP_GLK_GRAPHICS
3080 if (hack == Hack::ZorkZero) {
3081 // In Fanucci, mouse clicks are off by one, probably
3082 // due to the faking of the size of rectangle 384; a
3083 // better fix is surely possible, but this works for now.
3084 ev.val1++;
3085 ev.val2++;
3086 }
3087 #endif
3088 zterp_mouse_click(ev.val1 + 1, ev.val2 + 1);
3089 #ifdef ZTERP_GLK_GRAPHICS
3090 } else if (ev.win == graphics_window.id()) {
3091 glui32 x = std::round(ev.val1 / graphics_window.ratio());
3092 glui32 y = std::round(ev.val2 / graphics_window.ratio());
3093
3094 // Compensate for the maze being offset one block.
3095 if (hack == Hack::Shogun) {
3096 x -= SHOGUN_MAZE_BLOCK_WIDTH;
3097 y -= SHOGUN_MAZE_BLOCK_HEIGHT;
3098 }
3099
3100 zterp_mouse_click(x, y);
3101 #endif
3102 }
3103 status = InputStatus::Received;
3104
3105 switch (input.type) {
3106 case Input::Type::Char:
3107 input.key = ZSCII_CLICK_SINGLE;
3108 break;
3109 case Input::Type::Line:
3110 glk_cancel_line_event(curwin->id, &ev);
3111 input.len = ev.val1;
3112 input.term = ZSCII_CLICK_SINGLE;
3113 break;
3114 }
3115
3116 break;
3117 #ifdef GLK_MODULE_SOUND2
3118 case evtype_SoundNotify: {
3119 sound_stopped(ev.val2);
3120 uint16_t sound_routine = sound_get_routine(ev.val2);
3121 if (sound_routine != 0) {
3122 handle_interrupt(sound_routine, &line);
3123 restart_read_events(line, input, enable_mouse);
3124 }
3125 break;
3126 }
3127 #endif
3128 }
3129 }
3130
3131 stop_timer();
3132
3133 if (enable_mouse) {
3134 glk_cancel_mouse_event(upperwin->id);
3135 }
3136
3137 switch (input.type) {
3138 case Input::Type::Char:
3139 glk_cancel_char_event(curwin->id);
3140 break;
3141 case Input::Type::Line:
3142 // Copy the Glk line into the internal input structure.
3143 input.len = line.len;
3144 for (glui32 i = 0; i < line.len; i++) {
3145 if (have_unicode) {
3146 input.line[i] = line.unicode[i] > UINT16_MAX ? UNICODE_REPLACEMENT : line.unicode[i];
3147 } else {
3148 input.line[i] = static_cast<unsigned char>(line.latin1[i]);
3149 }
3150 }
3151
3152 // When line input echoing is turned off (which is the case on
3153 // Glk implementations that support it), input won’t be echoed
3154 // to the screen after it’s been entered. This will echo it
3155 // where appropriate, for both canceled and completed input.
3156 if (curwin->has_echo) {
3157 glk_set_style(style_Input);
3158 for (glui32 i = 0; i < input.len; i++) {
3159 xglk_put_char(input.line[i]);
3160 }
3161
3162 if (input.term == ZSCII_NEWLINE) {
3163 xglk_put_char(UNICODE_LINEFEED);
3164 }
3165 set_current_style();
3166 }
3167
3168 // If the current window is the upper window, the position of
3169 // the cursor needs to be tracked, so after a line has
3170 // successfully been read, advance the cursor to the initial
3171 // position of the next line, or if a terminating key was used
3172 // or input was canceled, to the end of the input.
3173 if (curwin == upperwin) {
3174 if (input.term != ZSCII_NEWLINE) {
3175 upperwin->x += input.len;
3176 }
3177
3178 if (input.term == ZSCII_NEWLINE || upperwin->x >= upper_window_width) {
3179 upperwin->x = 0;
3180 if (upperwin->y < upper_window_height) {
3181 upperwin->y++;
3182 }
3183 }
3184
3185 glk_window_move_cursor(upperwin->id, upperwin->x, upperwin->y);
3186 }
3187
3188 #ifdef ZTERP_GLK_GRAPHICS
3189 if (hack == Hack::Arthur) {
3190 switch (input.term) {
3191 // Switching to graphics: close the text window.
3192 case ZSCII_F1: case ZSCII_F2:
3193 glk_window_set_arrangement(glk_window_get_parent(arthurwin->id), winmethod_Above | winmethod_Fixed, 0, arthurwin->id);
3194 break;
3195 // Switching to text: close the graphics window and open the
3196 // text window.
3197 case ZSCII_F3: case ZSCII_F4: case ZSCII_F5:
3198 graphics_window.destroy();
3199 glk_window_set_arrangement(glk_window_get_parent(arthurwin->id), winmethod_Above | winmethod_Fixed, 12, arthurwin->id);
3200 break;
3201 // Switching to no window. Close graphics and text.
3202 case ZSCII_F6:
3203 graphics_window.destroy();
3204 glk_window_set_arrangement(glk_window_get_parent(arthurwin->id), winmethod_Above | winmethod_Fixed, 0, arthurwin->id);
3205 break;
3206 }
3207 }
3208 #endif
3209 }
3210
3211 saw_input = true;
3212
3213 if (errorwin != nullptr) {
3214 glk_window_close(errorwin, nullptr);
3215 errorwin = nullptr;
3216 }
3217
3218 if (saved != nullptr) {
3219 curwin = saved;
3220 glk_set_window(curwin->id);
3221 }
3222
3223 return status != InputStatus::Canceled;
3224 #else
3225 switch (input.type) {
3226 case Input::Type::Char: {
3227 std::vector<uint16_t> line;
3228
3229 try {
3230 line = IO::standard_in().readline();
3231 } catch (const IO::EndOfFile &) {
3232 zquit();
3233 }
3234
3235 if (line.empty()) {
3236 input.key = ZSCII_NEWLINE;
3237 } else if (line[0] == UNICODE_DELETE) {
3238 input.key = ZSCII_DELETE;
3239 } else if (line[0] == UNICODE_ESCAPE) {
3240 input.key = ZSCII_ESCAPE;
3241 } else {
3242 input.key = unicode_to_zscii[line[0]];
3243 if (input.key == 0) {
3244 input.key = ZSCII_NEWLINE;
3245 }
3246 }
3247 break;
3248 }
3249 case Input::Type::Line:
3250 input.len = input.preloaded;
3251
3252 if (input.maxlen > input.preloaded) {
3253 std::vector<uint16_t> line;
3254
3255 try {
3256 line = IO::standard_in().readline();
3257 } catch (const IO::EndOfFile &) {
3258 zquit();
3259 }
3260
3261 if (line.size() > input.maxlen - input.preloaded) {
3262 line.resize(input.maxlen - input.preloaded);
3263 }
3264
3265 std::copy(line.begin(), line.end(), &input.line[input.preloaded]);
3266 input.len += line.size();
3267 }
3268 break;
3269 }
3270
3271 return true;
3272 #endif
3273 }
3274
3275 void zread_char()
3276 {
3277 uint16_t timer = 0;
3278 uint16_t routine = zargs[2];
3279 Input input;
3280
3281 input.type = Input::Type::Char;
3282
3283 if (options.autosave && !in_interrupt()) {
3284 SaveType savetype = options.autosave_librarystate ? SaveType::AutosaveLib : SaveType::Autosave;
3285 do_save(savetype, SaveOpcode::ReadChar);
3286 }
3287
3288 if (zversion >= 4 && znargs > 1) {
3289 timer = zargs[1];
3290 }
3291
3292 if (!get_input(timer, routine, input)) {
3293 store(0);
3294 return;
3295 }
3296
3297 #ifdef ZTERP_GLK
3298 update_delayed();
3299 #endif
3300
3301 if (streams.test(OSTREAM_RECORD)) {
3302 // Values 127 to 159 are not valid Unicode, and these just happen to
3303 // match up to the values needed for special ZSCII keys, so store
3304 // them as-is.
3305 if (special_zscii(input.key)) {
3306 scriptio->putc(input.key);
3307 } else {
3308 scriptio->putc(zscii_to_unicode[input.key]);
3309 }
3310 }
3311
3312 store(input.key);
3313 }
3314
3315 // §8.2.3.2 says the hours can be assumed to be in the range [0, 23] and
3316 // can be reduced modulo 12 for 12-hour time. Cutthroats, however, sets
3317 // the hours to 111 if the watch is dropped, on the assumption that the
3318 // interpreter will convert 24-hour time to 12-hour time simply by
3319 // subtracting 12, resulting in an hours of 99 (the minutes are set to
3320 // 99 for a final time of 99:99). Perform the calculation as in
3321 // Cutthroats, which results in valid times for [0, 23] as well as
3322 // allowing the 99:99 hack to work.
3323 std::string screen_format_time(long hours, long minutes)
3324 {
3325 return fstring("Time: %ld:%02ld%s ", hours <= 12 ? (hours + 11) % 12 + 1 : hours - 12, minutes, hours < 12 ? "am" : "pm");
3326 }
3327
3328 void zshow_status()
3329 {
3330 #ifdef ZTERP_GLK
3331 glui32 width, height;
3332 std::string rhs;
3333 long first = as_signed(variable(0x11)), second = as_signed(variable(0x12));
3334
3335 if (statuswin.id == nullptr) {
3336 return;
3337 }
3338
3339 strid_t stream = glk_window_get_stream(statuswin.id);
3340
3341 glk_window_clear(statuswin.id);
3342
3343 glk_window_get_size(statuswin.id, &width, &height);
3344
3345 #ifdef GLK_MODULE_GARGLKTEXT
3346 garglk_set_reversevideo_stream(stream, 1);
3347 #else
3348 glk_set_style_stream(stream, style_Alert);
3349 #endif
3350 for (glui32 i = 0; i < width; i++) {
3351 xglk_put_char_stream(stream, UNICODE_SPACE);
3352 }
3353
3354 glk_window_move_cursor(statuswin.id, 1, 0);
3355
3356 // Variable 0x10 is global variable 1.
3357 print_object(variable(0x10), [](uint8_t c) {
3358 xglk_put_char_stream(glk_window_get_stream(statuswin.id), zscii_to_unicode[c]);
3359 });
3360
3361 if (status_is_time()) {
3362 rhs = screen_format_time(first, second);
3363 if (rhs.size() > width) {
3364 rhs = fstring("%02ld:%02ld", first, second);
3365 }
3366 } else {
3367 // Planetfall and Stationfall are score games, except the value
3368 // in the second global variable is the current Galactic
3369 // Standard Time, not the number of moves. Most of Infocom’s
3370 // interpreters displayed the score and moves as “score/moves”
3371 // so it didn’t look flat-out wrong to have a value that wasn’t
3372 // actually the number of moves. When it’s spelled out as
3373 // “Moves”, though, then the display is obviously wrong. For
3374 // these two games, rewrite “Moves” as “Time”. Note that this is
3375 // how it looks in the Solid Gold version, which is V5, meaning
3376 // Infocom had full control over the status line, implying it is
3377 // the most correct display.
3378 if (is_game(Game::Planetfall) || is_game(Game::Stationfall)) {
3379 rhs = fstring("Score: %ld Time: %ld ", first, second);
3380 } else {
3381 rhs = fstring("Score: %ld Moves: %ld ", first, second);
3382 }
3383
3384 if (rhs.size() > width) {
3385 rhs = fstring("%ld/%ld", first, second);
3386 }
3387 }
3388
3389 if (rhs.size() <= width) {
3390 glk_window_move_cursor(statuswin.id, width - rhs.size(), 0);
3391 glk_put_string_stream(stream, &rhs[0]);
3392 }
3393 #endif
3394 }
3395
3396 #ifdef ZTERP_GLK
3397 // These track the position of the cursor in the upper window at the
3398 // beginning of a @read call so that the cursor can be replaced in case
3399 // of a meta-command. They are also stored in the Scrn chunk of any
3400 // meta-saves. They are in Z-machine coordinate format, not Glk, which
3401 // means they are 1-based.
3402 static long starting_x, starting_y;
3403 #endif
3404
3405 // Attempt to read and parse a line of input. On success, return true.
3406 // Otherwise, return false to indicate that input should be requested
3407 // again.
3408 static bool read_handler()
3409 {
3410 uint16_t text = zargs[0], parse = zargs[1];
3411 ZASSERT(zversion >= 5 || user_byte(text) > 0, "text buffer cannot be zero sized");
3412 uint8_t maxchars = zversion >= 5 ? user_byte(text) : user_byte(text) - 1;
3413 std::array<uint8_t, 256> zscii_string;
3414 Input input;
3415 input.type = Input::Type::Line;
3416 input.maxlen = maxchars;
3417 input.preloaded = 0;
3418 uint16_t timer = 0;
3419 uint16_t routine = zargs[3];
3420
3421 if (options.autosave && !in_interrupt()) {
3422 SaveType savetype = options.autosave_librarystate ? SaveType::AutosaveLib : SaveType::Autosave;
3423 do_save(savetype, SaveOpcode::Read);
3424 }
3425
3426 #ifdef ZTERP_GLK
3427 starting_x = upperwin->x + 1;
3428 starting_y = upperwin->y + 1;
3429 #endif
3430
3431 if (zversion <= 3) {
3432 zshow_status();
3433 }
3434
3435 if (zversion >= 4 && znargs > 2) {
3436 timer = zargs[2];
3437 }
3438
3439 if (zversion >= 5) {
3440 int i;
3441
3442 input.preloaded = user_byte(text + 1);
3443 ZASSERT(input.preloaded <= maxchars, "too many preloaded characters: %d when max is %d", input.preloaded, maxchars);
3444
3445 for (i = 0; i < input.preloaded; i++) {
3446 input.line[i] = zscii_to_unicode[user_byte(text + i + 2)];
3447 }
3448 // Under Gargoyle, preloaded input generally works as it’s supposed to.
3449 // Under Glk, it can fail one of two ways:
3450 //
3451 // 1. The preloaded text is printed out once, but is not editable.
3452 // 2. The preloaded text is printed out twice, the second being editable.
3453 //
3454 // I have chosen option #2. For non-Glk, option #1 is done by necessity.
3455 //
3456 // The “normal” mode of operation for preloaded text seems to be that a
3457 // particular string is printed, and then that string is preloaded,
3458 // allowing the already-printed text to be edited. However, there is no
3459 // requirement that the preloaded text already be on-screen. For
3460 // example, what should happen if the text “ZZZ” is printed out, but the
3461 // text “AAA” is preloaded? Infocom’s interpreters display “ZZZ” (and
3462 // not “AAA”), and allow the user to edit it; but any characters not
3463 // edited by the user (that is, not backspaced over) are actually stored
3464 // as “A” characters. The on-screen “Z” characters are not stored.
3465 //
3466 // This isn’t possible under Glk, and as it stands, isn’t possible under
3467 // Gargoyle either (although it could be extended to support it). For
3468 // now I am not extending Gargoyle: the usual case (preloaded text
3469 // matching on-screen text) does work with Gargoyle’s unput extensions,
3470 // and the unusual/unexpected case (preloaded text not matching) at
3471 // least is usable: the whole preloaded string is displayed and can be
3472 // edited. I suspect nobody but Infocom ever uses preloaded text, and
3473 // Infocom uses it in the normal way, so things work just fine.
3474 #ifdef GARGLK
3475 input.line[i] = 0;
3476 if (curwin->id != nullptr) {
3477 // Convert the Z-machine’s 16-bit string to a 32-bit string for Glk.
3478 std::vector<glui32> line32;
3479 std::copy(input.line.begin(), input.line.begin() + input.preloaded + 1, std::back_inserter(line32));
3480 // If the preloaded text would wrap backward in the upper window
3481 // (to the previous line), limit it to just the current line. For
3482 // example:
3483 //
3484 // |This text bre|
3485 // |aks |
3486 //
3487 // If the string “breaks” is preloaded, only try to unput the “aks”
3488 // part. Backing all the way up to “bre” works (as in, is
3489 // successfully unput) in Gargoyle, but input won’t work: the cursor
3490 // will be placed at line 1, right after the “e”, and no input will
3491 // be allowed. At least by keeping the cursor on the second line,
3492 // proper user input will occur.
3493 if (curwin == upperwin) {
3494 uint16_t max = std::min<uint16_t>(input.preloaded, upperwin->x);
3495 uint8_t start = input.preloaded - max;
3496 glui32 unput = garglk_unput_string_count_uni(&line32[start]);
3497
3498 // Since the preloaded text might not have been on the screen
3499 // (or only partially so), reduce the current and starting X
3500 // coordinates by the number of unput characters, since that is
3501 // where Gargoyle will logically be starting input.
3502 curwin->x -= unput;
3503 starting_x -= unput;
3504 } else {
3505 garglk_unput_string_uni(line32.data());
3506 }
3507 }
3508 #endif
3509 }
3510
3511 if (!get_input(timer, routine, input)) {
3512 if (zversion >= 5) {
3513 store(0);
3514 }
3515 return true;
3516 }
3517
3518 #ifdef ZTERP_GLK
3519 update_delayed();
3520 #endif
3521
3522 if (curwin == mainwin) {
3523 history.add_input(input.line.data(), input.len);
3524 }
3525
3526 if (options.enable_escape) {
3527 transcribe(033);
3528 transcribe('[');
3529 for (const auto c : *options.escape_string) {
3530 transcribe(c);
3531 }
3532 }
3533
3534 for (int i = 0; i < input.len; i++) {
3535 transcribe(input.line[i]);
3536 if (streams.test(OSTREAM_RECORD)) {
3537 scriptio->putc(input.line[i]);
3538 }
3539 }
3540
3541 if (options.enable_escape) {
3542 transcribe(033);
3543 transcribe('[');
3544 transcribe('0');
3545 transcribe('m');
3546 }
3547
3548 transcribe(UNICODE_LINEFEED);
3549 if (streams.test(OSTREAM_RECORD)) {
3550 scriptio->putc(UNICODE_LINEFEED);
3551 }
3552
3553 if (!options.disable_meta_commands) {
3554 input.line[input.len] = 0;
3555
3556 if (input.line[0] == '/') {
3557 #ifdef ZTERP_GLK
3558 // If the game is currently in the upper window, blank out
3559 // everything the user typed so that a re-request of input has a
3560 // clean slate to work with. Replace the cursor where it was at the
3561 // start of input.
3562 if (curwin == upperwin) {
3563 set_cursor(starting_y, starting_x);
3564 for (int i = 0; i < input.len; i++) {
3565 put_char_u(UNICODE_SPACE);
3566 }
3567 set_cursor(starting_y, starting_x);
3568 }
3569 #endif
3570
3571 auto result = handle_meta_command(input.line.data(), input.len);
3572 switch (result.first) {
3573 case MetaResult::Rerequest:
3574 // The game still wants input, so try again. If this is the main
3575 // window, print a prompt that hopefully meshes well with the
3576 // game. If it’s the upper window, don’t print anything, because
3577 // that will almost certainly do more harm than good.
3578 #ifdef ZTERP_GLK
3579 if (curwin != upperwin)
3580 #endif
3581 {
3582 screen_print("\n>");
3583 }
3584
3585 // Any preloaded text is probably going to have been printed by
3586 // the game first, which allows Gargoyle to unput the preloaded
3587 // text. But when re-requesting input, the preloaded text will
3588 // not be on the screen anymore. Print it again so that it can
3589 // be unput.
3590 //
3591 // If this implementation is not Gargoyle, don’t print
3592 // anything. The original text (if there in fact was
3593 // any) will still be on the screen, and the preloaded
3594 // text will be displayed (and editable) by Glk.
3595 #ifdef GARGLK
3596 for (int i = 0; i < input.preloaded; i++) {
3597 put_char(zscii_to_unicode[user_byte(text + i + 2)]);
3598 }
3599 #endif
3600
3601 return false;
3602 case MetaResult::Say: {
3603 // Convert the UTF-8 result to Unicode using memory-backed I/O.
3604 IO io(std::vector<uint8_t>(result.second.begin(), result.second.end()), IO::Mode::ReadOnly);
3605 std::vector<uint16_t> string;
3606
3607 for (auto c = io.getc(true); c != -1; c = io.getc(true)) {
3608 string.push_back(c);
3609 }
3610
3611 input.len = string.size();
3612 std::copy(string.begin(), string.end(), input.line.begin());
3613 }
3614 }
3615 }
3616
3617 // V1–4 do not have @save_undo, so simulate one each time @read is
3618 // called.
3619 //
3620 // Although V5 introduced @save_undo, not all games make use of it
3621 // (e.g. Hitchhiker’s Guide). Until @save_undo is called, simulate
3622 // it each @read, just like in V1–4. If @save_undo is called, all
3623 // of these interpreter-generated save states are forgotten and the
3624 // game’s calls to @save_undo take over.
3625 //
3626 // Because V1–4 games will never call @save_undo, seen_save_undo
3627 // will never be true. Thus there is no need to test zversion.
3628 if (!seen_save_undo) {
3629 push_save(SaveStackType::Game, SaveType::Meta, SaveOpcode::Read, nullptr);
3630 }
3631 }
3632
3633 for (int i = 0; i < input.len; i++) {
3634 zscii_string[i] = unicode_to_zscii_q[unicode_tolower(input.line[i])];
3635 }
3636
3637 if (zversion >= 5) {
3638 user_store_byte(text + 1, input.len); // number of characters read
3639
3640 for (int i = 0; i < input.len; i++) {
3641 user_store_byte(text + i + 2, zscii_string[i]);
3642 }
3643
3644 if (parse != 0) {
3645 tokenize(text, parse, 0, false);
3646 }
3647
3648 store(input.term);
3649 } else {
3650 for (int i = 0; i < input.len; i++) {
3651 user_store_byte(text + i + 1, zscii_string[i]);
3652 }
3653
3654 user_store_byte(text + input.len + 1, 0);
3655
3656 tokenize(text, parse, 0, false);
3657 }
3658
3659 return true;
3660 }
3661
3662 void zread()
3663 {
3664 while (!read_handler()) {
3665 }
3666 }
3667
3668 void zprint_unicode()
3669 {
3670 if (valid_unicode(zargs[0])) {
3671 put_char_u(zargs[0]);
3672 } else {
3673 put_char_u(UNICODE_REPLACEMENT);
3674 }
3675 }
3676
3677 void zcheck_unicode()
3678 {
3679 uint16_t res = 0;
3680
3681 // valid_unicode() will tell which Unicode characters can be printed;
3682 // and if the Unicode character is in the Unicode input table, it can
3683 // also be read. If Unicode is not available, then any character >255
3684 // is invalid for both reading and writing.
3685 if (have_unicode || zargs[0] < 256) {
3686 // §3.8.5.4.5: “Unicode characters U+0000 to U+001F and U+007F to
3687 // U+009F are control codes, and must not be used.”
3688 //
3689 // Even though control characters can be read (e.g. delete and
3690 // linefeed), when they are looked at through a Unicode lens, they
3691 // should be considered invalid. I don’t know if this is the right
3692 // approach, but nobody seems to use @check_unicode, so it’s not
3693 // especially important. One implication of this is that it’s
3694 // impossible for this implementation of @check_unicode to return 2,
3695 // since a character must be valid for output before it’s even
3696 // checked for input, and all printable characters are also
3697 // readable.
3698 //
3699 // For what it’s worth, interpreters seem to disagree on this pretty
3700 // drastically:
3701 //
3702 // • Zoom 1.1.5 returns 1 for all control characters.
3703 // • Fizmo 0.7.8 returns 3 for characters 8, 10, 13, and 27, 1 for
3704 // all other control characters.
3705 // • Frotz 2.44 and Nitfol 0.5 return 0 for all control characters.
3706 // • Filfre 1.1.1 returns 3 for all control characters.
3707 // • Windows Frotz 1.19 returns 2 for characters 8, 13, and 27, 0
3708 // for other control characters in the range 00 to 1f. It returns
3709 // a mixture of 2 and 3 for control characters in the range 7F to
3710 // 9F based on whether the specified glyph is available.
3711 if (valid_unicode(zargs[0])) {
3712 res |= 0x01;
3713 if (unicode_to_zscii[zargs[0]] != 0) {
3714 res |= 0x02;
3715 }
3716 }
3717 }
3718
3719 #ifdef ZTERP_GLK
3720 if (glk_gestalt(gestalt_CharOutput, zargs[0]) == gestalt_CharOutput_CannotPrint) {
3721 res &= ~static_cast<uint16_t>(0x01);
3722 }
3723 if (!glk_gestalt(gestalt_CharInput, zargs[0])) {
3724 res &= ~static_cast<uint16_t>(0x02);
3725 }
3726 #endif
3727
3728 store(res);
3729 }
3730
3731 #ifdef ZTERP_GLK_BLORB
3732
3733 #ifdef GLK_MODULE_IMAGE
3734 static uint16_t blorb_reln;
3735
3736 struct ScaleInfo {
3737 uint32_t px;
3738 uint32_t py;
3739 double stdratio;
3740 double minratio;
3741 double maxratio;
3742 };
3743 static std::map<uint32_t, ScaleInfo> picture_scale;
3744 #endif
3745
3746 // If possible, load information for image scaling from the Blorb file.
3747 // Errors here aren’t fatal, since the images will just be drawn in
3748 // their original resolution if scale data can’t be loaded.
3749 void screen_load_scale_info(const std::string &blorb_file) {
3750 #ifdef GLK_MODULE_IMAGE
3751 if (!glk_gestalt(gestalt_Graphics, 0) || !glk_gestalt(gestalt_DrawImage, wintype_TextBuffer)) {
3752 return;
3753 }
3754
3755 try {
3756 auto io = std::make_shared<IO>(&blorb_file, IO::Mode::ReadOnly, IO::Purpose::Data);
3757 IFF iff(io, IFF::TypeID("IFRS"));
3758
3759 uint32_t size;
3760
3761 if (iff.find(IFF::TypeID("RelN"), size) && size == 2) {
3762 blorb_reln = io->read16();
3763 }
3764
3765 if (iff.find(IFF::TypeID("Reso"), size) && size >= 24 && (size - 24) % 28 == 0) {
3766 auto count = (size - 24) / 28;
3767 auto px = io->read32();
3768 auto py = io->read32();
3769
3770 if (px == 0 || py == 0) {
3771 throw std::runtime_error("invalid window size");
3772 }
3773
3774 io->seek(16, IO::SeekFrom::Current);
3775
3776 for (uint32_t i = 0; i < count; i++) {
3777 auto num = io->read32();
3778 double ratnum = io->read32();
3779 double ratden = io->read32();
3780 double minnum = io->read32();
3781 double minden = io->read32();
3782 double maxnum = io->read32();
3783 double maxden = io->read32();
3784
3785 auto stdratio = ratnum / ratden;
3786 auto minratio = (minnum == 0 || minden == 0) ? 0 : (minnum / minden);
3787 auto maxratio = (maxnum == 0 || maxden == 0) ? std::numeric_limits<double>::max() : (maxnum / maxden);
3788
3789 ScaleInfo scale_info = {
3790 px,
3791 py,
3792 stdratio,
3793 minratio,
3794 maxratio,
3795 };
3796
3797 picture_scale.insert({num, std::move(scale_info)});
3798 }
3799 }
3800 } catch (...) {
3801 picture_scale.clear();
3802 }
3803 #else
3804 #endif
3805 }
3806 #endif
3807
3808 #ifdef ZTERP_GLK_GRAPHICS
3809 // Map a pair of (palette image, requested image) to the ID of a
3810 // precomputed palette image: this corresponds to the BPal chunk.
3811 static std::map<std::pair<uint32_t, uint32_t>, uint32_t> palette_map;
3812
3813 static void build_palette_map()
3814 {
3815 auto *map = giblorb_get_resource_map();
3816
3817 if (map == nullptr) {
3818 return;
3819 }
3820
3821 auto be32 = [](const unsigned char *base) {
3822 return
3823 (static_cast<uint32_t>(base[0]) << 24) |
3824 (static_cast<uint32_t>(base[1]) << 16) |
3825 (static_cast<uint32_t>(base[2]) << 8) |
3826 (static_cast<uint32_t>(base[3]) << 0);
3827 };
3828
3829 giblorb_result_t res;
3830 if (giblorb_load_chunk_by_type(map, giblorb_method_Memory, &res, giblorb_make_id('B', 'P', 'a', 'l'), 0) == giblorb_err_None) {
3831 if (res.length % 12 == 0) {
3832 auto *ptr = static_cast<unsigned char *>(res.data.ptr);
3833 for (size_t i = 0; i < res.length; i += 12) {
3834 auto source = be32(ptr + i);
3835 auto apal = be32(ptr + i + 4);
3836 auto id = be32(ptr + i + 8);
3837 palette_map.insert({{source, apal}, id});
3838 }
3839 } else {
3840 show_message("Invalid BPal chunk detected; proceeding without adaptive palette");
3841 }
3842 }
3843 }
3844
3845 static std::unique_ptr<ImageGeometry> arthur_geom(glui32 pic)
3846 {
3847 switch (pic) {
3848
3849 // Intro / Ending
3850
3851 case 1: case 2: // Title screen and sword in stone
3852 return std::make_unique<ImageGeometry>(0, 0);
3853 case 3: // Merlin by sword in stone
3854 return std::make_unique<ImageGeometry>(26, 23);
3855 case 84: // game end
3856 return std::make_unique<ImageGeometry>(0, 0);
3857
3858 // Banner images
3859 case 4: case 7: case 10: case 11: case 12: case 13: case 14: case 15:
3860 case 16: case 18: case 19: case 20: case 21: case 22: case 23: case 24:
3861 case 25: case 26: case 27: case 28: case 29: case 30: case 31: case 32:
3862 case 33: case 34: case 35: case 36: case 37: case 38: case 39: case 40:
3863 case 41: case 42: case 43: case 44: case 45: case 46: case 47: case 48:
3864 case 49: case 50: case 51: case 52: case 53: case 55: case 56: case 57:
3865 case 58: case 59: case 60: case 61: case 62: case 63: case 64: case 65:
3866 case 66: case 67: case 68: case 69: case 70: case 71: case 72: case 73:
3867 case 74: case 75: case 76: case 77: case 78: case 81: case 86: case 89:
3868 case 101: case 102: case 154: case 157: case 162: case 165: case 166:
3869 return std::make_unique<ImageGeometry>(92, 7);
3870 case 6: // sword in stone
3871 return std::make_unique<ImageGeometry>(131, 54);
3872 case 9: // sword in stone (behind gravestone)
3873 return std::make_unique<ImageGeometry>(168, 51);
3874 case 17: // parade area
3875 return std::make_unique<ImageGeometry>(67, 6);
3876 case 54: // banner
3877 return std::make_unique<ImageGeometry>(0, 0);
3878 case 80: // key on necklace (woman)
3879 return std::make_unique<ImageGeometry>(39, 26);
3880 case 83: // key on necklace (demon)
3881 return std::make_unique<ImageGeometry>(41, 23);
3882 case 85: // angry demon
3883 return std::make_unique<ImageGeometry>(-3, 0);
3884 case 88: // boar (from south)
3885 return std::make_unique<ImageGeometry>(121, 17);
3886 case 91: // boar (from north, startled)
3887 return std::make_unique<ImageGeometry>(134, 34);
3888 case 93: // boar (charging)
3889 return std::make_unique<ImageGeometry>(127, 22);
3890 case 95: // gold egg
3891 return std::make_unique<ImageGeometry>(141, 46);
3892 case 97: // leprechaun
3893 return std::make_unique<ImageGeometry>(173, 31);
3894 case 99: // leprechaun (bottle)
3895 return std::make_unique<ImageGeometry>(176, 28);
3896 case 104: // boar (from north)
3897 return std::make_unique<ImageGeometry>(126, 33);
3898 case 156: // gauntlet (in chamber)
3899 return std::make_unique<ImageGeometry>(45, 28);
3900 case 158: // tower door
3901 return std::make_unique<ImageGeometry>(81, 13);
3902 case 161: // gauntlet (through window)
3903 return std::make_unique<ImageGeometry>(64, 35);
3904 case 163: // flying
3905 return std::make_unique<ImageGeometry>(48, 6);
3906 case 169: // boar (dead)
3907 return std::make_unique<ImageGeometry>(9, 8);
3908
3909 // Map images
3910
3911 case 137: // map
3912 return std::make_unique<ImageGeometry>(0, 0);
3913 case 138: case 139: case 140: case 141: case 142: case 143: case 144: case 145: case 146: // compass rose
3914 return std::make_unique<ImageGeometry>(260, 8);
3915 case 148: // down
3916 return std::make_unique<ImageGeometry>(260, 1);
3917 case 149: // up
3918 return std::make_unique<ImageGeometry>(292, 1);
3919 }
3920
3921 return nullptr;
3922 };
3923
3924 struct PaletteImage {
3925 PaletteImage(glui32 id_, glui32 parent_) :
3926 id(id_),
3927 parent(parent_)
3928 {
3929 }
3930
3931 glui32 id;
3932 glui32 parent;
3933 };
3934
3935 static long last_palette_image = -1;
3936
3937 static std::unique_ptr<PaletteImage> get_paletted_image(glui32 pic)
3938 {
3939 if (last_palette_image == -1) {
3940 return nullptr;
3941 }
3942
3943 auto id = palette_map.find(std::pair<uint32_t, uint32_t>(last_palette_image, pic));
3944 if (id != palette_map.end()) {
3945 return std::make_unique<PaletteImage>(id->second, pic);
3946 }
3947
3948 return nullptr;
3949 }
3950
3951 void GraphicsWindow::draw(glui32 pic, const ImageGeometry &geom, glui32 w, glui32 h) const
3952 {
3953 if (m_id == nullptr) {
3954 return;
3955 }
3956
3957 auto paletted_image = get_paletted_image(pic);
3958 if (paletted_image != nullptr) {
3959 pic = paletted_image->id;
3960 } else if (hack == Hack::Arthur) {
3961 // The Blorb standard’s recommendation for dealing with the
3962 // adaptive palette isn’t sufficient for Arthur. It says that
3963 // APal images (which in Arthur’s case is just the banner plus
3964 // staffs) should take on the palette of the last-drawn image;
3965 // but generally speaking, the banner and staffs are not
3966 // redrawn. Rather, when new rooms are entered, they're expected
3967 // to already be on screen, and just the room image is drawn.
3968 // For Arthur, if a room picture is drawn, redraw the banner and
3969 // staffs using the room picture as the palette.
3970 switch (pic) {
3971 // Rooms
3972 case 4: case 7: case 10: case 11: case 12: case 13: case 14: case 15:
3973 case 16: case 18: case 19: case 20: case 21: case 22: case 23: case 24:
3974 case 25: case 26: case 27: case 28: case 29: case 30: case 31: case 32:
3975 case 33: case 34: case 35: case 36: case 37: case 38: case 39: case 40:
3976 case 41: case 42: case 43: case 44: case 45: case 46: case 47: case 48:
3977 case 49: case 50: case 51: case 52: case 53: case 55: case 56: case 57:
3978 case 58: case 59: case 60: case 61: case 62: case 63: case 64: case 65:
3979 case 66: case 67: case 68: case 69: case 70: case 71: case 72: case 73:
3980 case 74: case 75: case 76: case 77: case 78: case 81: case 86: case 89:
3981 case 101: case 102: case 154: case 157: case 162: case 165: case 166:
3982
3983 // Parade area and flying
3984 case 17: case 163:
3985 last_palette_image = pic;
3986
3987 auto banner_geom = arthur_geom(54);
3988 if (banner_geom != nullptr) {
3989 draw(54, *banner_geom, 314, 84);
3990 }
3991
3992 glui32 staff = 170;
3993 auto paletted_staff = get_paletted_image(staff);
3994 if (paletted_staff != nullptr) {
3995 staff = paletted_staff->id;
3996 }
3997 draw_border(GraphicsWindow::Type::ArthurBanner, GraphicsWindow::Border::Left, staff);
3998 draw_border(GraphicsWindow::Type::ArthurBanner, GraphicsWindow::Border::Right, staff);
3999 }
4000 } else {
4001 last_palette_image = pic;
4002 }
4003
4004 auto x = m_ratio * geom.x;
4005 x += (m_width - (m_ratio * m_base_width)) / 2;
4006 glk_image_draw_scaled(m_id, pic, std::round(x), std::round(m_ratio * geom.y * aspect_scale()), std::round(m_ratio * w), std::round(m_ratio * h * aspect_scale()));
4007
4008 if (hack == Hack::ZorkZero && !is_game(Game::ZorkZeroDOS)) {
4009 // Only the DOS version splits the border into a top and sides,
4010 // and the DOS version is what the “official” Blorb file is
4011 // meant to be used with. For all other Zork Zero releases, when
4012 // a request comes in for the top image, draw the side images as
4013 // well, knowing that’s what’s intended.
4014 static const std::map<glui32, std::pair<glui32, glui32>> borderpairs = {
4015 {5, {497, 498}},
4016 {6, {501, 502}},
4017 {7, {499, 500}},
4018 {8, {503, 504}},
4019 };
4020
4021 auto borderpair = borderpairs.find(pic);
4022 if (borderpair != borderpairs.end()) {
4023 draw_border(GraphicsWindow::Type::ZorkZeroBorder, GraphicsWindow::Border::Left, borderpair->second.first);
4024 draw_border(GraphicsWindow::Type::ZorkZeroBorder, GraphicsWindow::Border::Right, borderpair->second.second);
4025 }
4026 }
4027 }
4028
4029 void GraphicsWindow::draw_border(Type type, Border border, glui32 pic) const
4030 {
4031 glui32 width, height;
4032
4033 winid_t id = border == Border::Left ? m_left_border : m_right_border;
4034
4035 if (id == nullptr || !glk_image_get_info(pic, &width, nullptr)) {
4036 return;
4037 }
4038
4039 int offset = 0;
4040 // Because the Zork Zero border images vary in size, but the window
4041 // size is fixed, offset each right-side border image to ensure the
4042 // right edge lines up.
4043 if (type == GraphicsWindow::Type::ZorkZeroBorder && border == Border::Right) {
4044 offset = 42 - width;
4045 }
4046
4047 glk_window_clear(id);
4048
4049 glk_window_get_size(id, nullptr, &height);
4050 glk_image_draw_scaled(id, pic, offset * ratio(), 0, width * ratio(), height);
4051 }
4052
4053 void GraphicsWindow::draw_shogun_borders() const
4054 {
4055 draw_border(Type::ShogunNormal, Border::Left, 3);
4056 draw_border(Type::ShogunNormal, Border::Right, 59);
4057 }
4058
4059 static bool draw_arthur(glui32 pic, glui32 w, glui32 h, glui32 x, glui32 y)
4060 {
4061 if (hack != Hack::Arthur) {
4062 return false;
4063 }
4064
4065 // These are the border staffs. Similar to the banner, Arthur does
4066 // not draw these frequently, instead drawing them once and
4067 // expecting them to remain on the screen. To get around this, when
4068 // room images are drawn, Bocfel unconditionally draws the staffs as
4069 // well, ensuring they both exist and are drawn in the correct
4070 // palette. As such, ignore any requests from the game to draw them.
4071 if (pic == 170 || pic == 171) {
4072 return true;
4073 }
4074
4075 // Arthur calculates map coordinates basically correctly; just need
4076 // to scale and offset the X axis a bit.
4077 if (pic >= 106 && pic <= 136) {
4078 ImageGeometry geom(x + 14, y);
4079 graphics_window.draw(pic, geom, w, h);
4080 return true;
4081 }
4082
4083 auto type = pic == 1 || pic == 2 || pic == 3 || pic == 84 ? GraphicsWindow::Type::ArthurIntro :
4084 pic == 85 ? GraphicsWindow::Type::ArthurDemon :
4085 (pic >= 106 && pic <= 149) ? GraphicsWindow::Type::ArthurMap :
4086 GraphicsWindow::Type::ArthurBanner;
4087
4088 if (!graphics_window.resize(type)) {
4089 return false;
4090 }
4091
4092 // Arthur draws blanks over the up and down arrow areas in the map
4093 // so that any previous arrows are gone when moving rooms. It always
4094 // does this over both arrows (since it will be redrawing the whole
4095 // map anyway), but since there are two arrows but only one blank,
4096 // this can’t directly use arthur_geom(). Instead, when a blank
4097 // request comes in, always write the blank over both arrows.
4098 if (pic == 147) {
4099 for (const auto arrow_pic : {148, 149}) {
4100 auto geom = arthur_geom(arrow_pic);
4101 if (geom != nullptr) {
4102 graphics_window.draw(147, *geom, 8, 7);
4103 }
4104 }
4105
4106 return true;
4107 }
4108
4109 // Arthur does a lot of checking of window sizes to determine where
4110 // to draw things. At the moment, window sizes are not tracked at
4111 // all, so they can’t accurately be reported, causing graphics to be
4112 // drawn in the wrong places. Instead of relying on the game, a
4113 // table of locations is used, given that these graphics never
4114 // change place. Ultimately it’d be nicer to track sizes so the game
4115 // can provide locations, but this is fine for now.
4116 auto geom = arthur_geom(pic);
4117 if (geom != nullptr) {
4118 graphics_window.draw(pic, *geom, w, h);
4119 return true;
4120 }
4121
4122 return false;
4123 }
4124
4125 static bool draw_zorkzero(glui32 pic, glui32 w, glui32 h, double x, double y)
4126 {
4127 if (hack != Hack::ZorkZero) {
4128 return false;
4129 }
4130
4131 static const std::unordered_map<glui32, GraphicsWindow::Border> borders = {
4132 {170, GraphicsWindow::Border::Left},
4133 {171, GraphicsWindow::Border::Right},
4134 {497, GraphicsWindow::Border::Left},
4135 {498, GraphicsWindow::Border::Right},
4136 {499, GraphicsWindow::Border::Left},
4137 {500, GraphicsWindow::Border::Right},
4138 {501, GraphicsWindow::Border::Left},
4139 {502, GraphicsWindow::Border::Right},
4140 {503, GraphicsWindow::Border::Left},
4141 {504, GraphicsWindow::Border::Right},
4142 };
4143
4144 auto border = borders.find(pic);
4145 if (border != borders.end()) {
4146 graphics_window.draw_border(GraphicsWindow::Type::ZorkZeroBorder, border->second, pic);
4147 return true;
4148 }
4149
4150 // 5, 6, and 7 are the borders. If a request comes in for one of
4151 // them, ensure the graphics window is the right size, and clear it
4152 // first: different borders are different sizes, so drawing on top
4153 // of each other causes the previous image to leak through.
4154 if (pic == 5 || pic == 6 || pic == 7) {
4155 if (!graphics_window.resize(GraphicsWindow::Type::ZorkZeroBorder)) {
4156 return false;
4157 }
4158 graphics_window.clear();
4159 }
4160
4161 // Infer 320x200 mode via the background (title, encyclopedia, map, rebus).
4162 if (pic == 1 || pic == 25 || pic == 163 || (pic >= 34 && pic <= 40)) {
4163 if (!graphics_window.resize(GraphicsWindow::Type::ZorkZero320)) {
4164 return false;
4165 }
4166 }
4167
4168 // Tower of Bozbar, Peggleboz, Snarfem, Double Fanucci.
4169 if (pic == 41 || pic == 49 || pic == 73 || pic == 99) {
4170 if (!graphics_window.resize(GraphicsWindow::Type::ZorkZeroGame)) {
4171 return false;
4172 }
4173 }
4174
4175 // The picture number can’t be used to determine whether this is a
4176 // map or border request, because some overlap, e.g. the compass
4177 // directions. Track which mode we’re in via the graphics window,
4178 // and if 320/game mode, assume the game’s got its geometry correct,
4179 // and plot the pictures just as they’re requested.
4180 if (graphics_window.type() == GraphicsWindow::Type::ZorkZero320 || graphics_window.type() == GraphicsWindow::Type::ZorkZeroGame) {
4181 ImageGeometry geom{x - 1, y - 1};
4182 graphics_window.draw(pic, geom, w, h);
4183 return true;
4184 }
4185
4186 if (pic == 5 || pic == 6 || pic == 7 || // Banner
4187 (pic >= 9 && pic <= 24) || // Compass directions
4188 (pic >= 479 && pic <= 481)) // Up & down
4189 {
4190 ImageGeometry geom{x - 1, y - 1};
4191 graphics_window.draw(pic, geom, w, h);
4192 return true;
4193 }
4194
4195 return false;
4196 }
4197
4198 // If this has to reduce the scaled value to UINT16_MAX, the image will
4199 // almost certainly be squashed horizontally or vertically (meaning this
4200 // will not take into account the original aspect ratio of the image),
4201 // but that’s really not something to worry about.
4202 static uint16_t scale_picture(uint32_t num, uint16_t val)
4203 {
4204 double r = 1.0;
4205
4206 ScaleInfo scale_info;
4207 try {
4208 scale_info = picture_scale.at(num);
4209 } catch (const std::out_of_range &) {
4210 return val;
4211 }
4212
4213 glui32 width, height;
4214 #ifdef GLK_MODULE_GARGLKWINSIZE
4215 garglk_window_get_size_pixels(mainwin->id, &width, &height);
4216 #else
4217 width = full_window_width;
4218 height = full_window_height;
4219 #endif
4220
4221 if (width != static_cast<glui32>(-1) && height != static_cast<glui32>(-1)) {
4222 // Scale according to §11.2 of the Blorb 2.0.4 specification.
4223 auto erf = std::min(static_cast<double>(width) / scale_info.px,
4224 static_cast<double>(height) / scale_info.py);
4225
4226 if (erf * scale_info.stdratio < scale_info.minratio) {
4227 r = scale_info.minratio;
4228 } else if (erf * scale_info.stdratio > scale_info.maxratio) {
4229 r = scale_info.maxratio;
4230 } else {
4231 r = erf * scale_info.stdratio;
4232 }
4233 }
4234
4235 auto max = static_cast<double>(std::numeric_limits<uint16_t>::max());
4236 return std::min(std::round(val * r), max);
4237 }
4238 #endif
4239
4240 #ifndef ZTERP_NO_V6
4241 void zdraw_picture()
4242 {
4243 #ifdef ZTERP_GLK_GRAPHICS
4244 uint16_t pic = zargs[0], scale_pic = zargs[0];
4245 uint16_t x = zargs[2];
4246 uint16_t y = zargs[1];
4247
4248 glui32 w, h;
4249 if (!glk_gestalt(gestalt_Graphics, 0) || !glk_image_get_info(pic, &w, &h)) {
4250 return;
4251 }
4252
4253 // These functions take care of drawing in graphics windows; if they
4254 // fail to draw, assume a marginal image. These will also fail if V6
4255 // hacks are turned off, effectively making _all_ images marginal.
4256 if (draw_arthur(pic, w, h, x, y) ||
4257 draw_zorkzero(pic, w, h, x, y) ||
4258 draw_journey(pic, w, h) ||
4259 draw_shogun(pic, w, h, x, y) ||
4260 draw_mysterious(pic, w, h, x, y)) {
4261 return;
4262 }
4263
4264 if (!glk_gestalt(gestalt_DrawImage, wintype_TextBuffer)) {
4265 return;
4266 }
4267
4268 glui32 align = imagealign_InlineUp;
4269
4270 if (hack == Hack::ZorkZero) {
4271 if (pic == 2 || pic == 3 || pic == 4 || (pic >= 204 && pic <= 329) || pic == 440) {
4272 align = imagealign_MarginLeft;
4273 }
4274 }
4275
4276 if (hack == Hack::Shogun) {
4277 static const std::unordered_set<glui32> right = {7, 8, 9, 10, 11, 12, 13, 14, 22, 24, 25, 26, 28, 30, 32, 37};
4278 static const std::unordered_set<glui32> left = {15, 17, 20, 27, 29, 33, 36};
4279
4280 if (right.find(pic) != right.end()) {
4281 align = imagealign_MarginRight;
4282 } else if (left.find(pic) != left.end()) {
4283 align = imagealign_MarginLeft;
4284 }
4285 }
4286
4287 auto paletted_image = get_paletted_image(pic);
4288 if (paletted_image != nullptr) {
4289 pic = paletted_image->id;
4290 scale_pic = paletted_image->parent;
4291 }
4292
4293 if (curwin->id != nullptr) {
4294 glk_image_draw_scaled(curwin->id, pic, align, 0, scale_picture(scale_pic, w), scale_picture(scale_pic, h) * aspect_scale());
4295 }
4296 #endif
4297 }
4298
4299 #ifdef ZTERP_GLK_GRAPHICS
4300 static bool image_or_rect_size(glui32 pic, glui32 &width, glui32 &height)
4301 {
4302 glui32 w, h;
4303 if (glk_image_get_info(zargs[0], &w, &h)) {
4304 width = w;
4305 height = h;
4306 return true;
4307 } else {
4308 auto *map = giblorb_get_resource_map();
4309 if (map == nullptr) {
4310 return false;
4311 }
4312 giblorb_result_t res;
4313 if (giblorb_load_resource(map, giblorb_method_Memory, &res, giblorb_ID_Pict, zargs[0]) == giblorb_err_None) {
4314 auto be32 = [](const unsigned char *base) {
4315 return
4316 (static_cast<uint32_t>(base[0]) << 24) |
4317 (static_cast<uint32_t>(base[1]) << 16) |
4318 (static_cast<uint32_t>(base[2]) << 8) |
4319 (static_cast<uint32_t>(base[3]) << 0);
4320 };
4321
4322 if (res.length == 8 && res.chunktype == giblorb_make_id('R', 'e', 'c', 't')) {
4323 auto *ptr = static_cast<unsigned char *>(res.data.ptr);
4324 width = be32(ptr + 0);
4325 height = be32(ptr + 4);
4326 return true;
4327 } else {
4328 return false;
4329 }
4330 } else {
4331 return false;
4332 }
4333 }
4334 }
4335 #endif
4336
4337 void zpicture_data()
4338 {
4339 #ifdef ZTERP_GLK_GRAPHICS
4340 auto *map = giblorb_get_resource_map();
4341
4342 if (map == nullptr || !glk_gestalt(gestalt_Graphics, 0) || !glk_gestalt(gestalt_DrawImage, wintype_TextBuffer)) {
4343 if (zargs[0] == 0) {
4344 user_store_word(zargs[1] + 0, 0);
4345 user_store_word(zargs[1] + 2, 0);
4346 }
4347
4348 branch_if(false);
4349 } else {
4350 if (zargs[0] == 0) {
4351 glui32 num = 0;
4352 giblorb_count_resources(map, giblorb_ID_Pict, &num, nullptr, nullptr);
4353
4354 user_store_word(zargs[1] + 0, num);
4355 user_store_word(zargs[1] + 2, blorb_reln);
4356
4357 branch_if(num != 0);
4358 } else {
4359 if (hack == Hack::ZorkZero) {
4360 // The following are very hacky, and hopefully will be
4361 // fixed up at some point.
4362 if (zargs[0] == 1) {
4363 // Title screen (P-TITLE). Zork Zero wants to split
4364 // the window based on the height of the title
4365 // screen, but V6 screen splitting isn’t supported,
4366 // so return the size as 0; the split won’t occur,
4367 // and the title will appear as intended.
4368 user_store_word(zargs[1] + 0, 0);
4369 user_store_word(zargs[1] + 2, 0);
4370 branch_if(true);
4371 return;
4372 } else if (zargs[0] == 382) {
4373 // This is HERE-LOC, which is meant to return where
4374 // to draw, for the status line, the name of the
4375 // current room, plus moves. Since the status line
4376 // here is just a text grid, it should be drawn at
4377 // 0,0. Zork Zero adds 1 to the values returned
4378 // here, so zeros are correct.
4379 user_store_word(zargs[1] + 0, 0);
4380 user_store_word(zargs[1] + 2, 0);
4381 branch_if(true);
4382 return;
4383 } else if (zargs[0] == 383) {
4384 // This is REGION-LOC, which is meant to return
4385 // where to draw, for the status line, the name of
4386 // the current region (Flatheadia, Antharia, etc),
4387 // plus moves. As with HERE-LOC above, this is drawn
4388 // in a text grid, and Zork Zero expects this to be
4389 // the very right-hand side of the region area, as
4390 // it calculates the actual location based on the
4391 // width of the region text; so returning the whole
4392 // width of the upper window is correct.
4393 user_store_word(zargs[1] + 0, 0);
4394 user_store_word(zargs[1] + 2, upper_window_width);
4395 branch_if(true);
4396 return;
4397 } else if (zargs[0] == 384) {
4398 // Fanucci menu location (F-MENU-LOC).
4399 user_store_word(zargs[1] + 0, 0);
4400 user_store_word(zargs[1] + 2, 0);
4401 branch_if(true);
4402 return;
4403 } else if (zargs[0] == 385) {
4404 // Fanucci score location (J-SCORE-LOC).
4405 user_store_word(zargs[1] + 0, 4);
4406 user_store_word(zargs[1] + 2, 0);
4407 branch_if(true);
4408 return;
4409 }
4410 }
4411
4412 glui32 w, h;
4413 if (image_or_rect_size(zargs[0], w, h)) {
4414 user_store_word(zargs[1] + 0, h);
4415 user_store_word(zargs[1] + 2, w);
4416 branch_if(true);
4417 } else {
4418 branch_if(false);
4419 }
4420 }
4421 }
4422 #else
4423 if (zargs[0] == 0) {
4424 user_store_word(zargs[1] + 0, 0);
4425 user_store_word(zargs[1] + 2, 0);
4426 }
4427
4428 // No pictures means no valid pictures, so never branch.
4429 branch_if(false);
4430 #endif
4431 }
4432
4433 void zget_wind_prop()
4434 {
4435 uint8_t font_width = 1, font_height = 1;
4436 uint16_t val;
4437
4438 #ifdef ZTERP_GLK_GRAPHICS
4439 if (hack == Hack::Shogun && zargs[0] == 0 && zargs[1] == 4) {
4440 // Check if this is the start of LEAVE-MAZE. This maybe should
4441 // occur instead during SETUP-TEXT-AND-STATUS but that would
4442 // have to deal with WINDEF which doesn’t currently get called
4443 // with good information (likely because there’s some
4444 // discrepancy in what Bocfel reports to the game regarding font
4445 // size, display size, etc). For now, it’s enough to “know” that
4446 // this instruction is part of a routine that handles leaving
4447 // the maze, and erase the maze screen.
4448 static const std::set<std::pair<std::string, unsigned long>> leave_maze = {
4449 {"292-890314", 0x3d4a9},
4450 {"295-890321", 0x3d691},
4451 {"311-890510", 0x3d63d},
4452 {"322-890706", 0x3d8a5},
4453 };
4454
4455 if (leave_maze.find({get_story_id(), current_instruction}) != leave_maze.end()) {
4456 graphics_window.destroy();
4457 // Force a redraw of the borders.
4458 if (graphics_window.resize(GraphicsWindow::Type::ShogunNormal)) {
4459 graphics_window.draw_shogun_borders();
4460 }
4461 }
4462 }
4463 #endif
4464
4465 Window *win = find_window(zargs[0]);
4466
4467 // These are mostly bald-faced lies.
4468 switch (zargs[1]) {
4469 case 0: // y coordinate
4470 val = 0;
4471 break;
4472 case 1: // x coordinate
4473 val = 0;
4474 break;
4475 case 2: // y size
4476 val = word(0x24) * font_height;
4477 break;
4478 case 3: // x size
4479 val = word(0x22) * font_width;
4480 break;
4481 case 4: // y cursor
4482 #ifdef ZTERP_GLK
4483 val = curwin->y + 1;
4484 #else
4485 val = 1;
4486 #endif
4487 break;
4488 case 5: // x cursor
4489 #ifdef ZTERP_GLK
4490 val = curwin->x + 1;
4491 #else
4492 val = 1;
4493 #endif
4494 break;
4495 case 6: // left margin size
4496 val = 0;
4497 break;
4498 case 7: // right margin size
4499 val = 0;
4500 break;
4501 case 8: // newline interrupt routine
4502 val = 0;
4503 break;
4504 case 9: // interrupt countdown
4505 val = 0;
4506 break;
4507 case 10: // text style
4508 val = win->style.to_ulong();
4509 break;
4510 case 11: // colour data
4511 val = (win->bg_color.as_zcolor() << 8) | win->fg_color.as_zcolor();
4512 break;
4513 case 12: // font number
4514 val = static_cast<uint16_t>(win->font);
4515 break;
4516 case 13: // font size
4517 val = (font_height << 8) | font_width;
4518 break;
4519 case 14: // attributes
4520 val = 0;
4521 break;
4522 case 15: // line count
4523 val = 0;
4524 break;
4525 case 16: // true foreground colour
4526 val = 0;
4527 break;
4528 case 17: // true background colour
4529 val = 0;
4530 break;
4531 default:
4532 die("unknown window property: %u", static_cast<unsigned int>(zargs[1]));
4533 }
4534
4535 store(val);
4536 }
4537
4538 // Output should be to the currently-selected window, but since V6 is
4539 // only marginally supported, other windows are not active. Send to the
4540 // main window for the time being.
4541 void zprint_form()
4542 {
4543 Window *saved = curwin;
4544
4545 curwin = mainwin;
4546 #ifdef ZTERP_GLK
4547 glk_set_window(mainwin->id);
4548 #endif
4549
4550 uint32_t addr = zargs[0];
4551 for (uint16_t count = user_word(addr); count != 0; count = user_word(addr)) {
4552 for (uint16_t i = 0; i < count; i++) {
4553 put_char(user_byte(addr + 2 + i));
4554 }
4555
4556 put_char(ZSCII_NEWLINE);
4557
4558 addr += 2 + count;
4559 }
4560
4561 curwin = saved;
4562 #ifdef ZTERP_GLK
4563 glk_set_window(curwin->id);
4564 #endif
4565 }
4566
4567 void zmake_menu()
4568 {
4569 branch_if(false);
4570 }
4571
4572 void zbuffer_screen()
4573 {
4574 store(0);
4575 }
4576
4577 void zjourney_dial()
4578 {
4579 #ifdef ZTERP_GLK_GRAPHICS
4580 if (hack != Hack::Journey || journey_window == nullptr) {
4581 return;
4582 }
4583
4584 glui32 w, h;
4585 if (!glk_image_get_info(zargs[0], &w, &h)) {
4586 return;
4587 }
4588
4589 auto stamp = zargs[1] == 0 ? JourneyStamp{150, ImageGeometry(0, 0)} :
4590 JourneyStamp{150, ImageGeometry(52, 0)};
4591
4592 draw_journey_stamp(zargs[0], w, h, stamp);
4593 #endif
4594 }
4595
4596 // This is a replacement for GET-FROM-MENU, which does not work properly
4597 // with Glk. zargs[0] is a packed string, which is the prompt for the
4598 // menu. zargs[1] is an LTABLE representing the menu items. zargs[2] is
4599 // a routine to call with the selected menu item, which will return true
4600 // on success or false if the user should be asked to select again.
4601 // zargs[3] is the default (selected) menu item (1-based).
4602 void zshogun_menu()
4603 {
4604 // Ordinals are ZSCII 1-9 then a-b. The color menu on Amiga goes to
4605 // 11, necessitating the alphabetic characters.
4606 std::vector<uint8_t> ordinals = {
4607 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x61, 0x62,
4608 };
4609
4610 auto table = zargs[1];
4611 auto nentries = word(table);
4612
4613 ZASSERT(nentries <= ordinals.size(), "too many menu entries");
4614 ordinals.resize(nentries);
4615
4616 while (true) {
4617 put_char(ZSCII_NEWLINE);
4618 print_handler(unpack_string(zargs[0]), nullptr);
4619 put_char(ZSCII_NEWLINE);
4620 put_char(ZSCII_NEWLINE);
4621
4622 for (int i = 0; i < nentries; i++) {
4623 auto addr = word(table + ((i + 1) * 2));
4624 int len = byte(addr++);
4625 ZASSERT(addr + len < header.static_end, "menu table out of bounds (0x%lx to 0x%lx)", static_cast<unsigned long>(addr), static_cast<unsigned long>(addr + len));
4626 std::stringstream ss;
4627 ss << static_cast<char>(ordinals.at(i)) << ". ";
4628 ss.write(reinterpret_cast<char *>(&memory[addr]), len);
4629 if (zargs[3] == i + 1) {
4630 ss << "[default]";
4631 }
4632 for (const auto &c : ss.str()) {
4633 put_char(c);
4634 }
4635 put_char(ZSCII_NEWLINE);
4636 }
4637
4638 Input input;
4639
4640 input.type = Input::Type::Char;
4641
4642 get_input(0, 0, input);
4643
4644 // Have ENTER select the default entry as in the original.
4645 auto it = input.key == ZSCII_NEWLINE && zargs[3] != 0 && (zargs[3] - 1) < nentries ?
4646 ordinals.begin() + (zargs[3] - 1) :
4647 std::find(ordinals.begin(), ordinals.end(), input.key);
4648
4649 if (it == ordinals.end()) {
4650 continue;
4651 }
4652
4653 uint8_t val = (it - ordinals.begin()) + 1;
4654
4655 interrupt_override = true;
4656 auto result = internal_call(zargs[2], {val, zargs[1]});
4657 interrupt_override = false;
4658 if (result != 0) {
4659 store(result);
4660 return;
4661 }
4662 }
4663 }
4664 #endif
4665
4666 #ifdef GLK_MODULE_GARGLKTEXT
4667 // Glk does not guarantee great control over how various styles are
4668 // going to look, but Gargoyle does. Abusing the Glk “style hints”
4669 // functions allows for quite fine-grained control over style
4670 // appearance. First, clear the (important) attributes for each style,
4671 // and then recreate each in whatever mold is necessary. Re-use some
4672 // that are expected to be correct (emphasized for italic, subheader for
4673 // bold, and so on).
4674 static void set_default_styles()
4675 {
4676 std::array<int, 7> styles = { style_Subheader, style_Emphasized, style_Alert, style_Preformatted, style_User1, style_User2, style_Note };
4677
4678 for (const auto &style : styles) {
4679 glk_stylehint_set(wintype_AllTypes, style, stylehint_Weight, 0);
4680 glk_stylehint_set(wintype_AllTypes, style, stylehint_Oblique, 0);
4681
4682 // This sets wintype_TextGrid to be proportional, which of course is
4683 // wrong; but text grids are required to be fixed, so Gargoyle
4684 // simply ignores this hint for those windows.
4685 glk_stylehint_set(wintype_AllTypes, style, stylehint_Proportional, 1);
4686 }
4687 }
4688 #endif
4689
4690 bool create_mainwin()
4691 {
4692 #ifdef ZTERP_GLK
4693
4694 #ifdef GLK_MODULE_UNICODE
4695 have_unicode = glk_gestalt(gestalt_Unicode, 0);
4696 #endif
4697
4698 #ifdef GLK_MODULE_GARGLKTEXT
4699 set_default_styles();
4700
4701 glk_stylehint_set(wintype_AllTypes, GStyleBold, stylehint_Weight, 1);
4702
4703 glk_stylehint_set(wintype_AllTypes, GStyleItalic, stylehint_Oblique, 1);
4704
4705 glk_stylehint_set(wintype_AllTypes, GStyleBoldItalic, stylehint_Weight, 1);
4706 glk_stylehint_set(wintype_AllTypes, GStyleBoldItalic, stylehint_Oblique, 1);
4707
4708 glk_stylehint_set(wintype_AllTypes, GStyleFixed, stylehint_Proportional, 0);
4709
4710 glk_stylehint_set(wintype_AllTypes, GStyleBoldFixed, stylehint_Weight, 1);
4711 glk_stylehint_set(wintype_AllTypes, GStyleBoldFixed, stylehint_Proportional, 0);
4712
4713 glk_stylehint_set(wintype_AllTypes, GStyleItalicFixed, stylehint_Oblique, 1);
4714 glk_stylehint_set(wintype_AllTypes, GStyleItalicFixed, stylehint_Proportional, 0);
4715
4716 glk_stylehint_set(wintype_AllTypes, GStyleBoldItalicFixed, stylehint_Weight, 1);
4717 glk_stylehint_set(wintype_AllTypes, GStyleBoldItalicFixed, stylehint_Oblique, 1);
4718 glk_stylehint_set(wintype_AllTypes, GStyleBoldItalicFixed, stylehint_Proportional, 0);
4719 #endif
4720
4721 #if defined(ZTERP_GLK_GRAPHICS) && !defined(GLK_MODULE_GARGLKWINSIZE)
4722 find_window_size(nullptr);
4723 #endif
4724
4725 mainwin->id = glk_window_open(nullptr, 0, 0, wintype_TextBuffer, static_cast<glui32>(WindowRock::MainWin));
4726 if (mainwin->id == nullptr) {
4727 return false;
4728 }
4729 glk_set_window(mainwin->id);
4730
4731 #ifdef GLK_MODULE_LINE_ECHO
4732 mainwin->has_echo = glk_gestalt(gestalt_LineInputEcho, 0);
4733 if (mainwin->has_echo) {
4734 glk_set_echo_line_event(mainwin->id, 0);
4735 }
4736 #endif
4737
4738 return true;
4739 #else
4740 return true;
4741 #endif
4742 }
4743
4744 bool create_statuswin()
4745 {
4746 #ifdef ZTERP_GLK
4747 statuswin.id = glk_window_open(mainwin->id, winmethod_Above | winmethod_Fixed, 1, wintype_TextGrid, static_cast<glui32>(WindowRock::StatusWin));
4748 return statuswin.id != nullptr;
4749 #else
4750 return false;
4751 #endif
4752 }
4753
4754 bool create_upperwin()
4755 {
4756 #ifdef ZTERP_GLK
4757 // The upper window appeared in V3. */
4758 if (zversion >= 3) {
4759 auto location = is_game(Game::Journey) ?
4760 winmethod_Below :
4761 winmethod_Above;
4762
4763 upperwin->id = glk_window_open(mainwin->id, location | winmethod_Fixed, 0, wintype_TextGrid, static_cast<glui32>(WindowRock::UpperWin));
4764 upperwin->x = upperwin->y = 0;
4765 upper_window_height = 0;
4766
4767 if (upperwin->id != nullptr) {
4768 glui32 w, h;
4769
4770 glk_window_get_size(upperwin->id, &w, &h);
4771 upper_window_width = w;
4772
4773 if (h != 0 || upper_window_width == 0) {
4774 glk_window_close(upperwin->id, nullptr);
4775 upperwin->id = nullptr;
4776 }
4777 }
4778 }
4779
4780 #ifdef ZTERP_GLK_GRAPHICS
4781 // For the “bordered” graphics games (Arthur, Zork Zero, and
4782 // Shogun), resize the graphics window before starting: the games
4783 // request the upper window size early on and store it, meaning the
4784 // border windows must already exist or else the upper window size
4785 // will be reported as larger than it will become.
4786 if (hack == Hack::ZorkZero) {
4787 graphics_window.resize(GraphicsWindow::Type::ZorkZeroBorder);
4788 } else if (hack == Hack::Shogun) {
4789 graphics_window.resize(GraphicsWindow::Type::ShogunNormal);
4790 } else if (hack == Hack::Arthur) {
4791 graphics_window.resize(GraphicsWindow::Type::ArthurBanner);
4792 }
4793 #endif
4794
4795 return upperwin->id != nullptr;
4796 #else
4797 return false;
4798 #endif
4799 }
4800
4801 // Write out the screen state for a Scrn chunk.
4802 //
4803 // This implements version 0 as described in stack.cpp.
4804 IFF::TypeID screen_write_scrn(IO &io)
4805 {
4806 io.write32(0);
4807
4808 io.write8(curwin - windows.data());
4809 #ifdef ZTERP_GLK
4810 io.write16(upper_window_height);
4811 io.write16(starting_x);
4812 io.write16(starting_y);
4813 #else
4814 io.write16(0);
4815 io.write16(0);
4816 io.write16(0);
4817 #endif
4818
4819 for (int i = 0; i < (zversion == 6 ? 8 : 2); i++) {
4820 io.write8(windows[i].style.to_ulong());
4821 io.write8(static_cast<uint8_t>(windows[i].font));
4822 io.write8(static_cast<uint8_t>(windows[i].fg_color.mode));
4823 io.write16(windows[i].fg_color.value);
4824 io.write8(static_cast<uint8_t>(windows[i].bg_color.mode));
4825 io.write16(windows[i].bg_color.value);
4826 }
4827
4828 return IFF::TypeID("Scrn");
4829 }
4830
4831 static void try_load_color(Color::Mode mode, uint16_t value, Color &color)
4832 {
4833 switch (mode) {
4834 case Color::Mode::ANSI:
4835 if (value >= 1 && value <= 12) {
4836 color = Color(Color::Mode::ANSI, value);
4837 }
4838 break;
4839 case Color::Mode::True:
4840 if (value < 32768) {
4841 color = Color(Color::Mode::True, value);
4842 }
4843 break;
4844 }
4845 }
4846
4847 // Read and restore the screen state from a Scrn chunk. Since this
4848 // actively touches the screen, it should only be called once the
4849 // restore function has determined that the restore is successful.
4850 void screen_read_scrn(IO &io, uint32_t size)
4851 {
4852 uint32_t version;
4853 size_t data_size = zversion == 6 ? 71 : 23;
4854 uint8_t current_window;
4855 uint16_t new_upper_window_height;
4856 struct {
4857 uint8_t style;
4858 Window::Font font;
4859 Color::Mode fgmode;
4860 uint16_t fgvalue;
4861 Color::Mode bgmode;
4862 uint16_t bgvalue;
4863 } window_data[8];
4864 #ifdef ZTERP_GLK
4865 uint16_t new_x, new_y;
4866 #endif
4867
4868 try {
4869 version = io.read32();
4870 } catch (const IO::IOError &) {
4871 throw RestoreError("short read");
4872 }
4873
4874 if (version != 0) {
4875 show_message("Unsupported Scrn version %lu; ignoring chunk", static_cast<unsigned long>(version));
4876 return;
4877 }
4878
4879 if (size != data_size + 4) {
4880 throw RestoreError(fstring("invalid size: %lu", static_cast<unsigned long>(size)));
4881 }
4882
4883 try {
4884 current_window = io.read8();
4885 new_upper_window_height = io.read16();
4886 #ifdef ZTERP_GLK
4887 new_x = io.read16();
4888 new_y = io.read16();
4889 #else
4890 io.read32();
4891 #endif
4892
4893 for (int i = 0; i < (zversion == 6 ? 8 : 2); i++) {
4894 window_data[i].style = io.read8();
4895 window_data[i].font = static_cast<Window::Font>(io.read8());
4896 window_data[i].fgmode = static_cast<Color::Mode>(io.read8());
4897 window_data[i].fgvalue = io.read16();
4898 window_data[i].bgmode = static_cast<Color::Mode>(io.read8());
4899 window_data[i].bgvalue = io.read16();
4900 }
4901 } catch (const IO::IOError &) {
4902 throw RestoreError("short read");
4903 }
4904
4905 if (current_window > 7) {
4906 throw RestoreError(fstring("invalid window: %d", current_window));
4907 }
4908
4909 set_current_window(&windows[current_window]);
4910 #ifdef ZTERP_GLK
4911 delayed_window_shrink = -1;
4912 saw_input = false;
4913 #endif
4914 resize_upper_window(new_upper_window_height, false);
4915
4916 #ifdef ZTERP_GLK
4917 if (new_x > upper_window_width) {
4918 new_x = upper_window_width;
4919 }
4920 if (new_y > upper_window_height) {
4921 new_y = upper_window_height;
4922 }
4923 if (new_y != 0 && new_x != 0) {
4924 set_cursor(new_y, new_x);
4925 }
4926 #endif
4927
4928 for (int i = 0; i < (zversion == 6 ? 8 : 2); i++) {
4929 if (window_data[i].style < 16) {
4930 windows[i].style = window_data[i].style;
4931 }
4932
4933 if (is_valid_font(window_data[i].font)) {
4934 windows[i].font = window_data[i].font;
4935 }
4936
4937 try_load_color(window_data[i].fgmode, window_data[i].fgvalue, windows[i].fg_color);
4938 try_load_color(window_data[i].bgmode, window_data[i].bgvalue, windows[i].bg_color);
4939 }
4940
4941 set_current_style();
4942 }
4943
4944 IFF::TypeID screen_write_bfhs(IO &io)
4945 {
4946 io.write32(0); // version
4947 io.write32(history.size());
4948
4949 for (const auto &entry : history.entries()) {
4950 switch (entry.type) {
4951 case History::Entry::Type::Style:
4952 io.write8(static_cast<uint8_t>(entry.type));
4953 io.write8(entry.contents.style);
4954 break;
4955 case History::Entry::Type::FGColor: case History::Entry::Type::BGColor:
4956 io.write8(static_cast<uint8_t>(entry.type));
4957 io.write8(static_cast<uint8_t>(entry.contents.color.mode));
4958 io.write16(entry.contents.color.value);
4959 break;
4960 case History::Entry::Type::InputStart: case History::Entry::Type::InputEnd:
4961 io.write8(static_cast<uint8_t>(entry.type));
4962 break;
4963 case History::Entry::Type::Char:
4964 io.write8(static_cast<uint8_t>(entry.type));
4965 io.putc(entry.contents.c);
4966 break;
4967 }
4968 };
4969
4970 return IFF::TypeID("Bfhs");
4971 }
4972
4973 class ScopeGuard {
4974 public:
4975 explicit ScopeGuard(std::function<void()> fn) : m_fn(std::move(fn)) {
4976 }
4977
4978 ScopeGuard(const ScopeGuard &) = delete;
4979 ScopeGuard &operator=(const ScopeGuard &) = delete;
4980
4981 ~ScopeGuard() {
4982 m_fn();
4983 }
4984
4985 private:
4986 std::function<void()> m_fn;
4987 };
4988
4989 void screen_read_bfhs(IO &io, bool autosave)
4990 {
4991 uint32_t version;
4992 Window saved = *mainwin;
4993 auto original_style = mainwin->style;
4994 uint32_t size;
4995 #ifdef ZTERP_GLK
4996 // Write directly to the main window’s stream instead of going
4997 // through screen_print() or similar: history playback should be
4998 // “transparent”, so to speak. It will have already been added to a
4999 // transcript during the previous round of play (if the user so
5000 // desired), and this function itself recreates all history directly
5001 // from the Bfhs chunk.
5002 strid_t stream = glk_window_get_stream(mainwin->id);
5003 #endif
5004
5005 try {
5006 version = io.read32();
5007 } catch (const IO::IOError &) {
5008 show_message("Unable to read history version");
5009 return;
5010 }
5011
5012 if (version != 0) {
5013 show_message("Unsupported history version: %lu", static_cast<unsigned long>(version));
5014 return;
5015 }
5016
5017 mainwin->fg_color = Color();
5018 mainwin->bg_color = Color();
5019 mainwin->style.reset();
5020 set_window_style(mainwin);
5021
5022 #ifdef ZTERP_GLK
5023 auto write = [&stream](std::string msg) {
5024 glk_put_string_stream(stream, &msg[0]);
5025 };
5026 #else
5027 auto write = [](const std::string &msg) {
5028 std::cout << msg;
5029 };
5030 #endif
5031
5032 ScopeGuard guard([&autosave, &saved, &write] {
5033 if (!autosave) {
5034 write("[End of history playback]\n\n");
5035 }
5036 *mainwin = saved;
5037 set_window_style(mainwin);
5038 });
5039
5040 if (!autosave) {
5041 write("[Starting history playback]\n");
5042 }
5043
5044 try {
5045 size = io.read32();
5046 } catch (const IO::IOError &) {
5047 return;
5048 }
5049
5050 if (size == 0 && autosave) {
5051 warning("empty history record");
5052 screen_print(">");
5053 return;
5054 }
5055
5056 for (uint32_t i = 0; i < size; i++) {
5057 uint8_t type;
5058 long c;
5059
5060 try {
5061 type = io.read8();
5062 } catch (const IO::IOError &) {
5063 return;
5064 }
5065
5066 // Each history entry is added to the history buffer. This is so
5067 // that new saves, after a restore, continue to include the
5068 // older save file’s history.
5069 switch (static_cast<History::Entry::Type>(type)) {
5070 case History::Entry::Type::Style: {
5071 uint8_t style;
5072
5073 try {
5074 style = io.read8();
5075 } catch (const IO::IOError &) {
5076 return;
5077 }
5078
5079 mainwin->style = style;
5080 set_window_style(mainwin);
5081
5082 history.add_style();
5083
5084 break;
5085 }
5086 case History::Entry::Type::FGColor: case History::Entry::Type::BGColor: {
5087 uint8_t mode;
5088 uint16_t value;
5089
5090 try {
5091 mode = io.read8();
5092 value = io.read16();
5093 } catch (const IO::IOError &) {
5094 return;
5095 }
5096
5097 Color &color = static_cast<History::Entry::Type>(type) == History::Entry::Type::FGColor ? mainwin->fg_color : mainwin->bg_color;
5098
5099 try_load_color(static_cast<Color::Mode>(mode), value, color);
5100 set_window_style(mainwin);
5101
5102 if (static_cast<History::Entry::Type>(type) == History::Entry::Type::FGColor) {
5103 history.add_fg_color(color);
5104 } else {
5105 history.add_bg_color(color);
5106 }
5107
5108 break;
5109 }
5110 case History::Entry::Type::InputStart:
5111 original_style = mainwin->style;
5112 mainwin->style.reset();
5113 set_window_style(mainwin);
5114 #ifdef ZTERP_GLK
5115 glk_set_style_stream(stream, style_Input);
5116 #endif
5117 history.add_input_start();
5118 break;
5119 case History::Entry::Type::InputEnd:
5120 mainwin->style = original_style;
5121 set_window_style(mainwin);
5122 history.add_input_end();
5123 break;
5124 case History::Entry::Type::Char:
5125 c = io.getc(false);
5126 if (c == -1) {
5127 return;
5128 }
5129 for (const auto &clean : cleanse_control(c)) {
5130 history.add_char(clean);
5131 #ifdef ZTERP_GLK
5132 xglk_put_char_stream(stream, clean);
5133 #else
5134 IO::standard_out().putc(clean);
5135 #endif
5136 }
5137 break;
5138 default:
5139 return;
5140 }
5141 }
5142 }
5143
5144 IFF::TypeID screen_write_bfts(IO &io)
5145 {
5146 if (!options.persistent_transcript || perstransio == nullptr) {
5147 return IFF::TypeID();
5148 }
5149
5150 io.write32(0); // Version
5151
5152 const auto &buf = perstransio->get_memory();
5153 io.write_exact(buf.data(), buf.size());
5154
5155 return IFF::TypeID("Bfts");
5156 }
5157
5158 void screen_read_bfts(IO &io, uint32_t size)
5159 {
5160 uint32_t version;
5161 std::vector<uint8_t> buf;
5162
5163 if (size < 4) {
5164 show_message("Corrupted Bfts entry (too small)");
5165 }
5166
5167 try {
5168 version = io.read32();
5169 } catch (const IO::IOError &) {
5170 show_message("Unable to read persistent transcript size from save file");
5171 return;
5172 }
5173
5174 if (version != 0) {
5175 show_message("Unsupported Bfts version %lu", static_cast<unsigned long>(version));
5176 return;
5177 }
5178
5179 // The size of the transcript is the size of the whole chunk minus
5180 // the 32-bit version.
5181 size -= 4;
5182
5183 if (size > 0) {
5184 try {
5185 buf.resize(size);
5186 } catch (const std::bad_alloc &) {
5187 show_message("Unable to allocate memory for persistent transcript");
5188 return;
5189 }
5190
5191 try {
5192 io.read_exact(buf.data(), size);
5193 } catch (const IO::IOError &) {
5194 show_message("Unable to read persistent transcript from save file");
5195 return;
5196 }
5197 }
5198
5199 perstransio = std::make_unique<IO>(buf, IO::Mode::Append);
5200 }
5201
5202 class PersistentTranscriptStasher : public Stasher {
5203 public:
5204 void backup() override {
5205 m_transcript.reset();
5206
5207 if (options.persistent_transcript && perstransio != nullptr) {
5208 const auto &buf = perstransio->get_memory();
5209 try {
5210 m_transcript = std::make_unique<std::vector<uint8_t>>(buf);
5211 } catch (const std::bad_alloc &) {
5212 }
5213 }
5214 }
5215
5216 // Never fail: this is an optional chunk so isn’t fatal on error.
5217 bool restore() override {
5218 if (m_transcript == nullptr) {
5219 return true;
5220 }
5221
5222 perstransio = std::make_unique<IO>(*m_transcript, IO::Mode::Append);
5223 m_transcript.reset();
5224
5225 return true;
5226 }
5227
5228 void free() override {
5229 m_transcript.reset();
5230 }
5231
5232 private:
5233 std::unique_ptr<std::vector<uint8_t>> m_transcript;
5234 };
5235
5236 static bool check_transcript()
5237 {
5238 if (!options.persistent_transcript) {
5239 screen_puts("[Persistent transcripting is turned off]");
5240 return false;
5241 }
5242
5243 if (perstransio == nullptr) {
5244 screen_puts("[Persistent transcripting failed to start]");
5245 return false;
5246 }
5247
5248 return true;
5249 }
5250
5251 void screen_save_persistent_transcript()
5252 {
5253 if (!check_transcript()) {
5254 return;
5255 }
5256
5257 const auto &buf = perstransio->get_memory();
5258
5259 try {
5260 IO io(nullptr, IO::Mode::WriteOnly, IO::Purpose::Transcript);
5261
5262 try {
5263 io.write_exact(buf.data(), buf.size());
5264 screen_puts("[Saved]");
5265 } catch (const IO::IOError &) {
5266 screen_puts("[Error writing transcript to file]");
5267 }
5268 } catch (const IO::OpenError &) {
5269 screen_puts("[Failed to open file]");
5270 return;
5271 }
5272 }
5273
5274 void screen_show_persistent_transcript() {
5275 if (!check_transcript()) {
5276 return;
5277 }
5278
5279 const auto &buf = perstransio->get_memory();
5280
5281 std::vector<char> transcript(buf.begin(), buf.end());
5282
5283 screen_puts("[Opening persistent transcript]");
5284 screen_flush();
5285
5286 try {
5287 zterp_os_show_transcript(transcript);
5288 } catch (const std::runtime_error &e) {
5289 screen_printf("[Error showing persistent transcript: %s]\n", e.what());
5290 }
5291 }
5292
5293 void create_graphicswin()
5294 {
5295 #ifdef ZTERP_GLK_GRAPHICS
5296 graphics_window.destroy();
5297 if (glk_gestalt(gestalt_DrawImage, wintype_Graphics)) {
5298 if ((is_game(Game::Arthur) ||
5299 is_game(Game::ZorkZero) ||
5300 is_game(Game::Shogun) ||
5301 is_game(Game::MysteriousAdventures)) &&
5302 graphics_window.create())
5303 {
5304 if (is_game(Game::Arthur)) {
5305 hack = Hack::Arthur;
5306 arthurwin->id = glk_window_open(mainwin->id, winmethod_Fixed | winmethod_Above, 0, wintype_TextGrid, 0);
5307 } else if (is_game(Game::ZorkZero)) {
5308 hack = Hack::ZorkZero;
5309 } else if (is_game(Game::Shogun)) {
5310 hack = Hack::Shogun;
5311 } else if (is_game(Game::MysteriousAdventures)) {
5312 hack = Hack::MysteriousAdventures;
5313
5314 auto *map = giblorb_get_resource_map();
5315 if (map == nullptr || giblorb_count_resources(map, giblorb_ID_Pict, &mysterious_max_image, nullptr, nullptr) != giblorb_err_None) {
5316 graphics_window.destroy();
5317 hack = Hack::None;
5318 }
5319 }
5320 } else if (is_game(Game::Journey)) {
5321 hack = Hack::Journey;
5322 }
5323 }
5324
5325 // Redirecting windows is unnecessary when a “supported” game is running.
5326 if (hack != Hack::None) {
5327 options.redirect_v6_windows = false;
5328 }
5329 #endif
5330 }
5331
5332 void init_screen(bool first_run)
5333 {
5334 for (auto &window : windows) {
5335 window.style.reset();
5336 window.fg_color = window.bg_color = Color();
5337 window.font = Window::Font::Normal;
5338
5339 #ifdef ZTERP_GLK
5340 clear_window(&window);
5341 #endif
5342 }
5343
5344 close_upper_window();
5345
5346 #ifdef ZTERP_GLK
5347 // For now, unless the user disables it, point windows 2–7 (from
5348 // version 6) to the main window, allowing all output (text and
5349 // graphics) to be seen. Things could get pretty jumbled but it’s
5350 // not inherently worse than a chunk of output missing.
5351 if (options.redirect_v6_windows) {
5352 for (int i = 2; i < 8; i++) {
5353 windows[i].id = windows[0].id;
5354 }
5355 }
5356
5357 if (statuswin.id != nullptr) {
5358 glk_window_clear(statuswin.id);
5359 }
5360
5361 if (errorwin != nullptr) {
5362 glk_window_close(errorwin, nullptr);
5363 errorwin = nullptr;
5364 }
5365
5366 stop_timer();
5367
5368 #ifdef ZTERP_GLK_GRAPHICS
5369 build_palette_map();
5370 #endif
5371
5372 #else
5373 have_unicode = true;
5374 #endif
5375
5376 if (first_run && options.persistent_transcript) {
5377 try {
5378 perstransio = std::make_unique<IO>(std::vector<uint8_t>(), IO::Mode::WriteOnly);
5379 } catch (const IO::OpenError &) {
5380 warning("Failed to start persistent transcripting");
5381 }
5382
5383 stash_register(std::make_unique<PersistentTranscriptStasher>());
5384 }
5385
5386 // On restart, deselect stream 3 and select stream 1. This allows
5387 // the command script and transcript to persist across restarts,
5388 // while resetting memory output and ensuring screen output.
5389 streams.reset(OSTREAM_MEMORY);
5390 streams.set(OSTREAM_SCREEN);
5391 stream_tables.clear();
5392
5393 set_current_window(mainwin);
5394 }