This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
don't bother testing if we can flush all handles when fflush(stdin)
[perl5.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})
108         if ((exists $ENV{TERMCAP}) &&
109             (($^O eq 'os2' || $^O eq 'MSWin32' || $^O eq 'dos')
110              ? $ENV{TERMCAP} =~ /^[a-z]:[\\\/]/is
111              : $ENV{TERMCAP} =~ /^\//s));
112     if ((exists $ENV{TERMPATH}) && ($ENV{TERMPATH})) {
113         # Add the users $TERMPATH
114         push(@termcap_path, split(/(:|\s+)/, $ENV{TERMPATH}))
115     }
116     else {
117         # Defaults
118         push(@termcap_path,
119             $ENV{'HOME'} . '/.termcap',
120             '/etc/termcap',
121             '/usr/share/misc/termcap',
122         );
123     }
124     # return the list of those termcaps that exist
125     grep(-f, @termcap_path);
126 }
127
128 sub Tgetent { ## public -- static method
129     my $class = shift;
130     my $self = bless shift, $class;
131     my($term,$cap,$search,$field,$max,$tmp_term,$TERMCAP);
132     local($termpat,$state,$first,$entry);       # used inside eval
133     local $_;
134
135     # Compute PADDING factor from OSPEED (to be used by Tpad)
136     if (! $self->{OSPEED}) {
137         carp "OSPEED was not set, defaulting to 9600";
138         $self->{OSPEED} = 9600;
139     }
140     if ($self->{OSPEED} < 16) {
141         # delays for old style speeds
142         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);
143         $self->{PADDING} = $pad[$self->{OSPEED}];
144     }
145     else {
146         $self->{PADDING} = 10000 / $self->{OSPEED};
147     }
148
149     $self->{TERM} = ($self->{TERM} || $ENV{TERM} || croak "TERM not set");
150     $term = $self->{TERM};      # $term is the term type we are looking for
151
152     # $tmp_term is always the next term (possibly :tc=...:) we are looking for
153     $tmp_term = $self->{TERM};
154     # protect any pattern metacharacters in $tmp_term 
155     $termpat = $tmp_term; $termpat =~ s/(\W)/\\$1/g;
156
157     my $foo = (exists $ENV{TERMCAP} ? $ENV{TERMCAP} : '');
158
159     # $entry is the extracted termcap entry
160     if (($foo !~ m:^/:s) && ($foo =~ m/(^|\|)${termpat}[:|]/s)) {
161         $entry = $foo;
162     }
163
164     my @termcap_path = termcap_path;
165     croak "Can't find a valid termcap file" unless @termcap_path || $entry;
166
167     $state = 1;                                 # 0 == finished
168                                                 # 1 == next file
169                                                 # 2 == search again
170
171     $first = 0;                                 # first entry (keeps term name)
172
173     $max = 32;                                  # max :tc=...:'s
174
175     if ($entry) {
176         # ok, we're starting with $TERMCAP
177         $first++;                               # we're the first entry
178         # do we need to continue?
179         if ($entry =~ s/:tc=([^:]+):/:/) {
180             $tmp_term = $1;
181             # protect any pattern metacharacters in $tmp_term 
182             $termpat = $tmp_term; $termpat =~ s/(\W)/\\$1/g;
183         }
184         else {
185             $state = 0;                         # we're already finished
186         }
187     }
188
189     # This is eval'ed inside the while loop for each file
190     $search = q{
191         while (<TERMCAP>) {
192             next if /^\\t/ || /^#/;
193             if ($_ =~ m/(^|\\|)${termpat}[:|]/o) {
194                 chomp;
195                 s/^[^:]*:// if $first++;
196                 $state = 0;
197                 while ($_ =~ s/\\\\$//) {
198                     defined(my $x = <TERMCAP>) or last;
199                     $_ .= $x; chomp;
200                 }
201                 last;
202             }
203         }
204         defined $entry or $entry = '';
205         $entry .= $_;
206     };
207
208     while ($state != 0) {
209         if ($state == 1) {
210             # get the next TERMCAP
211             $TERMCAP = shift @termcap_path
212                 || croak "failed termcap lookup on $tmp_term";
213         }
214         else {
215             # do the same file again
216             # prevent endless recursion
217             $max-- || croak "failed termcap loop at $tmp_term";
218             $state = 1;         # ok, maybe do a new file next time
219         }
220
221         open(TERMCAP,"< $TERMCAP\0") || croak "open $TERMCAP: $!";
222         eval $search;
223         die $@ if $@;
224         close TERMCAP;
225
226         # If :tc=...: found then search this file again
227         $entry =~ s/:tc=([^:]+):/:/ && ($tmp_term = $1, $state = 2);
228         # protect any pattern metacharacters in $tmp_term 
229         $termpat = $tmp_term; $termpat =~ s/(\W)/\\$1/g;
230     }
231
232     croak "Can't find $term" if $entry eq '';
233     $entry =~ s/:+\s*:+/:/g;                            # cleanup $entry
234     $entry =~ s/:+/:/g;                                 # cleanup $entry
235     $self->{TERMCAP} = $entry;                          # save it
236     # print STDERR "DEBUG: $entry = ", $entry, "\n";
237
238     # Precompile $entry into the object
239     $entry =~ s/^[^:]*://;
240     foreach $field (split(/:[\s:\\]*/,$entry)) {
241         if ($field =~ /^(\w\w)$/) {
242             $self->{'_' . $field} = 1 unless defined $self->{'_' . $1};
243             # print STDERR "DEBUG: flag $1\n";
244         }
245         elsif ($field =~ /^(\w\w)\@/) {
246             $self->{'_' . $1} = "";
247             # print STDERR "DEBUG: unset $1\n";
248         }
249         elsif ($field =~ /^(\w\w)#(.*)/) {
250             $self->{'_' . $1} = $2 unless defined $self->{'_' . $1};
251             # print STDERR "DEBUG: numeric $1 = $2\n";
252         }
253         elsif ($field =~ /^(\w\w)=(.*)/) {
254             # print STDERR "DEBUG: string $1 = $2\n";
255             next if defined $self->{'_' . ($cap = $1)};
256             $_ = $2;
257             s/\\E/\033/g;
258             s/\\(\d\d\d)/pack('c',oct($1) & 0177)/eg;
259             s/\\n/\n/g;
260             s/\\r/\r/g;
261             s/\\t/\t/g;
262             s/\\b/\b/g;
263             s/\\f/\f/g;
264             s/\\\^/\377/g;
265             s/\^\?/\177/g;
266             s/\^(.)/pack('c',ord($1) & 31)/eg;
267             s/\\(.)/$1/g;
268             s/\377/^/g;
269             $self->{'_' . $cap} = $_;
270         }
271         # else { carp "junk in $term ignored: $field"; }
272     }
273     $self->{'_pc'} = "\0" unless defined $self->{'_pc'};
274     $self->{'_bc'} = "\b" unless defined $self->{'_bc'};
275     $self;
276 }
277
278 # $terminal->Tpad($string, $cnt, $FH);
279 sub Tpad { ## public
280     my $self = shift;
281     my($string, $cnt, $FH) = @_;
282     my($decr, $ms);
283
284     if ($string =~ /(^[\d.]+)(\*?)(.*)$/) {
285         $ms = $1;
286         $ms *= $cnt if $2;
287         $string = $3;
288         $decr = $self->{PADDING};
289         if ($decr > .1) {
290             $ms += $decr / 2;
291             $string .= $self->{'_pc'} x ($ms / $decr);
292         }
293     }
294     print $FH $string if $FH;
295     $string;
296 }
297
298 # $terminal->Tputs($cap, $cnt, $FH);
299 sub Tputs { ## public
300     my $self = shift;
301     my($cap, $cnt, $FH) = @_;
302     my $string;
303
304     if ($cnt > 1) {
305         $string = Tpad($self, $self->{'_' . $cap}, $cnt);
306     } else {
307         # cache result because Tpad can be slow
308         $string = defined $self->{$cap} ? $self->{$cap} :
309             ($self->{$cap} = Tpad($self, $self->{'_' . $cap}, 1));
310     }
311     print $FH $string if $FH;
312     $string;
313 }
314
315 # %%   output `%'
316 # %d   output value as in printf %d
317 # %2   output value as in printf %2d
318 # %3   output value as in printf %3d
319 # %.   output value as in printf %c
320 # %+x  add x to value, then do %.
321 #
322 # %>xy if value > x then add y, no output
323 # %r   reverse order of two parameters, no output
324 # %i   increment by one, no output
325 # %B   BCD (16*(value/10)) + (value%10), no output
326 #
327 # %n   exclusive-or all parameters with 0140 (Datamedia 2500)
328 # %D   Reverse coding (value - 2*(value%16)), no output (Delta Data)
329 #
330 # $terminal->Tgoto($cap, $col, $row, $FH);
331 sub Tgoto { ## public
332     my $self = shift;
333     my($cap, $code, $tmp, $FH) = @_;
334     my $string = $self->{'_' . $cap};
335     my $result = '';
336     my $after = '';
337     my $online = 0;
338     my @tmp = ($tmp,$code);
339     my $cnt = $code;
340
341     while ($string =~ /^([^%]*)%(.)(.*)/) {
342         $result .= $1;
343         $code = $2;
344         $string = $3;
345         if ($code eq 'd') {
346             $result .= sprintf("%d",shift(@tmp));
347         }
348         elsif ($code eq '.') {
349             $tmp = shift(@tmp);
350             if ($tmp == 0 || $tmp == 4 || $tmp == 10) {
351                 if ($online) {
352                     ++$tmp, $after .= $self->{'_up'} if $self->{'_up'};
353                 }
354                 else {
355                     ++$tmp, $after .= $self->{'_bc'};
356                 }
357             }
358             $result .= sprintf("%c",$tmp);
359             $online = !$online;
360         }
361         elsif ($code eq '+') {
362             $result .= sprintf("%c",shift(@tmp)+ord($string));
363             $string = substr($string,1,99);
364             $online = !$online;
365         }
366         elsif ($code eq 'r') {
367             ($code,$tmp) = @tmp;
368             @tmp = ($tmp,$code);
369             $online = !$online;
370         }
371         elsif ($code eq '>') {
372             ($code,$tmp,$string) = unpack("CCa99",$string);
373             if ($tmp[$[] > $code) {
374                 $tmp[$[] += $tmp;
375             }
376         }
377         elsif ($code eq '2') {
378             $result .= sprintf("%02d",shift(@tmp));
379             $online = !$online;
380         }
381         elsif ($code eq '3') {
382             $result .= sprintf("%03d",shift(@tmp));
383             $online = !$online;
384         }
385         elsif ($code eq 'i') {
386             ($code,$tmp) = @tmp;
387             @tmp = ($code+1,$tmp+1);
388         }
389         else {
390             return "OOPS";
391         }
392     }
393     $string = Tpad($self, $result . $string . $after, $cnt);
394     print $FH $string if $FH;
395     $string;
396 }
397
398 # $terminal->Trequire(qw/ce ku kd/);
399 sub Trequire { ## public
400     my $self = shift;
401     my($cap,@undefined);
402     foreach $cap (@_) {
403         push(@undefined, $cap)
404             unless defined $self->{'_' . $cap} && $self->{'_' . $cap};
405     }
406     croak "Terminal does not support: (@undefined)" if @undefined;
407 }
408
409 1;
410