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