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