lib/Language/Zcode/Runtime/IO.pm untested

filter: Statementstmt 0.0% 0 / 1142 Branchbran 0.0% 0 / 290 Conditioncond 0.0% 0 / 118 MC/DCmcdc 0.0% 0 / 70 Subroutinesub 0.0% 0 / 253 Podpod 0.0% 0 / 156 totaltotal 0.0% 0 / 2029 CC 128 SCAR 23.7
CC
128
Cov
0%
update_header
72.0
show_status
72.0
erase_window
42.0
CRAP 10.7
1 package Language::Zcode::Runtime::IO;
2
3 use strict;
4 use warnings;
5
6 use IO::File; # for opening transcripts
7
8 use vars qw(@EXPORT @ISA);
9 use Exporter;
10 @ISA=qw(Exporter);
11 # TODO move these to Language::Zcode::Runtime::Opcodes?
12 # Export Z-functions called by translated Z-program
13 @EXPORT = qw(
14 &input_stream &output_stream
15 &newline &read_command &show_status
16 &write_text &write_zchar
17 &split_window &set_window &erase_window
18 &get_cursor &set_cursor
19 &set_text_style
20 );
21
22 use Language::Zcode::Runtime::Input;
23 use Language::Zcode::Runtime::Text;
24
25 =pod
26
27 =head1 NAME
28
29 Language::Zcode::Runtime::IO - IO for Perl runtimes created by L::Z translations
30
31 =head1 DESCRIPTION
32
33 This package contains a number of different packages that support
34 the IO features needed for a running Z-machine. This includes
35 windows, input and output streams, cursors, lines, and fonts.
36 See the Z-machine Spec for descriptions of what all these things means.
37
38 This package supports more than one "terminal", i.e., Perl toolkit for handling
39 the I/O into and out of the Z-machine. OK, right now, it only supports 2:
40 dumb, which is just regular print statements; and win32, which
41 involves Win32::Console tools. But in theory, it won't be hard to add support
42 for Tk, Curses, and others. Why? Because I stole nearly all the code in these
43 packages from Games::Rezrov, which already does support multiple terminal
44 types.
45
46 This package implements many of the Z-machine I/O opcodes,
47 things like print, output_stream, and read. It also handles the header,
48 which mostly deals with I/O.
49
50 This package is currently the most hacked of all the packages in
51 the Language::Zcode distribution. I hope it gets cleaner eventually.
52
53 =cut
54
55 # TODO get rid of lots of global variables.
56 # In general, localize things. Less calling back & forth between
57 # Perl IO & ZIO packages, if possible.
58 # Divide Language::Zcode::Runtime::IO into separate classes if possible to handle
59 # e.g., streams & maybe windows.
60
61 {
62 package Games::Rezrov::ZConst;
63 # constants
64
65 use strict;
66
67 use constant ASCII_DEL => 0x7f;
68 use constant ASCII_BS => 0x08;
69 use constant ASCII_LF => 0x0a;
70 use constant ASCII_CR => 0x0d;
71 use constant ASCII_SPACE => 0x20;
72
73 use constant LOWER_WIN => 0;
74 use constant UPPER_WIN => 1;
75 # XXX STATUS_WIN => 2?
76
77 use constant STYLE_ROMAN => 0;
78 use constant STYLE_REVERSE => 1;
79 use constant STYLE_BOLD => 2;
80 use constant STYLE_ITALIC => 4;
81 use constant STYLE_FIXED => 8;
82 # sect15.html#set_text_style
83
84 # 3.8, table 2:
85 use constant Z_NEWLINE => 13;
86 use constant Z_DELETE => 8;
87 use constant Z_UP => 129;
88 use constant Z_DOWN => 130;
89 use constant Z_LEFT => 131;
90 use constant Z_RIGHT => 132;
91
92 # 8.3.1:
93 use constant COLOR_CURRENT => 0;
94 use constant COLOR_DEFAULT => 1;
95
96 use constant COLOR_BLACK => 2;
97 use constant COLOR_RED => 3;
98 use constant COLOR_GREEN => 4;
99 use constant COLOR_YELLOW => 5;
100 use constant COLOR_BLUE => 6;
101 use constant COLOR_MAGENTA => 7;
102 use constant COLOR_CYAN => 8;
103 use constant COLOR_WHITE => 9;
104
105 # 8.1.2:
106 use constant FONT_NORMAL => 1;
107 use constant FONT_PICTURE => 2;
108 use constant FONT_CHAR_GRAPHICS => 3;
109 use constant FONT_FIXED => 4;
110
111 my %COLOR_MAP = (COLOR_BLACK() => "black",
112 COLOR_RED() => "red",
113 COLOR_GREEN() => "green",
114 COLOR_YELLOW() => "yellow",
115 COLOR_BLUE() => "blue",
116 COLOR_MAGENTA() => "magenta",
117 COLOR_CYAN() => "cyan",
118 COLOR_WHITE() => "white");
119
120 sub color_code_to_name {
121 return $COLOR_MAP{$_[0]} || undef;
122 }
123
124 }
125
126 # TODO XXX There's some ugly hacks here. These used to be separate modules.
127 # Now they're combined which makes exporting weird. Once the code has
128 # settled down, I should make it prettier.
129 ##################################
130
131 # location of various flags in the header
132 use constant FLAGS_1 => 0x01; # one byte
133 use constant FLAGS_2 => 0x10; # TWO BYTES
134
135 # Flags 1, v1-3
136 use constant IS_TIME_GAME => 0x02; # bit 1
137 # bit 2 - story split across two disks
138 use constant TANDY => 0x08; # bit 3
139 use constant STATUS_NOT_AVAILABLE => 0x10; # bit 4
140 use constant SCREEN_SPLITTING_AVAILABLE => 0x20; # bit 5
141 use constant VARIABLE_FONT_DEFAULT => 0x40; # bit 6
142
143 # Flags 1, v4+
144 use constant COLOURS_AVAILABLE => 0x01; # bit 0
145 use constant PICTURES_AVAILABLE => 0x02; # bit 1
146 use constant BOLDFACE_AVAILABLE => 0x04; # bit 2
147 use constant ITALIC_AVAILABLE => 0x08; # bit 3
148 use constant FIXED_FONT_AVAILABLE => 0x10; # bit 4
149 use constant SOUND_EFFECTS_AVAILABLE => 0x20; # bit 5 - v6+
150 use constant TIMED_INPUT_AVAILABLE => 0x80; # bit 7
151
152 # Flags 2
153 use constant TRANSCRIPT_ON => 0x01; # bit 0
154 use constant FORCE_FIXED => 0x02; # bit 1
155 use constant REQUEST_STATUS_REDRAW => 0x04; # bit 2 - v6+
156
157 # Flags 2, v5+:
158 # Spec 11: "For bits 3,4,5,7 and 8, Int clears again if it cannot provide the
159 # requested effect"
160 use constant WANTS_PICTURES => 0x08;
161 use constant WANTS_UNDO => 0x10;
162 use constant WANTS_MOUSE => 0x20;
163 use constant WANTS_COLOR => 0x40;
164 use constant WANTS_SOUND => 0x80;
165 # Flags 2, v6+:
166 use constant WANTS_MENUS => 0x0100; # v6+
167
168 use constant BACKGROUND_COLOR => 0x2c;
169 use constant FOREGROUND_COLOR => 0x2d;
170 # 8.3.2, 8.3.3
171
172 use constant SCREEN_HEIGHT_LINES => 0x20;
173 use constant SCREEN_WIDTH_CHARS => 0x21;
174 use constant SCREEN_WIDTH_UNITS => 0x22;
175 use constant SCREEN_HEIGHT_UNITS => 0x24;
176
177 use constant FONT_WIDTH_UNITS_V5 => 0x26;
178 use constant FONT_WIDTH_UNITS_V6 => 0x27;
179
180 use constant FONT_HEIGHT_UNITS_V5 => 0x27;
181 use constant FONT_HEIGHT_UNITS_V6 => 0x26;
182
183 my $zio;
184 my $prompt_buffer;
185 my ($Rows, $Columns);
186 # Save position in each window
187 my $window_cursors;
188
189 my $current_window = Games::Rezrov::ZConst::LOWER_WIN;
190 # XXX get rid of this
191 sub current_window { $current_window }
192
193 # HACKS, FIX ME [ADK: No kidding]
194 #my ($upper_lines, $lower_lines);
195 # Need to use from other packages
196 use vars qw($upper_lines $lower_lines);
197
198 # Call once when starting the program
199 sub start_IO {
200 my ($r, $c, $t) = @_;
201 # TODO intelligently figure out which terminal to use if none was given
202 $t = "dumb" unless defined $t;
203
204 # XXX These two lines mean I don't need to input -r/-c while
205 # testing with the ZIO_dumb interface.
206 # warn "For now, I'm ignoring -r and -c options\n" if $r || $c;
207 if ($t eq "dumb") {$r ||= 24; $c ||= 80}
208
209 if ($t eq "dumb") {
210 $zio = new Games::Rezrov::ZIO_dumb(rows=>$r, columns =>$c);
211 } elsif ($t eq "win32") {
212 $zio = new Games::Rezrov::ZIO_Win32(rows=>$r, columns =>$c);
213 } else {
214 die "Unknown terminal '$t'\n";
215 }
216 $zio->set_window(Games::Rezrov::ZConst::LOWER_WIN);
217 PlotzPerl::Output::start_output($zio);
218 # erase_window call in setup_IO calls clear_screen
219 # $zio->clear_screen();
220 }
221
222 # Call again for restart
223 sub setup_IO {
224 # XXX I don't handle undo yet ADK
225 # $undo_slots = [];
226 # cursor positions for individual windows
227 $window_cursors = [];
228
229 PlotzPerl::Output::setup();
230 Language::Zcode::Runtime::Input::setup();
231
232
233 # HACKS, FIX ME
234 # $zio->set_version($self);
235 # collapses the upper window
236 # XXX do we really want to clear screen on a restart?
237 erase_window(-1);
238
239 # Centralized management of the status line.
240 # Perform a split_window(), we'll use the "upper window"
241 # for the status line.
242 # This is BROKEN: Seastalker is a v3 game that uses the upper window!
243
244 =pod
245
246 # So [ADK] split to a SECOND window. This split will be internal to
247 # the Z-machine emulator: the Z-machine isn't able to split to more
248 # than one window (in v5), but presumably any I/O that can split once
249 # can split more than once. Put status in that window.
250 #
251 # Tk already does that. Just use manual_status_line for
252 # everything.
253 =cut
254
255 if ($main::Constants{version} <= 3 &&
256 $zio->can_split() &&
257 !$zio->manual_status_line()) {
258 split_window(1);
259 }
260
261 # XXX ADK I think we don't need the $current_window line below - that
262 # is taken care of by set_window
263 # $current_window = Games::Rezrov::ZConst::LOWER_WIN;
264 set_window(Games::Rezrov::ZConst::LOWER_WIN);
265 }
266
267 # Read IO stuff from header, write some back depending on interpreter/IO
268 sub update_header {
269 my $version = $main::Constants{version};
270
271 # First do flags1 stuff
272 # a "time" game: 8.2.3.2
273 #my $f1 = PlotzMemory::get_byte_at(FLAGS_1);
274 my $f1 = $PlotzMemory::Memory[FLAGS_1];
275
276 my $start_rows = rows();
277 my $start_columns = columns();
278
279 # $f1 |= TANDY if Games::Rezrov::ZOptions::TANDY_BIT();
280 # turn on the "tandy bit"
281
282 if ($version <= 3) {
283 if ($zio->can_split()) {
284 $f1 |= SCREEN_SPLITTING_AVAILABLE;
285 $f1 &= ~ STATUS_NOT_AVAILABLE;
286 } else {
287 $f1 &= ~ SCREEN_SPLITTING_AVAILABLE;
288 $f1 |= STATUS_NOT_AVAILABLE;
289 }
290
291 # XXX copied from Games::Rezrov::ZHeader. Isn't this backwards?!
292 if ($zio->fixed_font_default()) {
293 $f1 |= VARIABLE_FONT_DEFAULT;
294 } else {
295 $f1 &= ~VARIABLE_FONT_DEFAULT;
296 }
297
298 # versions 4+
299 } else {
300 # Are they always available? Even for dumb term?
301 $f1 |= BOLDFACE_AVAILABLE;
302 $f1 |= ITALIC_AVAILABLE;
303 $f1 |= FIXED_FONT_AVAILABLE;
304
305 # $f1 |= 0x80;
306 $f1 &= ~TIMED_INPUT_AVAILABLE; # timed input NOT available
307
308 set_header_columns($start_columns);
309 set_header_rows($start_rows);
310 if ($version >= 5) {
311 if ($zio->can_use_color()) {
312 $f1 |= COLOURS_AVAILABLE;
313 }
314 }
315 }
316 # write back flag1
317 PlotzMemory::set_byte_at(FLAGS_1, $f1);
318
319 # Now do flags2 stuff
320 if ($version >= 5) {
321 # 8.3.3: default foreground and background
322 # FIX ME!
323
324 my $f2 = PlotzMemory::get_word_at(FLAGS_2);
325 # if ($zio->groks_font_3() and
326 # !Games::Rezrov::StoryFile::font_3_disabled()) {
327 # ZIO can decode font 3 characters
328 # $f2 |= WANTS_PICTURES;
329 # } else {
330 # nope
331 # $f2 &= ~ WANTS_PICTURES;
332 # }
333
334 # $f2 |= WANTS_UNDO;
335 $f2 &= ~ WANTS_UNDO;
336 # FIX ME: should we never use this???
337
338 # if ($f2 & WANTS_COLOR) {
339 # 8.3.4: the game wants to use colors
340 # print "wants color!\n";
341 # }
342 PlotzMemory::set_word_at(FLAGS_2, $f2);
343 }
344
345 # Other
346 # XXX ADK Why isn't this default/default?!
347 if ($version >= 5) {
348 PlotzMemory::set_byte_at(BACKGROUND_COLOR, Games::Rezrov::ZConst::COLOR_BLACK);
349 PlotzMemory::set_byte_at(FOREGROUND_COLOR, Games::Rezrov::ZConst::COLOR_WHITE);
350 }
351
352 # Now read bits that get saved during restart/restore
353 Language::Zcode::Runtime::IO::restore_restart_bits();
354 }
355
356 {
357 my $restart_bits;
358 # Get the bits that stay even when you do a restart
359 # Namely, transcript and force-fixed-font bits in Flags 2
360 sub store_restart_bits {
361 my $f2 = PlotzMemory::get_word_at(FLAGS_2);
362 $restart_bits = $f2 & 3;
363 return;
364 }
365 # Write the bits that stay even when you do a restart
366 # Namely, transcript and force-fixed-font bits in Flags 2
367 sub restore_restart_bits {
368 # Doesn't do anything if we're starting program for the first time
369 return unless defined $restart_bits;
370 my $f2 = PlotzMemory::get_word_at(FLAGS_2);
371 $f2 &= ~3; # clear bits
372 PlotzMemory::set_word_at(FLAGS_2, $f2 || $restart_bits);
373 return;
374 }
375 }
376
377 sub set_header_columns {
378 # 8.4: set the dimensions of the screen.
379 # only needed in v4+
380 my $columns = shift;
381 my $version = $main::Constants{version};
382 PlotzMemory::set_byte_at(SCREEN_WIDTH_CHARS, $columns);
383 if ($version >= 5) {
384 PlotzMemory::set_byte_at($version >= 6 ?
385 FONT_WIDTH_UNITS_V6 : FONT_WIDTH_UNITS_V5, 1);
386 PlotzMemory::set_word_at(SCREEN_WIDTH_UNITS, $columns);
387 # ?
388 }
389 }
390
391 sub set_header_rows {
392 my $rows = shift;
393 my $version = $main::Constants{version};
394 PlotzMemory::set_byte_at(SCREEN_HEIGHT_LINES, $rows);
395 if ($version >= 5) {
396 PlotzMemory::set_byte_at($version >= 6 ?
397 FONT_HEIGHT_UNITS_V6 : FONT_HEIGHT_UNITS_V5, 1);
398 PlotzMemory::set_word_at(SCREEN_HEIGHT_UNITS, $rows);
399 }
400 }
401
402 sub rows {
403 if (defined $_[0]) {
404 $Rows = $_[0];
405 if ($zio) {
406 set_header_rows($Rows);
407 PlotzPerl::Output::reset_write_count();
408 }
409 $lower_lines = $Rows - $upper_lines if defined $upper_lines;
410 }
411 return $Rows;
412 }
413
414 sub columns {
415 if (defined $_[0]) {
416 # ZIO notifies us of its columns
417 $Columns = $_[0];
418 set_header_columns($_[0]) if $zio;
419 show_status() if $main::Constants{version} <= 3 and $zio;
420 }
421 return $Columns;
422 }
423
424 sub is_time_game {
425 my $f1 = $PlotzMemory::Memory[FLAGS_1];
426 return $f1 & IS_TIME_GAME;
427 }
428
429 # The I/O-heavy part of the "read" opcode
430 sub read_command {
431 my ($max_text_length, $time, $routine, $initial_buf) = @_;
432 # XXX can initial_buf affect read from script, too?
433 # Does game set initial buf or do we?!
434 my $version = $main::Constants{version};
435
436 # flush any buffered output (e.g. the '>') before the prompt.
437 PlotzPerl::Output::flush();
438
439 # Get commands from a script file? Returns undef if not
440 # currently reading from a file OR if that file ended
441 # (newline at end of command is NOT returned)
442 my ($s, $textref);
443 if (defined ($s = Language::Zcode::Runtime::Input::get_line_from_file())) {
444 $textref = new Language::Zcode::Runtime::Text::Input::File::Line $s;
445
446 } else { # read from keyboard
447 show_status() if $version <= 3;
448 # Restart the counter for [MORE] prompts. Note: do this only when
449 # reading from the screen, not from a file.
450 PlotzPerl::Output::reset_write_count();
451
452 $s = $zio->get_input($max_text_length, 0,
453 "-time" => $time,
454 "-routine" => $routine,
455 "-preloaded" => $initial_buf,
456 );
457 $textref = new Language::Zcode::Runtime::Text::Input::Screen::Line $s;
458 }
459 # Record command to transcript/command file(s)
460 $$textref .= chr Games::Rezrov::ZConst::Z_NEWLINE; # we chomped $s
461 PlotzPerl::Output->output($textref);
462 # printf STDERR "cmd: $s\n";
463
464 return $s;
465 }
466
467 =pod
468
469 # ascii
470 use constant LINEFEED => 10;
471
472 # Stolen from Games::Rezrov. I don't know what rezrov did with $zi arg.
473 # read a single character
474 # 10.7: only return characters defined in input stream
475 # 3.8: character "10" (linefeed) only defined for output.
476 sub read_char {
477 my ($useless, $time, $routine) = @_; #my ($argv, $zi) = @_;
478 PlotzPerl::Output::reset_write_count();
479 PlotzPerl::Output::flush();
480 die("read_char: 1st arg must be 1") unless $useless == 1;
481 my $result = screen_zio()->get_input(1, 1,
482 "-time" => $time,
483 "-routine" => $routine,
484 #"-zi" => $zi
485 );
486 # remap keyboard "linefeed" to what the Z-machine will recognize as a
487 # "carriage return". Required for startup form in "Bureaucracy"
488 # XXX - does keyboard ever return 13 (non-IBM-clones)?
489 # XXX can we just do s/\n/chr(Z_NEWLINE)/e?
490 my $code = ord(substr($result,0,1));
491 $code = Games::Rezrov::ZConst::Z_NEWLINE if ($code == LINEFEED);
492 return $code;
493 }
494
495 =cut
496
497 sub show_status {
498 # only called if needed; see spec 8.2
499 # Spec15 "show_status": In theory this opcode is illegal in later Versions
500 # but an interpreter should treat it as nop, because Version 5 Release 23
501 # of 'Wishbringer' contains this opcode by accident.)
502 return unless $main::Constants{version} <= 3;
503 return unless $zio->can_split();
504
505 # get the current location. (test for valid object id 8.2.2.1)
506 # XXX Move preliminary stuff to Language::Zcode::Runtime::Opcodes::show_status
507 # which calls this to do the IO?
508 my $room = Language::Zcode::Runtime::Opcodes::global_var(0);
509 my $loc = Language::Zcode::Runtime::Opcodes::thing_location($room, 'name');
510 my $room_name = defined $loc
511 ? Language::Zcode::Runtime::Opcodes::decode_text($loc)
512 : "[Unknown location]";
513 # die "loc = $room_name";
514
515 my $g1 = Language::Zcode::Runtime::Opcodes::global_var(1);
516 my $g2 = Language::Zcode::Runtime::Opcodes::global_var(2);
517 my $right_chunk;
518 if (&is_time_game()) {
519 my ($hours, $minutes) = ($g1, $g2);
520 my $m = $hours >= 12 ? "pm" : "am"; # 12:30 pm is lunchtime, not bedtime
521 if ($hours > 12) {
522 $hours -=12;
523 } elsif ($hours == 0) {
524 $hours = 12;
525 }
526 $right_chunk = "$hours:$minutes $m"
527 } else {
528 my $score = unpack('s', pack('s', $g1));
529 my $moves = $g2;
530 $right_chunk = "$score/$moves";
531 }
532
533 $zio->show_status($room_name, $right_chunk);
534 return;
535 }
536
537 # Write a newline to currently selected streams
538 # TODO Is this always PP::Text::Output("\n")?
539 sub newline { PlotzPerl::Output::newline(); }
540
541 # get the ZIO for the screen
542 sub screen_zio {
543 return $zio;
544 }
545
546 # write a given string to (0 or more streams of) output
547 sub write_text{PlotzPerl::Output->output(new Language::Zcode::Runtime::Text::Output shift)}
548
549 sub write_zchar { PlotzPerl::Output->write_zchar($_[0]); }
550
551 sub output_stream { PlotzPerl::Output::output_stream(@_); }
552
553 sub input_stream { Language::Zcode::Runtime::Input::input_stream($_[0]); }
554
555 sub clean_IO {
556 &Language::Zcode::Runtime::Input::cleanup();
557 &PlotzPerl::Output::cleanup();
558 }
559
560 ########################################
561 #
562 {
563
564 package PlotzPerl::Output;
565
566 =pod
567
568 This package handles (some) output from the game.
569
570 That output may go to various streams, one of which is the screen
571 (which includes windows et al.)
572
573 =cut
574
575 # 7.1.1
576 use constant STREAM_SCREEN => 1;
577 # transcript of user input and game output
578 use constant STREAM_TRANSCRIPT => 2;
579 # 7.1.2.1 - memory
580 use constant STREAM_MEMORY => 3;
581 # 7.1.2.3 - user input
582 use constant STREAM_USER_INPUT => 4;
583
584 # Mike Edmonson's extra stream for fancy stuff
585 # local: when redirecting screen output; when active send
586 # output here instead of to screen
587 #use constant STREAM_STEAL => 5;
588
589 my $Output; # singleton object handling this class
590
591 sub new {
592 my ($class, $zio) = @_;
593 my @streams;
594 # Create all streams, even if we don't end up using them.
595 $streams[STREAM_SCREEN] = new PlotzPerl::OutputStream::Screen "UI" => $zio;
596 $streams[STREAM_TRANSCRIPT] = new PlotzPerl::OutputStream::Transcript;
597 $streams[STREAM_MEMORY] = new PlotzPerl::OutputStream::Memory;
598 $streams[STREAM_USER_INPUT] = new PlotzPerl::OutputStream::UserInput;
599 my $self = {
600 streams => \@streams,
601 };
602 bless $self, $class;
603 return $self;
604 }
605
606 # array ref of currently selected streams
607 # Gets called at start but not restart
608 sub start_output {
609 my ($zio) = @_; # object that does UI for screen I/O
610 $Output = new PlotzPerl::Output $zio;
611 }
612
613 # Gets called at start AND restart
614 sub setup {
615 reset_write_count();
616 output_stream(STREAM_SCREEN);
617 }
618
619 sub get_streams {
620 my $self = shift;
621 # Don't return streams[0]
622 grep {ref} @{$self->{"streams"}};
623 }
624
625 sub get_stream {
626 my ($self, $str) = @_;
627 die "Bad args to get_stream" unless $#_ == 1;
628 # XXX late night hack - allow calling this sub w/ object or class
629 if (!ref $self) { $self = $Output; } # print "hi $self\n" }
630 my $ret = $self->{"streams"}[$str]
631 or die "Illegal arg '$str' to get_stream\n";
632 return $ret;
633 }
634
635 # Try writing to each stream. Each stream decides whether to output
636 # $text depending on whether that stream is selected, whether
637 # the current window echoes its text to that stream, and
638 # what kind of text $text is (e.g., input vs. output).
639 sub output {
640 my ($self, $text) = @_;
641 die "Output::output expects a self/class arg\n" unless defined $text;
642 # XXX call current_window in &output?
643 my $window = Language::Zcode::Runtime::IO::current_window();
644 # (Pass $window even to streams that don't really need it. Let them
645 # worry about whether they need it.)
646 # If we output to stream 3, don't output to any other stream.
647 $self->get_stream(STREAM_MEMORY)->output($text, $window) and return;
648
649 # Note: try writing to transcript before screen, because if someone
650 # sneakily modified the Z-machine transcript bit, then Transcript's
651 # output() needs to figure that out and prompt (on the screen!) for a
652 # transcript filename before printing the current $text to the screen.
653 $self->get_stream(STREAM_TRANSCRIPT)->output($text, $window);
654 $self->get_stream(STREAM_SCREEN)->output($text, $window);
655 $self->get_stream(STREAM_USER_INPUT)->output($text, $window);
656 }
657
658
659 # write a decoded z-char to selected output streams.
660 sub write_zchar {
661 my ($self, $char) = @_;
662 # 3.8.2.1: "null" has no effect on any output stream
663 return unless $char;
664
665 # TODO support ZSCII
666 my $trans = chr $char;
667
668 # TODO support graphics codes
669 =pod
670
671 if (($char >= 179 and $char <= 218) or
672 ($char >= 0x18 and $char <= 0x1b)) {
673 # sect16.html; convert IBM PC graphics codes
674 $trans = $Z_TRANSLATIONS{$char} || "*";
675 # print STDERR "trans for $char => $trans\n";
676 }
677
678 =cut
679
680 my $textref = new Language::Zcode::Runtime::Text::Output $trans;
681 $self->output($textref);
682 }
683
684 # Write to the screen's lower window whether or not
685 # stream 1 is currently selected.
686 # (Used for error messages, e.g.)
687 sub write_to_screen {
688 my ($self, $text) = @_;
689 my $window = Games::Rezrov::ZConst::LOWER_WIN;
690 # I.e., don't test whether it's selected or whatever else, just write to it
691 $self->get_stream(STREAM_SCREEN)->stream($text, $window);
692 }
693
694 sub newline { PlotzPerl::Output->write_zchar(Games::Rezrov::ZConst::Z_NEWLINE); }
695
696 sub register_newline { $Output->get_stream(STREAM_SCREEN)->register_newline }
697 sub reset_write_count { $Output->get_stream(STREAM_SCREEN)->reset_write_count }
698
699 =pod
700
701 wrote_something should only be set when doing stream 1? Also stream 2
702 will always be fixed font. In fact we will need to store x position
703 for stream 2 (but not y because we dont have to worry about scrolling)
704
705 =cut
706
707 # flush and format the characters buffered by the ZIO
708 sub flush {
709 my $screen = PlotzPerl::Output->get_stream(STREAM_SCREEN);
710 my $transcript = PlotzPerl::Output->get_stream(STREAM_TRANSCRIPT);
711 $_->flush for ($screen, $transcript);
712 }
713
714
715 #
716 # output streams
717 #
718
719 # select/deselect output streams. Spec 7
720 # XXX Handle selecting an already open stream, closing a closed one
721 sub output_stream {
722 # $str will be a signed number
723 my ($str, $table_start) = @_;
724
725 # selecting stream 0 does nothing
726 return if $str == 0;
727
728 # print STDERR "output_stream $str\n";
729 my $astr = abs($str);
730 my $selecting = $str > 0;
731
732 # XXX This is all we'll need in this sub!
733 my $stream = PlotzPerl::Output->get_stream($astr);
734 if ($selecting) {
735 # (Stream 3 needs table_start arg)
736 # Unset $selecting if we didn't successfully open file, e.g.
737 $selecting = $stream->select($table_start);
738 } else {
739 $stream->deselect();
740 }
741 }
742
743 # End of program cleanup
744 # XXX Eventually, the whole big "if" goes away
745 sub cleanup { $_->cleanup() for $Output->get_streams }
746
747 } # end package PlotzPerl::Output
748
749 ################################################################################
750 {
751
752 package PlotzPerl::OutputStream;
753
754 =head2 PlotzPerl::OutputStream
755
756 This class handles a single output stream, like the screen or a transcript
757 file.
758
759 =cut
760
761 @PlotzPerl::OutputStream::ISA = (); # No parents
762
763 sub new {
764 my ($class, %arg) = @_;
765 my $self = {};
766 bless $self, $class;
767 $self->init(%arg);
768 return $self;
769 }
770
771 sub init {
772 my ($self) = @_;
773 # I originally wanted to say "call all your parents' init()s
774 # and have this sub inherited. But it doesn't work. (Child classes
775 # can't loop over their own @ISA and call those classes' init()s.)
776 # Simplest solution is just to explicitly loop
777 # over each parent class' $self->parent::init sub in each class.
778 # foreach my $parent (@$name) {${parent}::init($self, %arg)}
779 # Or, even simpler, explicitly list the names of the parents & call
780 # their inits
781
782 # By default, don't select (but don't call deselect: it does more stuff)
783 $self->{"selected"} = 0;
784 }
785
786 sub is_selected { return shift->{"selected"} }
787
788 # Start writing to this stream
789 # XXX For all streams but 3, error to open when already open?
790 sub select { shift->{"selected"} = 1 }
791
792 # Stop writing to this stream
793 # (Use 0, not "", because for Transcript we need to set a bit to this value)
794 sub deselect { shift->{"selected"} = 0 }
795
796 # Is this OutputStream willing to accept the given text (in the given window)?
797 sub accept_stream { 1; }
798
799 # stream given text (in given window) to this stream, which may
800 # choose not to accept the stream for a number of reasons
801 # (e.g., the stream's not selected, or text in the given window
802 # isn't echoed to this stream)
803 sub output {
804 my ($self, $text, $window) = @_;
805 if ($self->is_selected() && $self->accept_stream($text, $window)) {
806 $self->stream($text, $window);
807 return 1;
808 } else {
809 return 0;
810 }
811 }
812
813 # Send given text (in given window) to this stream.
814 # Stream decides whether to buffer text or write it, and whether writing
815 # means writing to a file, screen, or memory.
816 # Subclasses will override this to do fancy buffering with newlines.
817 sub stream {
818 my ($self, $text, $window) = @_;
819 #my $nl = chr(Games::Rezrov::ZConst::Z_NEWLINE);
820 #$text =~ s/(.*?)($nl)?/something/g);
821 $self->write($text);
822 }
823
824 # End of program cleanup: make sure stream is deselected
825 sub cleanup {
826 my $self = shift;
827 $self->deselect if $self->is_selected();
828 }
829
830 } # end package PlotzPerl::OutputStream
831
832 #######################################
833
834 {
835
836 package PlotzPerl::OutputStream::File;
837
838 =head2 PlotzPerl::OutputStream::File
839
840 This abstract class handles output streams that write to files.
841
842 =cut
843 use vars qw(@ISA);
844 @ISA= qw(PlotzPerl::OutputStream);
845
846 sub init {
847 my ($self, %arg) = @_;
848 $self->PlotzPerl::OutputStream::init(%arg);
849 # Don't actually open the file yet
850 $self->filehandle(new IO::File);
851 $self->filename("");
852 return $self;
853 }
854
855 sub filename {
856 my ($self, $fn) = @_;
857 $self->{"filename"} = $fn if defined $fn;
858 return shift->{"filename"};
859 }
860
861 sub filehandle {
862 my ($self, $fh) = @_;
863 $self->{"filehandle"} = $fh if defined $fh;
864 return shift->{"filehandle"};
865 }
866
867 sub open {
868 my ($self) = @_;
869 my $fn = $self->filename() or die "No filename for stream\n";
870 # Should be IO::File object
871 my $fh = $self->filehandle() or die "No filehandle for stream\n";
872 if ($fh->open(">$fn")) {
873 return 1;
874 } else {
875 Language::Zcode::Runtime::IO::write_text("Can't open file $fn: $!\n");
876 return 0;
877 }
878 }
879
880 sub deselect {
881 my $self = shift;
882 if ($self->is_selected()) {
883 $self->SUPER::deselect;
884 my $fh = $self->filehandle();
885 $fh->close();
886 }
887 }
888
889 sub stream {
890 my ($self, $text, $window) = @_;
891 # warn "Streaming $$text\n";
892 # No need to buffer
893 $self->write($$text);
894 }
895
896 # Write a string: may have ZSCII newlines AND \n's.
897 sub write {
898 my ($self, $text) = @_;
899 my $nl = chr(Games::Rezrov::ZConst::Z_NEWLINE);
900 $text =~ s/$nl/\n/g;
901 $self->write_line($text);
902 }
903
904 # Write a string: guaranteed no ZSCII newlines
905 sub write_line {
906 my ($self, $text) = @_;
907 # warn "printing $text to file $self->filename\n";
908 my $fh = $self->filehandle()
909 or die "Can't find filehandle for file ",$self->filename,"\n";
910 print $fh $text;
911 }
912
913
914 # Print Perl newlines to files. Spec says output chr 13, but that's
915 # probably for the screen only.
916 sub newline {
917 # warn "printing newline to transcript\n";
918 shift->write_line("\n");
919 }
920
921 # End of program cleanup
922 # (Close on closed filehandle complains, but undef'ing it does close if nec.)
923 #sub cleanup { undef shift->{"filehandle"} }
924 # Just use parent's cleanup, which will call deselect
925
926 } # end package PlotzPerl::OutputStream::File
927
928 #######################################
929
930 {
931
932 package PlotzPerl::OutputStream::Buffered;
933
934 =head2 PlotzPerl::OutputStream::Buffered
935
936 This abstract class handles output streams that write buffered
937 (word-wrapped) output. We handle this by buffering output instead of
938 writing it, and whenever we flush, we replace spaces near the edge of
939 the current line with newlines.
940
941 =cut
942
943 use vars qw(@ISA);
944 @ISA = qw(PlotzPerl::OutputStream);
945
946 sub init {
947 my ($self, %arg) = @_;
948 $self->PlotzPerl::OutputStream::init(%arg);
949 $self->clear_buffer();
950 # 7.2.1: buffering is always on for v1-3, on by default for v4+.
951 $self->buffering(1);
952 $self->x_pos(0);
953 return $self;
954 }
955
956
957 sub x_pos {
958 my ($self, $x_pos) = @_;
959 $self->{"x_pos"} = $x_pos if defined $x_pos;
960 return shift->{"x_pos"};
961 }
962
963 sub buffer {
964 my ($self, $buffer) = @_;
965 $self->{"buffer"} = $buffer if defined $buffer;
966 return shift->{"buffer"};
967 }
968 sub clear_buffer { shift->{"buffer"} = "" }
969
970 sub add_to_buffer {
971 my ($self, $str) = @_;
972 my $buffer = $self->buffer();
973 $buffer .= $str;
974 # Put in actual buffer
975 $self->buffer($buffer);
976 # Word-wrap buffer and flush it if necessary
977 $self->maybe_flush();
978
979 }
980
981 =pod
982
983 Note that changing screen size, font changes the number of chars needed to
984 finish the line so I need to call maybe_flush (which flushes only if nec.)
985 from add_to_buffer as well as any time I change one of the above.
986
987 I need to call flush for sure any time I switch windows OR from, e.g.,
988 filename_prompt or read_command, where I want to make sure the user sees
989 something so that they can input. (Just call it from get_input instead?)
990 I shouldn't need to call word_wrap, tho, cuz anything that went into
991 buffer should already be wrapped.
992
993 =cut
994
995 # whether text buffering is active
996 sub buffering {
997 # XXX If they turn off buffer, do we flush it?
998 my ($self, $val) = @_;
999 if (defined $val) { $self->{"buffering"} = $val }
1000 $self->{"buffering"};
1001 # die "buffer _[1]\n";
1002 }
1003
1004 # Send a string to this stream. Buffer and/or write it.
1005 sub stream {
1006 my ($self, $text, $window) = @_;
1007 # warn "Streaming $$text\n";
1008 if ($self->buffering() && $window != Games::Rezrov::ZConst::UPPER_WIN) {
1009 # XXX v6: && $window->buffering
1010 # Add the string to the buffer, possibly causing a buffer flush
1011 $self->add_to_buffer($$text);
1012 } else { # just write whatever string we have
1013 $self->write($$text, $window);
1014 }
1015 }
1016
1017 # Write the given string to the stream. May have ZSCII newlines in it
1018 sub write {
1019 my ($self, $str) = @_;
1020 # Print one line at a time
1021 # (split() behaves too strangely with empty pre/post fields to use here)
1022 my $nl = chr(Games::Rezrov::ZConst::Z_NEWLINE);
1023 while ($str =~ s/(.*?)$nl//) {
1024 $self->write_line($1);
1025 $self->newline();
1026 }
1027 $self->write_line($str);
1028
1029 # XXX Added by ADK, not tested. Breaks transcript.
1030 Language::Zcode::Runtime::IO::prompt_buffer($str);
1031 # Add string to current position (which might be non-zero if no \n's
1032 # in this string).
1033 $self->x_pos($self->x_pos + length $str);
1034 }
1035
1036 # No "write_line" method here, because different buffered streams will
1037 # write differently (to file/screen, e.g.)
1038
1039 # Word-wrap buffer. If there's any NEWLINEs in it (before or because
1040 # of word-wrap) then flush it.
1041 # Wrapping depends on current screen size, window, etc. So we need to
1042 # call maybe_flush to re-wrap any time one of those things changes.
1043 #my $z = new IO::File('>zzz.txt');
1044 sub maybe_flush {
1045 my $self = shift;
1046 my $buffer = $self->buffer;
1047 my $cw = &Language::Zcode::Runtime::IO::current_window;
1048 my $nl = chr(Games::Rezrov::ZConst::Z_NEWLINE);
1049 # Word-wrap each line (including anything after last NEWLINE)
1050 # Add NEWLINE if string (plus anything already printed, for first line!)
1051 # is too long
1052 $buffer =~ s/(.*?)(?=$nl|$)/$self->word_wrap($1, $cw)/ge;
1053
1054 # Flush all finished lines (if any) out of the buffer
1055 if ($buffer =~ s/(.*$nl)//) {
1056 my $to_flush = $1;
1057 # XXX if there's newlines in here, change to \n and call
1058 # $zio->register_newlines. Are we doing that?
1059 $self->write($to_flush);
1060 }
1061 # Put any remaining string back in the buffer
1062 $self->buffer($buffer);
1063 }
1064
1065 # XXX Move $flushing check to maybe_flush?
1066 # Flush this stream's buffer, wordwrap
1067 my $flushing; # Needs to be object-specific?
1068 sub flush {
1069 # this can happen w/combinations of attributes and pausing
1070 return if $flushing;
1071 my $self = shift;
1072 my $buffer = $self->buffer();
1073 # printf STDERR "flush: buffer= ->%s<-\n", $buffer;
1074 $self->clear_buffer();
1075 # In theory, if this stream isn't selected, $buffer will be empty.
1076 # But check just in case.
1077 return unless length $buffer && $self->is_selected();
1078
1079 # print "fs\n";
1080 $flushing = 1;
1081 my $current_window = &Language::Zcode::Runtime::IO::current_window;
1082 # print out the string in a word-wrapped fashion
1083 $self->write($self->word_wrap($buffer, $current_window));
1084 $flushing = 0;
1085 # print "done flushing\n";
1086 }
1087
1088 # Word-wrap a string, adding newlines when we get to line's end,
1089 # knowing we're in fixed font
1090 sub fixed_word_wrap {
1091 my ($self, $str, $window) = @_;
1092
1093 my $x;
1094 if ($self->isa("PlotzPerl::OutputStream::Screen")) {
1095 # XXX change this to $self->x_pos once it's working
1096 my $zio = $self->UI or die "No UI found in fixed_word_wrap";
1097 ($x) = $zio->get_position(); # discard $y
1098 # (my$q=$str)=~s/\cM/\n/g;print("buffer is '$q' at pos $x\n");
1099 } else { # transcript
1100 $x = $self->x_pos();
1101 }
1102 # Get start column position; we can't be sure we're starting at
1103 # column 0. This is an issue when flush() is called when changing
1104 # attributes. Example: "bureaucracy" intro paragraphs ("But
1105 # Happitec is going to be _much_ more fun...")
1106 # XXX columns() shouldn't be used for the transcript
1107 my $have_left = (Language::Zcode::Runtime::IO::columns() - $x);
1108
1109 # We may go through this loop several times, once per line of output
1110 my $build_string = "";
1111 my $nl = chr(Games::Rezrov::ZConst::Z_NEWLINE);
1112 while (my $len = length($str)) {
1113 # No need to put in more newlines
1114 if ($len < $have_left) {
1115 last;
1116
1117 # Go up to space (or last column), then NEWLINE
1118 } else {
1119 # Space before the end of the line?
1120 # XXX Are we supposed to wordwrap on periods too? In games,
1121 # it shouldn't matter, cuz there's always a space after a period.
1122 # Spec 7.2 just says "new-lines are automatically printed to ensure
1123 # that no word (of length less than the width of the screen)
1124 # spreads across two lines." Hm. Define 'word'.
1125 my $first_space = rindex($str, " ", $have_left-1);
1126
1127 # watch out for spaceless string > number of columns left
1128 # In that case, do the best we can and force a newline
1129 my $print_size = $first_space == -1 ? $have_left - 1 : $first_space;
1130 # Remove first N characters from string,
1131 # add them to string we're building, plus a NEWLINE
1132 my $s = substr($str, 0, $print_size, "") . $nl;
1133 $str =~ s/^ //;
1134 $build_string .= $s;
1135 # printf STDERR "wrapping: %d, %d, %s x:$x y:$y col:$columns\n",
1136 # length $str, $have_left, $str;
1137 $have_left = Language::Zcode::Runtime::IO::columns(); # for next run through loop
1138 }
1139 }
1140
1141 $build_string .= $str; # add on whatever's left
1142 return $build_string;
1143 }
1144
1145 # Reset X x_pos
1146 sub newline { shift->x_pos(0) }
1147
1148 sub deselect {
1149 my $self = shift;
1150 $self->flush;
1151 $self->SUPER::deselect();
1152 }
1153
1154 } # end package PlotzPerl::OutputStream::Buffered
1155
1156 #######################################
1157
1158 {
1159
1160 package PlotzPerl::OutputStream::Screen;
1161
1162 =head2 PlotzPerl::OutputStream::Screen
1163
1164 This class handles the screen output stream.
1165
1166 =cut
1167
1168 use vars qw(@ISA);
1169 @ISA = qw(PlotzPerl::OutputStream::Buffered);
1170 use File::Basename;
1171
1172 sub init {
1173 my ($self, %arg) = @_;
1174 $self->PlotzPerl::OutputStream::Buffered::init(%arg);
1175 # actual UI screen object
1176 my $zio = $arg{"UI"};
1177 die "Need UI object to create a ", ref $self,"object\n"
1178 unless ref($zio)&& $zio->isa("Games::Rezrov::ZIO_Generic");
1179 $self->{"UI"} = $zio;
1180 $self->reset_write_count(); # didn't write anything yet
1181 my $gamename = basename($0);
1182 $zio->set_game_title("Plotz - $gamename");
1183
1184 return $self;
1185 }
1186
1187 sub UI { shift->{"UI"} }
1188
1189 sub reset_write_count {
1190 my $self = shift;
1191 $self->lines_wrote(0);
1192 $self->wrote_something(0);
1193 }
1194
1195 sub lines_wrote {
1196 my ($self, $val) = @_;
1197 $self->{"lines_wrote"} = $val if (defined $val);
1198 $self->{"lines_wrote"};
1199 }
1200
1201 sub wrote_something {
1202 my ($self, $val) = @_;
1203 $self->{"wrote_something"} = $val if (defined $val);
1204 $self->{"wrote_something"};
1205 }
1206
1207 # Note: select and deselect subs don't DO anything, except set the
1208 # "selected" attribute, so just inherit the parent class version of the subs
1209
1210 sub accept_stream {
1211 my ($self, $text, $window) = @_;
1212 !$text->isa("Language::Zcode::Runtime::Text::Input::Keypress") && # read_char doesn't echo
1213 !$text->isa("Language::Zcode::Runtime::Text::Input::Screen"); # Already echoed to screen
1214 }
1215
1216 sub newline {
1217 my ($self) = @_; # don't need $window
1218 $self->SUPER::newline(); # reset X cursor in $self
1219 my $screen = $self->UI(); # Tk, Win32, etc. Screen object
1220 Language::Zcode::Runtime::IO::prompt_buffer("");
1221 $screen->newline;
1222 }
1223
1224 # Write given string (which has no ZSCII newlines) to the stream
1225 sub write_line {
1226 my ($self, $str) = @_;
1227 my $screen = $self->UI(); # Tk, Win32, etc. Screen object
1228 $screen->write_string($str);
1229 }
1230
1231 # Print [MORE] if we've written a whole page
1232 # Stream 1 is the only stream that does "y-buffering"
1233 # XXX BUG!
1234 # XXX Spec 10.2.4: When the the current stream is stream 1, the interpreter
1235 # should not hold up long passages of text (by printing "[MORE]" and waiting
1236 # for a keypress, for instance). input_stream(1) should call
1237 # PlotzPerl::Output::no_y_buffering, which should set something that
1238 # this checks. Actually, frotz ASKS if you want [MORE]s. Maybe do that
1239 # with a -M option or something. Even if we are printing [MORE]s, we should
1240 # still not reset_write_count whenever we do a @read from a file.
1241 # 8.4.1: screen height of 255 means never print [MORE]
1242 sub register_newline {
1243 my $self = shift;
1244 my $lower_lines = $Language::Zcode::Runtime::IO::lower_lines;
1245 # print "rn1 $wrote_something $current_window $lower_lines\n";
1246 # print " rn1 $lower_lines ";
1247 return unless (Language::Zcode::Runtime::IO::rows() != 255 &&
1248 $self->wrote_something() &&
1249 # don't count newlines that occur before any text;
1250 # example: start of "plundered hearts", after initial RETURN
1251 defined(&Language::Zcode::Runtime::IO::current_window) &&
1252 $lower_lines &&
1253 $current_window == Games::Rezrov::ZConst::LOWER_WIN
1254 );
1255 my $wrote = $self->lines_wrote() + 1;
1256 # print " rn2 $wrote ";
1257 # printf STDERR "rn: %d/%d\n", $wrote, $lower_lines;
1258
1259 if ($wrote + 1 >= $lower_lines - 1) {
1260 # need to pause; show prompt.
1261 # print STDERR "pausing...\n";
1262 # XXX more_prompt really does NOT belong in ZIO package.
1263 # Move it back to this package (once I'm handling cursor &
1264 # some more stuff in OutputStream::Screen package).
1265 $self->UI->more_prompt($lower_lines);
1266 $wrote = 0;
1267 }
1268 $self->lines_wrote($wrote);
1269 }
1270
1271 sub word_wrap {
1272 my ($self, $str, $window) = @_;
1273 my $ret = "";
1274 $self->wrote_something(1); # XXX shouldn't be in word_wrap? Put in write()?
1275 my $zio = $self->UI;
1276
1277 my ($i, $have_left, $len);
1278 if ($window != Games::Rezrov::ZConst::LOWER_WIN) {
1279 # buffering in upper window: nonstandard hack in effect.
1280 # assume we know what we're doing :)
1281 # print STDERR "hack! \"$buffer\"\n";
1282 #$zio->write_string($str);
1283 $ret = $str;
1284
1285 # Only stream 1 can print in variable font
1286 # XXX Does this test font_mask too?
1287 } elsif (!$zio->fixed_font_default()) {
1288 die "Not yet handling variable font\n";
1289
1290 =pod
1291
1292 Need to change this to just add newlines, not actually print!
1293 #
1294 # Variable font; graphical wrapping
1295 #
1296 my ($x, $y) = $zio->get_pixel_position();
1297 my $total_width = ($zio->get_pixel_geometry())[0];
1298 my $pixels_left = $total_width - $x;
1299 my $plen;
1300 while ($len = length($str)) {
1301 $plen = $zio->string_width($str);
1302 if ($plen < $pixels_left) {
1303 # it'll fit; we're done
1304 # print STDERR "fits: $str\n";
1305 Add $str to $ret
1306 $zio->write_string($str);
1307 last;
1308 } else {
1309 my $wrapped = 0;
1310 my $i = int(length($str) * ($pixels_left / $plen));
1311 # print STDERR "pl=$pixels_left, plen=$plen i=$i\n";
1312 # Do this with rindex
1313 while (substr($str,$i,1) ne " ") {
1314 # move ahead to a word boundary
1315 # print STDERR "boundarizing\n";
1316 last if ++$i >= $len;
1317 }
1318
1319 while (1) {
1320 $plen = $zio->string_width(substr($str,0,$i));
1321 # printf STDERR "%s = %s\n", substr($str,0,$i), $plen;
1322 if ($plen < $pixels_left) {
1323 # it'll fit
1324 Change this to add to $ret
1325 $zio->write_string(substr($str,0,$i));
1326 $zio->newline();
1327 $str = substr($str, $i + 1);
1328 $wrapped = 1;
1329 last;
1330 } else {
1331 # retreat back a word
1332 while (--$i >= 0 and substr($str,$i,1) ne " ") { }
1333 last if ($i < 0);
1334 }
1335 }
1336
1337 $zio->newline() unless ($wrapped);
1338 # if couldn't wrap at all on this line
1339 $pixels_left = $total_width;
1340 }
1341 }
1342
1343 =cut
1344
1345 } else {
1346 #
1347 # Fixed font; do line/column wrapping
1348 $ret = $self->fixed_word_wrap($str, $window);
1349 }
1350 Language::Zcode::Runtime::IO::prompt_buffer($ret);
1351 return $ret;
1352 }
1353
1354 # End of program cleanup
1355 sub cleanup {
1356 my $self = shift;
1357 # First flush buffer. Then cleanup the GUI
1358 $self->PlotzPerl::OutputStream::Buffered::cleanup();
1359 $self->UI->cleanup();
1360 }
1361
1362 } # end package PlotzPerl::OutputStream::Screen
1363
1364 #######################################
1365
1366 {
1367
1368 package PlotzPerl::OutputStream::Transcript;
1369
1370 =head2 PlotzPerl::OutputStream::Transcript
1371
1372 This class handles the output stream that stores the
1373 user's commands (to @read) as well as the game's screen output.
1374
1375 =cut
1376
1377 use vars qw(@ISA);
1378 @ISA = qw(PlotzPerl::OutputStream::Buffered PlotzPerl::OutputStream::File);
1379
1380 sub init {
1381 my ($self, %arg) = @_;
1382 $self->PlotzPerl::OutputStream::Buffered::init(%arg);
1383 $self->PlotzPerl::OutputStream::File::init(%arg);
1384 return $self;
1385 }
1386
1387 # Either always look at Flags1 before trying to write to transcript,
1388 # or change set_word_at to check if we are setting Flags1.
1389 #Former seems a *bit* less messy. Especially because we sometimes
1390 #set using direct access to $PlotzMemory::Memory
1391
1392 # Anytime you're trying to figure out if transcript is selected
1393 # also check/update transcript bit of Flags2
1394 # If someone sets the bit explicitly, then the transcript won't turn on
1395 # right away, BUT we're guaranteed that this sub will be called any time
1396 # a person is thinking of writing to the transcript file, so as soon as it's
1397 # important for them to be in synch, we'll synch them.
1398 #
1399 # One problem: If we call select() here, then when we prompt for a filename,
1400 # system will try to print that prompt string to the transcript, which will
1401 # call this sub, and since ->{"selected"} hasn't changed yet (and shouldn't
1402 # change until we're sure the file exists) it'll recurse. HACK around it.
1403 my $beware_recursion = "";
1404 sub is_selected {
1405 my $self = shift;
1406 my $is_selected = $self->SUPER::is_selected();
1407 my $mem = PlotzMemory::get_word_at(Language::Zcode::Runtime::IO::FLAGS_2); # memory says should be on
1408 # If FLAGS2 and selected are inconsistent, then the interpreter
1409 # set/unset FLAGS2 behind our back, so select or deselect the stream
1410 my $mem_on = $mem & Language::Zcode::Runtime::IO::TRANSCRIPT_ON;
1411 if ($mem_on != $is_selected && !$beware_recursion) {
1412 $beware_recursion = 1; # this is the case that can cause it
1413 $mem_on ? $self->select() : $self->deselect();
1414 $is_selected = $mem_on;
1415 $beware_recursion = ""; # don't worry anymore
1416 }
1417 return $is_selected;
1418 }
1419
1420 sub select {
1421 my $self = shift;
1422 my $success = 1;
1423 # print STDERR "opening transcript\n";
1424 # 7.1.1.2: only ask once per session
1425 my $filename = $self->filename();
1426 if (!$filename) {
1427 $filename = Language::Zcode::Runtime::IO::filename_prompt("-check"=>1, "-ext"=>"txt");
1428 $self->filename($filename);
1429 }
1430 if ($filename && $self->open()) {
1431 my $fh = $self->filehandle();
1432 # Only write this to screen?
1433 Language::Zcode::Runtime::IO::write_text("Writing transcript to $filename.");
1434
1435 $self->SUPER::select();
1436 # Update FLAGS2 any time interpreter selects
1437 my $mem = PlotzMemory::get_word_at(Language::Zcode::Runtime::IO::FLAGS_2);
1438 PlotzMemory::set_word_at(Language::Zcode::Runtime::IO::FLAGS_2,
1439 $mem | Language::Zcode::Runtime::IO::TRANSCRIPT_ON);
1440
1441 } else {
1442 # I.e., write newline to screen etc., not just to transcript
1443 PlotzPerl::Output::newline();
1444 $success = 0;
1445 }
1446 PlotzPerl::Output::newline();
1447 PlotzPerl::Output::newline();
1448 return $success;
1449 }
1450
1451 sub deselect {
1452 my $self = shift;
1453 # Update FLAGS2 any time interpreter deselects
1454 # Do this BEFORE SUPER::select. Otherwise, tests for is_selected
1455 # in base classes cause us to think transcript bit is on, and
1456 # this stream gets re-selected!
1457 my $mem = PlotzMemory::get_word_at(Language::Zcode::Runtime::IO::FLAGS_2);
1458 PlotzMemory::set_word_at(Language::Zcode::Runtime::IO::FLAGS_2,
1459 $mem & ~Language::Zcode::Runtime::IO::TRANSCRIPT_ON);
1460
1461 # flush buffer
1462 $self->PlotzPerl::OutputStream::Buffered::deselect();
1463 # Close file
1464 $self->PlotzPerl::OutputStream::File::deselect();
1465 }
1466
1467 # Stream 2 doesn't write text from upper window OR keypresses
1468 sub accept_stream {
1469 my ($self, $text, $window) = @_;
1470 # Better to use: #$window->echo_to_transcript() ??
1471 #or maybe: $window->echo(STREAM_TRANSCRIPT)
1472 return $window != Games::Rezrov::ZConst::UPPER_WIN &&
1473 !$text->isa("Language::Zcode::Runtime::Text::Input::Keypress");
1474 }
1475
1476 # Use Buffered::stream, not File::stream
1477 sub stream {
1478 my $self = shift;
1479 $self->PlotzPerl::OutputStream::Buffered::stream(@_);
1480 }
1481
1482 sub word_wrap {
1483 my ($self, $str, $window) = @_;
1484 return $self->fixed_word_wrap($str, $window);
1485 }
1486
1487 # XXX There's probably a cleaner way to do this than dictating which
1488 # base class to use for each sub!
1489 sub write { shift->PlotzPerl::OutputStream::Buffered::write(@_) }
1490
1491 sub newline {
1492 my ($self) = @_; # don't need $window
1493 $self->PlotzPerl::OutputStream::Buffered::newline(); # reset position
1494 $self->PlotzPerl::OutputStream::File::newline(); # write \n to file
1495 }
1496
1497 # End of program cleanup
1498 sub cleanup {
1499 my $self = shift;
1500 # FIRST flush buffer, THEN close filehandle
1501 $self->PlotzPerl::OutputStream::Buffered::cleanup();
1502 $self->PlotzPerl::OutputStream::File::cleanup();
1503 }
1504
1505 } # end package PlotzPerl::OutputStream::Transcript
1506
1507 #######################################
1508
1509 {
1510
1511 package PlotzPerl::OutputStream::Memory;
1512
1513 =head2 PlotzPerl::OutputStream::Memory
1514
1515 This class handles the output stream that stores game output to memory.
1516
1517 =cut
1518
1519 @PlotzPerl::OutputStream::Memory::ISA= qw(PlotzPerl::OutputStream);
1520
1521 sub init {
1522 my ($self, %arg) = @_;
1523 $self->SUPER::init(%arg);
1524 $self->{"streams"} = [];
1525 return $self;
1526 }
1527
1528 sub new_buffer {
1529 my ($self, $table_start) = @_;
1530 my $buf = new PlotzPerl::OutputStream::Table $table_start;
1531 push @{$self->{"streams"}}, $buf;
1532 # XXX ADK steal code from GR::ZReceiver so table stream works like file
1533 # my $buf = new Games::Rezrov::ZReceiver();
1534
1535 # 7.1.2.1.1: max 16 legal redirects
1536 die "illegal number of stream3 opens!" if @{$self->{"streams"}} > 16;
1537 }
1538
1539 sub select {
1540 my ($self, $table_start) = @_;
1541 die "Not supporting redirect stream yet\n";
1542
1543 $self->new_buffer($table_start);
1544 return 1;
1545 }
1546
1547 # deselecting: copy table to memory
1548 sub deselect {
1549 my $self = shift;
1550 die "Not yet supporting stream 3\n";
1551 # XXX BUG Newlines are written to output stream 3 as ZSCII 13. 7.1.2.2.1
1552
1553 my $stack;
1554 my $buf = pop @{$stack};
1555 my $table_start = $buf->misc();
1556 my $pointer = $table_start + 2;
1557 my $buffer = $buf->buffer();
1558 # printf STDERR "Writing redirected chunk %s to %d\n", $buffer, $pointer;
1559 set_byte_at($pointer++, ord) for split //, $buffer;
1560 #for (my $i=0; $i < length($buffer); $i++) {
1561 # set_byte_at($pointer++, ord substr($buffer,$i,1));
1562 #}
1563 # record number of bytes written
1564 set_word_at($table_start, ($pointer - $table_start - 2));
1565
1566 if (!@{$stack}) { # no streams left
1567 $self->SUPER::deselect();
1568 }
1569
1570 if ($main::Constants{version} == 6) {
1571 # 7.1.2.1
1572 fatal_error("stream 3 close under v6, needs a-fixin");
1573 }
1574
1575 }
1576
1577 # Stream 3 doesn't store anything the user input, only game output
1578 sub accept_stream {
1579 my ($self, $text) = @_;
1580 !$text->isa("Language::Zcode::Runtime::Text::Input");
1581 }
1582
1583 sub stream {
1584 # my $stack = $zios->[STREAM_MEMORY];
1585 # printf STDERR "redirected chunk: %s\n", $$text;
1586 # $stack->[$#$stack]->buffer_zchunk($text);
1587 }
1588
1589 sub write {
1590 die "OutputStream::Memory::write not yet implemented\n";
1591 # write chars to memory
1592 }
1593
1594 } # end package PlotzPerl::OutputStream::Memory
1595
1596 #######################################
1597
1598 {
1599
1600 package PlotzPerl::OutputStream::UserInput;
1601
1602 =head2 PlotzPerl::OutputStream::UserInput
1603
1604 This class handles the output stream that stores the
1605 user's commands (to @read) as well as the game's screen output.
1606
1607 =cut
1608
1609 @PlotzPerl::OutputStream::UserInput::ISA= qw(PlotzPerl::OutputStream::File);
1610
1611 # No init sub here
1612
1613 sub select {
1614 my $self = shift;
1615 my $success = 1;
1616 my $filename = Language::Zcode::Runtime::IO::filename_prompt("-ext"=>"cmd", "-check" => 1);
1617 if ($filename) {
1618 $self->filename($filename);
1619 if ($self->open()) {
1620 Language::Zcode::Runtime::IO::write_text("Recording commands to $filename.");
1621 $self->SUPER::select();
1622 } else {
1623 Language::Zcode::Runtime::IO::write_text("Can't write to $filename: $!");
1624 $success = 0;
1625 }
1626 } else {
1627 $success = 0;
1628 }
1629 PlotzPerl::Output::newline();
1630 PlotzPerl::Output::newline();
1631 return $success;
1632 }
1633
1634 sub deselect {
1635 my $self = shift;
1636 if ($self->is_selected()) {
1637 $self->SUPER::deselect();
1638 Language::Zcode::Runtime::IO::write_text("Command recording stopped.");
1639 } else {
1640 Language::Zcode::Runtime::IO::write_text("Um, I'm not recording commands now.");
1641 }
1642 PlotzPerl::Output::newline();
1643 PlotzPerl::Output::newline();
1644 }
1645
1646 # Stream 4 prints ALL user input - including @read and @read_char -
1647 # whether from a file or the screen
1648 sub accept_stream { $_[1]->isa("Language::Zcode::Runtime::Text::Input") }
1649
1650 # cleanup: Just do OS::File->cleanup
1651
1652 } # end package PlotzPerl::OutputStream::UserInput
1653
1654 ################################################################################
1655
1656
1657
1658 # Tools for streams
1659 sub filename_prompt {
1660 my (%options) = @_;
1661
1662 my $ext = $options{"-ext"} || die "No extension given to filename_prompt";
1663 my $default;
1664 $default = $options{"-default"} or ($default = $0) =~ s/(\b\..*|)$/.$ext/;
1665
1666 my $zio = screen_zio();
1667 PlotzPerl::Output::flush(); # print leftover buffered stuff before prompting
1668 newline();
1669 my $prompt = "Filename [$default]: ";
1670 # XXX write this to any open streams
1671 $zio->write_string($prompt);
1672 $prompt_buffer = $prompt;
1673 # write_text(sprintf "Filename [%s]: ", $default);
1674 my $filename = $zio->get_input(50, 0) || $default;
1675 if ($filename) {
1676 if ($options{"-check"} and -f $filename) {
1677 $zio->write_string($filename . " exists, overwrite? [y/n]: ");
1678 my $proceed = $zio->get_input(1, 1);
1679 if ($proceed =~ /^y/i) {
1680 # XXX Should this be a special kind of text that doesn't
1681 # get echoed to transcript?
1682 write_text("Yes.");
1683 # In theory, don't need to do this. open ">" will overwrite.
1684 unlink($filename);
1685 } else {
1686 write_text("No.");
1687 $filename = "";
1688 }
1689 newline();
1690 }
1691 }
1692
1693 return $filename;
1694 }
1695
1696 ########################################
1697 #
1698 # Cursor
1699 #
1700 # XXX ADK Need to check out font_mask, set_cursor, set_text_style,
1701 # erase_window, set_window
1702 sub set_cursor {
1703 my ($line, $column, $win) = @_;
1704 my $zio = screen_zio();
1705 $zio->fatal_error("set_cursor on window $win not supported") if $win;
1706
1707 $line--;
1708 $column--;
1709 # given starting at 1, not 0
1710
1711 # print STDERR "set_cursor\n";
1712 if ($current_window == Games::Rezrov::ZConst::UPPER_WIN) {
1713 # upper window: use offsets as specified
1714 $zio->absolute_move($column, $line);
1715 } else {
1716 # XXX Huh? Spec 8.7.2.3: "The opcode has no effect when the lower
1717 # window is selected." Maybe we need to have a z_set_cursor,
1718 # which does nothing if in lower window, but calls this if in
1719 # upper window - because we need to call set_cursor from
1720 # inside the program when we do things like erase the screen.
1721 # lower window: map coordinates given upper window size
1722 $zio->absolute_move($column, $line + $upper_lines);
1723 }
1724 }
1725
1726 sub get_cursor {
1727 # put cursor coordinates at given offset
1728 untested();
1729 my ($x, $y) = screen_zio()->get_position();
1730 PlotzMemory::set_word_at($_[0], $y);
1731 PlotzMemory::set_word_at($_[1], $x);
1732 }
1733
1734 ########################################
1735 #
1736 # Fonts
1737 #
1738 my $fm;
1739 my $fm2;
1740 sub font_mask {
1741 $fm = $_[0] if defined $_[0];
1742 my $fm2 = $fm || 0;
1743 $fm2 |= Games::Rezrov::ZConst::STYLE_FIXED
1744 if $current_window == Games::Rezrov::ZConst::UPPER_WIN;
1745 # 8.7.2.4:
1746 # An interpreter should use a fixed-pitch font when printing on the
1747 # upper window.
1748
1749 =pod
1750 if (0 and $header and $header->fixed_font_forced()) {
1751 # 8.1: game forcing use of fixed-width font
1752 # DISABLED: something seems to be wrong here...
1753 # photopia (all v5 games?) turn on this bit after 1 move?
1754 $fm2 |= Games::Rezrov::ZConst::STYLE_FIXED;
1755 }
1756 =cut
1757
1758 return $fm2;
1759 }
1760
1761 sub set_text_style {
1762 my $text_style = $_[0];
1763 PlotzPerl::Output::flush();
1764 my $mask = font_mask();
1765 if ($text_style == Games::Rezrov::ZConst::STYLE_ROMAN) {
1766 # turn off all
1767 $mask = 0;
1768 } else {
1769 $mask |= $text_style;
1770 }
1771 $mask = font_mask($mask);
1772 # might be modified for upper window
1773
1774 screen_zio()->set_text_style($mask);
1775 }
1776
1777 ########################################
1778 #
1779 # Windows
1780 #
1781 sub split_window {
1782 my ($lines) = @_;
1783 my $zio = screen_zio();
1784
1785 $upper_lines = $lines;
1786 $lower_lines = rows() - $lines;
1787 # print STDERR "split_window to $lines, ll=$lower_lines ul=$upper_lines\n";
1788
1789 my ($x, $y) = $zio->get_position();
1790 if ($y < $upper_lines) {
1791 # 8.7.2.2
1792 $zio->absolute_move($x, $upper_lines);
1793 }
1794 screen_zio()->split_window($lines);
1795 # any local housekeeping
1796 }
1797
1798 sub set_window {
1799 my ($window) = @_;
1800 my $version = $main::Constants{version};
1801 my $rows = rows();
1802 # print STDERR "set_window $window\n";
1803 PlotzPerl::Output::flush();
1804 my $zio = screen_zio();
1805
1806 $window_cursors->[$current_window] = $zio->get_position(1);
1807 # save callback to restore cursor position when we return to
1808 # this window
1809
1810 $current_window = $window;
1811 # set current window
1812
1813 if ($version >= 4) {
1814 if ($current_window == Games::Rezrov::ZConst::UPPER_WIN) {
1815 # 8.7.2: whenever upper window selected, cursor goes to top left
1816 set_cursor(1,1);
1817 } else {
1818 # restore old cursor position
1819 my $restore;
1820 if (defined $window_cursors->[$current_window]) {
1821 # restore former cursor position
1822 &{$window_cursors->[$current_window]};
1823 } else {
1824 # first switch to window
1825 # 8.7.2.2: in v4 lower window cursor is always on last line.
1826 $zio->absolute_move(0, $rows - 1);
1827 }
1828 }
1829
1830 } else {
1831 # in v3, cursor always in lower left
1832 $zio->absolute_move(0, $rows - 1);
1833 }
1834
1835 # for any local housekeeping
1836 $zio->set_window($window);
1837 # since we always print in fixed font in the upper window,
1838 # make sure the zio gets a chance to turn this on/off as we enter/leave;
1839 # example: photopia.
1840 $zio->set_text_style(font_mask());
1841 }
1842
1843 sub erase_window {
1844 # $window will be signed
1845 my ($window) = @_;
1846 my $zio = screen_zio();
1847 my $version = $main::Constants{version};
1848 my $rows = rows();
1849 if ($window == -1) {
1850 # 8.7.3.3:
1851 # $self->split_window(Games::Rezrov::ZConst::UPPER_WIN, 0);
1852 # WRONG!
1853 split_window(0);
1854 # collapse upper window to size 0
1855 clear_screen();
1856 # erase the entire screen
1857 PlotzPerl::Output::reset_write_count();
1858 set_window(Games::Rezrov::ZConst::LOWER_WIN);
1859 set_cursor(($version == 4 ? $rows : 1), 1);
1860 # move cursor to the appropriate line for this version;
1861 # hack: at least it\'s abstracted :)
1862 } elsif ($window < 0 or $window > 1) {
1863 $zio->fatal_error("erase_window $window !");
1864
1865 } else {
1866 #
1867 # erase specified window
1868 #
1869 my $restore = $zio->get_position(1);
1870 my ($start, $end);
1871 if ($window == Games::Rezrov::ZConst::UPPER_WIN) {
1872 $start = 0;
1873 $end = $upper_lines;
1874 } elsif ($window == Games::Rezrov::ZConst::LOWER_WIN) {
1875 $start = $upper_lines;
1876 $end = $rows;
1877 PlotzPerl::Output::reset_write_count();
1878 } else {
1879 die "clear window $window!";
1880 }
1881 for (my $i = $start; $i < $end; $i++) {
1882 # $zio->erase_line($i);
1883 $zio->absolute_move(0, $i);
1884 $zio->clear_to_eol();
1885 }
1886 &$restore();
1887 # restore cursor position
1888 }
1889 }
1890
1891 sub clear_screen {
1892 my $zio = screen_zio();
1893
1894 if ($zio->can_use_color()) {
1895 my $fg = $zio->fg() || "";
1896 my $bg = $zio->bg() || "";
1897 my $dbg = $zio->default_bg() || "";
1898 # FIX ME!
1899
1900 # printf STDERR "fg=%s/%s bg=%s/%s\n",$fg,$zio->default_fg, $bg, $zio->default_bg;
1901 if ($bg ne $dbg) {
1902 # the background color has changed; change the cursor color
1903 # to the current foreground color so we don't run the risk of it
1904 # "disappearing".
1905 $zio->cc($fg);
1906 }
1907 $zio->default_bg($bg);
1908 $zio->default_fg($fg);
1909 $zio->set_background_color();
1910 }
1911
1912 $zio->clear_screen();
1913 }
1914
1915 sub prompt_buffer {
1916 $prompt_buffer = $_[0] if defined $_[0];
1917 return $prompt_buffer;
1918 }
1919
1920 ################################################################################
1921
1922 package Games::Rezrov::ZIO_Generic;
1923 #
1924 # shared z-machine i/o
1925 #
1926 use strict;
1927
1928 #use Games::Rezrov::ZIO_Tools;
1929 #use Games::Rezrov::ZConst;
1930
1931 sub new {
1932 return bless {}, $_[0];
1933 }
1934
1935 sub current_window {
1936 return (defined $_[1] ?
1937 $_[0]->{"current_window"} = $_[1] :
1938 $_[0]->{"current_window"});
1939 }
1940
1941 sub can_split {
1942 # true or false: can this zio split the screen?
1943 return 1;
1944 }
1945
1946 sub groks_font_3 {
1947 # true or false: can this zio handle graphical "font 3" z-characters?
1948 return 0;
1949 }
1950
1951 sub fixed_font_default {
1952 # true or false: does this zio use a fixed-width font?
1953 return 1;
1954 }
1955
1956 sub can_use_color {
1957 return 0;
1958 }
1959
1960 # I/O part of show_status opcode
1961 sub show_status {
1962 # right_chunk is scores/moves or hours:minutes
1963 my ($self, $room_name, $right_chunk) = @_;
1964
1965 my $columns = Language::Zcode::Runtime::IO::columns();
1966 if ($self->manual_status_line()) {
1967 # the ZIO wants to handle it
1968 $self->status_hook($room_name, $right_chunk);
1969 } else {
1970 # "generic" status line handling; broken for screen-splitting v3 games
1971 my $restore = $self->get_position(1);
1972 $self->status_hook(0);
1973 # erase
1974 $self->write_string((" " x $columns), 0, 0);
1975 $self->write_string($room_name, 0, 0);
1976
1977 $self->write_string($right_chunk, $columns - length($right_chunk), 0);
1978 $self->status_hook(1);
1979 &$restore();
1980 }
1981 }
1982
1983 sub split_window {}
1984 sub set_text_style {}
1985 sub clear_screen {}
1986 sub color_change_notify {}
1987
1988 sub set_game_title {
1989 Games::Rezrov::ZIO_Tools::set_xterm_title($_[1]);
1990 }
1991
1992 sub manual_status_line {
1993 # true or false: does this zio want to draw the status line itself?
1994 return 0;
1995 }
1996
1997 sub set_font {
1998 # print STDERR "set_font $_[1]\n";
1999 return 0;
2000 }
2001
2002 sub play_sound_effect {
2003 my ($self, $effect) = @_;
2004 # flash();
2005 }
2006
2007 sub set_window {
2008 $_[0]->current_window($_[1]);
2009 }
2010
2011 # write [MORE] at end of page
2012 sub more_prompt {
2013 my ($self, $lower_lines) = @_;
2014 # Don't even bother doing Language::Zcode::Runtime::IO::font_mask, since we just
2015 # reset it. I guess we do need to
2016 # call Language::Zcode::Runtime::IO::set_cursor, but prob. only at end
2017 # (other call can be an internal ZIO call)
2018 my $restore = $self->get_position(1);
2019
2020 # XXX Change these to internal ZIO calls (absolute move)
2021 Language::Zcode::Runtime::IO::set_cursor($lower_lines, 1);
2022 my $more_prompt = "[MORE]";
2023 my $old = Language::Zcode::Runtime::IO::font_mask();
2024 $self->set_text_style(Games::Rezrov::ZConst::STYLE_REVERSE);
2025 $self->write_string($more_prompt);
2026 $self->set_text_style(Games::Rezrov::ZConst::STYLE_ROMAN);
2027 Language::Zcode::Runtime::IO::font_mask($old);
2028 $self->update();
2029 $self->get_input(1,1);
2030 Language::Zcode::Runtime::IO::set_cursor($lower_lines, 1);
2031 $self->clear_to_eol();
2032 # $zio->erase_line($lower_lines);
2033 # $zio->erase_line($lower_lines - 1);
2034
2035 # restore old position
2036 &$restore();
2037 }
2038
2039 sub cleanup {
2040 }
2041
2042 sub DESTROY {
2043 # in case of a crash, make sure we exit politely
2044 $_[0]->cleanup();
2045 }
2046
2047 sub fatal_error {
2048 my ($self, $msg) = @_;
2049 $self->write_string("Fatal error: " . $msg);
2050 $self->newline();
2051 $self->get_input(1,1);
2052 $self->cleanup();
2053 exit 1;
2054 }
2055
2056 sub set_background_color {
2057 # set the background to the current background color.
2058 # That's the *whole* background, not just for the next characters
2059 # to print (some games switch background colors before clearing
2060 # the screen, which should reset the entire background to that
2061 # color); eg "photopia.z5".
2062 #
2063 # "That's the *whole* bass..."
2064 1;
2065 }
2066
2067
2068 1;
2069
2070 ################################################################################
2071 package Games::Rezrov::ZIO_dumb;
2072 # z-machine i/o for dumb/semi-dumb terminals.
2073
2074 BEGIN {
2075 $ENV{"PERL_RL"} = 'Perl';
2076 }
2077
2078 use strict;
2079
2080 #use Games::Rezrov::GetKey;
2081 #use Games::Rezrov::GetSize;
2082 #use Games::Rezrov::ZIO_Tools;
2083 #use Games::Rezrov::ZIO_Generic;
2084
2085 @Games::Rezrov::ZIO_dumb::ISA = qw(Games::Rezrov::ZIO_Generic);
2086
2087 my $have_term_readline = 0;
2088 my $tr;
2089
2090 my $have_term_readkey;
2091 my ($rows, $columns);
2092 my ($clear_prog);
2093
2094 my $abs_x = 0;
2095 my $abs_y = 0;
2096
2097 $|=1;
2098
2099 sub new {
2100 my ($type, %options) = @_;
2101 my $self = new Games::Rezrov::ZIO_Generic();
2102 bless $self, $type;
2103 $self->io_setup($options{"readline"});
2104
2105 ($columns, $rows) = Games::Rezrov::GetSize::get_size();
2106 $columns = $options{columns} if $options{columns};
2107 $rows = $options{rows} if $options{rows};
2108
2109 unless ($columns and $rows) {
2110 #print "I couldn't guess the number of rows and columns in your display,\n";
2111 #print "so you must use -r and -c to specify them manually.\n";
2112 #exit;
2113 # XXX HACK!
2114 $columns = 80; $rows = 250;
2115 }
2116 Language::Zcode::Runtime::IO::rows($rows);
2117 Language::Zcode::Runtime::IO::columns($columns);
2118 return $self;
2119 }
2120
2121 sub io_setup {
2122 my ($self, $readline_ok) = @_;
2123
2124 if (eval('require Term::ReadKey')) {
2125 import Term::ReadKey;
2126 $have_term_readkey = 1;
2127 # ReadMode(3);
2128 # disable echoing
2129 # ReadLine(-1);
2130 # make sure we don't buffer any (invisible) characters
2131 }
2132
2133 if ($readline_ok && eval('require Term::ReadLine')) {
2134 require Term::ReadLine;
2135 $have_term_readline = 1;
2136 $tr = new Term::ReadLine 'what?', \*main::STDIN, \*main::STDOUT;
2137 $tr->ornaments(0);
2138 }
2139
2140 # TODO if $^O == windows, "cls". If unix, `which clear`
2141 $clear_prog = undef; # find_prog("clear");
2142 }
2143
2144 sub write_string {
2145 my ($self, $string, $x, $y) = @_;
2146 $self->absolute_move($x, $y) if defined($x) && defined($y);
2147 print $string;
2148 # print STDERR "ws: $string\n";
2149 $abs_x += length($string);
2150 }
2151
2152 sub clear_to_eol {
2153 # print STDERR "clear to eol; at $abs_x\n";
2154 my $diff = $columns - $abs_x;
2155 if ($diff > 0) {
2156 print " " x $diff;
2157 # erase
2158 print pack("c", 0x08) x $diff;
2159 # restore cursor
2160 }
2161 }
2162
2163 sub update {
2164 }
2165
2166 #sub find_prog {
2167 # foreach ("/bin/", "/usr/bin/") {
2168 # my $fn = $_ . $_[0];
2169 # return $fn if -x $fn;
2170 # }
2171 # return undef;
2172 #}
2173
2174 sub can_split {
2175 # true or false: can this zio split the screen?
2176 return 0;
2177 }
2178
2179 sub set_version {
2180 die "Not using set_version any more";
2181 # my ($self, $status_needed, $callback) = @_;
2182 # Games::Rezrov::StoryFile::rows($rows);
2183 # Games::Rezrov::StoryFile::columns($columns);
2184 # print STDERR "$columns\n";
2185 # $self->clear_screen();
2186 return 0;
2187 }
2188
2189 sub absolute_move {
2190 my ($nx, $ny) = @_[1,2];
2191 # printf STDERR "move X to $nx from $abs_x\n";
2192 if (0 and $nx < $abs_x) {
2193 # DISABLED
2194 # "this sidewalk's for regular walkin', not fancy walkin'..."
2195 my $diff = $abs_x - $nx;
2196 # printf STDERR "going back %d\n", $abs_x - $nx;
2197 print pack("c", 0x08) x $diff;
2198 # go back
2199 print " " x $diff;
2200 # erase
2201 print pack("c", 0x08) x $diff;
2202 # go back again
2203 }
2204 $abs_x = $nx;
2205 $abs_y = $ny;
2206 }
2207
2208 sub newline {
2209 # check to see if we need to pause
2210 print "\n";
2211 $abs_x = 0;
2212 PlotzPerl::Output::register_newline();
2213 }
2214
2215 sub write_zchar {
2216 if ($_[0]->current_window() == Games::Rezrov::ZConst::LOWER_WIN) {
2217 print chr($_[1]);
2218 # printf STDERR "wc: %s\n", chr($_[1]);
2219 $abs_x++;
2220 } else {
2221 # printf STDERR "ignoring char: %s\n", chr($_[1]);
2222 }
2223 }
2224
2225 sub get_input {
2226 my ($self, $max, $single_char, %options) = @_;
2227 if ($single_char) {
2228 # XXX ADK put in explicit package name cuz I'm not use'ing GetSize
2229 return Games::Rezrov::GetKey::get_key();
2230 } else {
2231 if ($have_term_readkey) {
2232 # re-enable terminal before prompt
2233 ReadMode(0);
2234 # ReadLine(0);
2235 }
2236 my $line;
2237 if ($have_term_readline) {
2238 # readline insists on resetting the line so we need to give it
2239 # everything up to the cursor position.
2240 $line = $tr->readline(Language::Zcode::Runtime::IO::prompt_buffer());
2241 # this doesn't work with v5+ preloaded input
2242 } else {
2243 $line = <STDIN>;
2244 # this doesn't work with v5+ preloaded input
2245 }
2246 unless (defined $line) {
2247 $line = "";
2248 print "\n";
2249 }
2250 chomp $line;
2251 if ($have_term_readkey) {
2252 ReadMode(3);
2253 # ReadLine(-1);
2254 }
2255 return $line;
2256 }
2257 }
2258
2259 sub get_position {
2260 my ($self, $sub) = @_;
2261 if ($sub) {
2262 return sub { };
2263 } else {
2264 return ($abs_x, $abs_y);
2265 }
2266 }
2267
2268 sub clear_screen {
2269 system($clear_prog) if $clear_prog;
2270 for (my $i=0; $i < $rows; $i++) {
2271 # move cursor to lower left
2272 print "\n";
2273 }
2274 }
2275
2276 my $warned;
2277 sub set_window {
2278 my ($self, $window) = @_;
2279 $self->SUPER::set_window($window);
2280 if ($window != Games::Rezrov::ZConst::LOWER_WIN) {
2281 # ignore output except on lower window
2282 unless ($warned++) {
2283 my $pb = Language::Zcode::Runtime::IO::prompt_buffer();
2284 $self->newline();
2285 Language::Zcode::Runtime::IO::set_window(Games::Rezrov::ZConst::LOWER_WIN);
2286 my $message = "WARNING: this game is attempting to use multiple windows, which this interface can't handle. The game may be unplayable using this interface. You should probably use the Tk, Curses, Termcap, or Win32 interfaces if you can; see the documentation.";
2287 # XXX ADK my replacement might not be 100% compatible to buffer_zchunk
2288 # $self->SUPER::buffer_zchunk(\$message);
2289 PlotzPerl::Output->write_to_screen(\$message);
2290 PlotzPerl::Output::flush();
2291 $self->newline();
2292 Language::Zcode::Runtime::IO::prompt_buffer($pb) if $pb;
2293 Language::Zcode::Runtime::IO::set_window($window);
2294 }
2295 }
2296 }
2297
2298 sub erase_chars {
2299 my $count = shift;
2300
2301 print pack 'c', 0x0d; # carriage return
2302 print ' ' x $count; # erase
2303 print pack 'c', 0x0d; # carriage return
2304 # 2nd pass required in case of user input on same line as more prompt;
2305 # example: start "enchanter" in 80x36 terminal.
2306 # I'm not sure why just sending $count 0x08's (backspace) doesn't
2307 # work in this case, but it doesn't.
2308 }
2309
2310 sub cleanup {
2311 if ($have_term_readkey) {
2312 ReadMode(0);
2313 # ReadLine(0);
2314 }
2315 }
2316
2317
2318 1;
2319
2320 ################################################################################
2321 #
2322 # Try as hard as we can to guess the number of rows and columns
2323 # in the display.
2324 #
2325 # Use a "nice" approach if available, wallow if we must.
2326 # Michael Edmonson 10/1/98
2327 #
2328
2329 package Games::Rezrov::GetSize;
2330
2331 use strict;
2332 use Exporter;
2333
2334 @Games::Rezrov::GetSize::ISA = qw(Exporter);
2335 @Games::Rezrov::GetSize::EXPORT = qw(get_size);
2336
2337 $Games::Rezrov::GetSize::DEBUG = 0;
2338
2339 eval 'use Term::ReadKey';
2340 if (!$@) {
2341 #
2342 # use Term::ReadKey
2343 #
2344 print STDERR "term::readkey\n" if $Games::Rezrov::GetSize::DEBUG;
2345
2346 eval << 'DONE'
2347 sub get_size {
2348 my @terminal = GetTerminalSize();
2349 return @terminal ? ($terminal[0], $terminal[1]) : undef;
2350 }
2351 DONE
2352 } elsif ($ENV{"COLUMNS"} and $ENV{"ROWS"}) {
2353 #
2354 # use environment variables
2355 #
2356 print STDERR "environment vars\n" if $Games::Rezrov::GetSize::DEBUG;
2357 eval << 'DONE'
2358 sub get_size {
2359 return ($ENV{"COLUMNS"}, $ENV{"ROWS"});
2360 }
2361 DONE
2362 } else {
2363 foreach ("/bin/", "/usr/bin/") {
2364 my $fn = $_ . "/stty";
2365 $Games::Rezrov::GetSize::stty_prog = $fn, last if -x $fn;
2366 }
2367 if ($Games::Rezrov::GetSize::stty_prog) {
2368 #
2369 # use stty
2370 #
2371 print STDERR "stty\n" if $Games::Rezrov::GetSize::DEBUG;
2372 eval << 'DONE'
2373 sub get_size {
2374 my ($columns, $rows);
2375 my $data = `$Games::Rezrov::GetSize::stty_prog -a`;
2376 foreach (["rows", \$rows],
2377 ["columns", \$columns]) {
2378 my ($what, $ref) = @{$_};
2379 if ($data =~ /$what\s+=*\s*(\d+)/) {
2380 $$ref = $1;
2381 } elsif ($data =~ /(\d+)\s+$what/) {
2382 $$ref = $1;
2383 }
2384 }
2385 return ($columns, $rows);
2386 }
2387 DONE
2388 } else {
2389 #
2390 # give up
2391 #
2392 print STDERR "giving up\n" if $Games::Rezrov::GetSize::DEBUG;
2393 eval << 'DONE'
2394 sub get_size {
2395 return undef;
2396 }
2397 DONE
2398 }
2399 }
2400
2401
2402 1;
2403
2404 ################################################################################
2405
2406 package Games::Rezrov::GetKey;
2407 # Try as hard as we can to read a single key from the keyboard.
2408 # Use a "nice" approach if available, wallow if we must.
2409 # Michael Edmonson 9/29/98
2410 #
2411 # POSIX code taken from Tom Christiansen's "HotKey.pm", see
2412 # perlfaq8, or <6k403m$r1l$9@csnews.cs.colorado.edu>
2413 #
2414 # TO DO: add DOS and other OS-specific code if Term::ReadKey not available
2415
2416 use strict;
2417 use Exporter;
2418
2419 @Games::Rezrov::GetKey::ISA = qw(Exporter);
2420 @Games::Rezrov::GetKey::EXPORT = qw(get_key);
2421
2422 use constant DEBUG => 0;
2423
2424 $Games::Rezrov::GetKey::STTY = "";
2425
2426 my $CAN_READ_SINGLE = 1;
2427
2428 sub can_read_single {
2429 return $CAN_READ_SINGLE;
2430 }
2431
2432 eval 'use Term::ReadKey';
2433 if (!$@) {
2434 #
2435 # use Term::ReadKey
2436 #
2437 print STDERR "term::readkey\n" if DEBUG;
2438 eval << 'DONE'
2439 sub get_key {
2440 ReadMode(3);
2441 my $z;
2442 read(STDIN, $z, 1);
2443 ReadMode(0);
2444 return $z;
2445 }
2446
2447 sub END {
2448 ReadMode(0);
2449 }
2450 DONE
2451
2452 } else {
2453 my $posix_ok = 0;
2454 eval 'use POSIX qw(:termios_h)';
2455 if (!$@) {
2456 eval 'my $term = POSIX::Termios->new();';
2457 if ($@) {
2458 # we have the POSIX module but Termios doesn't work!
2459 # die "aha";
2460 } else {
2461 $posix_ok = 1;
2462 }
2463 }
2464
2465 if ($posix_ok) {
2466 #
2467 # use POSIX termios
2468 #
2469 print STDERR "posix\n" if DEBUG;
2470
2471 eval << 'DONE'
2472
2473 my $fd_stdin = fileno(STDIN);
2474 my $term = POSIX::Termios->new();
2475 $term->getattr($fd_stdin);
2476 my $oterm = $term->getlflag();
2477 my $echo = ECHO | ECHOK | ICANON;
2478 my $noecho = $oterm & ~$echo;
2479
2480 sub cbreak {
2481 $term->setlflag($noecho);
2482 $term->setcc(VTIME, 1);
2483 $term->setattr($fd_stdin, TCSANOW);
2484 }
2485
2486 sub cooked {
2487 $term->setlflag($oterm);
2488 $term->setcc(VTIME, 0);
2489 $term->setattr($fd_stdin, TCSANOW);
2490 }
2491
2492 sub get_key {
2493 my $key = '';
2494 cbreak();
2495 sysread(STDIN, $key, 1);
2496 cooked();
2497 return $key;
2498 }
2499
2500 sub END {
2501 cooked();
2502 }
2503 DONE
2504 } else {
2505 #
2506 # Ugh, hopefully it won't come to this :)
2507 #
2508 my $prog;
2509 foreach ("/bin/", "/usr/bin/") {
2510 my $fn = $_ . "stty";
2511 $Games::Rezrov::GetKey::STTY = $fn, last if -x $fn;
2512 }
2513
2514 if ($Games::Rezrov::GetKey::STTY) {
2515 # use stty program
2516 print STDERR "stty\n" if DEBUG;
2517
2518 eval << 'DONE'
2519 sub get_key {
2520 my $z;
2521 system "$Games::Rezrov::GetKey::STTY -icanon -echo";
2522 read(STDIN, $z, 1);
2523 system "$Games::Rezrov::GetKey::STTY icanon echo";
2524 return $z;
2525 }
2526
2527 sub END {
2528 system "$Games::Rezrov::GetKey::STTY icanon echo";
2529 }
2530 DONE
2531 } else {
2532 $CAN_READ_SINGLE = 0;
2533 print STDERR "giving up" if DEBUG;
2534 eval << 'DONE'
2535 sub get_key {
2536 my $z;
2537 read(STDIN, $z, 1);
2538 return $z;
2539 }
2540 DONE
2541 }
2542 }
2543 }
2544
2545 1;
2546
2547
2548 ################################################################################
2549 package Games::Rezrov::ZIO_Tools;
2550
2551 use strict;
2552 use Exporter;
2553
2554 @Games::Rezrov::ZIO_Tools::ISA = qw(Exporter);
2555 @Games::Rezrov::ZIO_Tools::EXPORT = qw(set_xterm_title
2556 find_module);
2557
2558 sub set_xterm_title {
2559 # if title is not defined, return whether or not the title *can* be
2560 # changed.
2561 my $title = shift;
2562 # see the comp.windows.x FAQ.
2563 if ($ENV{"DISPLAY"}) {
2564 # these are X-specific, so...
2565 my $term = $ENV{"TERM"};
2566 my $esc = pack 'c', 27;
2567 # escape
2568
2569 if ($term =~ /xterm/i) {
2570 # XTerm
2571 if (defined $title) {
2572 printf "%s]2;%s%s", $esc, $title, pack('c', 7); # bell
2573 } else {
2574 return 1;
2575 }
2576 } elsif ($term eq "vt300") {
2577 # DECTerm?
2578 if (defined $title) {
2579 printf '%s]21;%s%s\\', $esc, $title, $esc;
2580 } else {
2581 return 1;
2582 }
2583 }
2584 }
2585
2586 return 0;
2587 }
2588
2589 sub find_module {
2590 #
2591 # Determine whether or not a given Perl module or library is installed
2592 #
2593 my $cmd = 'use ' . $_[0];
2594 eval $cmd;
2595 return $@ ? 0 : 1;
2596 }
2597
2598 1;
2599
2600 ################################################################################
2601
2602
2603 package Games::Rezrov::ZIO_Color;
2604 #
2605 # stuff for ZIOs that have color support
2606 #
2607
2608 use strict;
2609
2610 my %Color;
2611 sub cc {$Color{cc} = $_[1] if defined $_[1]; return $Color{cc}}
2612 sub fg {$Color{fg} = $_[1] if defined $_[1]; return $Color{fg}}
2613 sub bg {$Color{bg} = $_[1] if defined $_[1]; return $Color{bg}}
2614 sub sfg {$Color{sfg} = $_[1] if defined $_[1]; return $Color{sfg}}
2615 sub sbg {$Color{sbg} = $_[1] if defined $_[1]; return $Color{sbg}}
2616 sub default_fg {$Color{default_fg} = $_[1] if defined $_[1]; return $Color{default_fg}}
2617 sub default_bg {$Color{default_bg} = $_[1] if defined $_[1]; return $Color{default_bg}}
2618
2619 use constant DEFAULT_BACKGROUND_COLOR => 'blue';
2620 use constant DEFAULT_FOREGROUND_COLOR => 'white';
2621 use constant DEFAULT_CURSOR_COLOR => 'black';
2622
2623 sub parse_color_options {
2624 # - interpret standard command-line options for colors
2625 # - set up defaults
2626 my ($self, $options) = @_;
2627 my $fg = lc($options->{"fg"} || DEFAULT_FOREGROUND_COLOR);
2628 my $bg = lc($options->{"bg"} || DEFAULT_BACKGROUND_COLOR);
2629 my $sfg = lc($options->{"sfg"} || $bg);
2630 my $sbg = lc($options->{"sbg"} || $fg);
2631 # status line: default to inverse of foreground/background colors
2632
2633 $self->fg($fg);
2634 $self->bg($bg);
2635 $self->default_fg($fg);
2636 $self->default_bg($bg);
2637 $self->sfg($sfg);
2638 $self->sbg($sbg);
2639
2640 my $cc = lc($options->{"cc"} || DEFAULT_CURSOR_COLOR);
2641 $self->cc($cc eq $bg ? $fg : $cc);
2642 # if cursor color is the same as the background color,
2643 # change it to the foreground color
2644 }
2645
2646 1;
2647
2648 ################################################################################
2649 # UNBELIEVABLY UGLY HACK TO ALLOW RUNNING ON NON-WIN32 OSes.
2650 # TODO Move to LZ::Term::Win32 and require it only if we're on win32
2651 # Note: can't split it now because Games::Rezrov::ZConst constants are
2652 # needed in this package (and others). We need to separate out GR::ZConst
2653 # and export all those constants or something, then use from here and other
2654 # LZ::Term packages.
2655 eval <<'ENDWIN32';
2656 package Games::Rezrov::ZIO_Win32;
2657 # z-machine i/o for perls with Win32::Console
2658 # TO DO:
2659 # - can we set hourglass when busy?
2660
2661 use strict;
2662 use Win32::Console;
2663
2664 #use Games::Rezrov::ZIO_Generic;
2665 #use Games::Rezrov::ZIO_Color;
2666 #use Games::Rezrov::ZConst;
2667
2668
2669 use constant WIN32_DEBUG => 0;
2670
2671 @Games::Rezrov::ZIO_Win32::ISA = qw(Games::Rezrov::ZIO_Generic
2672 Games::Rezrov::ZIO_Color
2673 );
2674
2675 my ($orig_columns, $orig_rows);
2676 my ($s_upper_lines, $s_rows, $s_columns, $in_status);
2677 # number of lines in upper window, geometry
2678
2679 my ($IN, $OUT);
2680 # Win32::Console instances
2681
2682 if (WIN32_DEBUG) {
2683 # debugging; tough to redirect STDERR under win32 :(
2684 open(LOG, ">zio.log") || die;
2685 select(LOG);
2686 $|=1;
2687 select(STDOUT);
2688 }
2689
2690 my %KEYCODES = (
2691 38 => Games::Rezrov::ZConst::Z_UP,
2692 40 => Games::Rezrov::ZConst::Z_DOWN,
2693 37 => Games::Rezrov::ZConst::Z_LEFT,
2694 39 => Games::Rezrov::ZConst::Z_RIGHT,
2695 );
2696
2697 my (%FOREGROUND, %BACKGROUND);
2698 foreach (qw(black
2699 blue
2700 lightblue
2701 red
2702 lightred
2703 green
2704 lightgreen
2705 magenta
2706 lightmagenta
2707 cyan
2708 lightcyan
2709 brown
2710 yellow
2711 gray
2712 white)) {
2713 # make hash translating names to color codes exported by Win32::Console
2714 no strict "refs";
2715 $FOREGROUND{$_} = ${"main::FG_" . uc($_)};
2716 $BACKGROUND{$_} = ${"main::BG_" . uc($_)};
2717 }
2718
2719 sub new {
2720 my ($type, %options) = @_;
2721 my $self = new Games::Rezrov::ZIO_Generic();
2722 bless $self, $type;
2723
2724 if ($options{fg}) {
2725 $options{fg} = "gray" if $options{fg} eq "white";
2726 # since INTENSITY mode has no effect "white",
2727 # use gray instead. Feh.
2728 # How to get *true* bold here???
2729 } else {
2730 $options{fg} = "gray" unless $options{fg};
2731 $options{bg} = "blue" unless $options{bg};
2732 $options{sfg} = "black" unless $options{sfg};
2733 $options{sbg} = "cyan" unless $options{sbg};
2734 }
2735
2736 $self->parse_color_options(\%options);
2737
2738 foreach ("bg", "fg", "sfg", "sbg") {
2739 next unless exists $options{$_};
2740 my $c = $self->$_() || next;
2741 die sprintf "Unknown color \"%s\"; available colors: %s\n", $c, join(", ", sort keys %FOREGROUND)
2742 unless exists $FOREGROUND{$c};
2743 }
2744
2745 # set up i/o
2746 $IN = new Win32::Console(STD_INPUT_HANDLE);
2747 $OUT = new Win32::Console(STD_OUTPUT_HANDLE);
2748
2749 my @size = $OUT->Size();
2750 $s_columns = $options{"-columns"} || $size[0] || die "need columns!";
2751 $s_rows = $options{"-rows"} || $size[1] || die "need rows!";
2752 ($orig_columns, $orig_rows) = @size;
2753
2754 ###########
2755 # ADK XXX I have no idea if this is right, but it shrinks the Windows
2756 # buffer to be the same size as the screen, so that the status line
2757 # on row zero is visible without scrolling upward!
2758 # Seems like there should be a way to keep the scrollbar and to
2759 # allow the lower window to scroll up, always rewriting the upper
2760 # window. But maybe Win32::Console doesn't play nice with that.
2761 my @w = $OUT->Window();
2762 my ($c, $r) = ($w[2]-$w[0]+1, $w[3]-$w[1]+1);
2763 # $OUT->Write($size[0]." "); $OUT->Write($size[1]." "); $OUT->Write("$r $c");
2764 $OUT->Size($c, $r);
2765 $s_columns = $options{"-columns"} || $c || die "need columns!";
2766 $s_rows = $options{"-rows"} || $r || die "need rows!";
2767 ###########
2768
2769 Language::Zcode::Runtime::IO::rows($s_rows);
2770 Language::Zcode::Runtime::IO::columns($s_columns);
2771 $s_upper_lines = 0;
2772 return $self;
2773 }
2774
2775 sub update {
2776 $OUT->Flush();
2777 }
2778
2779 sub set_version {
2780 # called by the game
2781 my ($self, $status_needed, $callback) = @_;
2782 Games::Rezrov::StoryFile::rows($s_rows);
2783 Games::Rezrov::StoryFile::columns($s_columns);
2784 return 0;
2785 }
2786
2787 sub absolute_move {
2788 # move to X, Y
2789 $OUT->Cursor($_[1], $_[2]);
2790 }
2791
2792 sub write_string {
2793 my ($self, $string, $x, $y) = @_;
2794 $self->absolute_move($x, $y) if defined($x) and defined($y);
2795 # $OUT->Attr($current_attr);
2796 $OUT->Attr($self->get_attr());
2797 $OUT->Write($string);
2798 }
2799
2800 sub newline {
2801 # newline/scroll
2802 my ($x, $y) = $OUT->Cursor();
2803 if (++$y >= $s_rows) {
2804 # scroll needed
2805 my $last_line = $s_rows - 1;
2806 $y = $last_line;
2807 my $top = $s_upper_lines;
2808 # $OUT->Write(sprintf "before: at %d,%d, top=%d last=%d\n", $x, $y, $top, $last_line);
2809 # log_it(sprintf "before: at %d,%d, top=%d last=%d\n", $x, $y, $top, $last_line);
2810 # sleep(1);
2811 $OUT->Scroll(0, $top + 1, $s_columns - 1, $last_line,
2812 0, $top, Games::Rezrov::ZConst::ASCII_SPACE, $_[0]->get_attr(0),
2813 0, $top, $s_columns - 1, $last_line);
2814 # ugh: we have to specify the clipping region, or else
2815 # Win32::Console barfs about uninitialized variables (with -w)
2816 }
2817 PlotzPerl::Output::register_newline();
2818 $_[0]->absolute_move(0, $y);
2819 }
2820
2821 sub write_zchar {
2822 # log_it("wzchar: " . chr($_[1]));
2823 $OUT->Attr($_[0]->get_attr());
2824 $OUT->Write(chr($_[1]));
2825 }
2826
2827 sub status_hook {
2828 my ($self, $type) = @_;
2829 # 0 = before
2830 # 1 = after
2831 if ($type == 0) {
2832 # before printing status line
2833 $OUT->Cursor(0,0);
2834 $in_status = 1;
2835 $OUT->FillAttr($self->get_attr(), $s_columns, 0, 0);
2836 } else {
2837 # after printing status line
2838 $in_status = 0;
2839 }
2840 }
2841
2842 sub get_input {
2843 my ($self, $max, $single_char, %options) = @_;
2844 # $IN->Flush();
2845 # don't flush input (allow buffered keystrokes)
2846
2847 my ($start_x, $y) = $OUT->Cursor();
2848 my $buf = $options{"-preloaded"} || "";
2849 # preloaded text in the buffer, but already displayed by the game; ugh.
2850 my @event;
2851 my ($code, $char);
2852 # TODO More keys F1, num lock, etc.- see NOTES.txt
2853 # Event type (1 keyboard, 2 mouse), key down or up (1,0)
2854 # repeat count, virtual keycode, virtual scan code (?)
2855 # char (if ASCII, otherwise 0), control key state
2856 while (1) {
2857 @event = $IN->Input() or next; # ignore changing window focus
2858 my $known;
2859 if ($event[0] == 1 and $event[1]) {
2860 # a key pressed
2861 $code = $event[5];
2862 if ($code == 0) {
2863 # non-character key pressed
2864 if ($KEYCODES{$event[3]}) {
2865 $code = $KEYCODES{$event[3]};
2866 $known = 1;
2867 } else {
2868 log_it(sprintf "got unknown non-char: %s", join ",", @event);
2869 }
2870 }
2871
2872 if ($single_char and ($known or ($code >= 1 and $code <= 127))) {
2873 return chr($code);
2874 } elsif ($code == Games::Rezrov::ZConst::ASCII_BS) {
2875 if (length($buf) > 0) {
2876 # log_it("backsp " . length($buf) . " " . $buf);
2877 my ($x, $y) = $OUT->Cursor();
2878 $OUT->Cursor($x - 1, $y);
2879 $OUT->Write(" ");
2880 $OUT->Cursor($x - 1, $y);
2881 $buf = substr($buf, 0, length($buf) - 1);
2882 }
2883 } elsif ($code == Games::Rezrov::ZConst::ASCII_CR) {
2884 last;
2885 } else {
2886 if ($code >= 32 and $code <= 127) {
2887 $char = chr($code);
2888 $buf .= $char;
2889 $OUT->Attr($self->get_attr(0));
2890 $OUT->Write($char);
2891 }
2892 }
2893 }
2894 }
2895 $self->newline();
2896 return $buf;
2897 }
2898
2899 sub clear_screen {
2900 $OUT->Cls($_[0]->get_attr(0));
2901 # log_it("cls");
2902 }
2903
2904 sub clear_to_eol {
2905 $OUT->Attr($_[0]->get_attr(0));
2906 $OUT->Write(" " x ($s_columns - ($OUT->Cursor())[1]));
2907 }
2908
2909 sub split_window {
2910 # split upper window to specified number of lines
2911 my ($self, $lines) = @_;
2912 # $w_main->setscrreg($lines, $s_rows - 1);
2913 $s_upper_lines = $lines;
2914 # print STDERR "split_window to $lines\n";
2915 }
2916
2917 sub can_change_title {
2918 return 1;
2919 }
2920
2921 sub can_use_color {
2922 return 1;
2923 }
2924
2925 sub set_game_title {
2926 $OUT->Title($_[1]);
2927 }
2928
2929 sub log_it {
2930 if (WIN32_DEBUG) {
2931 print LOG $_[0] . "\n";
2932 }
2933 }
2934
2935 sub get_attr {
2936 # return attribute code for color/style currently in effect.
2937 my ($self, $mask) = @_;
2938
2939 $mask = Language::Zcode::Runtime::IO::font_mask() unless defined($mask);
2940 # might be called with an override
2941 my ($fg, $bg);
2942 if ($in_status) {
2943 $fg = $self->sfg();
2944 $bg = $self->sbg();
2945 } else {
2946 if ($mask & Games::Rezrov::ZConst::STYLE_REVERSE) {
2947 $fg = $self->bg();
2948 $bg = $self->fg();
2949 } else {
2950 $fg = $self->fg();
2951 $bg = $self->bg();
2952 }
2953 }
2954
2955 my $code = $BACKGROUND{$bg} | $FOREGROUND{$fg};
2956
2957 # ADK What's main::FOREGROUND_INTENSITY? Couldn't find it in
2958 # any Games::Rezrov file!
2959 =pod
2960 $code |= main::FOREGROUND_INTENSITY if
2961 ($mask & (Games::Rezrov::ZConst::STYLE_BOLD|Games::Rezrov::ZConst::STYLE_ITALIC));
2962 =cut
2963
2964 return $code;
2965 }
2966
2967 sub get_position {
2968 # with no arguments, return absolute X and Y coordinates.
2969 # With an argument, return a sub that will restore the current cursor
2970 # position.
2971 my ($self, $sub) = @_;
2972 my ($x, $y) = $OUT->Cursor();
2973 if ($sub) {
2974 return sub { $OUT->Cursor($x, $y); };
2975 } else {
2976 return ($x, $y);
2977 }
2978 }
2979
2980 my $is_clean = "";
2981 sub cleanup {
2982 my $self = shift;
2983 return if $is_clean++; # only clean once!
2984 if (defined $OUT) {
2985 $self->write_string("[Hit any key to exit]");
2986 $self->get_input(1,1);
2987 # TODO save Attr so user gets back exactly the window they started with
2988 $OUT->Attr($main::ATTR_NORMAL);
2989 #print "rows is $orig_rows\n";
2990 $OUT->Size($orig_columns, $orig_rows);
2991 } else {warn "cleanup called with undefined zio\n"}
2992 print "Cleaned IO\n";
2993 }
2994 ENDWIN32
2995
2996 1;