http://ftp.x.org/contrib/applications/xscreensaver-3.20.tar.gz
[xscreensaver] / hacks / webcollage
1 #!/usr/local/bin/perl5 -w
2 #
3 # webcollage, Copyright (c) 1999 by Jamie Zawinski <jwz@jwz.org>
4 # This program decorates the screen with random images from the web.
5 # One satisfied customer described it as "a nonstop pop culture brainbath."
6 #
7 # Permission to use, copy, modify, distribute, and sell this software and its
8 # documentation for any purpose is hereby granted without fee, provided that
9 # the above copyright notice appear in all copies and that both that
10 # copyright notice and this permission notice appear in supporting
11 # documentation.  No representations are made about the suitability of this
12 # software for any purpose.  It is provided "as is" without express or 
13 # implied warranty.
14
15 # To run this as a display mode with xscreensaver, add this to `programs':
16 #
17 #   default-n:  webcollage -root                                        \n\
18 #   default-n:  webcollage -root -filter 'vidwhacker -stdin -stdout'    \n\
19
20 require 5;
21 #use diagnostics;
22 use strict;
23
24 use Socket;
25 require Time::Local;
26 require POSIX;
27 use Fcntl ':flock'; # import LOCK_* constants
28
29
30 my $version = q{ $Revision: 1.41 $ }; $version =~ s/^[^0-9]+([0-9.]+).*$/$1/;
31 my $copyright = "WebCollage $version, Copyright (c) 1999" .
32     " Jamie Zawinski <jwz\@jwz.org>\n" .
33     "            http://www.jwz.org/xscreensaver/\n";
34
35 my $argv0 = $0;
36 my $progname = $argv0; $progname =~ s@.*/@@g;
37
38 my $random_redirector = "http://random.yahoo.com/bin/ryl";
39 my $image_randomizer_1 = "http://www.altavista.com/query" .
40                          "?mmdo=3" .
41                          "&nbq=12" .
42                          "&stype=simage" .
43                          "&oart=1" .
44                          "&obw=1" .
45                          "&oshape=0" .
46                          "&what=web" .
47                          "&q=";
48 my $image_randomizer_2 = "http://www.hotbot.com/?clickSrc=search" .
49                          "&submit=SEARCH&SM=SC&LG=any" .
50                          "&AM0=MC&AT0=words&AW0=" .
51                          "&AM1=MN&AT1=words&AW1=" .
52                          "&savenummod=2&date=within" .
53                          "&DV=0&DR=newer&DM=1&DD=1&DY=99&FVI=1&FS=&RD=RG" .
54                          "&RG=all&Domain=&PS=A&PD=&STEM=1&DC=50&DE=0&_v=2" .
55                          "&OPs=MDRTP&NUMMOD=2" .
56                          "&MT=";
57 my $image_randomizer_3 = "http://www.altavista.com/cgi-bin/query?pg=q" .
58                          "&text=yes&kl=XX&stype=stext&q=";
59
60 # I guess Photopoint got wise to me, because now they are doing error
61 # checking on the user ("u=") and album ("a=") parameters.  Oh well.
62 #
63 #my $photo_randomizer   = "http://albums.photopoint.com/j/View?u=1&a=1&p=";
64 #my $photo_randomizer_lo = 10000001;
65 #my $photo_randomizer_hi = 12400000;
66
67 my $image_ppm   = ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp") . "/webcollage." . $$;
68 my $image_tmp1  = $image_ppm . "-1";
69 my $image_tmp2  = $image_ppm . "-2";
70
71 my $img_width;            # size of the image being generated.
72 my $img_height;
73
74 my $http_proxy = undef;
75 my $http_timeout = 30;
76 my $cvt_timeout = 10;
77
78 # programs we can use to write to the root window (tried in ascending order.)
79 my $ppm_to_root_window_cmd_1 = "xloadimage -onroot -quiet %%PPM%%";
80 my $ppm_to_root_window_cmd_2 = "xli -quiet -onroot -center" .
81                                " -border black %%PPM%%";
82 my $ppm_to_root_window_cmd_3 = "xv -root -rmode 5 -viewonly" .
83                                " +noresetroot %%PPM%% -quit";
84
85 my $ppm_to_root_window_cmd = undef;     # initialized by x_output()
86
87 my $filter_cmd = undef;
88 my $post_filter_cmd = undef;
89 my $background = undef;
90 my $no_output_p = 0;
91 my $urls_only_p = 0;
92 my $delay = 0;
93
94 my $wordlist = "/usr/dict/words";
95
96 if (!-r $wordlist) {
97     $wordlist = "/usr/share/lib/dict/words";    # irix
98 }
99 die "$wordlist doesn't exist!\n" unless (-r $wordlist);
100
101
102 my $min_width = 50;
103 my $min_height = 50;
104 my $min_ratio = 1/5;
105
106 my $verbose = 0;
107
108 my %rejected_urls;
109 my @tripwire_words = ("aberrate", "abode", "amorphous", "antioch",
110                       "arrhenius", "arteriole", "blanket", "brainchild",
111                       "burdensome", "carnival", "cherub", "chord", "clever",
112                       "dedicate", "dilogarithm", "dolan", "dryden",
113                       "eggplant");
114
115
116
117
118 ##############################################################################
119 #
120 # Retrieving URLs
121 #
122 ##############################################################################
123
124 # returns three values: the HTTP response line; the document headers;
125 # and the document body.
126 #
127 sub get_document_1 {
128     my ( $url, $referer, $timeout ) = @_;
129
130     if (!defined($timeout)) { $timeout = $http_timeout; }
131     if ($timeout <= 0) { return (); }
132     if ($timeout > $http_timeout) { $timeout = $http_timeout; }
133
134     if ( $verbose > 3 ) {
135         print STDERR "$progname: get_document_1 $url " .
136             ($referer ? $referer : "") . "\n";
137     }
138
139     my($url_proto, $dummy, $serverstring, $path) = split(/\//, $url, 4);
140     if (! ($url_proto && $url_proto =~ m/^http:$/i)) {
141         if ($verbose) { print STDERR "$progname: not an HTTP URL: $url\n"; }
142         return ();
143     }
144
145     $path = "" unless $path;
146
147     my($them,$port) = split(/:/, $serverstring);
148     $port = 80 unless $port;
149
150     my $them2 = $them;
151     my $port2 = $port;
152     if ($http_proxy) {
153         $serverstring = $http_proxy if $http_proxy;
154         ($them2,$port2) = split(/:/, $serverstring);
155         $port2 = 80 unless $port2;
156     }
157
158     my ($remote, $iaddr, $paddr, $proto, $line);
159     $remote = $them2;
160     if ($port2 =~ /\D/) { $port2 = getservbyname($port2, 'tcp') }
161     return unless $port2;
162     $iaddr   = inet_aton($remote) || return;
163     $paddr   = sockaddr_in($port2, $iaddr);
164
165
166     @_ =
167     eval {
168         local $SIG{ALRM}  = sub {
169             if ($verbose > 0) {
170                 print STDERR "$progname: timed out ($timeout) for $url\n";
171             }
172             die "alarm\n"
173             };
174         alarm $timeout;
175
176         $proto   = getprotobyname('tcp');
177         if (!socket(S, PF_INET, SOCK_STREAM, $proto)) {
178             print STDERR "$progname: socket: $!\n" if ($verbose);
179             return;
180         }
181         if (!connect(S, $paddr)) {
182             print STDERR "$progname: connect($serverstring): $!\n"
183                 if ($verbose);
184             return;
185         }
186
187         select(S); $| = 1; select(STDOUT);
188
189         my $cookie;
190         if ($remote =~ m/\baltavista\.com$/i) {
191             # kludge to tell the various altavista sites to be uncensored.
192             $cookie = "AV_ALL=1";
193         }
194
195         print S ("GET " . ($http_proxy ? $url : "/$path") . " HTTP/1.0\n" .
196                  "Host: $them\n" .
197                  "User-Agent: $progname/$version\n" .
198                  ($referer ? "Referer: $referer\n" : "") .
199                  ($cookie ? "Cookie: $cookie\n" : "") .
200                  "\n");
201         my $http = <S>;
202
203         my $head = "";
204         my $body = "";
205         while (<S>) {
206             $head .= $_;
207             last if m@^[\r\n]@;
208         }
209         while (<S>) {
210             $body .= $_;
211         }
212
213         close S;
214
215         if ( $verbose > 3 ) {
216             print STDERR "$progname:    ==> $http\n";
217         }
218
219         return ( $http, $head, $body );
220     };
221     die if ($@ && $@ ne "alarm\n");       # propagate errors
222     if ($@) {
223         # timed out
224         return ();
225     } else {
226         # didn't
227         alarm 0;
228         return @_;
229     }
230 }
231
232
233 # returns two values: the document headers; and the document body.
234 # if the given URL did a redirect, returns the redirected-to document.
235 #
236 sub get_document {
237     my ( $url, $referer, $timeout ) = @_;
238     my $start = time;
239
240     my $orig_url = $url;
241     my $loop_count = 0;
242     my $max_loop_count = 4;
243
244     do {
245         if (defined($timeout) && $timeout <= 0) { return (); }
246
247         my ( $http, $head, $body ) = get_document_1 ($url, $referer, $timeout);
248
249         if (defined ($timeout)) {
250             my $now = time;
251             my $elapsed = $now - $start;
252             $timeout -= $elapsed;
253             $start = $now;
254         }
255
256         return () if ( ! $body );
257
258         if ( $http =~ m@HTTP/[0-9.]+ 30[23]@ ) {
259             $_ = $head;
260             my ( $location ) = m@^location:[ \t]*(.*)$@im;
261             if ( $location ) {
262                 $location =~ s/[\r\n]$//;
263
264                 if ( $verbose > 3 ) {
265                     print STDERR "$progname: redirect from " .
266                         "$url to $location\n";
267                 }
268                 $referer = $url;
269                 $url = $location;
270
271                 if ($url =~ m@^/@) {
272                     $referer =~ m@^(http://[^/]+)@i;
273                     $url = $1 . $url;
274                 } elsif (! ($url =~ m@^[a-z]+:@i)) {
275                     $_ = $referer;
276                     s@[^/]+$@@g if m@^http://[^/]+/@i;
277                     $_ .= "/" if m@^http://[^/]+$@i;
278                     $url = $_ . $url;
279                 }
280
281             } else {
282                 return ( $url, $body );
283             }
284
285             if ($loop_count++ > $max_loop_count) {
286                 if ( $verbose > 1 ) {
287                     print STDERR "$progname: too many redirects " .
288                         "($max_loop_count) from $orig_url\n";
289                 }
290                 return ();
291             }
292
293         } elsif ( $http =~ m@HTTP/[0-9.]+ [4-9][0-9][0-9]@ ) {
294             # http errors -- return nothing.
295             return ();
296
297         } else {
298
299             return ( $url, $body );
300         }
301
302     } while (1);
303 }
304
305
306 # given a URL and the body text at that URL, selects and returns a random
307 # image from it.  returns () if no suitable images found.
308 #
309 sub pick_image_from_body {
310     my ( $url, $body ) = @_;
311
312     my $base = $url;
313     $_ = $url;
314
315     # if there's at least one slash after the host, take off the last
316     # pathname component
317     if ( m@^http://[^/]+/@io ) {
318         $base =~ s@[^/]+$@@go;
319     }
320
321     # if there are no slashes after the host at all, put one on the end.
322     if ( m@^http://[^/]+$@io ) {
323         $base .= "/";
324     }
325
326     if ( $verbose > 3 ) {
327         print STDERR "$progname: base is $base\n";
328     }
329
330
331     $_ = $body;
332
333     # strip out newlines, compress whitespace
334     s/[\r\n\t ]+/ /go;
335
336     # nuke comments
337     s/<!--.*?-->//go;
338
339
340     # There are certain web sites that list huge numbers of dictionary
341     # words in their bodies or in their <META NAME=KEYWORDS> tags (surprise!
342     # Porn sites tend not to be reputable!)
343     #
344     # I do not want webcollage to filter on content: I want it to select
345     # randomly from the set of images on the web.  All the logic here for
346     # rejecting some images is really a set of heuristics for rejecting
347     # images that are not really images: for rejecting *text* that is in
348     # GIF/JPEG form.  I don't want text, I want pictures, and I want the
349     # content of the pictures to be randomly selected from among all the
350     # available content.
351     #
352     # So, filtering out "dirty" pictures by looking for "dirty" keywords
353     # would be wrong: dirty pictures exist, like it or not, so webcollage
354     # should be able to select them.
355     #
356     # However, picking a random URL is a hard thing to do.  The mechanism I'm
357     # using is to search for a selection of random words.  This is not
358     # perfect, but works ok most of the time.  The way it breaks down is when
359     # some URLs get precedence because their pages list *every word* as
360     # related -- those URLs come up more often than others.
361     #
362     # So, after we've retrieved a URL, if it has too many keywords, reject
363     # it.  We reject it not on the basis of what those keywords are, but on
364     # the basis that by having so many, the page has gotten an unfair
365     # advantage against our randomizer.
366     #
367     my $trip_count = 0;
368     foreach my $trip (@tripwire_words) {
369         $trip_count++ if m/$trip/i;
370     }
371     if ($trip_count >= $#tripwire_words - 2) {
372         if ($verbose > 1) {
373             print STDERR "$progname: there is probably a dictionary in" .
374                 " \"$url\": rejecting.\n";
375         }
376         $rejected_urls{$url} = -1;
377         return ();
378     }
379
380
381     my @urls;
382     my %unique_urls;
383
384     foreach (split(/ *</)) {
385         if ( m/^meta /i ) {
386
387             # Likewise, reject any web pages that have a KEYWORDS meta tag
388             # that is too long.
389             #
390             if (m/name ?= ?\"?keywords\"?/i &&
391                 m/content ?= ?\"([^\"]+)\"/) {
392                 my $L = length($1);
393                 if ($L > 1000) {
394                     if ($verbose > 1) {
395                         print STDERR "$progname: keywords of" .
396                             " length $L in $url: rejecting.\n";
397                     }
398                     $rejected_urls{$url} = $L;
399                     return ();
400                 } elsif ( $verbose > 2 ) {
401                     print STDERR "$progname: keywords of length $L" .
402                         " in $url (ok.)\n";
403                 }
404             }
405
406         } elsif ( m/^(img|a) .*(src|href) ?= ?\"? ?(.*?)[ >\"]/io ) {
407
408             my $was_inline = ( "$1" eq "a" || "$1" eq "A" );
409             my $link = $3;
410             my ( $width )  = m/width ?=[ \"]*(\d+)/oi;
411             my ( $height ) = m/height ?=[ \"]*(\d+)/oi;
412             $_ = $link;
413
414             if ( m@^/@o ) {
415                 my $site;
416                 ( $site = $base ) =~ s@^(http://[^/]*).*@$1@gio;
417                 $_ = "$site$link";
418             } elsif ( ! m@^[^/:?]+:@ ) {
419                 $_ = "$base$link";
420                 s@/\./@/@g;
421                 while (s@/\.\./@/@g) {
422                 }
423             }
424
425             # skip non-http
426             if ( ! m@^http://@io ) {
427                 next;
428             }
429
430             # skip non-image
431             if ( ! m@[.](gif|jpg|jpeg|pjpg|pjpeg)$@io ) {
432                 next;
433             }
434
435             # skip really short or really narrow images
436             if ( $width && $width < $min_width) {
437                 if ( $verbose > 2 ) {
438                     if (!$height) { $height = "?"; }
439                     print STDERR "$progname: skip narrow image " .
440                         "$_ (${width}x$height)\n";
441                 }
442                 next;
443             }
444
445             if ( $height && $height < $min_height) {
446                 if ( $verbose > 2 ) {
447                     if (!$width) { $width = "?"; }
448                     print STDERR "$progname: skip short image " .
449                         "$_ (${width}x$height)\n";
450                 }
451                 next;
452             }
453
454             # skip images with ratios that make them look like banners.
455             if ( $min_ratio && $width && $height &&
456                 ($width * $min_ratio ) > $height ) {
457                 if ( $verbose > 2 ) {
458                     if (!$height) { $height = "?"; }
459                     print STDERR "$progname: skip bad ratio " .
460                         "$_ (${width}x$height)\n";
461                 }
462                 next;
463             }
464
465             my $url = $_;
466
467             if ( $unique_urls{$url} ) {
468                 if ( $verbose > 2 ) {
469                     print STDERR "$progname: skip duplicate image $_\n";
470                 }
471                 next;
472             }
473
474             if ( $verbose > 2 ) {
475                 print STDERR "$progname: got $url" . 
476                     ($width && $height ? " (${width}x${height})" : "") .
477                     ($was_inline ? " (inline)" : "") . "\n";
478             }
479
480             $urls[++$#urls] = $url;
481             $unique_urls{$url}++;
482
483             # jpegs are preferable to gifs.
484             $_ = $url;
485             if ( ! m@[.]gif$@io ) {
486                 $urls[++$#urls] = $url;
487             }
488
489             # pointers to images are preferable to inlined images.
490             if ( ! $was_inline ) {
491                 $urls[++$#urls] = $url;
492                 $urls[++$#urls] = $url;
493             }
494         }
495     }
496
497     if ( $#urls == 0 ) {
498         if ( $verbose > 2 ) {
499             print STDERR "$progname: no images on $base\n";
500         }
501         return ();
502     }
503
504     return () if ( $#urls < 1 );
505
506     # pick a random element of the table
507     my $i = ((rand() * 99999) % $#urls);
508     $url = $urls[$i];
509
510     if ( $verbose > 2 ) {
511         print STDERR "$progname: picked $url\n";
512     }
513
514     return $url;
515 }
516
517
518 # Using the URL-randomizer, picks a random image on a random page, and
519 # returns two URLs: the page containing the image, and the image.
520 # Returns () if nothing found this time.
521 #
522 sub pick_from_url_randomizer {
523     my ( $timeout ) = @_;
524
525     if ( $verbose > 3 ) {
526         print STDERR "\n\n$progname: picking from $random_redirector...\n\n";
527     }
528
529     my ( $base, $body ) = get_document ($random_redirector, undef, $timeout);
530
531     return if (!$base || !$body);
532     my $img = pick_image_from_body ($base, $body);
533
534     if ($img) {
535         return ($base, $img, "yahoo");
536     } else {
537         return ();
538     }
539 }
540
541
542 sub random_word {
543     
544     my $word = 0;
545     if (open (IN, "<$wordlist")) {
546         my $size = (stat(IN))[7];
547         my $pos = rand $size;
548         if (seek (IN, $pos, 0)) {
549             $word = <IN>;   # toss partial line
550             $word = <IN>;   # keep next line
551         }
552         close (IN);
553     }
554
555     return 0 if (!$word);
556
557     $word =~ s/^[ \t\n\r]+//;
558     $word =~ s/[ \t\n\r]+$//;
559     $word =~ s/ys$/y/;
560     $word =~ s/ally$//;
561     $word =~ s/ly$//;
562     $word =~ s/ies$/y/;
563     $word =~ s/ally$/al/;
564     $word =~ s/izes$/ize/;
565     $word =~ tr/A-Z/a-z/;
566
567     return $word;
568 }
569
570
571
572 # Using the image-randomizer, picks a random image on a random page, and
573 # returns two URLs: the page containing the image, and the image.
574 # Returns () if nothing found this time.
575 #
576 sub pick_from_image_randomizer {
577     my ( $timeout, $which ) = @_;
578
579     my $words = random_word;
580     $words .= "%20" . random_word;
581     $words .= "%20" . random_word;
582     $words .= "%20" . random_word;
583     $words .= "%20" . random_word;
584
585     my $search_url = ($which == 0 ? $image_randomizer_1 :
586                       $which == 1 ? $image_randomizer_2 :
587                       $image_randomizer_3) .
588         $words;
589
590     # Pick a random search-result page instead of always taking the first.
591     # This assumes there are at least 10 pages...
592     if ($which == 0) {
593         $search_url .= "&pgno=" . (int(rand(9)) + 1);
594     } elsif ($which == 2) {
595         $search_url .= "&stq=" . (10 * (int(rand(9)) + 1));
596     }
597
598     if ( $verbose > 3 ) {
599         $_ = $words; s/%20/ /g; print STDERR "$progname: search words: $_\n";
600     }
601
602     if ( $verbose > 3 ) {
603         print STDERR "\n\n$progname: picking from $search_url\n";
604     }
605
606     my $start = time;
607     my ( $base, $body ) = get_document ($search_url, undef, $timeout);
608     if (defined ($timeout)) {
609         $timeout -= (time - $start);
610         return () if ($timeout <= 0);
611     }
612
613     return () if (! $body);
614
615
616     my @subpages;
617     my $skipped = 0;
618
619     my $search_count = "?";
620     if ($which == 0 &&
621         $body =~ m@found (approximately |about )?(<B>)?(\d+)(</B>)? image@) {
622         $search_count = $3;
623     } elsif ($which == 1 && $body =~ m@<NOBR>((\d{1,3})(,\d{3})*)&nbsp;@i) {
624         $search_count = $1;
625     } elsif ($which == 2 && $body =~ m@found ((\d{1,3})(,\d{3})*|\d+) Web p@) {
626         $search_count = $1;
627     }
628     1 while ($search_count =~ s/^(\d+)(\d{3})/$1,$2/);
629
630     my $length = length($body);
631     my $href_count = 0;
632
633     $_ = $body;
634
635     s/Result [Pp]ages:.*$//s;            # trim off page footer
636     s/^.*?IMAGE RESULTS//s;              # trim off page header
637
638     s/[\r\n\t ]+/ /g;
639
640     s/(<A )/\n$1/gi;
641     foreach (split(/\n/)) {
642         $href_count++;
643         my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
644         next unless $u;
645         if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; }   # quoted string
646         elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; }  # or token
647
648         if ($which == 1) {
649             # Kludge to decode HotBot pages
650             next unless ($u =~ m@/director\.asp\?target=(http%3A[^&>]+)@);
651             $u = url_decode($1);
652         }
653
654         next unless ($u =~ m@^http://@i);  # skip non-http and relative urls.
655
656         next if ($u =~ m@[/.]altavista\.com@i);  # skip altavista builtins
657         next if ($u =~ m@[/.]av\.com@i);
658         next if ($u =~ m@[/.]virage\.com@i);
659         next if ($u =~ m@[/.]photoloft\.com@i);
660         next if ($u =~ m@[/.]shopping\.com@i);
661         next if ($u =~ m@[/.]thetrip\.com@i);
662         next if ($u =~ m@[/.]cmgi\.com@i);
663         next if ($u =~ m@[/.]intelihealth\.com@i);
664         next if ($u =~ m@[/.]wildweb\.com@i);
665         next if ($u =~ m@[/.]digital\.com@i);
666         next if ($u =~ m@[/.]doubleclick\.net@i);
667
668         if ($which == 0 && $u =~ m@[/.]corbis\.com@) {
669             $skipped = 1;
670             if ( $verbose > 3 ) {
671                 print STDERR "$progname: skipping corbis URL: $u\n";
672             }
673             next;
674
675         } elsif ( $rejected_urls{$u} ) {
676             if ( $verbose > 3 ) {
677                 my $L = $rejected_urls{$u};
678                 print STDERR "$progname: pre-rejecting sub-page: $u\n";
679             }
680             next;
681
682         } elsif ( $verbose > 3 ) {
683             print STDERR "$progname: sub-page: $u\n";
684         }
685
686         $subpages[++$#subpages] = $u;
687     }
688
689     if ( $#subpages < 0 ) {
690         if (!$skipped && $verbose > 1) {
691             print STDERR "$progname: found nothing on $base " .
692                 "($length bytes, $href_count links).\n";
693         }
694         return ();
695     }
696
697     # pick a random element of the table
698     my $i = ((rand() * 99999) % ($#subpages + 1));
699     my $subpage = $subpages[$i];
700
701     if ( $verbose > 3 ) {
702         print STDERR "$progname: picked page $subpage\n";
703     }
704
705
706
707     my ( $base2, $body2 ) = get_document ($subpage, $base, $timeout);
708
709     return () if (!$base2 || !$body2);
710
711     my $img = pick_image_from_body ($base2, $body2);
712
713     if ($img) {
714         return ($base2, $img,
715                 ($which == 0 ? "imagevista" :
716                  $which == 1 ? "hotbot" : "altavista") .
717                 "/$search_count");
718     } else {
719         return ();
720     }
721 }
722
723
724 # Using the photo site, generate a random URL that will hopefully point
725 # to an image.  Returns two URLs, both of which are the URL of the image.
726 # Returns () if nothing found this time.
727 #
728 #sub pick_from_photo_randomizer {
729 #    my ( $timeout ) = @_;
730 #    my $n = ($photo_randomizer_lo +
731 #             int(rand() * ($photo_randomizer_hi - $photo_randomizer_lo)));
732 #    my $url = $photo_randomizer . $n;
733 #    return ( $url, $url, "photopoint" );
734 #}
735
736
737 # Picks a random image on a random page, and returns two URLs:
738 # the page containing the image, and the image. 
739 # Returns () if nothing found this time.
740 # Uses the url-randomizer 1 time in 5, else the image randomizer.
741 #
742 my $total_0 = 0;
743 my $total_1 = 0;
744 my $total_2 = 0;
745 my $total_3 = 0;
746 my $total_4 = 0;
747 my $count_0 = 0;
748 my $count_1 = 0;
749 my $count_2 = 0;
750 my $count_3 = 0;
751 my $count_4 = 0;
752
753 sub pick_image {
754     my ( $timeout ) = @_;
755
756     my $r = int(rand(100));
757     my ($base, $img, $source, $total, $count);
758
759     if ($r < 20) {
760         ($base, $img, $source) = pick_from_url_randomizer ($timeout);
761         $total = ++$total_0;
762         $count = ++$count_0 if $img;
763
764     } elsif ($r < 60) {
765         ($base, $img, $source) = pick_from_image_randomizer ($timeout, 0);
766         $total = ++$total_1;
767         $count = ++$count_1 if $img;
768
769 #    } elsif ($r < 70) {
770 #        ($base, $img, $source) = pick_from_photo_randomizer ($timeout);
771 #        $total = ++$total_4;
772 #        $count = ++$count_4 if $img;
773
774 #    } elsif ($r < 80) {
775 #        # HotBot sucks: 98% of the time, it says "no pages match your
776 #        # search", and then if I load the URL again by hand, it works.
777 #        # I don't understand what's going wrong here, but we're not getting
778 #        # any good data back from them, so forget it for now.
779 #
780 #        ($base, $img, $source) = pick_from_image_randomizer ($timeout, 1);
781 #        $total = ++$total_2;
782 #        $count = ++$count_2 if $img;
783
784     } else {
785         ($base, $img, $source) = pick_from_image_randomizer ($timeout, 2);
786         $total = ++$total_3;
787         $count = ++$count_3 if $img;
788     }
789
790     if ($source && $total > 0) {
791         $source .= " " . int(($count / $total) * 100) . "%";
792     }
793     return ($base, $img, $source);
794 }
795
796
797 # Does %-decoding.
798 #
799 sub url_decode {
800     ($_) = @_;
801     tr/+/ /;
802     s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
803     return $_;
804 }
805
806
807 # Given the raw body of a GIF document, returns the dimensions of the image.
808 #
809 sub gif_size {
810     my ($body) = @_;
811     my $type = substr($body, 0, 6);
812     my $s;
813     return () unless ($type =~ /GIF8[7,9]a/);
814     $s = substr ($body, 6, 10);
815     my ($a,$b,$c,$d) = unpack ("C"x4, $s);
816     return (($b<<8|$a), ($d<<8|$c));
817 }
818
819 # Given the raw body of a JPEG document, returns the dimensions of the image.
820 #
821 sub jpeg_size {
822     my ($body) = @_;
823     my $i = 0;
824     my $L = length($body);
825     
826     my $c1 = substr($body, $i, 1); $i++;
827     my $c2 = substr($body, $i, 1); $i++;
828     return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
829
830     my $ch = "0";
831     while (ord($ch) != 0xDA && $i < $L) {
832         # Find next marker, beginning with 0xFF.
833         while (ord($ch) != 0xFF) {
834             $ch = substr($body, $i, 1); $i++;
835         }
836         # markers can be padded with any number of 0xFF.
837         while (ord($ch) == 0xFF) {
838             $ch = substr($body, $i, 1); $i++;
839         }
840
841         # $ch contains the value of the marker.
842         my $marker = ord($ch);
843
844         if (($marker >= 0xC0) &&
845             ($marker <= 0xCF) &&
846             ($marker != 0xC4) &&
847             ($marker != 0xCC)) {  # it's a SOFn marker
848             $i += 3;
849             my $s = substr($body, $i, 4); $i += 4;
850             my ($a,$b,$c,$d) = unpack("C"x4, $s);
851             return (($c<<8|$d), ($a<<8|$b));
852
853         } else {
854             # We must skip variables, since FFs in variable names aren't
855             # valid JPEG markers.
856             my $s = substr($body, $i, 2); $i += 2;
857             my ($c1, $c2) = unpack ("C"x2, $s); 
858             my $length = ($c1 << 8) | $c2;
859             return () if ($length < 2);
860             $i += $length-2;
861         }
862     }
863     return ();
864 }
865
866 # Given the raw body of a GIF or JPEG document, returns the dimensions of
867 # the image.
868 #
869 sub image_size {
870     my ($body) = @_;
871     my ($w, $h) = gif_size ($body);
872     if ($w && $h) { return ($w, $h); }
873     return jpeg_size ($body);
874 }
875
876
877 # returns the full path of the named program, or undef.
878 #
879 sub which {
880     my ($prog) = @_;
881     foreach (split (/:/, $ENV{PATH})) {
882         if (-x "$_/$prog") {
883             return $prog;
884         }
885     }
886     return undef;
887 }
888
889
890 # Like rand(), but chooses numbers with a bell curve distribution.
891 sub bellrand {
892     ($_) = @_;
893     $_ = 1.0 unless defined($_);
894     $_ /= 3.0;
895     return (rand($_) + rand($_) + rand($_));
896 }
897
898
899 ##############################################################################
900 #
901 # Generating a list of urls only
902 #
903 ##############################################################################
904
905 sub url_only_output {
906     do {
907         my ($base, $img) = pick_image;
908         if ($img) {
909             $base =~ s/ /%20/g;
910             $img  =~ s/ /%20/g;
911             print "$img $base\n";
912         }
913     } while (1);
914 }
915
916 ##############################################################################
917 #
918 # Running as an xscreensaver module
919 #
920 ##############################################################################
921
922 sub x_cleanup {
923     my ($sig) = @_;
924     if ($verbose > 0) { print STDERR "$progname: caught signal $sig.\n"; }
925     unlink $image_ppm, $image_tmp1, $image_tmp2;
926     exit 1;
927 }
928
929
930 # Like system, but prints status about exit codes, and kills this process
931 # with whatever signal killed the sub-process, if any.
932 #
933 sub nontrapping_system {
934     $! = 0;
935     
936     if ($verbose > 1) {
937         $_ = join(" ", @_);
938         s/\"[^\"]+\"/\"...\"/g;
939         print STDERR "$progname: executing \"$_\"\n";
940     }
941
942     my $rc = system @_;
943
944     if ($rc == 0) {
945         if ($verbose > 1) {
946             print STDERR "$progname: subproc exited normally.\n";
947         }
948     } elsif (($rc & 0xff) == 0) {
949         $rc >>= 8;
950         if ($verbose) {
951             print "$progname: subproc exited with status $rc.\n";
952         }
953     } else {
954         if ($rc & 0x80) {
955             if ($verbose) {
956                 print "$progname: subproc dumped core.\n";
957             }
958             $rc &= ~0x80;
959         }
960         if ($verbose) {
961             print "$progname: subproc died with signal $rc.\n";
962         }
963         # die that way ourselves.
964         kill $rc, $$;
965     }
966
967     return $rc;
968 }
969
970
971 # Given the URL of a GIF or JPEG image, and the body of that image, writes a
972 # PPM to the given output file.  Returns the width/height of the image if 
973 # successful.
974 #
975 sub image_to_pnm {
976     my ($url, $body, $output) = @_;
977     my ($cmd, $cmd2, $w, $h);
978
979     if ((@_ = gif_size ($body))) {
980         ($w, $h) = @_;
981         $cmd = "giftopnm";
982     } elsif ((@_ = jpeg_size ($body))) {
983         ($w, $h) = @_;
984         $cmd = "djpeg";
985     } else {
986         return ();
987     }
988
989     $cmd2 = "exec $cmd";        # yes, this really is necessary.  if we don't
990                                 # do this, the process doesn't die properly.
991     if ($verbose == 0) {
992         $cmd2 .= " 2>/dev/null";
993     }
994
995     # There exist corrupted GIF and JPEG files that can make giftopnm and
996     # djpeg lose their minds and go into a loop.  So this gives those programs
997     # a small timeout -- if they don't complete in time, kill them.
998     #
999     my $pid;
1000     @_ = eval {
1001         my $timed_out;
1002
1003         local $SIG{ALRM}  = sub {
1004             if ($verbose > 0) {
1005                 print STDERR "$progname: timed out ($cvt_timeout) for " .
1006                     "$cmd on \"$url\" in pid $pid\n";
1007             }
1008             kill ('TERM', $pid) if ($pid);
1009             $timed_out = 1;
1010         };
1011
1012         if (($pid = open(PIPE, "| $cmd2 > $output"))) {
1013             $timed_out = 0;
1014             alarm $cvt_timeout;
1015             print PIPE $body;
1016             close PIPE;
1017
1018             if ($verbose > 3) { print STDERR "$progname: awaiting $pid\n"; }
1019             waitpid ($pid, 0);
1020             if ($verbose > 3) { print STDERR "$progname: $pid completed\n"; }
1021
1022
1023             my $size = (stat($output))[7];
1024             if ($size < 5) {
1025                 if ($verbose) {
1026                     print STDERR "$progname: $cmd on ${w}x$h \"$url\" failed" .
1027                         " ($size bytes)\n";
1028                 }
1029                 return ();
1030             }
1031
1032             if ($verbose > 1) {
1033                 print STDERR "$progname: created ${w}x$h $output ($cmd)\n";
1034             }
1035             return ($w, $h);
1036         } else {
1037             print STDERR "$progname: $cmd failed: $!\n";
1038             return ();
1039         }
1040     };
1041     die if ($@ && $@ ne "alarm\n");       # propagate errors
1042     if ($@) {
1043         # timed out
1044         return ();
1045     } else {
1046         # didn't
1047         alarm 0;
1048         return @_;
1049     }
1050 }
1051
1052 sub x_output {
1053
1054     my $win_cmd_1 = $ppm_to_root_window_cmd_1;
1055     my $win_cmd_2 = $ppm_to_root_window_cmd_2;
1056     my $win_cmd_3 = $ppm_to_root_window_cmd_3;
1057     $win_cmd_1 =~ s/^([^ \t\r\n]+).*$/$1/;
1058     $win_cmd_2 =~ s/^([^ \t\r\n]+).*$/$1/;
1059     $win_cmd_3 =~ s/^([^ \t\r\n]+).*$/$1/;
1060
1061     # make sure the various programs we execute exist, right up front.
1062     foreach ("ppmmake", "giftopnm", "djpeg", "pnmpaste", "pnmscale",
1063              "pnmcut") {
1064         which ($_) || die "$progname: $_ not found on \$PATH.\n";
1065     }
1066
1067     if (which($win_cmd_1)) {
1068         $ppm_to_root_window_cmd = $ppm_to_root_window_cmd_1;
1069     } elsif (which($win_cmd_2)) {
1070         $ppm_to_root_window_cmd = $ppm_to_root_window_cmd_2;
1071     } elsif (which($win_cmd_3)) {
1072         $ppm_to_root_window_cmd = $ppm_to_root_window_cmd_3;
1073      } else {
1074         die "$progname: didn't find $win_cmd_1, $win_cmd_2, or $win_cmd_3 on \$PATH.\n";
1075     }
1076
1077     $SIG{HUP}  = \&x_cleanup;
1078     $SIG{INT}  = \&x_cleanup;
1079     $SIG{QUIT} = \&x_cleanup;
1080     $SIG{ABRT} = \&x_cleanup;
1081     $SIG{KILL} = \&x_cleanup;
1082     $SIG{TERM} = \&x_cleanup;
1083
1084     # Need this so that if giftopnm dies, we don't die.
1085     $SIG{PIPE} = 'IGNORE';
1086
1087     if (!$img_width || !$img_height) {
1088         $_ = "xdpyinfo";
1089         which ($_) || die "$progname: $_ not found on \$PATH.\n";
1090         $_ = `$_`;
1091         ($img_width, $img_height) = m/dimensions: *(\d+)x(\d+) /;
1092         if (!defined($img_height)) {
1093             die "$progname: xdpyinfo failed.\n";
1094         }
1095     }
1096
1097     my $bgcolor = "#000000";
1098     my $bgimage = undef;
1099
1100     if ($background) {
1101         if ($background =~ m/^\#[0-9a-f]+$/i) {
1102             $bgcolor = $background;
1103         } elsif (-r $background) {
1104             $bgimage = $background;
1105             
1106         } elsif (! $background =~ m@^[-a-z0-9 ]+$@i) {
1107             print STDERR "$progname: not a color or readable file: " .
1108                 "$background\n";
1109             exit 1;
1110         } else {
1111             # default to assuming it's a color
1112             $bgcolor = $background;
1113         }
1114     }
1115
1116     # Create the sold-colored base image.
1117     #
1118     $_ = "ppmmake '$bgcolor' $img_width $img_height";
1119     if ($verbose > 1) {
1120         print STDERR "$progname: creating base image: $_\n";
1121     }
1122     nontrapping_system "$_ > $image_ppm";
1123
1124     # Paste the default background image in the middle of it.
1125     #
1126     if ($bgimage) {
1127         my ($iw, $ih);
1128
1129         my $body = "";
1130         local *IMG;
1131         open(IMG, "<$bgimage") || die ("couldn't open $bgimage: $!\n");
1132         my $cmd;
1133         while (<IMG>) { $body .= $_; }
1134         close (IMG);
1135         if ((@_ = gif_size ($body))) {
1136             ($iw, $ih) = @_;
1137             $cmd = "giftopnm |";
1138         } elsif ((@_ = jpeg_size ($body))) {
1139             ($iw, $ih) = @_;
1140             $cmd = "djpeg |";
1141         } elsif ($body =~ "^P\d\n(\d+) (\d+)\n") {
1142             $iw = $1;
1143             $ih = $2;
1144             $cmd = "";
1145         } else {
1146             die "$progname: $bgimage is not a GIF, JPEG, or PPM.\n";
1147         }
1148
1149         my $x = int (($img_width  - $iw) / 2);
1150         my $y = int (($img_height - $ih) / 2);
1151         if ($verbose > 1) {
1152             print STDERR "$progname: pasting $bgimage (${iw}x$ih) into base ".
1153                 "image at $x,$y\n";
1154         }
1155
1156         $cmd .= "pnmpaste - $x $y $image_ppm > $image_tmp1";
1157         open (IMG, "| $cmd") || die ("running $cmd: $!\n");
1158         print IMG $body;
1159         close (IMG);
1160         if ($verbose > 1) {
1161             print STDERR "$progname: subproc exited normally.\n";
1162         }
1163         rename ($image_tmp1, $image_ppm) ||
1164             die ("renaming $image_tmp1 to $image_ppm: $!\n");
1165     }
1166
1167     while (1) {
1168         my ($base, $img, $source) = pick_image();
1169         if ($img) {
1170             my ($headers, $body) = get_document ($img, $base);
1171             if ($body) {
1172                 handle_image ($base, $img, $body, $source);
1173             }
1174         }
1175         unlink $image_tmp1, $image_tmp2;
1176         sleep $delay;
1177     }
1178 }
1179
1180 sub handle_image {
1181     my ($base, $img, $body, $source) = @_;
1182
1183     if ($verbose > 1) {
1184         print STDERR "$progname: got $img (" . length($body) . ")\n";
1185     }
1186
1187     my ($iw, $ih) = image_to_pnm ($img, $body, $image_tmp1);
1188     return 0 unless ($iw && $ih);
1189
1190     my $ow = $iw;  # used only for error messages
1191     my $oh = $ih;
1192
1193     # don't just tack this onto the front of the pipeline -- we want it to
1194     # be able to change the size of the input image.
1195     #
1196     if ($filter_cmd) {
1197         if ($verbose > 1) {
1198             print STDERR "$progname: running $filter_cmd\n";
1199         }
1200
1201         my $rc = nontrapping_system "($filter_cmd) < $image_tmp1 >$image_tmp2";
1202         if ($rc != 0) {
1203             if ($verbose) {
1204                 print STDERR "$progname: failed command: \"$filter_cmd\"\n";
1205                 print STDERR "$progname: failed url: \"$img\" (${ow}x$oh)\n";
1206             }
1207             return;
1208         }
1209         rename ($image_tmp2, $image_tmp1);
1210
1211         # re-get the width/height in case the filter resized it.
1212         local *IMG;
1213         open(IMG, "<$image_tmp1") || return 0;
1214         $_ = <IMG>;
1215         $_ = <IMG>;
1216         ($iw, $ih) = m/^(\d+) (\d+)$/;
1217         close (IMG);
1218         return 0 unless ($iw && $ih);
1219     }
1220
1221     my $target_w = $img_width;
1222     my $target_h = $img_height;
1223
1224     my $cmd = "";
1225
1226
1227     # Usually scale the image to fit on the screen -- but sometimes scale it
1228     # to fit on half or a quarter of the screen.  Note that we don't merely
1229     # scale it to fit, we instead cut it in half until it fits -- that should
1230     # give a wider distribution of sizes.
1231     #
1232     if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
1233     if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
1234
1235     if ($iw > $target_w || $ih > $target_h) {
1236         while ($iw > $target_w ||
1237                $ih > $target_h) {
1238             $iw = int($iw / 2);
1239             $ih = int($ih / 2);
1240         }
1241         if ($iw <= 10 || $ih <= 10) {
1242             if ($verbose > 1) {
1243                 print STDERR "$progname: scaling to ${iw}x$ih would " .
1244                     "have been bogus.\n";
1245             }
1246             return 0;
1247         }
1248
1249         if ($verbose > 1) {
1250             print STDERR "$progname: scaling to ${iw}x$ih\n";
1251         }
1252
1253         $cmd .= " | pnmscale -xsize $iw -ysize $ih";
1254     }
1255
1256
1257     my $src = $image_tmp1;
1258
1259     my $crop_x = 0;     # the sub-rectangle of the image
1260     my $crop_y = 0;     # that we will actually paste.
1261     my $crop_w = $iw;
1262     my $crop_h = $ih;
1263
1264     # The chance that we will randomly crop out a section of an image starts
1265     # out fairly low, but goes up for images that are very large, or images
1266     # that have ratios that make them look like banners (we try to avoid
1267     # banner images entirely, but they slip through when the IMG tags didn't
1268     # have WIDTH and HEIGHT specified.)
1269     #
1270     my $crop_chance = 0.2;
1271     if ($iw > $img_width * 0.4 || $ih > $img_height * 0.4) {
1272         $crop_chance += 0.2;
1273     }
1274     if ($iw > $img_width * 0.7 || $ih > $img_height * 0.7) {
1275         $crop_chance += 0.2;
1276     }
1277     if ($min_ratio && ($iw * $min_ratio) > $ih) {
1278         $crop_chance += 0.7;
1279     }
1280
1281     if ($verbose > 2 && $crop_chance > 0.1) {
1282         print STDERR "$progname: crop chance: $crop_chance\n";
1283     }
1284
1285     if (rand() < $crop_chance) {
1286
1287         my $ow = $crop_w;
1288         my $oh = $crop_h;
1289
1290         if ($crop_w > $min_width) {
1291             # if it's a banner, select the width linearly.
1292             # otherwise, select a bell.
1293             my $r = (($min_ratio && ($iw * $min_ratio) > $ih)
1294                      ? rand()
1295                      : bellrand());
1296             $crop_w = $min_width + int ($r * ($crop_w - $min_width));
1297             $crop_x = int (rand() * ($ow - $crop_w));
1298         }
1299         if ($crop_h > $min_height) {
1300             # height always selects as a bell.
1301             $crop_h = $min_height + int (bellrand() * ($crop_h - $min_height));
1302             $crop_y = int (rand() * ($oh - $crop_h));
1303         }
1304
1305         if ($verbose > 1 &&
1306             ($crop_x != 0   || $crop_y != 0 ||
1307              $crop_w != $iw || $crop_h != $ih)) {
1308             print STDERR "$progname: randomly cropping to " .
1309                 "${crop_w}x$crop_h \@ $crop_x,$crop_y\n";
1310         }
1311     }
1312
1313     # Where the image should logically land -- this might be negative.
1314     #
1315     my $x = int((rand() * ($img_width  + $crop_w/2)) - $crop_w*3/4);
1316     my $y = int((rand() * ($img_height + $crop_h/2)) - $crop_h*3/4);
1317
1318     # if we have chosen to paste the image outside of the rectangle of the
1319     # screen, then we need to crop it.
1320     #
1321     if ($x < 0 ||
1322         $y < 0 ||
1323         $x + $crop_w > $img_width ||
1324         $y + $crop_h > $img_height) {
1325
1326         if ($verbose > 1) {
1327             print STDERR "$progname: cropping for effective paste of " .
1328                 "${crop_w}x$crop_h \@ $x,$y\n";
1329         }
1330
1331         if ($x < 0) { $crop_x -= $x; $crop_w += $x; $x = 0; }
1332         if ($y < 0) { $crop_y -= $y; $crop_h += $y; $y = 0; }
1333
1334         if ($x + $crop_w >= $img_width)  { $crop_w = $img_width  - $x - 1; }
1335         if ($y + $crop_h >= $img_height) { $crop_h = $img_height - $y - 1; }
1336     }
1337
1338     # If any cropping needs to happen, add pnmcut.
1339     #
1340     if ($crop_x != 0   || $crop_y != 0 ||
1341         $crop_w != $iw || $crop_h != $ih) {
1342         $iw = $crop_w;
1343         $ih = $crop_h;
1344         $cmd .= " | pnmcut $crop_x $crop_y $iw $ih";
1345         if ($verbose > 1) {
1346             print STDERR "$progname: cropping to ${crop_w}x$crop_h \@ " .
1347                 "$crop_x,$crop_y\n";
1348         }
1349     }
1350
1351     if ($verbose > 1) {
1352         print STDERR "$progname: pasting ${iw}x$ih \@ $x,$y in $image_ppm\n";
1353     }
1354
1355     $cmd .= " | pnmpaste - $x $y $image_ppm";
1356
1357     $cmd =~ s@^ *\| *@@;
1358     my $rc = nontrapping_system "($cmd) < $image_tmp1 > $image_tmp2";
1359
1360     if ($rc != 0) {
1361         if ($verbose) {
1362             print STDERR "$progname: failed command: \"$cmd\"\n";
1363             print STDERR "$progname: failed url: \"$img\" (${ow}x$oh)\n";
1364         }
1365         return;
1366     }
1367
1368     rename ($image_tmp2, $image_ppm) || return;
1369
1370     my $target = "$image_ppm";
1371
1372     # don't just tack this onto the end of the pipeline -- we don't want it
1373     # to end up in $image_ppm, because we don't want the results to be
1374     # cumulative.
1375     #
1376     if ($post_filter_cmd) {
1377         $target = $image_tmp1;
1378         $rc = nontrapping_system "($post_filter_cmd) < $image_ppm > $target";
1379         if ($rc != 0) {
1380             if ($verbose) {
1381                 print STDERR "$progname: filter failed: " .
1382                     "\"$post_filter_cmd\"\n";
1383             }
1384             return;
1385         }
1386     }
1387
1388     if (!$no_output_p) {
1389         my $tsize = (stat($target))[7];
1390         if ($tsize > 200) {
1391             $cmd = $ppm_to_root_window_cmd;
1392             $cmd =~ s/%%PPM%%/$target/;
1393
1394             # xv seems to hate being killed.  it tends to forget to clean
1395             # up after itself, and leaves windows around and colors allocated.
1396             # I had this same problem with vidwhacker, and I'm not entirely
1397             # sure what I did to fix it.  But, let's try this: launch xv
1398             # in the background, so that killing this process doesn't kill it.
1399             # it will die of its own accord soon enough.  So this means we
1400             # start pumping bits to the root window in parallel with starting
1401             # the next network retrieval, which is probably a better thing
1402             # to do anyway.
1403             #
1404             $cmd .= "&";
1405
1406             $rc = nontrapping_system ($cmd);
1407
1408             if ($rc != 0) {
1409                 if ($verbose) {
1410                     print STDERR "$progname: display failed: \"$cmd\"\n";
1411                 }
1412                 return;
1413             }
1414
1415         } elsif ($verbose > 1) {
1416             print STDERR "$progname: $target size is $tsize\n";
1417         }
1418     }
1419
1420     if ($verbose > 0) {
1421         print STDOUT "image: ${iw}x${ih} @ $x,$y $base $source\n";
1422     }
1423
1424     return 1;
1425 }
1426
1427
1428 sub main {
1429     $| = 1;
1430     srand(time ^ $$);
1431
1432     my $root_p = 0;
1433
1434     # historical suckage: the environment variable name is lower case.
1435     $http_proxy = $ENV{http_proxy} || $ENV{HTTP_PROXY};
1436
1437     while ($_ = $ARGV[0]) {
1438         shift @ARGV;
1439         if ($_ eq "-display" ||
1440             $_ eq "-displ" ||
1441             $_ eq "-disp" ||
1442             $_ eq "-dis" ||
1443             $_ eq "-dpy" ||
1444             $_ eq "-d") {
1445             $ENV{DISPLAY} = shift @ARGV;
1446         } elsif ($_ eq "-root") {
1447             $root_p = 1;
1448         } elsif ($_ eq "-no-output") {
1449             $no_output_p = 1;
1450         } elsif ($_ eq "-urls-only") {
1451             $urls_only_p = 1;
1452             $no_output_p = 1;
1453         } elsif ($_ eq "-verbose") {
1454             $verbose++;
1455         } elsif (m/^-v+$/) {
1456             $verbose += length($_)-1;
1457         } elsif ($_ eq "-delay") {
1458             $delay = shift @ARGV;
1459         } elsif ($_ eq "-timeout") {
1460             $http_timeout = shift @ARGV;
1461         } elsif ($_ eq "-filter") {
1462             $filter_cmd = shift @ARGV;
1463         } elsif ($_ eq "-filter2") {
1464             $post_filter_cmd = shift @ARGV;
1465         } elsif ($_ eq "-background" || $_ eq "-bg") {
1466             $background = shift @ARGV;
1467         } elsif ($_ eq "-size") {
1468             $_ = shift @ARGV;
1469             if (m@^(\d+)x(\d+)$@) {
1470                 $img_width = $1;
1471                 $img_height = $2;
1472             } else {
1473                 die "$progname: argument to \"-size\" must be" .
1474                     " of the form \"640x400\"\n";
1475             }
1476         } elsif ($_ eq "-proxy" || $_ eq "-http-proxy") {
1477             $http_proxy = shift @ARGV;
1478         } else {
1479             die "$copyright\nusage: $progname [-root]" .
1480                 " [-display dpy] [-root] [-verbose] [-timeout secs]\n" .
1481                 "\t\t  [-delay secs] [-filter cmd] [-filter2 cmd]\n" .
1482                 "\t\t  [-http-proxy host[:port]]\n";
1483         }
1484     }
1485
1486     if ($http_proxy && $http_proxy eq "") {
1487         $http_proxy = undef;
1488     }
1489     if ($http_proxy && $http_proxy =~ m@^http://([^/]*)/?$@ ) {
1490         # historical suckage: allow "http://host:port" as well as "host:port".
1491         $http_proxy = $1;
1492     }
1493
1494     if (!$root_p && !$no_output_p) {
1495         die "$copyright" .
1496             "$progname: the -root argument is manditory (for now.)\n";
1497     }
1498
1499     if (!$no_output_p && !$ENV{DISPLAY}) {
1500         die "$progname: \$DISPLAY is not set.\n";
1501     }
1502
1503     if ($urls_only_p) {
1504         url_only_output;
1505     } else {
1506         x_output;
1507     }
1508 }
1509
1510 main;
1511 exit (0);