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