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