ftp://ftp.krokus.ru/pub/OpenBSD/distfiles/xscreensaver-5.01.tar.gz
[xscreensaver] / driver / xscreensaver-text
1 #!/usr/bin/perl -w
2 # Copyright © 2005, 2006 Jamie Zawinski <jwz@jwz.org>
3 #
4 # Permission to use, copy, modify, distribute, and sell this software and its
5 # documentation for any purpose is hereby granted without fee, provided that
6 # the above copyright notice appear in all copies and that both that
7 # copyright notice and this permission notice appear in supporting
8 # documentation.  No representations are made about the suitability of this
9 # software for any purpose.  It is provided "as is" without express or 
10 # implied warranty.
11 #
12 # This program writes some text to stdout, based on preferences in the
13 # .xscreensaver file.  It may load a file, a URL, run a program, or just
14 # print the date.
15 #
16 # In a native MacOS build of xscreensaver, this script is included in
17 # the Contents/Resources/ directory of each screen saver .bundle that
18 # uses it; and in that case, it looks up its resources using
19 # /usr/bin/defaults instead.
20 #
21 # Created: 19-Mar-2005.
22
23 require 5;
24 use diagnostics;
25 use strict;
26 use Socket;
27 use POSIX qw(strftime);
28 use Text::Wrap qw(wrap);
29 use bytes;
30
31 my $progname = $0; $progname =~ s@.*/@@g;
32 my $version = q{ $Revision: 1.14 $ }; $version =~ s/^[^0-9]+([0-9.]+).*$/$1/;
33
34 my $verbose = 0;
35 my $http_proxy = undef;
36
37 my $config_file = $ENV{HOME} . "/.xscreensaver";
38 my $text_mode     = 'date';
39 my $text_literal  = '';
40 my $text_file     = '';
41 my $text_program  = '';
42 my $text_url      = '';
43
44 my $wrap_columns  = undef;
45 my $nyarlathotep_p = 0;
46
47
48 # Maps HTML character entities to the corresponding Latin1 characters.
49 #
50 my %entity_table = (
51    "quot"   => '"', "amp"    => '&', "lt"     => '<', "gt"     => '>',
52    "nbsp"   => ' ', "iexcl"  => '¡', "cent"   => '¢', "pound"  => '£',
53    "curren" => '¤', "yen"    => '¥', "brvbar" => '¦', "sect"   => '§',
54    "uml"    => '¨', "copy"   => '©', "ordf"   => 'ª', "laquo"  => '«',
55    "not"    => '¬', "shy"    => '­', "reg"    => '®', "macr"   => '¯',
56    "deg"    => '°', "plusmn" => '±', "sup2"   => '²', "sup3"   => '³',
57    "acute"  => '´', "micro"  => 'µ', "para"   => '¶', "middot" => '·',
58    "cedil"  => '¸', "sup1"   => '¹', "ordm"   => 'º', "raquo"  => '»',
59    "frac14" => '¼', "frac12" => '½', "frac34" => '¾', "iquest" => '¿',
60    "Agrave" => 'À', "Aacute" => 'Á', "Acirc"  => 'Â', "Atilde" => 'Ã',
61    "Auml"   => 'Ä', "Aring"  => 'Å', "AElig"  => 'Æ', "Ccedil" => 'Ç',
62    "Egrave" => 'È', "Eacute" => 'É', "Ecirc"  => 'Ê', "Euml"   => 'Ë',
63    "Igrave" => 'Ì', "Iacute" => 'Í', "Icirc"  => 'Î', "Iuml"   => 'Ï',
64    "ETH"    => 'Ð', "Ntilde" => 'Ñ', "Ograve" => 'Ò', "Oacute" => 'Ó',
65    "Ocirc"  => 'Ô', "Otilde" => 'Õ', "Ouml"   => 'Ö', "times"  => '×',
66    "Oslash" => 'Ø', "Ugrave" => 'Ù', "Uacute" => 'Ú', "Ucirc"  => 'Û',
67    "Uuml"   => 'Ü', "Yacute" => 'Ý', "THORN"  => 'Þ', "szlig"  => 'ß',
68    "agrave" => 'à', "aacute" => 'á', "acirc"  => 'â', "atilde" => 'ã',
69    "auml"   => 'ä', "aring"  => 'å', "aelig"  => 'æ', "ccedil" => 'ç',
70    "egrave" => 'è', "eacute" => 'é', "ecirc"  => 'ê', "euml"   => 'ë',
71    "igrave" => 'ì', "iacute" => 'í', "icirc"  => 'î', "iuml"   => 'ï',
72    "eth"    => 'ð', "ntilde" => 'ñ', "ograve" => 'ò', "oacute" => 'ó',
73    "ocirc"  => 'ô', "otilde" => 'õ', "ouml"   => 'ö', "divide" => '÷',
74    "oslash" => 'ø', "ugrave" => 'ù', "uacute" => 'ú', "ucirc"  => 'û',
75    "uuml"   => 'ü', "yacute" => 'ý', "thorn"  => 'þ', "yuml"   => 'ÿ',
76    "apos"   => '\''
77 );
78
79 # Maps certain UTF8 characters (2 or 3 bytes) to the corresponding
80 # Latin1 characters.
81 #
82 my %unicode_latin1_table = (
83    "\xC2\xA1" => '¡', "\xC2\xA2" => '¢', "\xC2\xA3" => '£', "\xC2\xA4" => '¤',
84    "\xC2\xA5" => '¥', "\xC2\xA6" => '¦', "\xC2\xA7" => '§', "\xC2\xA8" => '¨',
85    "\xC2\xA9" => '©', "\xC2\xAA" => 'ª', "\xC2\xAB" => '«', "\xC2\xAC" => '¬',
86    "\xC2\xAD" => '­', "\xC2\xAE" => '®', "\xC2\xAF" => '¯', "\xC2\xB0" => '°',
87    "\xC2\xB1" => '±', "\xC2\xB2" => '²', "\xC2\xB3" => '³', "\xC2\xB4" => '´',
88    "\xC2\xB5" => 'µ', "\xC2\xB6" => '¶', "\xC2\xB7" => '·', "\xC2\xB8" => '¸',
89    "\xC2\xB9" => '¹', "\xC2\xBA" => 'º', "\xC2\xBB" => '»', "\xC2\xBC" => '¼',
90    "\xC2\xBD" => '½', "\xC2\xBE" => '¾', "\xC2\xBF" => '¿', "\xC3\x80" => 'À',
91    "\xC3\x81" => 'Á', "\xC3\x82" => 'Â', "\xC3\x83" => 'Ã', "\xC3\x84" => 'Ä',
92    "\xC3\x85" => 'Å', "\xC3\x86" => 'Æ', "\xC3\x87" => 'Ç', "\xC3\x88" => 'È',
93    "\xC3\x89" => 'É', "\xC3\x8A" => 'Ê', "\xC3\x8B" => 'Ë', "\xC3\x8C" => 'Ì',
94    "\xC3\x8D" => 'Í', "\xC3\x8E" => 'Î', "\xC3\x8F" => 'Ï', "\xC3\x90" => 'Ð',
95    "\xC3\x91" => 'Ñ', "\xC3\x92" => 'Ò', "\xC3\x93" => 'Ó', "\xC3\x94" => 'Ô',
96    "\xC3\x95" => 'Õ', "\xC3\x96" => 'Ö', "\xC3\x97" => '×', "\xC3\x98" => 'Ø',
97    "\xC3\x99" => 'Ù', "\xC3\x9A" => 'Ú', "\xC3\x9B" => 'Û', "\xC3\x9C" => 'Ü',
98    "\xC3\x9D" => 'Ý', "\xC3\x9E" => 'Þ', "\xC3\x9F" => 'ß', "\xC3\xA0" => 'à',
99    "\xC3\xA1" => 'á', "\xC3\xA2" => 'â', "\xC3\xA3" => 'ã', "\xC3\xA4" => 'ä',
100    "\xC3\xA5" => 'å', "\xC3\xA6" => 'æ', "\xC3\xA7" => 'ç', "\xC3\xA8" => 'è',
101    "\xC3\xA9" => 'é', "\xC3\xAA" => 'ê', "\xC3\xAB" => 'ë', "\xC3\xAC" => 'ì',
102    "\xC3\xAD" => 'í', "\xC3\xAE" => 'î', "\xC3\xAF" => 'ï', "\xC3\xB0" => 'ð',
103    "\xC3\xB1" => 'ñ', "\xC3\xB2" => 'ò', "\xC3\xB3" => 'ó', "\xC3\xB4" => 'ô',
104    "\xC3\xB5" => 'õ', "\xC3\xB6" => 'ö', "\xC3\xB7" => '÷', "\xC3\xB8" => 'ø',
105    "\xC3\xB9" => 'ù', "\xC3\xBA" => 'ú', "\xC3\xBB" => 'û', "\xC3\xBC" => 'ü',
106    "\xC3\xBD" => 'ý', "\xC3\xBE" => 'þ', "\xC3\xBF" => 'ÿ',
107
108    "\xE2\x80\x93" => '--',  "\xE2\x80\x94" => '--',
109    "\xE2\x80\x98" => '`',   "\xE2\x80\x99" => '\'',
110    "\xE2\x80\x9C" => "``",  "\xE2\x80\x9D" => "''",
111    "\xE2\x80\xA6" => '...',
112 );
113
114
115 # Convert any HTML entities to Latin1 characters.
116 #
117 sub de_entify($) {
118   my ($text) = @_;
119   $text =~ s/(&(\#)?([[:alpha:]\d]+);?)/
120     {
121      my $c;
122      if ($2) {
123        $c = chr($3);  # the &#number is always decimal, right?
124      } else {
125        $c = $entity_table{$3};
126      }
127 #    print STDERR "$progname: warning: unknown HTML character entity \"$1\"\n"
128 #     unless $c;
129      ($c ? $c : "[$3]");
130     }
131    /gexi;
132   return $text;
133 }
134
135
136 # Convert any Unicode characters to Latin1 if possible.
137 # Unconvertable bytes are left alone.
138 #
139 sub de_unicoddle($) {
140   my ($text) = @_;
141   foreach my $key (keys (%unicode_latin1_table)) {
142     my $val = $unicode_latin1_table{$key};
143     $text =~ s/$key/$val/gs;
144   }
145   return $text;
146 }
147
148
149 # Reads the prefs we use from ~/.xscreensaver
150 #
151 sub get_x11_prefs() {
152   my $got_any_p = 0;
153   local *IN;
154
155   if (open (IN, "<$config_file")) {
156     print STDERR "$progname: reading $config_file\n" if ($verbose > 1);
157     my $body = '';
158     while (<IN>) { $body .= $_; }
159     close IN;
160     $got_any_p = get_x11_prefs_1 ($body);
161
162   } elsif ($verbose > 1) {
163     print STDERR "$progname: $config_file: $!\n";
164   }
165
166   if (! $got_any_p && defined ($ENV{DISPLAY})) {
167     # We weren't able to read settings from the .xscreensaver file.
168     # Fall back to any settings in the X resource database
169     # (/usr/X11R6/lib/X11/app-defaults/XScreenSaver)
170     #
171     print STDERR "$progname: reading X resources\n" if ($verbose > 1);
172     my $body = `appres XScreenSaver xscreensaver -1`;
173     $got_any_p = get_x11_prefs_1 ($body);
174   }
175
176   if ($verbose > 1) {
177     printf STDERR "$progname: mode:    $text_mode\n";
178     printf STDERR "$progname: literal: $text_literal\n";
179     printf STDERR "$progname: file:    $text_file\n";
180     printf STDERR "$progname: program: $text_program\n";
181     printf STDERR "$progname: url:     $text_url\n";
182   }
183
184   $text_mode =~ tr/A-Z/a-z/;
185   $text_literal =~ s@\\n@\n@gs;
186 }
187
188
189 sub get_x11_prefs_1($) {
190   my ($body) = @_;
191
192   my $got_any_p = 0;
193   $body =~ s@\\\n@@gs;
194
195   if ($body =~ m/^[.*]*textMode:[ \t]*([^\s]+)\s*$/im) {
196     $text_mode = $1;
197     $got_any_p = 1;
198   }
199   if ($body =~ m/^[.*]*textLiteral:[ \t]*(.*?)[ \t]*$/im) {
200     $text_literal = $1;
201   }
202   if ($body =~ m/^[.*]*textFile:[ \t]*(.*?)[ \t]*$/im) {
203     $text_file = $1;
204   }
205   if ($body =~ m/^[.*]*textProgram:[ \t]*(.*?)[ \t]*$/im) {
206     $text_program = $1;
207   }
208   if ($body =~ m/^[.*]*textURL:[ \t]*(.*?)[ \t]*$/im) {
209     $text_url = $1;
210   }
211
212   return $got_any_p;
213 }
214
215
216 sub get_cocoa_prefs($) {
217   my ($id) = @_;
218   my $v;
219  
220   print STDERR "$progname: reading Cocoa prefs: \"$id\"\n" if ($verbose > 1);
221
222   $v = get_cocoa_pref_1 ($id, "textMode");
223   $text_mode = $v if defined ($v);
224
225   # The "textMode" pref is set to a number instead of a string because I
226   # can't figure out the black magic to make Cocoa bindings work right.
227   #
228   if    ($text_mode eq '0') { $text_mode = 'date';    }
229   elsif ($text_mode eq '1') { $text_mode = 'literal'; }
230   elsif ($text_mode eq '2') { $text_mode = 'file';    }
231   elsif ($text_mode eq '3') { $text_mode = 'url';     }
232
233   $v = get_cocoa_pref_1 ($id, "textLiteral");
234   $text_literal = $v if defined ($v);
235
236   $v = get_cocoa_pref_1 ($id, "textFile");
237   $text_file = $v if defined ($v);
238
239   $v = get_cocoa_pref_1 ($id, "textProgram");
240   $text_program = $v if defined ($v);
241
242   $v = get_cocoa_pref_1 ($id, "textURL");
243   $text_url = $v if defined ($v);
244 }
245
246
247 sub get_cocoa_pref_1($$) {
248   my ($id, $key) = @_;
249   # make sure there's nothing stupid/malicious in either string.
250   $id  =~ s/[^-a-z\d. ]/_/gsi;
251   $key =~ s/[^-a-z\d. ]/_/gsi;
252   my $cmd = "defaults -currentHost read \"$id\" \"$key\"";
253
254   print STDERR "$progname: executing $cmd\n"
255     if ($verbose > 3);
256
257   my $val = `$cmd 2>/dev/null`;
258   $val =~ s/^\s+//s;
259   $val =~ s/\s+$//s;
260
261   print STDERR "$progname: Cocoa: $id $key = \"$val\"\n"
262     if ($verbose > 2);
263
264   $val = undef if ($val =~ m/^$/s);
265
266   return $val;
267 }
268
269
270 # like system() but checks errors.
271 #
272 sub safe_system(@) {
273   my (@cmd) = @_;
274
275   print STDERR "$progname: executing " . join(' ', @cmd) . "\n"
276     if ($verbose > 3);
277
278   system @cmd;
279   my $exit_value  = $? >> 8;
280   my $signal_num  = $? & 127;
281   my $dumped_core = $? & 128;
282   error ("$cmd[0]: core dumped!") if ($dumped_core);
283   error ("$cmd[0]: signal $signal_num!") if ($signal_num);
284   error ("$cmd[0]: exited with $exit_value!") if ($exit_value);
285 }
286
287
288 sub which($) {
289   my ($cmd) = @_;
290
291   if ($cmd =~ m@^\./|^/@) {
292     error ("cannot execute $cmd") unless (-x $cmd);
293     return $cmd;
294   }
295  
296  foreach my $dir (split (/:/, $ENV{PATH})) {
297     my $cmd2 = "$dir/$cmd";
298     print STDERR "$progname:   checking $cmd2\n" if ($verbose > 3);
299     return $cmd2 if (-x "$cmd2");
300   }
301   error ("$cmd not found on \$PATH");
302 }
303
304
305 sub output() {
306
307   # Do some basic sanity checking (null text, null file names, etc.)
308   #
309   if (($text_mode eq 'literal' && $text_literal =~ m/^\s*$/i) ||
310       ($text_mode eq 'file'    && $text_file    =~ m/^\s*$/i) ||
311       ($text_mode eq 'program' && $text_program =~ m/^\s*$/i) ||
312       ($text_mode eq 'url'     && $text_url     =~ m/^\s*$/i)) {
313     print STDERR "$progname: falling back to 'date'\n" if ($verbose);
314     $text_mode = 'date';
315   }
316
317   if ($text_mode eq 'literal') {
318     $text_literal = strftime ($text_literal, localtime);
319     $text_literal =~ y/A-Za-z/N-ZA-Mn-za-m/ if ($nyarlathotep_p);
320     print STDOUT $text_literal;
321     print STDOUT "\n" unless ($text_literal =~ m/\n$/s);
322
323   } elsif ($text_mode eq 'file') {
324
325     $text_file =~ s@^~/@$ENV{HOME}/@s;     # allow literal "~/"
326
327     local *IN;
328     if (open (IN, "<$text_file")) {
329       print STDERR "$progname: reading $text_file\n" if ($verbose);
330
331       if ($wrap_columns && $wrap_columns > 0) {
332         # read it, then reformat it.
333         my $body = '';
334         while (<IN>) { $body .= $_; }
335         reformat_text ($body);
336       } else {
337         # stream it
338         while (<IN>) { 
339           y/A-Za-z/N-ZA-Mn-za-m/ if ($nyarlathotep_p);
340           print $_;
341         }
342       }
343       close IN;
344     } else {
345       error ("$text_file: $!");
346     }
347
348   } elsif ($text_mode eq 'program') {
349
350     my ($prog, $args) = ($text_program =~ m/^([^\s]+)(.*)$/);
351     $text_program = which ($prog) . $args;
352     print STDERR "$progname: running $text_program\n" if ($verbose);
353
354     if ($wrap_columns && $wrap_columns > 0) {
355       # read it, then reformat it.
356       my $body = `( $text_program ) 2>&1`;
357       reformat_text ($body);
358     } else {
359       # stream it
360       safe_system ("$text_program");
361     }
362
363   } elsif ($text_mode eq 'url') {
364
365     get_url_text ($text_url);
366
367   } else { # $text_mode eq 'date'
368
369     safe_system ("uname", "-n");
370
371     my $unamep = 1;
372
373     if (-f "/etc/redhat-release") {         # "Fedora Core release 4 (Stentz)"
374       system ("cat", "/etc/redhat-release");
375     }
376
377     if (-f "/etc/release") {                # "Solaris 10 3/05 s10_74L2a X86"
378       safe_system ("head", "-1", "/etc/release");
379     }
380
381     if (-f "/usr/sbin/system_profiler") {   # "Mac OS X 10.4.5 (8H14)"
382       my $sp =                              # "iMac G5"
383         `/usr/sbin/system_profiler SPSoftwareDataType SPHardwareDataType`;
384       my ($v) = ($sp =~ m/^\s*System Version:\s*(.*)$/mi);
385       my ($s) = ($sp =~ m/^\s*CPU Speed:\s*(.*)$/mi);
386       my ($t) = ($sp =~ m/^\s*Machine Name:\s*(.*)$/mi);
387       print "$v\n" if ($v);
388       print "$s $t\n" if ($s && $t);
389       $unamep = !defined ($v);
390     }
391
392     if ($unamep) {
393       safe_system ("uname", "-sr");         # "Linux 2.6.15-1.1831_FC4"
394     }
395
396     print "\n";
397     safe_system ("date", "+%c");
398     print "\n";
399     my $ut = `uptime`;
400     $ut =~ s/^[ \d:]*(am|pm)?//i;
401     $ut =~ s/,\s*(load)/\n$1/;
402     print "$ut\n";
403   }
404
405 }
406
407
408 # Loads the given URL, returns: $http, $head, $body.
409 #
410 sub get_url_1($;$) {
411   my ($url, $referer) = @_;
412   
413   if (! ($url =~ m@^(http|feed)://@i)) {
414     error ("not an HTTP URL: $url");
415   }
416
417   my ($url_proto, $dummy, $serverstring, $path) = split(/\//, $url, 4);
418   $path = "" unless $path;
419
420   my ($them,$port) = split(/:/, $serverstring);
421   $port = 80 unless $port;
422
423   my $them2 = $them;
424   my $port2 = $port;
425   if ($http_proxy) {
426     $serverstring = $http_proxy if $http_proxy;
427     $serverstring =~ s@^[a-z]+://@@;
428     ($them2,$port2) = split(/:/, $serverstring);
429     $port2 = 80 unless $port2;
430   }
431
432   my ($remote, $iaddr, $paddr, $proto, $line);
433   $remote = $them2;
434   if ($port2 =~ /\D/) { $port2 = getservbyname($port2, 'tcp') }
435   if (!$port2) {
436     error ("unrecognised port in $url");
437   }
438
439   $iaddr = inet_aton($remote);
440   error ("host not found: $remote") unless ($iaddr);
441
442   $paddr   = sockaddr_in($port2, $iaddr);
443
444
445   my $head = "";
446   my $body = "";
447
448   $proto   = getprotobyname('tcp');
449   if (!socket(S, PF_INET, SOCK_STREAM, $proto)) {
450     error ("socket: $!");
451   }
452   if (!connect(S, $paddr)) {
453     error ("connect($serverstring): $!");
454   }
455
456   select(S); $| = 1; select(STDOUT);
457
458   my $user_agent = "$progname/$version";
459
460   my $hdrs = ("GET " . ($http_proxy ? $url : "/$path") . " HTTP/1.0\r\n" .
461               "Host: $them\r\n" .
462               "User-Agent: $user_agent\r\n");
463   if ($referer) {
464     $hdrs .= "Referer: $referer\r\n";
465   }
466   $hdrs .= "\r\n";
467
468   if ($verbose > 3) {
469     foreach (split('\r?\n', $hdrs)) {
470       print STDERR "  ==> $_\n";
471     }
472   }
473   print S $hdrs;
474   my $http = <S> || "";
475
476   $_  = $http;
477   s/[\r\n]+$//s;
478   print STDERR "  <== $_\n" if ($verbose > 3);
479
480   while (<S>) {
481     $head .= $_;
482     s/[\r\n]+$//s;
483     last if m@^$@;
484     print STDERR "  <== $_\n" if ($verbose > 3);
485   }
486
487   print STDERR "  <== \n" if ($verbose > 4);
488   my $lines = 0;
489   while (<S>) {
490     s/\r\n/\n/gs;
491     print STDERR "  <== $_" if ($verbose > 4);
492     $body .= $_;
493     $lines++;
494   }
495
496   print STDERR "  <== [ body ]: $lines lines, " . length($body) . " bytes\n"
497     if ($verbose == 4);
498
499   close S;
500
501   if (!$http) {
502     error ("null response: $url");
503   }
504
505   return ( $http, $head, $body );
506 }
507
508
509 # Loads the given URL, processes redirects, returns (content-type, body).
510 #
511 sub get_url($;$) {
512   my ($url, $referer) = @_;
513
514   print STDERR "$progname: loading $url\n" if ($verbose > 2);
515
516   my $orig_url = $url;
517   my $loop_count = 0;
518   my $max_loop_count = 10;
519
520   do {
521     my ( $http, $head, $body ) = get_url_1 ($url, $referer);
522
523     $http =~ s/[\r\n]+$//s;
524
525     if ( $http =~ m@^HTTP/[0-9.]+ 30[123]@ ) {
526       $_ = $head;
527
528       my ( $location ) = m@^location:[ \t]*(.*)$@im;
529       if ( $location ) {
530         $location =~ s/[\r\n]$//;
531
532         print STDERR "$progname: redirect from $url to $location\n"
533           if ($verbose > 3);
534
535         $referer = $url;
536         $url = $location;
537
538         if ($url =~ m@^/@) {
539           $referer =~ m@^(http://[^/]+)@i;
540           $url = $1 . $url;
541         } elsif (! ($url =~ m@^[a-z]+:@i)) {
542           $_ = $referer;
543           s@[^/]+$@@g if m@^http://[^/]+/@i;
544           $_ .= "/" if m@^http://[^/]+$@i;
545           $url = $_ . $url;
546         }
547
548       } else {
549         error ("no Location with \"$http\"");
550       }
551
552       if ($loop_count++ > $max_loop_count) {
553         error ("too many redirects ($max_loop_count) from $orig_url");
554       }
555
556     } elsif ( $http =~ m@^HTTP/[0-9.]+ ([4-9][0-9][0-9].*)$@ ) {
557       error ("failed: $1 ($url)");
558
559     } else {
560       my $ct = 'text/plain';
561       $ct = $1 if ($head =~ m/^content-type:\s*([^\s]+)/mi);
562       return ($ct, $body);
563     }
564   } while (1);
565 }
566
567
568 # Make an educated guess as to what's in this document.
569 # We don't necessarily take the Content-Type header at face value.
570 # Returns 'html', 'rss', or 'text';
571 #
572 sub guess_content_type($$) {
573   my ($ct, $body) = @_;
574
575   $body =~ s/^(.{512}).*/$1/s;  # only look in first half K of file
576
577   if ($ct =~ m@^text/.*html@i)          { return 'html'; }
578   if ($ct =~ m@\b(atom|rss|xml)\b@i)    { return 'rss';  }
579
580   if ($body =~ m@^\s*<\?xml@is)         { return 'rss';  }
581   if ($body =~ m@^\s*<!DOCTYPE RSS@is)  { return 'rss';  }
582   if ($body =~ m@^\s*<!DOCTYPE HTML@is) { return 'html'; }
583
584   if ($body =~ m@<(BASE|HTML|HEAD|BODY|SCRIPT|STYLE|TABLE|A\s+HREF)\b@i) {
585     return 'html';
586   }
587
588   if ($body =~ m@<(RSS|CHANNEL|GENERATOR|DESCRIPTION|CONTENT|FEED|ENTRY)\b@i) {
589     return 'rss';
590   }
591
592   return 'text';
593 }
594
595 sub reformat_html($$) {
596   my ($body, $rss_p) = @_;
597   $_ = $body;
598
599   if (! $rss_p) {
600     # In HTML, unfold lines (this breaks PRE.  Sue me.)
601     # In RSS, assume \n means literal line break.
602     s@[\r\n]@ @gsi;
603   }
604
605   s@<!--.*?-->@@gsi;                             # lose comments
606   s@<(STYLE|SCRIPT)\b[^<>]*>.*?</\1\s*>@@gsi;    # lose css and js
607
608   s@</?(BR|TR|TD|LI|DIV)\b[^<>]*>@\n@gsi; # line break at BR, TD, DIV, etc
609   s@</?(P|UL|OL|BLOCKQUOTE)\b[^<>]*>@\n\n@gsi; # two line breaks
610
611   s@<lj\s+user=\"?([^<>\"]+)\"?[^<>]*>?@$1@gsi;  # handle <LJ USER=>
612   s@</?[BI]>@*@gsi;                              # bold, italic => asterisks
613
614
615   s@<[^<>]*>?@@gs;                # lose all other HTML tags
616   $_ = de_entify ($_);            # convert HTML entities
617
618   # elide any remaining non-Latin1 binary data...
619   s/([\177-\377]+(\s*[\177-\377]+)[^a-z\d]*)/«...» /g;
620   #s/([\177-\377]+(\s*[\177-\377]+)[^a-z\d]*)/«$1» /g;
621
622   $_ .= "\n";
623
624   s/[ \t]+$//gm;                  # lose whitespace at end of line
625   s@\n\n\n+@\n\n@gs;              # compress blank lines
626
627   if (!defined($wrap_columns) || $wrap_columns > 0) {
628     $Text::Wrap::columns = ($wrap_columns || 72);
629     $_ = wrap ("", "  ", $_);     # wrap the lines as a paragraph
630     s/[ \t]+$//gm;                # lose whitespace at end of line again
631   }
632
633   y/A-Za-z/N-ZA-Mn-za-m/ if ($nyarlathotep_p);
634   print STDOUT $_;
635 }
636
637
638 sub reformat_rss($) {
639   my ($body) = @_;
640
641   $body =~ s/(<(ITEM|ENTRY)\b)/\001\001$1/gsi;
642   my @items = split (/\001\001/, $body);
643
644   print STDERR "$progname: converting RSS ($#items items)...\n"
645     if ($verbose > 2);
646
647   shift @items;
648
649   # Let's skip forward in the stream by a random amount, so that if
650   # two copies of ljlatest are running at the same time (e.g., on a
651   # multi-headed machine), they get different text.  (Put the items
652   # that we take off the front back on the back.)
653   #
654   if ($#items > 7) {
655     my $n = int (rand ($#items - 5));
656     print STDERR "$progname: rotating by $n items...\n" if ($verbose > 2);
657     while ($n-- > 0) {
658       push @items, (shift @items);
659     }
660   }
661
662   my $i = -1;
663   foreach (@items) {
664     $i++;
665
666     my ($title, $body1, $body2, $body3);
667     
668     $title = $3 if (m@<((TITLE)       [^<>\s]*)[^<>]*>\s*(.*?)\s*</\1>@xsi);
669     $body1 = $3 if (m@<((DESCRIPTION) [^<>\s]*)[^<>]*>\s*(.*?)\s*</\1>@xsi);
670     $body2 = $3 if (m@<((CONTENT)     [^<>\s]*)[^<>]*>\s*(.*?)\s*</\1>@xsi);
671     $body3 = $3 if (m@<((SUMMARY)     [^<>\s]*)[^<>]*>\s*(.*?)\s*</\1>@xsi);
672
673     # If there are both <description> and <content> or <content:encoded>,
674     # use whichever one contains more text.
675     #
676     if ($body3 && length($body3) >= length($body2 || '')) {
677       $body2 = $body3;
678     }
679     if ($body2 && length($body2) >= length($body1 || '')) {
680       $body1 = $body2;
681     }
682
683     if (! $body1) {
684       if ($title) {
685         print STDERR "$progname: no body in item $i (\"$title\")\n"
686           if ($verbose > 2);
687       } else {
688         print STDERR "$progname: no body or title in item $i\n"
689           if ($verbose > 2);
690         next;
691       }
692     }
693
694     $title = rss_field_to_html ($title || '');
695     $body1 = rss_field_to_html ($body1 || '');
696
697     reformat_html ("$title<P>$body1", 1);
698     print "\n";
699   }
700 }
701
702
703 sub rss_field_to_html($) {
704   my ($body) = @_;
705
706   # Assume that if <![CDATA[...]]> is present, everything inside that.
707   #
708   if ($body =~ m/^\s*<!\[CDATA\[(.*?)\]\s*\]/is) {
709     $body = $1;
710   } else {
711     $body = de_entify ($body);      # convert entities to get HTML from XML
712   }
713
714   $body = de_unicoddle ($body);     # convert UTF8 to Latin1
715   return $body;
716 }
717
718
719 sub reformat_text($) {
720   my ($body) = @_;
721
722   # only re-wrap if --cols was specified.  Otherwise, dump it as is.
723   #
724   if ($wrap_columns && $wrap_columns > 0) {
725     print STDERR "$progname: wrapping at $wrap_columns...\n" if ($verbose > 2);
726     $Text::Wrap::columns = $wrap_columns;
727     $body = wrap ("", "", $body);
728     $body =~ s/[ \t]+$//gm;
729   }
730
731   $body =~ y/A-Za-z/N-ZA-Mn-za-m/ if ($nyarlathotep_p);
732   print STDOUT $body;
733 }
734
735
736 sub get_url_text($) {
737   my ($url) = @_;
738
739   # historical suckage: the environment variable name is lower case.
740   $http_proxy = $ENV{http_proxy} || $ENV{HTTP_PROXY};
741
742   if ($http_proxy && $http_proxy =~ m@^http://([^/]*)/?$@ ) {
743     # historical suckage: allow "http://host:port" as well as "host:port".
744     $http_proxy = $1;
745   }
746
747   my ($ct, $body) = get_url ($url);
748
749   $ct = guess_content_type ($ct, $body);
750   if ($ct eq 'html') {
751     print STDERR "$progname: converting HTML...\n" if ($verbose > 2);
752     reformat_html ($body, 0);
753   } elsif ($ct eq 'rss')  {
754     reformat_rss ($body);
755   } else {
756     print STDERR "$progname: plain text...\n" if ($verbose > 2);
757     reformat_text ($body);
758   }
759 }
760
761
762
763 sub error($) {
764   my ($err) = @_;
765   print STDERR "$progname: $err\n";
766   exit 1;
767 }
768
769 sub usage() {
770   print STDERR "usage: $progname [ --options ... ]\n" .
771    ("\n" .
772     "       Prints out some text for use by various screensavers,\n" .
773     "       according to the options in the ~/.xscreensaver file.\n" .
774     "       This may dump the contents of a file, run a program,\n" .
775     "       or load a URL.\n".
776     "\n" .
777     "   Options:\n" .
778     "\n" .
779     "       --date           Print the host name and current time.\n" .
780     "\n" .
781     "       --text STRING    Print out the given text.  It may contain %\n" .
782     "                        escape sequences as per strftime(2).\n" .
783     "\n" .
784     "       --file PATH      Print the contents of the given file.\n" .
785     "                        If --cols is specified, re-wrap the lines;\n" .
786     "                        otherwise, print them as-is.\n" .
787     "\n" .
788     "       --program CMD    Run the given program and print its output.\n" .
789     "                        If --cols is specified, re-wrap the output.\n" .
790     "\n" .
791     "       --url HTTP-URL   Download and print the contents of the HTTP\n" .
792     "                        document.  If it contains HTML, RSS, or Atom,\n" .
793     "                        it will be converted to plain-text.\n" .
794     "\n" .
795     "       --cols N         Wrap lines at this column.  Default 72.\n" .
796     "\n");
797   exit 1;
798 }
799
800 sub main() {
801
802   my $load_p = 1;
803   my $cocoa_id = undef;
804
805   while ($#ARGV >= 0) {
806     $_ = shift @ARGV;
807     if ($_ eq "--verbose") { $verbose++; }
808     elsif (m/^-v+$/) { $verbose += length($_)-1; }
809     elsif (m/^--?date$/)    { $text_mode = 'date';
810                               $load_p = 0; }
811     elsif (m/^--?text$/)    { $text_mode = 'literal';
812                               $text_literal = shift @ARGV;
813                               $load_p = 0; }
814     elsif (m/^--?file$/)    { $text_mode = 'file';
815                               $text_file = shift @ARGV;
816                               $load_p = 0; }
817     elsif (m/^--?program$/) { $text_mode = 'program';
818                               $text_program = shift @ARGV;
819                               $load_p = 0; }
820     elsif (m/^--?url$/)     { $text_mode = 'url';
821                               $text_url = shift @ARGV;
822                               $load_p = 0; }
823     elsif (m/^--?col(umn)?s?$/) { $wrap_columns = 0 + shift @ARGV; }
824     elsif (m/^--?cocoa$/)   { $cocoa_id = shift @ARGV; }
825     elsif (m/^--?nyarlathotep$/) { $nyarlathotep_p++; }
826     elsif (m/^-./) { usage; }
827     else { usage; }
828   }
829
830   if ($load_p) {
831
832     if (!defined ($cocoa_id)) {
833       # see OSX/XScreenSaverView.m
834       $cocoa_id = $ENV{XSCREENSAVER_CLASSPATH};
835     }
836
837     if (defined ($cocoa_id)) {
838       get_cocoa_prefs($cocoa_id);
839     } else {
840       get_x11_prefs();
841     }
842   }
843
844   output();
845 }
846
847 main();
848 exit 0;