big speedup
[p5sagit/p5-mst-13.2.git] / lib / Term / Cap.pm
CommitLineData
a0d0e21e 1package Term::Cap;
cb1a09d0 2use Carp;
85e6fe83 3
b75c8c73 4our $VERSION = '1.00';
5
6# Last updated: Thu Nov 30 23:34:29 EST 2000 by schwern@pobox.com
a687059c 7
cb1a09d0 8# TODO:
9# support Berkeley DB termcaps
10# should probably be a .xs module
11# force $FH into callers package?
12# keep $FH in object at Tgetent time?
13
14=head1 NAME
15
16Term::Cap - Perl termcap interface
17
18=head1 SYNOPSIS
19
20 require Term::Cap;
21 $terminal = Tgetent Term::Cap { TERM => undef, OSPEED => $ospeed };
22 $terminal->Trequire(qw/ce ku kd/);
23 $terminal->Tgoto('cm', $col, $row, $FH);
24 $terminal->Tputs('dl', $count, $FH);
25 $terminal->Tpad($string, $count, $FH);
26
27=head1 DESCRIPTION
28
29These are low-level functions to extract and use capabilities from
30a terminal capability (termcap) database.
31
32The B<Tgetent> function extracts the entry of the specified terminal
33type I<TERM> (defaults to the environment variable I<TERM>) from the
34database.
35
36It will look in the environment for a I<TERMCAP> variable. If
37found, and the value does not begin with a slash, and the terminal
38type name is the same as the environment string I<TERM>, the
39I<TERMCAP> string is used instead of reading a termcap file. If
40it does begin with a slash, the string is used as a path name of
41the termcap file to search. If I<TERMCAP> does not begin with a
42slash and name is different from I<TERM>, B<Tgetent> searches the
43files F<$HOME/.termcap>, F</etc/termcap>, and F</usr/share/misc/termcap>,
44in that order, unless the environment variable I<TERMPATH> exists,
45in which case it specifies a list of file pathnames (separated by
46spaces or colons) to be searched B<instead>. Whenever multiple
47files are searched and a tc field occurs in the requested entry,
48the entry it names must be found in the same file or one of the
49succeeding files. If there is a C<:tc=...:> in the I<TERMCAP>
50environment variable string it will continue the search in the
51files as above.
52
53I<OSPEED> is the terminal output bit rate (often mistakenly called
54the baud rate). I<OSPEED> can be specified as either a POSIX
55termios/SYSV termio speeds (where 9600 equals 9600) or an old
56BSD-style speeds (where 13 equals 9600).
57
58B<Tgetent> returns a blessed object reference which the user can
59then use to send the control strings to the terminal using B<Tputs>
60and B<Tgoto>. It calls C<croak> on failure.
61
62B<Tgoto> decodes a cursor addressing string with the given parameters.
63
64The output strings for B<Tputs> are cached for counts of 1 for performance.
65B<Tgoto> and B<Tpad> do not cache. C<$self-E<gt>{_xx}> is the raw termcap
66data and C<$self-E<gt>{xx}> is the cached version.
67
68 print $terminal->Tpad($self->{_xx}, 1);
69
70B<Tgoto>, B<Tputs>, and B<Tpad> return the string and will also
71output the string to $FH if specified.
72
73The extracted termcap entry is available in the object
74as C<$self-E<gt>{TERMCAP}>.
75
76=head1 EXAMPLES
77
78 # Get terminal output speed
79 require POSIX;
80 my $termios = new POSIX::Termios;
81 $termios->getattr;
82 my $ospeed = $termios->getospeed;
83
84 # Old-style ioctl code to get ospeed:
85 # require 'ioctl.pl';
86 # ioctl(TTY,$TIOCGETP,$sgtty);
87 # ($ispeed,$ospeed) = unpack('cc',$sgtty);
88
89 # allocate and initialize a terminal structure
90 $terminal = Tgetent Term::Cap { TERM => undef, OSPEED => $ospeed };
91
92 # require certain capabilities to be available
93 $terminal->Trequire(qw/ce ku kd/);
94
95 # Output Routines, if $FH is undefined these just return the string
96
97 # Tgoto does the % expansion stuff with the given args
98 $terminal->Tgoto('cm', $col, $row, $FH);
99
100 # Tputs doesn't do any % expansion.
101 $terminal->Tputs('dl', $count = 1, $FH);
102
103=cut
104
105# Returns a list of termcap files to check.
106sub termcap_path { ## private
107 my @termcap_path;
108 # $TERMCAP, if it's a filespec
7a2e2cd6 109 push(@termcap_path, $ENV{TERMCAP})
110 if ((exists $ENV{TERMCAP}) &&
39e571d4 111 (($^O eq 'os2' || $^O eq 'MSWin32' || $^O eq 'dos')
fe6f1558 112 ? $ENV{TERMCAP} =~ /^[a-z]:[\\\/]/is
113 : $ENV{TERMCAP} =~ /^\//s));
c07a80fd 114 if ((exists $ENV{TERMPATH}) && ($ENV{TERMPATH})) {
cb1a09d0 115 # Add the users $TERMPATH
116 push(@termcap_path, split(/(:|\s+)/, $ENV{TERMPATH}))
117 }
118 else {
119 # Defaults
120 push(@termcap_path,
121 $ENV{'HOME'} . '/.termcap',
122 '/etc/termcap',
123 '/usr/share/misc/termcap',
124 );
a687059c 125 }
cb1a09d0 126 # return the list of those termcaps that exist
748a9306 127 grep(-f, @termcap_path);
128}
129
cb1a09d0 130sub Tgetent { ## public -- static method
131 my $class = shift;
132 my $self = bless shift, $class;
133 my($term,$cap,$search,$field,$max,$tmp_term,$TERMCAP);
134 local($termpat,$state,$first,$entry); # used inside eval
135 local $_;
136
137 # Compute PADDING factor from OSPEED (to be used by Tpad)
138 if (! $self->{OSPEED}) {
139 carp "OSPEED was not set, defaulting to 9600";
140 $self->{OSPEED} = 9600;
141 }
142 if ($self->{OSPEED} < 16) {
143 # delays for old style speeds
144 my @pad = (0,200,133.3,90.9,74.3,66.7,50,33.3,16.7,8.3,5.5,4.1,2,1,.5,.2);
145 $self->{PADDING} = $pad[$self->{OSPEED}];
146 }
147 else {
148 $self->{PADDING} = 10000 / $self->{OSPEED};
149 }
150
151 $self->{TERM} = ($self->{TERM} || $ENV{TERM} || croak "TERM not set");
152 $term = $self->{TERM}; # $term is the term type we are looking for
153
154 # $tmp_term is always the next term (possibly :tc=...:) we are looking for
155 $tmp_term = $self->{TERM};
156 # protect any pattern metacharacters in $tmp_term
157 $termpat = $tmp_term; $termpat =~ s/(\W)/\\$1/g;
158
c07a80fd 159 my $foo = (exists $ENV{TERMCAP} ? $ENV{TERMCAP} : '');
cb1a09d0 160
161 # $entry is the extracted termcap entry
fe6f1558 162 if (($foo !~ m:^/:s) && ($foo =~ m/(^|\|)${termpat}[:|]/s)) {
cb1a09d0 163 $entry = $foo;
164 }
165
166 my @termcap_path = termcap_path;
167 croak "Can't find a valid termcap file" unless @termcap_path || $entry;
168
169 $state = 1; # 0 == finished
170 # 1 == next file
171 # 2 == search again
172
173 $first = 0; # first entry (keeps term name)
174
175 $max = 32; # max :tc=...:'s
176
177 if ($entry) {
178 # ok, we're starting with $TERMCAP
179 $first++; # we're the first entry
180 # do we need to continue?
181 if ($entry =~ s/:tc=([^:]+):/:/) {
182 $tmp_term = $1;
183 # protect any pattern metacharacters in $tmp_term
184 $termpat = $tmp_term; $termpat =~ s/(\W)/\\$1/g;
185 }
186 else {
187 $state = 0; # we're already finished
188 }
189 }
190
191 # This is eval'ed inside the while loop for each file
192 $search = q{
54310121 193 while (<TERMCAP>) {
cb1a09d0 194 next if /^\\t/ || /^#/;
195 if ($_ =~ m/(^|\\|)${termpat}[:|]/o) {
196 chomp;
197 s/^[^:]*:// if $first++;
198 $state = 0;
54310121 199 while ($_ =~ s/\\\\$//) {
200 defined(my $x = <TERMCAP>) or last;
201 $_ .= $x; chomp;
202 }
cb1a09d0 203 last;
748a9306 204 }
cb1a09d0 205 }
55497cff 206 defined $entry or $entry = '';
207 $entry .= $_;
cb1a09d0 208 };
748a9306 209
cb1a09d0 210 while ($state != 0) {
211 if ($state == 1) {
212 # get the next TERMCAP
213 $TERMCAP = shift @termcap_path
214 || croak "failed termcap lookup on $tmp_term";
215 }
216 else {
217 # do the same file again
218 # prevent endless recursion
219 $max-- || croak "failed termcap loop at $tmp_term";
220 $state = 1; # ok, maybe do a new file next time
221 }
222
223 open(TERMCAP,"< $TERMCAP\0") || croak "open $TERMCAP: $!";
224 eval $search;
225 die $@ if $@;
226 close TERMCAP;
227
228 # If :tc=...: found then search this file again
229 $entry =~ s/:tc=([^:]+):/:/ && ($tmp_term = $1, $state = 2);
230 # protect any pattern metacharacters in $tmp_term
231 $termpat = $tmp_term; $termpat =~ s/(\W)/\\$1/g;
a687059c 232 }
cb1a09d0 233
234 croak "Can't find $term" if $entry eq '';
235 $entry =~ s/:+\s*:+/:/g; # cleanup $entry
236 $entry =~ s/:+/:/g; # cleanup $entry
237 $self->{TERMCAP} = $entry; # save it
238 # print STDERR "DEBUG: $entry = ", $entry, "\n";
a687059c 239
748a9306 240 # Precompile $entry into the object
cb1a09d0 241 $entry =~ s/^[^:]*://;
748a9306 242 foreach $field (split(/:[\s:\\]*/,$entry)) {
cb1a09d0 243 if ($field =~ /^(\w\w)$/) {
244 $self->{'_' . $field} = 1 unless defined $self->{'_' . $1};
245 # print STDERR "DEBUG: flag $1\n";
748a9306 246 }
247 elsif ($field =~ /^(\w\w)\@/) {
cb1a09d0 248 $self->{'_' . $1} = "";
249 # print STDERR "DEBUG: unset $1\n";
a687059c 250 }
251 elsif ($field =~ /^(\w\w)#(.*)/) {
cb1a09d0 252 $self->{'_' . $1} = $2 unless defined $self->{'_' . $1};
253 # print STDERR "DEBUG: numeric $1 = $2\n";
a687059c 254 }
255 elsif ($field =~ /^(\w\w)=(.*)/) {
cb1a09d0 256 # print STDERR "DEBUG: string $1 = $2\n";
257 next if defined $self->{'_' . ($cap = $1)};
a687059c 258 $_ = $2;
259 s/\\E/\033/g;
ecfc5424 260 s/\\(\d\d\d)/pack('c',oct($1) & 0177)/eg;
a687059c 261 s/\\n/\n/g;
262 s/\\r/\r/g;
263 s/\\t/\t/g;
264 s/\\b/\b/g;
265 s/\\f/\f/g;
266 s/\\\^/\377/g;
267 s/\^\?/\177/g;
63f2c1e1 268 s/\^(.)/pack('c',ord($1) & 31)/eg;
a687059c 269 s/\\(.)/$1/g;
270 s/\377/^/g;
cb1a09d0 271 $self->{'_' . $cap} = $_;
a687059c 272 }
cb1a09d0 273 # else { carp "junk in $term ignored: $field"; }
a687059c 274 }
cb1a09d0 275 $self->{'_pc'} = "\0" unless defined $self->{'_pc'};
276 $self->{'_bc'} = "\b" unless defined $self->{'_bc'};
277 $self;
a687059c 278}
279
cb1a09d0 280# $terminal->Tpad($string, $cnt, $FH);
281sub Tpad { ## public
282 my $self = shift;
283 my($string, $cnt, $FH) = @_;
284 my($decr, $ms);
a687059c 285
a687059c 286 if ($string =~ /(^[\d.]+)(\*?)(.*)$/) {
287 $ms = $1;
748a9306 288 $ms *= $cnt if $2;
a687059c 289 $string = $3;
cb1a09d0 290 $decr = $self->{PADDING};
a687059c 291 if ($decr > .1) {
292 $ms += $decr / 2;
cb1a09d0 293 $string .= $self->{'_pc'} x ($ms / $decr);
a687059c 294 }
295 }
296 print $FH $string if $FH;
297 $string;
298}
299
cb1a09d0 300# $terminal->Tputs($cap, $cnt, $FH);
301sub Tputs { ## public
302 my $self = shift;
303 my($cap, $cnt, $FH) = @_;
304 my $string;
748a9306 305
306 if ($cnt > 1) {
cb1a09d0 307 $string = Tpad($self, $self->{'_' . $cap}, $cnt);
748a9306 308 } else {
cb1a09d0 309 # cache result because Tpad can be slow
310 $string = defined $self->{$cap} ? $self->{$cap} :
311 ($self->{$cap} = Tpad($self, $self->{'_' . $cap}, 1));
748a9306 312 }
313 print $FH $string if $FH;
314 $string;
315}
316
317# %% output `%'
318# %d output value as in printf %d
319# %2 output value as in printf %2d
320# %3 output value as in printf %3d
321# %. output value as in printf %c
322# %+x add x to value, then do %.
323#
324# %>xy if value > x then add y, no output
325# %r reverse order of two parameters, no output
326# %i increment by one, no output
327# %B BCD (16*(value/10)) + (value%10), no output
328#
329# %n exclusive-or all parameters with 0140 (Datamedia 2500)
330# %D Reverse coding (value - 2*(value%16)), no output (Delta Data)
331#
cb1a09d0 332# $terminal->Tgoto($cap, $col, $row, $FH);
333sub Tgoto { ## public
334 my $self = shift;
335 my($cap, $code, $tmp, $FH) = @_;
336 my $string = $self->{'_' . $cap};
337 my $result = '';
338 my $after = '';
339 my $online = 0;
340 my @tmp = ($tmp,$code);
341 my $cnt = $code;
748a9306 342
a687059c 343 while ($string =~ /^([^%]*)%(.)(.*)/) {
344 $result .= $1;
345 $code = $2;
346 $string = $3;
347 if ($code eq 'd') {
9f68db38 348 $result .= sprintf("%d",shift(@tmp));
a687059c 349 }
350 elsif ($code eq '.') {
9f68db38 351 $tmp = shift(@tmp);
a687059c 352 if ($tmp == 0 || $tmp == 4 || $tmp == 10) {
353 if ($online) {
cb1a09d0 354 ++$tmp, $after .= $self->{'_up'} if $self->{'_up'};
a687059c 355 }
356 else {
cb1a09d0 357 ++$tmp, $after .= $self->{'_bc'};
a687059c 358 }
359 }
360 $result .= sprintf("%c",$tmp);
361 $online = !$online;
362 }
363 elsif ($code eq '+') {
9f68db38 364 $result .= sprintf("%c",shift(@tmp)+ord($string));
a687059c 365 $string = substr($string,1,99);
366 $online = !$online;
367 }
368 elsif ($code eq 'r') {
9f68db38 369 ($code,$tmp) = @tmp;
370 @tmp = ($tmp,$code);
a687059c 371 $online = !$online;
372 }
373 elsif ($code eq '>') {
374 ($code,$tmp,$string) = unpack("CCa99",$string);
9f68db38 375 if ($tmp[$[] > $code) {
376 $tmp[$[] += $tmp;
a687059c 377 }
378 }
379 elsif ($code eq '2') {
9f68db38 380 $result .= sprintf("%02d",shift(@tmp));
a687059c 381 $online = !$online;
382 }
383 elsif ($code eq '3') {
9f68db38 384 $result .= sprintf("%03d",shift(@tmp));
a687059c 385 $online = !$online;
386 }
387 elsif ($code eq 'i') {
9f68db38 388 ($code,$tmp) = @tmp;
389 @tmp = ($code+1,$tmp+1);
a687059c 390 }
391 else {
392 return "OOPS";
393 }
394 }
cb1a09d0 395 $string = Tpad($self, $result . $string . $after, $cnt);
748a9306 396 print $FH $string if $FH;
397 $string;
398}
399
cb1a09d0 400# $terminal->Trequire(qw/ce ku kd/);
401sub Trequire { ## public
402 my $self = shift;
403 my($cap,@undefined);
404 foreach $cap (@_) {
405 push(@undefined, $cap)
406 unless defined $self->{'_' . $cap} && $self->{'_' . $cap};
748a9306 407 }
cb1a09d0 408 croak "Terminal does not support: (@undefined)" if @undefined;
a687059c 409}
410
4111;
cb1a09d0 412