From http://www.jwz.org/xscreensaver/xscreensaver-5.31.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 # Not sure how prevalent this is. Hope it's part of the default install.
32 BEGIN { eval 'use HTML::Entities;' }
33
34 use Socket;
35 use POSIX qw(strftime);
36 use Text::Wrap qw(wrap);
37 use bytes;
38
39 my $progname = $0; $progname =~ s@.*/@@g;
40 my ($version) = ('$Revision: 1.37 $' =~ m/\s(\d[.\d]+)\s/s);
41
42 my $verbose = 0;
43 my $http_proxy = undef;
44
45 my $config_file = $ENV{HOME} . "/.xscreensaver";
46 my $text_mode     = 'date';
47 my $text_literal  = '';
48 my $text_file     = '';
49 my $text_program  = '';
50 my $text_url      = 'http://en.wikipedia.org/w/index.php?title=Special:NewPages&feed=rss';
51 # Default URL needs to be set and match what's in OSX/XScreenSaverView.m
52
53 my $wrap_columns   = undef;
54 my $truncate_lines = undef;
55 my $latin1_p = 0;
56 my $nyarlathotep_p = 0;
57
58
59 # Convert any HTML entities to Latin1 characters.
60 #
61 sub de_entify($) {
62   my ($text) = @_;
63
64   return '' unless defined($text);
65   return $text unless ($text =~ m/&/s);
66
67   # Convert any HTML entities to Unicode characters,
68   # if the HTML::Entities module is installed.
69   eval {
70     my $t2 = $text;
71     $text = undef;
72     $text = HTML::Entities::decode_entities ($t2);
73   };
74   return $text if defined($text);
75
76   # If it's not installed, just complain instead of trying to halfass it.
77   print STDOUT ("\n\tPerl is broken. Do this to repair it:\n" .
78                 "\n\tsudo cpan HTML::Entities\n\n");
79   exit (1);
80 }
81
82
83 # Convert any Unicode characters to Latin1 if possible.
84 # Unconvertable bytes are left alone.
85 #
86 sub utf8_to_latin1($) {
87   my ($text) = @_;
88
89   utf8::encode ($text);  # Unpack Unicode back to multi-byte UTF-8.
90
91   # Maybe it would be better to handle this in the Unicode domain
92   # by doing things like s/\x{2018}/\"/g, but without decoding the
93   # string back to UTF-8 first, I'm at a loss as to how to have
94   # "&aacute;" print as "\340" instead of as "\303\240".
95
96   $text =~ s/ \xC2 ( [\xA0-\xFF] ) / $1 /gsex;
97   $text =~ s/ \xC3 ( [\x80-\xFF] ) / chr (ord($1) | 0x40) /gsex;
98
99   # Handles a few 3-byte sequences too.
100   $text =~ s/\xE2\x80\x93/--/gs;
101   $text =~ s/\xE2\x80\x94/--/gs;
102   $text =~ s/\xE2\x80\x98/`/gs;
103   $text =~ s/\xE2\x80\x99/'/gs;
104   $text =~ s/\xE2\x80\x9C/``/gs;
105   $text =~ s/\xE2\x80\x9D/'/gs;
106   $text =~ s/\xE2\x80\xA2/&bull;/gs;
107   $text =~ s/\xE2\x80\xA6/.../gs;
108   $text =~ s/\xE2\x80\xB2/'/gs;
109   $text =~ s/\xE2\x84\xA2/&trade;/gs;
110   $text =~ s/\xE2\x86\x90/ &larr; /gs;
111
112   return $text;
113 }
114
115
116 # Reads the prefs we use from ~/.xscreensaver
117 #
118 sub get_x11_prefs() {
119   my $got_any_p = 0;
120
121   if (open (my $in, '<', $config_file)) {
122     print STDERR "$progname: reading $config_file\n" if ($verbose > 1);
123     local $/ = undef;  # read entire file
124     my $body = <$in>;
125     close $in;
126     $got_any_p = get_x11_prefs_1 ($body);
127
128   } elsif ($verbose > 1) {
129     print STDERR "$progname: $config_file: $!\n";
130   }
131
132   if (! $got_any_p && defined ($ENV{DISPLAY})) {
133     # We weren't able to read settings from the .xscreensaver file.
134     # Fall back to any settings in the X resource database
135     # (/usr/X11R6/lib/X11/app-defaults/XScreenSaver)
136     #
137     print STDERR "$progname: reading X resources\n" if ($verbose > 1);
138     my $body = `appres XScreenSaver xscreensaver -1`;
139     $got_any_p = get_x11_prefs_1 ($body);
140   }
141
142   if ($verbose > 1) {
143     print STDERR "$progname: mode:    $text_mode\n";
144     print STDERR "$progname: literal: $text_literal\n";
145     print STDERR "$progname: file:    $text_file\n";
146     print STDERR "$progname: program: $text_program\n";
147     print STDERR "$progname: url:     $text_url\n";
148   }
149
150   $text_mode =~ tr/A-Z/a-z/;
151   $text_literal =~ s@\\n@\n@gs;
152   $text_literal =~ s@\\\n@\n@gs;
153 }
154
155
156 sub get_x11_prefs_1($) {
157   my ($body) = @_;
158
159   my $got_any_p = 0;
160   $body =~ s@\\\n@@gs;
161
162   if ($body =~ m/^[.*]*textMode:[ \t]*([^\s]+)\s*$/im) {
163     $text_mode = $1;
164     $got_any_p = 1;
165   }
166   if ($body =~ m/^[.*]*textLiteral:[ \t]*(.*?)[ \t]*$/im) {
167     $text_literal = $1;
168   }
169   if ($body =~ m/^[.*]*textFile:[ \t]*(.*?)[ \t]*$/im) {
170     $text_file = $1;
171   }
172   if ($body =~ m/^[.*]*textProgram:[ \t]*(.*?)[ \t]*$/im) {
173     $text_program = $1;
174   }
175   if ($body =~ m/^[.*]*textURL:[ \t]*(.*?)[ \t]*$/im) {
176     $text_url = $1;
177   }
178
179   return $got_any_p;
180 }
181
182
183 sub get_cocoa_prefs($) {
184   my ($id) = @_;
185   my $v;
186  
187   print STDERR "$progname: reading Cocoa prefs: \"$id\"\n" if ($verbose > 1);
188
189   $v = get_cocoa_pref_1 ($id, "textMode");
190   $text_mode = $v if defined ($v);
191
192   # The "textMode" pref is set to a number instead of a string because I
193   # can't figure out the black magic to make Cocoa bindings work right.
194   #
195   if    ($text_mode eq '0') { $text_mode = 'date';    }
196   elsif ($text_mode eq '1') { $text_mode = 'literal'; }
197   elsif ($text_mode eq '2') { $text_mode = 'file';    }
198   elsif ($text_mode eq '3') { $text_mode = 'url';     }
199   elsif ($text_mode eq '4') { $text_mode = 'program'; }
200
201   $v = get_cocoa_pref_1 ($id, "textLiteral");
202   $text_literal = $v if defined ($v);
203   $text_literal =~ s@\\n@\n@gs;
204   $text_literal =~ s@\\\n@\n@gs;
205
206   $v = get_cocoa_pref_1 ($id, "textFile");
207   $text_file = $v if defined ($v);
208
209   $v = get_cocoa_pref_1 ($id, "textProgram");
210   $text_program = $v if defined ($v);
211
212   $v = get_cocoa_pref_1 ($id, "textURL");
213   $text_url = $v if defined ($v);
214 }
215
216
217 sub get_cocoa_pref_1($$) {
218   my ($id, $key) = @_;
219   # make sure there's nothing stupid/malicious in either string.
220   $id  =~ s/[^-a-z\d. ]/_/gsi;
221   $key =~ s/[^-a-z\d. ]/_/gsi;
222   my $cmd = "defaults -currentHost read \"$id\" \"$key\"";
223
224   print STDERR "$progname: executing $cmd\n"
225     if ($verbose > 3);
226
227   my $val = `$cmd 2>/dev/null`;
228   $val =~ s/^\s+//s;
229   $val =~ s/\s+$//s;
230
231   print STDERR "$progname: Cocoa: $id $key = \"$val\"\n"
232     if ($verbose > 2);
233
234   $val = undef if ($val =~ m/^$/s);
235
236   return $val;
237 }
238
239
240 # like system() but checks errors.
241 #
242 sub safe_system(@) {
243   my (@cmd) = @_;
244
245   print STDERR "$progname: executing " . join(' ', @cmd) . "\n"
246     if ($verbose > 3);
247
248   system @cmd;
249   my $exit_value  = $? >> 8;
250   my $signal_num  = $? & 127;
251   my $dumped_core = $? & 128;
252   error ("$cmd[0]: core dumped!") if ($dumped_core);
253   error ("$cmd[0]: signal $signal_num!") if ($signal_num);
254   error ("$cmd[0]: exited with $exit_value!") if ($exit_value);
255 }
256
257
258 sub which($) {
259   my ($cmd) = @_;
260
261   if ($cmd =~ m@^\./|^/@) {
262     error ("cannot execute $cmd") unless (-x $cmd);
263     return $cmd;
264   }
265  
266  foreach my $dir (split (/:/, $ENV{PATH})) {
267     my $cmd2 = "$dir/$cmd";
268     print STDERR "$progname:   checking $cmd2\n" if ($verbose > 3);
269     return $cmd2 if (-x "$cmd2");
270   }
271   error ("$cmd not found on \$PATH");
272 }
273
274
275 sub output() {
276
277   # Do some basic sanity checking (null text, null file names, etc.)
278   #
279   if (($text_mode eq 'literal' && $text_literal =~ m/^\s*$/i) ||
280       ($text_mode eq 'file'    && $text_file    =~ m/^\s*$/i) ||
281       ($text_mode eq 'program' && $text_program =~ m/^\s*$/i) ||
282       ($text_mode eq 'url'     && $text_url     =~ m/^\s*$/i)) {
283     print STDERR "$progname: falling back to 'date'\n" if ($verbose);
284     $text_mode = 'date';
285   }
286
287   if ($text_mode eq 'literal') {
288     $text_literal = strftime ($text_literal, localtime);
289     $text_literal = utf8_to_latin1($text_literal) if ($latin1_p);
290     $text_literal =~ y/A-Za-z/N-ZA-Mn-za-m/ if ($nyarlathotep_p);
291     print STDOUT $text_literal;
292     print STDOUT "\n" unless ($text_literal =~ m/\n$/s);
293
294   } elsif ($text_mode eq 'file') {
295
296     $text_file =~ s@^~/@$ENV{HOME}/@s;     # allow literal "~/"
297
298     if (open (my $in, '<', $text_file)) {
299       print STDERR "$progname: reading $text_file\n" if ($verbose);
300
301       if (($wrap_columns && $wrap_columns > 0) || $truncate_lines) {
302         # read it, then reformat it.
303         local $/ = undef;  # read entire file
304         my $body = <$in>;
305         $body = reformat_text ($body);
306         print STDOUT $body;
307       } else {
308         # stream it by lines
309         while (<$in>) { 
310           $_ = utf8_to_latin1($_) if ($latin1_p);
311           y/A-Za-z/N-ZA-Mn-za-m/ if ($nyarlathotep_p);
312           print STDOUT $_;
313         }
314       }
315       close $in;
316     } else {
317       error ("$text_file: $!");
318     }
319
320   } elsif ($text_mode eq 'program') {
321
322     my ($prog, $args) = ($text_program =~ m/^([^\s]+)(.*)$/);
323     $text_program = which ($prog) . $args;
324     print STDERR "$progname: running $text_program\n" if ($verbose);
325
326     if (($wrap_columns && $wrap_columns > 0) || $truncate_lines) {
327       # read it, then reformat it.
328       my $lines = 0;
329       my $body = "";
330       my $cmd = "( $text_program ) 2>&1";
331       # $cmd .= " | sed -l"; # line buffer instead of 4k pipe buffer
332       open (my $pipe, '-|:unix', $cmd);
333       while (my $line = <$pipe>) {
334         $body .= $line;
335         $lines++;
336         last if ($truncate_lines && $lines > $truncate_lines);
337       }
338       close $pipe;
339       $body = reformat_text ($body);
340       print STDOUT $body;
341     } else {
342       # stream it
343       safe_system ("$text_program");
344     }
345
346   } elsif ($text_mode eq 'url') {
347
348     get_url_text ($text_url);
349
350   } else { # $text_mode eq 'date'
351
352     my $n = `uname -n`;
353     $n =~ s/\.local\n/\n/s;
354     print $n;
355
356     my $unamep = 1;
357
358     if (-f "/etc/redhat-release") {         # "Fedora Core release 4 (Stentz)"
359       safe_system ("cat", "/etc/redhat-release");
360     }
361
362     if (-f "/etc/release") {                # "Solaris 10 3/05 s10_74L2a X86"
363       safe_system ("head", "-1", "/etc/release");
364     }
365
366     if (-f "/usr/sbin/system_profiler") {   # "Mac OS X 10.4.5 (8H14)"
367       my $sp =                              # "iMac G5"
368         `/usr/sbin/system_profiler SPSoftwareDataType SPHardwareDataType 2>/dev/null`;
369       # system_profiler on OS X 10.10 generates spurious error messages.
370       my ($v) = ($sp =~ m/^\s*System Version:\s*(.*)$/mi);
371       my ($s) = ($sp =~ m/^\s*(?:CPU|Processor) Speed:\s*(.*)$/mi);
372       my ($t) = ($sp =~ m/^\s*(?:Machine|Model) Name:\s*(.*)$/mi);
373       print "$v\n" if ($v);
374       print "$s $t\n" if ($s && $t);
375       $unamep = !defined ($v);
376     }
377
378     if ($unamep) {
379       safe_system ("uname", "-sr");         # "Linux 2.6.15-1.1831_FC4"
380     }
381
382     print "\n";
383     safe_system ("date", "+%c");
384     print "\n";
385     my $ut = `uptime`;
386     $ut =~ s/^[ \d:]*(am|pm)?//i;
387     $ut =~ s/,\s*(load)/\n$1/;
388     print "$ut\n";
389   }
390
391 }
392
393
394 # Make an educated guess as to what's in this document.
395 # We don't necessarily take the Content-Type header at face value.
396 # Returns 'html', 'rss', or 'text';
397 #
398 sub guess_content_type($$) {
399   my ($ct, $body) = @_;
400
401   $body =~ s/^(.{512}).*/$1/s;  # only look in first half K of file
402
403   if ($ct =~ m@^text/.*html@i)          { return 'html'; }
404   if ($ct =~ m@\b(atom|rss|xml)\b@i)    { return 'rss';  }
405
406   if ($body =~ m@^\s*<\?xml@is)         { return 'rss';  }
407   if ($body =~ m@^\s*<!DOCTYPE RSS@is)  { return 'rss';  }
408   if ($body =~ m@^\s*<!DOCTYPE HTML@is) { return 'html'; }
409
410   if ($body =~ m@<(BASE|HTML|HEAD|BODY|SCRIPT|STYLE|TABLE|A\s+HREF)\b@i) {
411     return 'html';
412   }
413
414   if ($body =~ m@<(RSS|CHANNEL|GENERATOR|DESCRIPTION|CONTENT|FEED|ENTRY)\b@i) {
415     return 'rss';
416   }
417
418   return 'text';
419 }
420
421
422 sub reformat_html($$) {
423   my ($body, $rss_p) = @_;
424   $_ = $body;
425
426   # In HTML, try to preserve newlines inside of PRE.
427   #
428   if (! $rss_p) {
429     s@(<PRE\b[^<>]*>\s*)(.*?)(</PRE)@{
430       my ($a, $b, $c) = ($1, $2, $3);
431       $b =~ s/[\r\n]/<BR>/gs;
432       $a . $b . $c;
433      }@gsexi;
434   }
435
436   if (! $rss_p) {
437     # In HTML, unfold lines.
438     # In RSS, assume \n means literal line break.
439     s@[\r\n]@ @gsi;
440   }
441
442   # This right here is the part where I doom us all to inhuman
443   # toil for the One whose Name cannot be expressed in the
444   # Basic Multilingual Plane. http://jwz.org/b/yhAT He comes.
445
446   s@<!--.*?-->@@gsi;                             # lose comments
447   s@<(STYLE|SCRIPT)\b[^<>]*>.*?</\1\s*>@@gsi;    # lose css and js
448
449   s@</?(BR|TR|TD|LI|DIV)\b[^<>]*>@\n@gsi; # line break at BR, TD, DIV, etc
450   s@</?(P|UL|OL|BLOCKQUOTE)\b[^<>]*>@\n\n@gsi; # two line breaks
451
452   s@<lj\s+user=\"?([^<>\"]+)\"?[^<>]*>?@$1@gsi;  # handle <LJ USER=>
453   s@</?[BI]>@*@gsi;                              # bold, italic => asterisks
454
455
456   s@<[^<>]*>?@@gs;                # lose all other HTML tags
457   $_ = de_entify ($_);            # convert HTML entities
458
459   # For Wikipedia: delete anything inside {{ }} and unwrap [[tags]],
460   # among other things.
461   #
462   if ($rss_p eq 'wiki') {
463
464     s@<!--.*?-->@@gsi;                           # lose HTML comments again
465
466     # Creation line is often truncated: screws up parsing with unbalanced {{.
467     s@(: +[^a-zA-Z ]* *Created page) with [^\n]+@$1@s;
468
469     s@/\*.*?\*/@@si;                               # /* ... */
470
471     # Try to omit all tables, since they're impossible to read as text.
472     #
473     1 while (s/{{[^{}]*}}/ /gs);                   # {{ ... }}
474     1 while (s/{\|.*?\|}/\n\n/gs);                 # {| ... |}
475     1 while (s/\|-.*?\|/ /gs);                     # |- ... |  (table cell)
476
477     # Convert anchors to something more readable.
478     #
479     s/\[\[([^\[\]\|]+)\|([^\[\]]+)\]\]/$2/gs;      # [[link|anchor]]
480     s/\[\[([^:\[\]\|]+)\]\]/$1/gs;                 # [[anchor]]
481     s/\[https?:[^\[\]\s]+\s+([^\[\]]+)\]/$1/gs;    # [url anchor]
482
483     # Convert all references to asterisks.
484     s@\s*<ref>\s*.*?</ref>@*@gs;                   # <ref> ... <ref> ->  "*"
485     s@\n[ \t]*\d+\s*\^\s*http[^\s]+[ \t]*\n@\n@gs; # 1 ^ URL (a Reflist)
486
487     s@\[\[File:([^\|\]]+).*?\]\]@\n$1\n@gs;       # [[File: X | ... ]]
488     s@\[\[Category:.*?\]\]@@gs;                   # omit categories
489
490     s/<[^<>]*>//gs;     # Omit all remaining tags
491     s/\'{3,}//gs;       # Omit ''' and ''''
492     s/\'\'/\"/gs;       # ''  ->  "
493     s/\`\`/\"/gs;       # ``  ->  "
494     s/\"\"+/\"/gs;      # ""  ->  "
495
496     s/^[ \t]*[*#]+[ \t]*$//gm;  # Omit lines with just * or # on them
497
498     # Omit trailing headlines with no text after them (e.g. == Notes ==)
499     1 while (s/\n==+[ \t]*[^\n=]+[ \t]*==+\s*$/\n/s);
500
501     $_ = de_entify ($_);            # convert HTML entities, again
502   }
503
504
505   # elide any remaining non-Latin1 binary data.
506   if ($latin1_p) {
507     utf8::encode ($_);  # Unpack Unicode back to multi-byte UTF-8.
508     s/([^\000-\176]+(\s*[^\000-\176]+)[^a-z\d]*)/\xAB...\xBB /g;
509   }
510
511   $_ .= "\n";
512
513   s/[ \t]+$//gm;                  # lose whitespace at end of line
514   s@\n\n\n+@\n\n@gs;              # compress blank lines
515
516   if (!defined($wrap_columns) || $wrap_columns > 0) {
517     $Text::Wrap::columns = ($wrap_columns || 72);
518     $Text::Wrap::break = '[\s/|]';  # wrap on slashes for URLs
519     $_ = wrap ("", "  ", $_);       # wrap the lines as a paragraph
520     s/[ \t]+$//gm;                  # lose whitespace at end of line again
521   }
522
523   s/^\n+//gs;
524
525   if ($truncate_lines) {
526     s/^(([^\n]*\n){$truncate_lines}).*$/$1/s;
527   }
528
529   $_ = utf8_to_latin1($_) if ($latin1_p);
530   y/A-Za-z/N-ZA-Mn-za-m/ if ($nyarlathotep_p);
531
532   return $_;
533 }
534
535
536 sub reformat_rss($) {
537   my ($body) = @_;
538
539   my $wiki_p = ($body =~ m@<generator>[^<>]*Wiki@si);
540
541   $body =~ s/(<(ITEM|ENTRY)\b)/\001\001$1/gsi;
542   my @items = split (/\001\001/, $body);
543
544   print STDERR "$progname: converting RSS ($#items items)...\n"
545     if ($verbose > 2);
546
547   shift @items;
548
549   # Let's skip forward in the stream by a random amount, so that if
550   # two copies of ljlatest are running at the same time (e.g., on a
551   # multi-headed machine), they get different text.  (Put the items
552   # that we take off the front back on the back.)
553   #
554   if ($#items > 7) {
555     my $n = int (rand ($#items - 5));
556     print STDERR "$progname: rotating by $n items...\n" if ($verbose > 2);
557     while ($n-- > 0) {
558       push @items, (shift @items);
559     }
560   }
561
562   my $out = '';
563
564   my $i = -1;
565   foreach (@items) {
566     $i++;
567
568     my ($title, $body1, $body2, $body3);
569     
570     $title = $3 if (m@<((TITLE)       [^<>\s]*)[^<>]*>\s*(.*?)\s*</\1>@xsi);
571     $body1 = $3 if (m@<((DESCRIPTION) [^<>\s]*)[^<>]*>\s*(.*?)\s*</\1>@xsi);
572     $body2 = $3 if (m@<((CONTENT)     [^<>\s]*)[^<>]*>\s*(.*?)\s*</\1>@xsi);
573     $body3 = $3 if (m@<((SUMMARY)     [^<>\s]*)[^<>]*>\s*(.*?)\s*</\1>@xsi);
574
575     # If there are both <description> and <content> or <content:encoded>,
576     # use whichever one contains more text.
577     #
578     if ($body3 && length($body3) >= length($body2 || '')) {
579       $body2 = $body3;
580     }
581     if ($body2 && length($body2) >= length($body1 || '')) {
582       $body1 = $body2;
583     }
584
585     if (! $body1) {
586       if ($title) {
587         print STDERR "$progname: no body in item $i (\"$title\")\n"
588           if ($verbose > 2);
589       } else {
590         print STDERR "$progname: no body or title in item $i\n"
591           if ($verbose > 2);
592         next;
593       }
594     }
595
596     $title = rss_field_to_html ($title || '');
597     $body1 = rss_field_to_html ($body1 || '');
598
599     $title = '' if ($body1 eq $title);  # Identical in Twitter's atom feed.
600
601     $out .= reformat_html ("$title<P>$body1", $wiki_p ? 'wiki' : 'rss');
602     $out .= "\n";
603   }
604
605   if ($truncate_lines) {
606     $out =~ s/^(([^\n]*\n){$truncate_lines}).*$/$1/s;
607   }
608
609   return $out;
610 }
611
612
613 sub rss_field_to_html($) {
614   my ($body) = @_;
615
616   # If <![CDATA[...]]> is present, everything inside that is HTML,
617   # and not double-encoded.
618   #
619   if ($body =~ m/^\s*<!\[CDATA\[(.*?)\]\s*\]/is) {
620     $body = $1;
621   } else {
622     $body = de_entify ($body);      # convert entities to get HTML from XML
623   }
624
625   return $body;
626 }
627
628
629 sub reformat_text($) {
630   my ($body) = @_;
631
632   # only re-wrap if --cols was specified.  Otherwise, dump it as is.
633   #
634   if ($wrap_columns && $wrap_columns > 0) {
635     print STDERR "$progname: wrapping at $wrap_columns...\n" if ($verbose > 2);
636     $Text::Wrap::columns = $wrap_columns;
637     $Text::Wrap::break = '[\s/]';  # wrap on slashes for URLs
638     $body = wrap ("", "", $body);
639     $body =~ s/[ \t]+$//gm;
640   }
641
642   if ($truncate_lines) {
643     $body =~ s/^(([^\n]*\n){$truncate_lines}).*$/$1/s;
644   }
645
646   $body = utf8_to_latin1($body) if ($latin1_p);
647   $body =~ y/A-Za-z/N-ZA-Mn-za-m/ if ($nyarlathotep_p);
648   return $body;
649 }
650
651
652 # Figure out what the proxy server should be, either from environment
653 # variables or by parsing the output of the (MacOS) program "scutil",
654 # which tells us what the system-wide proxy settings are.
655 #
656 sub set_proxy($) {
657   my ($ua) = @_;
658
659   if (!defined($ENV{http_proxy}) && !defined($ENV{HTTP_PROXY})) {
660     my $proxy_data = `scutil --proxy 2>/dev/null`;
661     my ($server) = ($proxy_data =~ m/\bHTTPProxy\s*:\s*([^\s]+)/s);
662     my ($port)   = ($proxy_data =~ m/\bHTTPPort\s*:\s*([^\s]+)/s);
663     if ($server) {
664       # Note: this ignores the "ExceptionsList".
665       $ENV{http_proxy} = "http://" . $server . ($port ? ":$port" : "") . "/";
666       print STDERR "$progname: MacOS proxy: $ENV{http_proxy}\n"
667         if ($verbose > 2)
668       }
669   }
670
671   $ua->env_proxy();
672 }
673
674
675 sub get_url_text($) {
676   my ($url) = @_;
677
678   my $ua = eval 'LWP::UserAgent->new';
679
680   if (! $ua) {
681     print STDOUT ("\n\tPerl is broken. Do this to repair it:\n" .
682                   "\n\tsudo cpan LWP::UserAgent\n\n");
683     return;
684   }
685
686   set_proxy ($ua);
687   $ua->agent ("$progname/$version");
688   my $res = $ua->get ($url);
689   my $body;
690   my $ct;
691
692   if ($res && $res->is_success) {
693     $body = $res->decoded_content || '';
694     $ct   = $res->header ('Content-Type') || 'text/plain';
695
696   } else {
697     my $err = ($res ? $res->status_line : '') || '';
698     $err = 'unknown error' unless $err;
699     $err = "$url: $err";
700     # error ($err);
701     $body = "Error loading URL $err\n\n";
702     $ct = 'text/plain';
703   }
704
705   utf8::decode ($body);  # Pack multi-byte UTF-8 back into wide chars.
706
707   $ct = guess_content_type ($ct, $body);
708   if ($ct eq 'html') {
709     print STDERR "$progname: converting HTML...\n" if ($verbose > 2);
710     $body = reformat_html ($body, 0);
711   } elsif ($ct eq 'rss')  {
712     $body = reformat_rss ($body);
713   } else {
714     print STDERR "$progname: plain text...\n" if ($verbose > 2);
715     $body = reformat_text ($body);
716   }
717   print STDOUT $body;
718 }
719
720
721
722 sub error($) {
723   my ($err) = @_;
724   print STDERR "$progname: $err\n";
725   exit 1;
726 }
727
728 sub usage() {
729   print STDERR "usage: $progname [ --options ... ]\n" .
730    ("\n" .
731     "       Prints out some text for use by various screensavers,\n" .
732     "       according to the options in the ~/.xscreensaver file.\n" .
733     "       This may dump the contents of a file, run a program,\n" .
734     "       or load a URL.\n".
735     "\n" .
736     "   Options:\n" .
737     "\n" .
738     "       --date           Print the host name and current time.\n" .
739     "\n" .
740     "       --text STRING    Print out the given text.  It may contain %\n" .
741     "                        escape sequences as per strftime(2).\n" .
742     "\n" .
743     "       --file PATH      Print the contents of the given file.\n" .
744     "                        If --cols is specified, re-wrap the lines;\n" .
745     "                        otherwise, print them as-is.\n" .
746     "\n" .
747     "       --program CMD    Run the given program and print its output.\n" .
748     "                        If --cols is specified, re-wrap the output.\n" .
749     "\n" .
750     "       --url HTTP-URL   Download and print the contents of the HTTP\n" .
751     "                        document.  If it contains HTML, RSS, or Atom,\n" .
752     "                        it will be converted to plain-text.\n" .
753     "\n" .
754     "       --cols N         Wrap lines at this column.  Default 72.\n" .
755     "\n" .
756     "       --lines N        No more than N lines of output.\n" .
757     "\n" .
758     "       --latin1         Emit Latin1 instead of UTF-8.\n" .
759     "\n");
760   exit 1;
761 }
762
763 sub main() {
764
765   my $load_p = 1;
766   my $cocoa_id = undef;
767
768   while ($#ARGV >= 0) {
769     $_ = shift @ARGV;
770     if ($_ eq "--verbose") { $verbose++; }
771     elsif (m/^-v+$/) { $verbose += length($_)-1; }
772     elsif (m/^--?date$/)    { $text_mode = 'date';
773                               $load_p = 0; }
774     elsif (m/^--?text$/)    { $text_mode = 'literal';
775                               $text_literal = shift @ARGV || '';
776                               $load_p = 0; }
777     elsif (m/^--?file$/)    { $text_mode = 'file';
778                               $text_file = shift @ARGV || '';
779                               $load_p = 0; }
780     elsif (m/^--?program$/) { $text_mode = 'program';
781                               $text_program = shift @ARGV || '';
782                               $load_p = 0; }
783     elsif (m/^--?url$/)     { $text_mode = 'url';
784                               $text_url = shift @ARGV || '';
785                               $load_p = 0; }
786     elsif (m/^--?col(umn)?s?$/) { $wrap_columns = 0 + shift @ARGV; }
787     elsif (m/^--?lines?$/)  { $truncate_lines = 0 + shift @ARGV; }
788     elsif (m/^--?cocoa$/)   { $cocoa_id = shift @ARGV; }
789     elsif (m/^--?latin1$/)  { $latin1_p++; }
790     elsif (m/^--?nyarlathotep$/) { $nyarlathotep_p++; }
791     elsif (m/^-./) { usage; }
792     else { usage; }
793   }
794
795   if ($load_p) {
796
797     if (!defined ($cocoa_id)) {
798       # see OSX/XScreenSaverView.m
799       $cocoa_id = $ENV{XSCREENSAVER_CLASSPATH};
800     }
801
802     if (defined ($cocoa_id)) {
803       get_cocoa_prefs($cocoa_id);
804     } else {
805       get_x11_prefs();
806     }
807   }
808
809   output();
810
811
812   if (defined ($cocoa_id)) {
813     #
814     # On MacOS, sleep for 10 seconds between when the last output is
815     # printed, and when this process exits.  This is because MacOS
816     # 10.5.0 and later broke ptys in a new and exciting way: basically,
817     # once the process at the end of the pty exits, you have exactly
818     # 1 second to read all the queued data off the pipe before it is
819     # summarily flushed.
820     #
821     # Many of the screen savers were written to depend on being able
822     # to read a small number of bytes, and continue reading until they
823     # reached EOF.  This is no longer possible.
824     #
825     # Note that the current MacOS behavior has all four of these
826     # awesome properties: 1) Inconvenient; 2) Has no sane workaround;
827     # 3) Different behavior than MacOS 10.1 through 10.4; and 4)
828     # Different behavior than every other Unix in the world.
829     #
830     # See http://jwz.org/b/DHke, and for those of you inside Apple,
831     # "Problem ID 5606018".
832     #
833     # One workaround would be to rewrite the savers to have an
834     # internal buffer, and always read as much data as possible as
835     # soon as a pipe has input available.  However, that's a lot more
836     # work, so instead, let's just not exit right away, and hope that
837     # 10 seconds is enough.
838     #
839     # This will solve the problem for invocations of xscreensaver-text
840     # that produce little output (e.g., date-mode); and won't solve it
841     # in cases where a large amount of text is generated in a short
842     # amount of time (e.g., url-mode.)
843     #
844     sleep (10);
845   }
846 }
847
848 main();
849 exit 0;