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