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