ZIO_Tk.pm untested

filter: Statementstmt 0.0% 0 / 489 Branchbran 0.0% 0 / 156 Conditioncond 0.0% 0 / 36 MC/DCmcdc 0.0% 0 / 24 Subroutinesub 0.0% 0 / 60 Podpod 0.0% 0 / 45 totaltotal 0.0% 0 / 810 CC 79 SCAR 43.5
CC
79
Cov
0%
get_input
272.0
write_string
240.0
newline
110.0
CRAP 77.5
1 package Games::Rezrov::ZIO_Tk;
2 #
3 # z-machine i/o for perls with Perl/Tk.
4 #
5  
6 use strict;
7 use Tk;
8 use Tk::Font;
9  
10 use Carp qw(cluck carp confess);
11  
12 use Games::Rezrov::ZConst;
13 use Games::Rezrov::ZIO_Generic;
14 use Games::Rezrov::ZIO_Color;
15 use Games::Rezrov::FontVectors;
16  
17 use constant X_BORDER => 2;
18 # FIX ME?
19  
20 use constant STANDARD_COMPLIANT_BUT_EVEN_SLOWER => 0;
21 # if 0 (noncompliant) we buffer output in the upper window.
22  
23 use constant FIXED_FAMILY => "Courier";
24 # FIX ME!
25  
26 use constant DEFAULT_BLINK_DELAY => 1000;
27  
28 #use constant TEXT_ANCHOR => "nw";
29 use constant TEXT_ANCHOR => "w";
30  
31 @Games::Rezrov::ZIO_Tk::ISA = qw(
32 Games::Rezrov::ZIO_Generic
33 Games::Rezrov::ZIO_Color
34 );
35  
36 use Games::Rezrov::MethodMaker qw(
37 dumb_fonts
38 font_cache
39  
40 font_size
41 line_height
42 fixed_font_width
43 current_font
44  
45 cursor_id
46 cursor_x
47 cursor_status
48 blink_id
49  
50 zfont
51 last_text_id
52  
53 variable_font_family
54 );
55  
56 # again, a lot of statics for speed...
57 my ($w_main, $c, $status_line, $upper_lines);
58 my ($abs_x, $abs_row, $abs_col, $rows, @widgets);
59 my $Y_BORDER;
60 my $initialized;
61  
62 sub new {
63 my ($type, %options) = @_;
64 my $self = new Games::Rezrov::ZIO_Generic(%options);
65 bless $self, $type;
66 $self->font_cache({});
67 $self->zfont(Games::Rezrov::ZConst::FONT_NORMAL);
68 $abs_row=0;
69  
70 return $self;
71 }
72  
73 sub set_version {
74 my ($self, $need_status, $init_sub) = @_;
75 # set up window
76 $w_main = MainWindow->new();
77 $w_main->title("rezrov");
78 $w_main->bind('<Configure>' => [ $self => 'set_geometry' ]);
79 $w_main->bind('<Control-c>' => [ $self => 'cleanup' ]);
80 # $w_main->bind('<Tab>' => [ $self => 'i_am_too_dumb_to_figure_this_out' ]);
81  
82 my $is_win32 = ($^O =~ /mswin32/i) ? 1 : 0;
83 my ($DEFAULT_VARIABLE_FAMILY, $DEFAULT_FONT_SIZE);
84 if ($is_win32) {
85 $DEFAULT_VARIABLE_FAMILY = "times new roman";
86 $DEFAULT_FONT_SIZE = 14;
87 } else {
88 $DEFAULT_VARIABLE_FAMILY = "times";
89 $DEFAULT_FONT_SIZE = 18;
90 }
91  
92 my $options = $self->zio_options();
93 my $vff = lc($options->{"family"} || $DEFAULT_VARIABLE_FAMILY);
94 unless (grep {lc($_) eq $vff} $w_main->fontFamilies()) {
95 $self->fatal_error(sprintf "Invalid font family \"%s\"; available families are:\n %s\n", $vff, join "\n ", column_list([sort $w_main->fontFamilies()]));
96 }
97 $self->variable_font_family($vff);
98 $self->font_size($options->{"fontsize"} || $DEFAULT_FONT_SIZE);
99
100 $self->parse_color_options($options);
101  
102 my $f_variable = $self->set_text_style(Games::Rezrov::ZConst::STYLE_ROMAN);
103 my $f_fixed = $self->set_text_style(Games::Rezrov::ZConst::STYLE_FIXED);
104 $self->set_text_style(Games::Rezrov::ZConst::STYLE_ROMAN);
105  
106 # Determine the approximate font geometry
107 die "Couldn't init fixed font!" unless $f_fixed;
108 die "Couldn't init variable font!" unless $f_variable;
109  
110 my $font_width = $w_main->fontMeasure($f_fixed, "X");
111  
112 my $line_height = $self->biggest_metric($f_fixed, $f_variable, "-linespace");
113 # my $line_height = $w_main->fontMetrics($f_fixed, "-linespace");
114  
115 $line_height += $options->{"fontspace"} if exists $options->{"fontspace"};
116  
117 # $self->line_ascent($self->biggest_metric($f_fixed, $f_variable, "-ascent"));
118 # $self->line_descent($self->biggest_metric($f_fixed, $f_variable, "-descent"));
119  
120 my $canvas_x = $options->{"x"} || int($w_main->screenwidth * 0.7);
121 my $canvas_y;
122 if ($options->{"y"}) {
123 $canvas_y = $options->{"y"};
124 } else {
125 my $y = int($w_main->screenheight * 0.6);
126 my $rows = int($y / $line_height);
127 $canvas_y = $rows * $line_height;
128 # round to a multiple of the line height
129 }
130  
131 $c = $w_main->Canvas(
132 "-width" => $canvas_x,
133 "-height" => $canvas_y,
134 "-bg" => $self->default_bg(),
135 "-takefocus" => 1,
136 "-highlightthickness" => 0,
137 );
138  
139 if ($need_status) {
140 $status_line = $w_main->Canvas(
141 "-borderwidth" => 0,
142 "-relief" => "flat",
143 "-width" => $canvas_x,
144 "-height" => $line_height,
145 "-bg" => $self->sbg(),
146 "-takefocus" => 0,
147 );
148
149 $status_line->pack("-anchor" => "n",
150 "-fill" => "x");
151 }
152  
153 $self->line_height($line_height);
154 $Y_BORDER = $line_height / 2;
155  
156 $self->fixed_font_width($font_width);
157  
158 $self->set_geometry();
159  
160 $abs_x = X_BORDER;
161 # HACK
162  
163 $abs_col = 0;
164 $abs_row = int($canvas_y / $line_height);
165  
166 $c->pack("-anchor" => "s",
167 "-expand" => 1,
168 "-fill" => "both");
169  
170 $w_main->after(0, $init_sub);
171 # delay required??
172  
173 $initialized = 1;
174  
175 MainLoop;
176  
177 return 1;
178 }
179  
180 sub update {
181 # force screen refresh
182 $c->update();
183 }
184  
185 sub fatal_error {
186 if ($initialized) {
187 $_[0]->SUPER::fatal_error($_[1]);
188 } else {
189 die $_[1];
190 }
191 }
192  
193 sub fixed_font_default {
194 # true or false: does this zio use a fixed-width font?
195 return 0;
196 }
197  
198 sub manual_status_line {
199 # true or false: does this zio want to draw the status line itself?
200 return 1;
201 }
202  
203 sub create_text {
204 # given a widget, create text w/specified properties.
205 # automatically adds the tag for the current font in effect.
206 my ($self, $widget, @args) = @_;
207 push @args, ("-font" => $self->current_font()) if $self->current_font();
208 # printf STDERR "ct in %s: %s\n", $widget, join ",",@args;
209 return $self->last_text_id($widget->create("text", @args));
210 }
211  
212 sub write_string {
213 my ($self, $string, $x, $y) = @_;
214 $self->absolute_move($x, $y) if defined($x) and defined($y);
215 my $abs_y = $self->get_y();
216
217 # printf STDERR "ws: \"%s\" at %d,%d; font=%s\n", $string, $abs_col, $abs_row, $self->zfont();
218  
219 my $is_f3;
220 if ($self->zfont() == 3) {
221 $self->fatal_error("long buf in write_string w/font 3 on") if length($string) > 1;
222 $is_f3 = 1;
223 }
224  
225 foreach my $list (@widgets) {
226 # for each window...
227 my $line = $list->[$abs_row];
228 my $after = $abs_col + length($string);
229 for (my $col=$abs_col; $col < $after; $col++) {
230 # see if existing widgets exist at this location
231 if (exists $line->{$col}) {
232 # they do,
233 foreach (@{$line->{$col}}) {
234 # so toss them.
235 $c->delete($_);
236 }
237 delete $line->{$col};
238 }
239 }
240 }
241
242 my $is_reverse = Games::Rezrov::StoryFile::font_mask() & Games::Rezrov::ZConst::STYLE_REVERSE;
243  
244 my $id;
245 if ($is_f3) {
246 # printf STDERR "f3: %d (%s), at %d,%d\n", ord($string), $string, $abs_col, $abs_row;
247 print STDERR "reverse f3 char!\n" if $is_reverse;
248 if (my $vec_list = $Games::Rezrov::FontVectors::vecs{ord($string)}) {
249 # list of vectors describing how to paint this character.
250 # These are grid coordinates based on section 16 of the spec, to wit:
251 #
252 # 33(!): 76543210 34("): 76543210 35(#): 76543210
253 # 0 0 0 #
254 # 1 1 1 #
255 # 2 # 2 # 2 #
256 # 3 ## 3 ## 3 #
257 # 4####### 4####### 4 #
258 # 5 ## 5 ## 5 #
259 # 6 # 6 # 6 #
260 # 7 7 7#
261 my ($x1, $y1);
262 my $x_mult = $self->fixed_font_width() / 7;
263 # my $y_mult = $self->line_height() / 8;
264 my $y_mult = $self->line_height() / 7;
265 my $si;
266 foreach my $list (@{$vec_list}) {
267 next unless @{$list};
268 # a blank char
269 my @mapped;
270 my ($is_rect, $is_poly);
271 if ($list->[0] eq "R") {
272 $si = 1;
273 $is_rect = 1;
274 } elsif ($list->[0] eq "P") {
275 $si = 1;
276 $is_poly = 1;
277 } else {
278 $si = 0;
279 }
280 while ($si < @{$list}) {
281 ($x1, $y1) = @{$list}[$si, $si+1];
282 $si += 2;
283 push @mapped, ($abs_x + ((8 - $x1) * $x_mult),
284 # $abs_y + ($y1 * $y_mult));
285 $abs_y + (($y1 - 4) * $y_mult));
286 }
287 # printf STDERR " at: %s\n", join ",",@mapped;
288 if ($is_rect) {
289 $id = $c->create("rectangle", @mapped,
290 "-fill" => $self->fg(),
291 "-outline" => undef,
292 );
293 } elsif ($is_poly) {
294 $id = $c->create("polygon", @mapped,
295 "-fill" => $self->fg(),
296 "-outline" => undef,
297 );
298 } else {
299 $id = $c->create("line", @mapped, "-fill" => $self->fg());
300 }
301 $self->track_widget($id);
302 }
303 } else {
304 printf STDERR "Unhandled font 3 char %d (%s)\n", ord($string), $string;
305 $id = $self->create_text($c, $abs_x, $abs_y,
306 "-anchor" => TEXT_ANCHOR,
307 "-text" => "*",
308 "-fill" => $self->fg());
309 }
310 $abs_x += $self->fixed_font_width();
311 $abs_col++;
312 } else {
313 $id = $self->create_text($c, $abs_x, $abs_y,
314 "-anchor" => TEXT_ANCHOR,
315 "-text" => $string,
316 "-fill" => $is_reverse ? $self->bg() : $self->fg());
317  
318 # printf STDERR "Creating %s at line %d\n", $string, $abs_row;
319 $self->track_widget($id);
320  
321 my $sw = $self->string_width($string);
322 $self->create_reverse($id, $sw + X_BORDER, $is_reverse) if $is_reverse or
323 $self->bg() ne $self->default_bg();
324 $abs_x += $sw;
325 # FIX ME; if using default fonts!
326 $abs_col += length($string);
327 }
328  
329 }
330  
331 sub create_reverse {
332 my ($self, $text_id, $width, $is_reverse) = @_;
333  
334 # printf STDERR "reversing: %s\n", $c->itemcget($text_id, "-text");
335  
336 unless (defined $text_id) {
337 $width = $self->get_width() - $abs_x;
338 $is_reverse = 0;
339 }
340  
341 my $abs_y = $self->get_y();
342 my $top = $abs_y;
343 my $bottom = $abs_y + $self->line_height();
344  
345 my $lh2 = $self->line_height() / 2;
346 $top = $abs_y - $lh2;
347 $bottom = $abs_y + $lh2;
348  
349 my $id = $c->create("polygon",
350 $abs_x, $top,
351 $abs_x + $width, $top,
352 $abs_x + $width, $bottom,
353 $abs_x, $bottom,
354 "-fill" => $is_reverse ? $self->fg() : $self->bg(),
355 );
356 $c->lower($id);
357 $self->track_widget($id);
358  
359 $c->lower($id, $text_id) if defined $text_id;
360 }
361  
362 sub string_width {
363 # return width, in pixels, of the given string
364 my $cf = $_[0]->current_font();
365 if ($cf) {
366 return $w_main->fontMeasure($cf, $_[1]);
367 } else {
368 my $id = $c->create("text", 0,0, "-text" => $_[1]);
369 my ($x1, $y1, $x2, $y2) = $c->bbox($id);
370 $c->delete($id);
371 printf STDERR "eek! %d\n", $x2 - $x1;
372 return ($x2 - $x1);
373 }
374 }
375  
376 sub newline {
377 # print STDERR "nl\n";
378 # carp "nl";
379 Games::Rezrov::StoryFile::flush();
380 if ($_[0]->bg() ne $_[0]->default_bg()) {
381 # we're ending the line, and the current background color
382 # differs from the default. Fill out the rest of the line
383 # the the current background color.
384 print "newline fill\n";
385 $_[0]->create_reverse();
386 }
387  
388 my $line_height = $_[0]->line_height();
389 $abs_x = X_BORDER;
390 $abs_row++;
391 $abs_col = 0;
392  
393 if ($abs_row >= $rows) {
394 # cursor is at bottom of screen; scroll needed
395  
396 my ($id, $line, $ref);
397 for (my $win = 0; $win < @widgets; $win++) {
398 die "eek, unknown window $win" if
399 $win != Games::Rezrov::ZConst::LOWER_WIN and
400 $win != Games::Rezrov::ZConst::UPPER_WIN;
401 my $is_lower = $win == Games::Rezrov::ZConst::LOWER_WIN;
402
403 my $ref = $widgets[$win];
404 my @goner_rows;
405  
406 for (my $line=0; $line < $#{$ref}; $line++) {
407 if ($is_lower) {
408 # lower window:
409 if ($line <= $upper_lines) {
410 # if a lower window line is "underneath" the upper window,
411 # delete its contents.
412 push @goner_rows, $ref->[$line];
413 }
414 } else {
415 # upper window:
416 #
417 # items created in the upper window do not scroll if they are
418 # within the current bounds of the upper window.
419 next if ($line < $upper_lines);
420 @goner_rows = $ref->[$line] if $line == $upper_lines;
421 }
422 $ref->[$line] = $ref->[$line + 1];
423 # scroll line references up one
424
425 foreach (values %{$ref->[$line]}) {
426 foreach (@{$_}) {
427 # scroll each widget on the line
428 $c->move($_, 0, - $line_height);
429 if (0 and $c->type($_) eq "text") {
430 printf "now line %d (upr=%d): %s\n",
431 $line,
432 $upper_lines,
433 $c->itemcget($_, "-text");
434 }
435 }
436 }
437 }
438 $ref->[$#{$ref}] = {};
439 # "blank" last line
440  
441 # printf "goners: %d\n", scalar @goner_rows;
442 foreach (@goner_rows) {
443 # something still funny about this...why ever more than one?
444 # [bureaucracy]
445 foreach (values %{$_}) {
446 $c->delete($_) foreach @{$_};
447 # print "goner: $_\n", $c->delete($_) foreach @{$_};
448 }
449 }
450  
451 }
452
453 $abs_row--;
454 }
455  
456 Games::Rezrov::StoryFile::register_newline();
457 $c->update() if Games::Rezrov::ZOptions::MAXIMUM_SCROLLING();
458 }
459  
460 sub write_zchar {
461 # write an unbuffered character
462 if (STANDARD_COMPLIANT_BUT_EVEN_SLOWER or $_[0]->zfont == 3) {
463 # This is compliant with the spec but bogs down mighty quick.
464 # Spec says the upper window output must not be buffered;
465 # unfortunately this requires we create a widget for every
466 # character in the upper window :P
467 # printf STDERR "unbuffered wz: \"%s\"\n", chr($_[1]);
468 $_[0]->write_string(chr($_[1]));
469 } else {
470 # not compliant with spec but much more efficient.
471 # the various other flush() calls in the package are required
472 # to make this work.
473 $_[0]->SUPER::buffer_zchar($_[1]);
474 }
475 }
476  
477 sub absolute_move {
478 # set absolute column, row position; independent of window!
479 my ($self, $col, $row) = @_;
480  
481 # printf STDERR "am: %d,%d = %s,%s\n", $col, $row, $abs_x, $self->get_y();
482  
483 Games::Rezrov::StoryFile::flush();
484 $abs_x = X_BORDER + ($col * $self->fixed_font_width());
485 # $abs_x is needed because of variable-width font in lower window
486 # makes column-to-pixel translations inconvenient.
487 #
488 # absolute Y pixel position is calculated dynamically because the
489 # same line height is used for both fixed-width and variable fonts.
490 #
491 # when text items are created, with anchor "w" they are centered
492 # vertically at the given coordinates. So at row 0, text will
493 # be drawn from (- (font_height / 2)) to (font_height / 2).
494 #
495 # An earlier version just anchored text to the NW which was
496 # simpler. However, reversed text was centered funny if the font
497 # metrics were very different between fixed and variable fonts.
498  
499 $abs_row = $row;
500 $abs_col = $col;
501 }
502  
503 sub get_pixel_position {
504 return ($abs_x, $_[0]->get_y());
505 }
506  
507 sub get_pixel_geometry {
508 return (get_width() - X_BORDER, get_height());
509 # HACK
510 }
511  
512 sub get_position {
513 # with no arguments, return absolute X and Y coordinates (column/row).
514 # With an argument, return a sub that will restore the current cursor
515 # position.
516 my ($self, $sub) = @_;
517 # my ($x, $y, $r, $c) = ($abs_x, $abs_y, $abs_row, $abs_col);
518 my ($x, $r, $c) = ($abs_x, $abs_row, $abs_col);
519 if ($sub) {
520 return sub {
521 # print STDERR "restoring x=$x y=$y, ar=$r, ac=$c\n";
522 $abs_x = $x;
523 # $abs_y = $y;
524 $abs_row = $r;
525 $abs_col = $c;
526 };
527 } else {
528 # printf STDERR "get_position: x=$abs_col y=$abs_row\n";
529 return ($abs_col, $abs_row);
530 # return (int($abs_x / $self->fixed_font_width()),
531 # int($abs_y / $self->line_height()));
532 }
533 }
534  
535 sub status_hook {
536 # we're drawing the status line manually.
537 # might be possible to move this back to story:
538 # - measure string widths to position?
539 # - redraw when columns change?
540 my ($self, $location, $right_chunk) = @_;
541  
542 my $y = $status_line->height() / 2;
543 $status_line->delete($status_line->find("all"));
544 my $id = $self->create_text($status_line,
545 X_BORDER, $y,
546 "-anchor" => "w",
547 "-text" => $location,
548 "-fill" => $self->sfg());
549  
550 $id = $self->create_text($status_line,
551 200, $y,
552 "-anchor" => "e",
553 "-text" => $right_chunk,
554 "-fill" => $self->sfg());
555 my ($x1, $y1, $x2, $y2) = $status_line->bbox($id);
556 $status_line->move($id, $c->width() - X_BORDER - $x2, 0);
557 # right-justify the text
558 }
559  
560 sub cursor_on {
561 my ($self, $x) = @_;
562 # printf STDERR "cursor_on at (%d, %d), line %d\n", $x, $abs_y, $abs_row;
563 $self->cursor_x($x);
564 $self->cursor_status(1);
565 $self->draw_cursor();
566 $self->blink_init();
567 }
568  
569 sub draw_cursor {
570 my ($self) = @_;
571 my $x = $self->cursor_x();
572 return unless $x;
573 $self->cursor_off();
574 # make sure we remove old cursor
575 if ($self->cursor_status()) {
576 # if "blinking" only draw if on
577 # my $top = $abs_y;
578 # my $bottom = $abs_y + $self->line_height();
579  
580 my $lh2 = $self->line_height() / 2;
581 my $abs_y = $self->get_y();
582 my $top = $abs_y - $lh2;
583 my $bottom = $abs_y + $lh2;
584  
585 my $cx = $self->fixed_font_width() * 0.7;
586 my $id = $c->create("polygon",
587 $x, $top,
588 $x + $cx, $top,
589 $x + $cx, $bottom,
590 $x, $bottom,
591 "-fill" => $self->cc());
592 # print "drawing cursor at $x w=$cx t=$top b=$bottom\n";
593 $self->cursor_id($id);
594 }
595 }
596  
597 sub cursor_off {
598 $c->delete($_[0]->cursor_id()) if $_[0]->cursor_id();
599 }
600  
601 sub get_input {
602 my ($self, $max, $single_char, %options) = @_;
603 my $buffer = "";
604 my $last_id;
605  
606 if ($self->listening) {
607 $self->update();
608 $buffer = $self->recognize_line();
609 $self->write_string($buffer);
610 $self->newline();
611 return $buffer;
612 }
613  
614 if ($options{"-preloaded"}) {
615 # preloaded text in the buffer, but already displayed by the game; ugh.
616 #
617 # from sect15.html#read --
618 #
619 # "Just a tremendous pain in my butt"
620 # -- Andrew Plotkin
621 # "the most unfortunate feature of the Z-machine design"
622 # -- Stefan Jokisch
623 #
624 my $pre = $options{"-preloaded"};
625 my $last = $self->last_text_id();
626 my $last_text = $c->itemcget($last, "-text");
627 if ($last_text =~ /$pre$/) {
628 $last_text =~ s/$pre$//;
629 $c->itemconfigure($last, "-text" => $last_text);
630 my $width = $self->string_width($pre);
631 $last_id = $self->create_text($c,
632 $abs_x - $width,
633 # $abs_y,
634 $self->get_y(),
635 "-anchor" => TEXT_ANCHOR,
636 "-text" => $pre,
637 "-fill" => $self->fg(),
638 );
639 $self->track_widget($last_id);
640 $buffer = $pre;
641 $self->cursor_on($abs_x);
642 # start the cursor *after* the preloaded input...
643 $abs_x -= $width;
644 # ...and redraw the line from *before* it
645 } else {
646 print STDERR "miserable preload failure in get_input...\n";
647 }
648 } else {
649 $self->cursor_on($abs_x);
650 }
651 my $done = 0;
652  
653 my $callback = sub {
654 my $key;
655 my $supplied;
656 if (ref $_[0]) {
657 if ($_[1]) {
658 # supplied
659 $supplied = 1;
660 $key = $_[1];
661 } else {
662 $key = ord($w_main->XEvent()->A());
663 }
664 } else {
665 # manually passed; documentation for XEvent methods???
666 $key = $_[0];
667 $supplied = 1;
668 }
669  
670 $w_main->break() if $key == 9;
671 # simple fix for weird tab key handler crash.
672 # Duh. Thanks, Oliver.
673  
674 if ($key == Games::Rezrov::ZConst::ASCII_CR or
675 $key == Games::Rezrov::ZConst::ASCII_LF) {
676 $done = 1;
677 $self->cursor_off();
678 if ($single_char) {
679 $buffer = chr(Games::Rezrov::ZConst::Z_NEWLINE);
680 } else {
681 $self->newline();
682 }
683 return;
684 } elsif ($key == Games::Rezrov::ZConst::ASCII_DEL or
685 $key == Games::Rezrov::ZConst::ASCII_BS) {
686 if ($single_char) {
687 $done = 1;
688 $buffer = chr(Games::Rezrov::ZConst::Z_DELETE);
689 } else {
690 $buffer = substr($buffer, 0, length($buffer) - 1) if length $buffer;
691 }
692 } elsif ($supplied or ($key >= 32 and $key <= 126)) {
693 $buffer .= chr($key);
694 } else {
695 printf STDERR "unhandled key code %d (%s)\n", $key, chr($key) if $key;
696 # $buffer .= $key;
697 # $buffer .= chr($key);
698 }
699 if ($single_char) {
700 $done = 1;
701 } else {
702 my $cwin = $self->current_window();
703 if ($last_id) {
704 $c->delete($last_id);
705 }
706 $self->cursor_off();
707 $last_id = $self->create_text($c,
708 $abs_x,
709 #$abs_y,
710 $self->get_y(),
711 "-anchor" => TEXT_ANCHOR,
712 "-text" => $buffer,
713 "-fill" => $self->fg());
714 $self->track_widget($last_id);
715  
716 my ($x1, $y1, $x2, $y2) = $c->bbox($last_id);
717 # FIX ME: get_width(), etc.
718 $self->cursor_on($x2);
719 $c->update();
720 }
721 };
722 $self->bind_keys_to($callback);
723  
724 while ($done == 0) {
725 $c->after(10);
726 # to cut down on CPU time a little (does this help?)
727 $c->update();
728 }
729 $self->cursor_off();
730 $self->blink_init(1);
731 $self->bind_keys_to(sub {});
732  
733 return $buffer;
734 }
735  
736 sub bind_keys_to {
737 my ($self, $callback) = @_;
738  
739 $w_main->bind("<Any-KeyPress>" => $callback);
740 $w_main->bind("<Any-Down>" => [ $callback => Games::Rezrov::ZConst::Z_DOWN ]);
741 $w_main->bind("<Any-Up>" => [ $callback => Games::Rezrov::ZConst::Z_UP ]);
742 $w_main->bind("<Any-Left>" => [ $callback => Games::Rezrov::ZConst::Z_LEFT ]);
743 $w_main->bind("<Any-Right>" => [ $callback => Games::Rezrov::ZConst::Z_RIGHT ]);
744  
745 }
746  
747 sub clear_to_eol {
748 foreach my $list (@widgets) {
749 # for each window's widgets...
750 while (my ($column, $ids) = each %{$list->[$abs_row]}) {
751 # find the widgets in the line to be cleared...
752 if ($column >= $abs_col) {
753 $c->delete($_) foreach (@{$ids});
754 # and toss them.
755 delete $list->[$abs_row]->{$column};
756 }
757 }
758 }
759 }
760  
761 sub set_background_color {
762 $c->configure("-bg" => $_[0]->bg());
763 }
764  
765 sub clear_screen {
766 # clear the entire screen
767 $c->delete($c->find("all"));
768 @widgets = ();
769 widget_setup();
770 }
771  
772 sub widget_setup {
773 for (my $win=0; $win < 2; $win++) {
774 $widgets[$win] = [] unless defined $widgets[$win];
775 my $ref = $widgets[$win];
776 for (my $row = 0; $row <= $rows; $row++) {
777 $ref->[$row] = {} unless defined $ref->[$row];
778 }
779 }
780 }
781  
782 sub set_text_style {
783 # arg is the font mask currently in effect; higher-level code
784 # manages this
785 my ($self, $mask) = @_;
786 if ($self->dumb_fonts()) {
787 return $self->current_font("");
788 } else {
789 my $family = ($mask & Games::Rezrov::ZConst::STYLE_FIXED) ?
790 FIXED_FAMILY : $self->variable_font_family();
791 my $weight = ($mask & Games::Rezrov::ZConst::STYLE_BOLD) ? "bold" : "normal";
792 my $slant = ($mask & Games::Rezrov::ZConst::STYLE_ITALIC) ? "italic" : "roman";
793
794 my $key = $family . "_" . $weight . "_" . $slant;
795 my $fc = $self->font_cache();
796 my $font;
797 unless ($font = $fc->{$key}) {
798 # print "new font\n";
799 $font = $w_main->fontCreate("-family" => $family,
800 "-weight" => $weight,
801 "-slant" => $slant,
802 "-size" => $self->font_size());
803 $fc->{$key} = $font;
804 }
805 # printf "%d: %s/%s/%s = %s\n", $mask, $family, $weight, $slant, $font;
806 $self->current_font($font);
807 return $font;
808 }
809 }
810  
811 sub groks_font_3 {
812 return 1;
813 }
814  
815 sub can_change_title {
816 return 1;
817 }
818  
819 sub can_use_color {
820 return 1;
821 }
822  
823 sub set_game_title {
824 $w_main->title($_[1]);
825 }
826  
827 sub cleanup {
828 # don't just rely on DESTROY, doesn't work for interrupts
829 $w_main->destroy() if $w_main;
830  
831 Tk::exit();
832 # cleaner; see Tk::exit.pod. Without, often coredumps.
833 # but if we do this, will we miss a die() message elsewhere?
834
835 # November 2003: Tk-804.025_beta6 segfaults on exit, WTF?
836 # Didn't use to!
837 }
838  
839 sub validate_family {
840 my ($self, $family) = @_;
841 my %families = map {lc($_) => 1} $w_main->fontFamilies();
842 if (exists ($families{lc($family)})) {
843 return $family;
844 } else {
845 die sprintf "%s is not a valid font family on your system. Valid families are: %s\n", $family, join ", ", sort keys %families;
846 }
847 }
848  
849 sub blink_init {
850 my ($self, $cancel) = @_;
851 $w_main->afterCancel($self->blink_id()) if $self->blink_id();
852 # called whenever cursor is turned on by the app; leave cursor
853 # alone for X milliseconds, then blink periodically
854  
855 unless ($cancel) {
856 my $blink_delay = exists $self->zio_options()->{"blink"} ?
857 $self->zio_options()->{"blink"} : DEFAULT_BLINK_DELAY;
858 if ($blink_delay) {
859 $self->blink_id($w_main->repeat($blink_delay, [ $self => 'cursor_blinker' ]));
860 }
861 }
862 }
863  
864 sub cursor_blinker {
865 my ($self) = @_;
866 $self->cursor_status(!$self->cursor_status());
867 $self->draw_cursor();
868 # needs work: if cursor is printed by the app, we should
869 # leave it on for awhile...
870 }
871  
872 sub split_window {
873 $upper_lines = $_[1];
874 # print STDERR "ul: $upper_lines\n";
875 }
876  
877 sub get_height {
878 return $c->height() == 1 ? $c->reqheight() : $c->height();
879 }
880  
881 sub get_width {
882 return $c->width() == 1 ? $c->reqwidth() : $c->width();
883 }
884  
885 sub set_geometry {
886 # figure out rows/columns
887 my $self = shift;
888 my ($cx, $cy) = $self->get_pixel_geometry();
889 my $lh = $self->line_height();
890  
891 my $old_y = $self->get_y();
892  
893 my $old_rows = $rows;
894 $rows = int($cy / $lh);
895 widget_setup();
896 my $columns = int($cx / $self->fixed_font_width());
897 # printf STDERR "set_geometry: cx:%d cy:%d lh:%d geometry: %dx%d\n", $cx, $cy, $self->line_height(), $columns, $rows;
898 # print STDERR "rows: $rows\n";
899 Games::Rezrov::StoryFile::rows($rows);
900 Games::Rezrov::StoryFile::columns($columns);
901  
902 # if window is now smaller than where cursor was last, scroll the window up and then correct the cursor row
903 if ($abs_row >= $rows) {
904 my ($save_col, $save_x) = ($abs_col, $abs_x);
905 $self->newline for $rows .. $old_rows - 1;
906 ($abs_col, $abs_x, $abs_row) = ($save_col, $save_x, $rows - 1);
907 }
908  
909 }
910  
911 sub biggest_metric {
912 my ($self, $f1, $f2, $metric) = @_;
913 my $v1 = $w_main->fontMetrics($f1, $metric);
914 my $v2 = $w_main->fontMetrics($f2, $metric);
915 # print "$metric $v1 $v2\n";
916 return $v1 > $v2 ? $v1 : $v2;
917 }
918  
919 sub set_font {
920 # printf STDERR "set_font: %s win=%s\n", $_[1], $_[0]->current_window();
921 return $_[0]->zfont($_[1]);
922 }
923  
924 sub track_widget {
925 # push @{$widgets[$cwin][$abs_row]->{$abs_col}}, $_[1];
926 push @{$widgets[$_[0]->current_window()][$abs_row]->{$abs_col}}, $_[1];
927 # an array is required for each location, as layered widgets are
928 # used to achieve "inverse video" effect
929 }
930  
931 sub column_list {
932 # print a list in "column" format
933 my ($list, %options) = @_;
934  
935 my $longest = 0;
936 foreach (@{$list}) {
937 my $len = length($_);
938 $longest = $len if $len > $longest;
939 }
940 $longest += 2;
941 my $columns = 75 / $longest;
942 my $format = ("%-" . $longest . "s") x $columns;
943 my @results;
944 my @list = @{$list};
945 while (@list) {
946 push @results, sprintf $format, splice(@list,0,$columns);
947 }
948 return @results;
949 }
950  
951 sub get_y {
952 # translate current row into a pixel position
953 return $Y_BORDER + ($abs_row * $_[0]->line_height());
954 }
955  
956 sub i_am_too_dumb_to_figure_this_out {
957 # 9/2004:
958 # Pressing the "Tab" key wreaks havoc...once pressed, program
959 # seems to think every subsequent keypress is also a tab key!
960 # Maybe some queue needs to be flushed? I dunno.
961  
962 # Anyway, we could:
963 # - instead of binding "Any-KeyPress" we could bind all the individual
964 # keys EXCEPT the tab key. I think this would work, but there are
965 # an awful lot of symbols to bind and I'm sure I'll forget some.
966 # - unbind the tab key. Can't get this to work (undef, " ").
967 # - bind the tab key to a null sub. Works temporarily, but
968 # somehow subsequent Any-Keypress binds seem to override it!
969 # - cop out (this subroutine)
970  
971 my $msg = "I hate the tab key in Tk";
972 if (1) {
973 *Tk::Error = sub {};
974 # trash the error handler to keep this quiet.
975 die $msg;
976 # unless we die() the tab event seems to cause the (queueing?) lockup.
977 } else {
978 # aborted attempt to save/restore the original Tk handler.
979 # seems to work once, but tab key then causes lockups.
980 unless ($Games::Rezrov::ZIO_Tk::ORIG_TK_HANDLER) {
981 $Games::Rezrov::ZIO_Tk::ORIG_TK_HANDLER = \&Tk::Error;
982 }
983 my $restore_sub = sub {
984 no warnings;
985 *Tk::Error = $Games::Rezrov::ZIO_Tk::ORIG_TK_HANDLER;
986 $w_main->bind("<Bogus>" => sub {});
987 # test whether original handler is restored
988 };
989 $w_main->after(100, $restore_sub);
990 *Tk::Error = sub {};
991 die $msg;
992 }
993 }
994  
995 1;