Once again syncing after too long an absence
[p5sagit/p5-mst-13.2.git] / lib / Term / Cap.pm
1 package Term::Cap;
2 use Carp;
3
4 our $VERSION = '1.00';
5
6 # Last updated: Thu Nov 30 23:34:29 EST 2000 by schwern@pobox.com
7
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
16 Term::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
29 These are low-level functions to extract and use capabilities from
30 a terminal capability (termcap) database.
31
32 The B<Tgetent> function extracts the entry of the specified terminal
33 type I<TERM> (defaults to the environment variable I<TERM>) from the
34 database.
35
36 It will look in the environment for a I<TERMCAP> variable.  If
37 found, and the value does not begin with a slash, and the terminal
38 type name is the same as the environment string I<TERM>, the
39 I<TERMCAP> string is used instead of reading a termcap file.  If
40 it does begin with a slash, the string is used as a path name of
41 the termcap file to search.  If I<TERMCAP> does not begin with a
42 slash and name is different from I<TERM>, B<Tgetent> searches the
43 files F<$HOME/.termcap>, F</etc/termcap>, and F</usr/share/misc/termcap>,
44 in that order, unless the environment variable I<TERMPATH> exists,
45 in which case it specifies a list of file pathnames (separated by
46 spaces or colons) to be searched B<instead>.  Whenever multiple
47 files are searched and a tc field occurs in the requested entry,
48 the entry it names must be found in the same file or one of the
49 succeeding files.  If there is a C<:tc=...:> in the I<TERMCAP>
50 environment variable string it will continue the search in the
51 files as above.
52
53 I<OSPEED> is the terminal output bit rate (often mistakenly called
54 the baud rate).  I<OSPEED> can be specified as either a POSIX
55 termios/SYSV termio speeds (where 9600 equals 9600) or an old
56 BSD-style speeds (where 13 equals 9600).
57
58 B<Tgetent> returns a blessed object reference which the user can
59 then use to send the control strings to the terminal using B<Tputs>
60 and B<Tgoto>.  It calls C<croak> on failure.
61
62 B<Tgoto> decodes a cursor addressing string with the given parameters.
63
64 The output strings for B<Tputs> are cached for counts of 1 for performance.
65 B<Tgoto> and B<Tpad> do not cache.  C<$self-E<gt>{_xx}> is the raw termcap
66 data and C<$self-E<gt>{xx}> is the cached version.
67
68     print $terminal->Tpad($self->{_xx}, 1);
69
70 B<Tgoto>, B<Tputs>, and B<Tpad> return the string and will also
71 output the string to $FH if specified.
72
73 The extracted termcap entry is available in the object
74 as 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.
106 sub termcap_path { ## private
107     my @termcap_path;
108     # $TERMCAP, if it's a filespec
109     push(@termcap_path, $ENV{TERMCAP})
110         if ((exists $ENV{TERMCAP}) &&
111             (($^O eq 'os2' || $^O eq 'MSWin32' || $^O eq 'dos')
112              ? $ENV{TERMCAP} =~ /^[a-z]:[\\\/]/is
113              : $ENV{TERMCAP} =~ /^\//s));
114     if ((exists $ENV{TERMPATH}) && ($ENV{TERMPATH})) {
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         );
125     }
126     # return the list of those termcaps that exist
127     grep(-f, @termcap_path);
128 }
129
130 sub 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
159     my $foo = (exists $ENV{TERMCAP} ? $ENV{TERMCAP} : '');
160
161     # $entry is the extracted termcap entry
162     if (($foo !~ m:^/:s) && ($foo =~ m/(^|\|)${termpat}[:|]/s)) {
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{
193         while (<TERMCAP>) {
194             next if /^\\t/ || /^#/;
195             if ($_ =~ m/(^|\\|)${termpat}[:|]/o) {
196                 chomp;
197                 s/^[^:]*:// if $first++;
198                 $state = 0;
199                 while ($_ =~ s/\\\\$//) {
200                     defined(my $x = <TERMCAP>) or last;
201                     $_ .= $x; chomp;
202                 }
203                 last;
204             }
205         }
206         defined $entry or $entry = '';
207         $entry .= $_;
208     };
209
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;
232     }
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";
239
240     # Precompile $entry into the object
241     $entry =~ s/^[^:]*://;
242     foreach $field (split(/:[\s:\\]*/,$entry)) {
243         if ($field =~ /^(\w\w)$/) {
244             $self->{'_' . $field} = 1 unless defined $self->{'_' . $1};
245             # print STDERR "DEBUG: flag $1\n";
246         }
247         elsif ($field =~ /^(\w\w)\@/) {
248             $self->{'_' . $1} = "";
249             # print STDERR "DEBUG: unset $1\n";
250         }
251         elsif ($field =~ /^(\w\w)#(.*)/) {
252             $self->{'_' . $1} = $2 unless defined $self->{'_' . $1};
253             # print STDERR "DEBUG: numeric $1 = $2\n";
254         }
255         elsif ($field =~ /^(\w\w)=(.*)/) {
256             # print STDERR "DEBUG: string $1 = $2\n";
257             next if defined $self->{'_' . ($cap = $1)};
258             $_ = $2;
259             s/\\E/\033/g;
260             s/\\(\d\d\d)/pack('c',oct($1) & 0177)/eg;
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;
268             s/\^(.)/pack('c',ord($1) & 31)/eg;
269             s/\\(.)/$1/g;
270             s/\377/^/g;
271             $self->{'_' . $cap} = $_;
272         }
273         # else { carp "junk in $term ignored: $field"; }
274     }
275     $self->{'_pc'} = "\0" unless defined $self->{'_pc'};
276     $self->{'_bc'} = "\b" unless defined $self->{'_bc'};
277     $self;
278 }
279
280 # $terminal->Tpad($string, $cnt, $FH);
281 sub Tpad { ## public
282     my $self = shift;
283     my($string, $cnt, $FH) = @_;
284     my($decr, $ms);
285
286     if ($string =~ /(^[\d.]+)(\*?)(.*)$/) {
287         $ms = $1;
288         $ms *= $cnt if $2;
289         $string = $3;
290         $decr = $self->{PADDING};
291         if ($decr > .1) {
292             $ms += $decr / 2;
293             $string .= $self->{'_pc'} x ($ms / $decr);
294         }
295     }
296     print $FH $string if $FH;
297     $string;
298 }
299
300 # $terminal->Tputs($cap, $cnt, $FH);
301 sub Tputs { ## public
302     my $self = shift;
303     my($cap, $cnt, $FH) = @_;
304     my $string;
305
306     if ($cnt > 1) {
307         $string = Tpad($self, $self->{'_' . $cap}, $cnt);
308     } else {
309         # cache result because Tpad can be slow
310         $string = defined $self->{$cap} ? $self->{$cap} :
311             ($self->{$cap} = Tpad($self, $self->{'_' . $cap}, 1));
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 #
332 # $terminal->Tgoto($cap, $col, $row, $FH);
333 sub 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;
342
343     while ($string =~ /^([^%]*)%(.)(.*)/) {
344         $result .= $1;
345         $code = $2;
346         $string = $3;
347         if ($code eq 'd') {
348             $result .= sprintf("%d",shift(@tmp));
349         }
350         elsif ($code eq '.') {
351             $tmp = shift(@tmp);
352             if ($tmp == 0 || $tmp == 4 || $tmp == 10) {
353                 if ($online) {
354                     ++$tmp, $after .= $self->{'_up'} if $self->{'_up'};
355                 }
356                 else {
357                     ++$tmp, $after .= $self->{'_bc'};
358                 }
359             }
360             $result .= sprintf("%c",$tmp);
361             $online = !$online;
362         }
363         elsif ($code eq '+') {
364             $result .= sprintf("%c",shift(@tmp)+ord($string));
365             $string = substr($string,1,99);
366             $online = !$online;
367         }
368         elsif ($code eq 'r') {
369             ($code,$tmp) = @tmp;
370             @tmp = ($tmp,$code);
371             $online = !$online;
372         }
373         elsif ($code eq '>') {
374             ($code,$tmp,$string) = unpack("CCa99",$string);
375             if ($tmp[$[] > $code) {
376                 $tmp[$[] += $tmp;
377             }
378         }
379         elsif ($code eq '2') {
380             $result .= sprintf("%02d",shift(@tmp));
381             $online = !$online;
382         }
383         elsif ($code eq '3') {
384             $result .= sprintf("%03d",shift(@tmp));
385             $online = !$online;
386         }
387         elsif ($code eq 'i') {
388             ($code,$tmp) = @tmp;
389             @tmp = ($code+1,$tmp+1);
390         }
391         else {
392             return "OOPS";
393         }
394     }
395     $string = Tpad($self, $result . $string . $after, $cnt);
396     print $FH $string if $FH;
397     $string;
398 }
399
400 # $terminal->Trequire(qw/ce ku kd/);
401 sub Trequire { ## public
402     my $self = shift;
403     my($cap,@undefined);
404     foreach $cap (@_) {
405         push(@undefined, $cap)
406             unless defined $self->{'_' . $cap} && $self->{'_' . $cap};
407     }
408     croak "Terminal does not support: (@undefined)" if @undefined;
409 }
410
411 1;
412