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