1 #!/usr/local/bin/perl5 -w
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."
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
15 # To run this as a display mode with xscreensaver, add this to `programs':
17 # default-n: webcollage -root \n\
18 # default-n: webcollage -root -filter 'vidwhacker -stdin -stdout' \n\
27 use Fcntl ':flock'; # import LOCK_* constants
30 my $version = q{ $Revision: 1.54 $ }; $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";
36 my $progname = $argv0; $progname =~ s@.*/@@g;
38 my $random_redirector = "http://random.yahoo.com/bin/ryl";
39 my $image_randomizer_1 = "http://www.altavista.com/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" .
57 my $image_randomizer_3 = "http://www.altavista.com/cgi-bin/query?pg=q" .
58 "&text=yes&kl=XX&stype=stext&q=";
59 my $image_randomizer_4 = "http://search.news.yahoo.com/search/news_photos?" .
60 "&z=&n=100&o=o&2=&3=&p=";
62 # I guess Photopoint got wise to me, because now they are doing error
63 # checking on the user ("u=") and album ("a=") parameters. Oh well.
65 #my $photo_randomizer = "http://albums.photopoint.com/j/View?u=1&a=1&p=";
66 #my $photo_randomizer_lo = 10000001;
67 #my $photo_randomizer_hi = 12400000;
69 my $image_ppm = ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp") . "/webcollage." . $$;
70 my $image_tmp1 = $image_ppm . "-1";
71 my $image_tmp2 = $image_ppm . "-2";
73 my $img_width; # size of the image being generated.
76 my $http_proxy = undef;
77 my $http_timeout = 30;
80 # programs we can use to write to the root window (tried in ascending order.)
81 my $ppm_to_root_window_cmd_1 = "xloadimage -onroot -quiet %%PPM%%";
82 my $ppm_to_root_window_cmd_2 = "xli -quiet -onroot -center" .
83 " -border black %%PPM%%";
84 my $ppm_to_root_window_cmd_3 = "xv -root -rmode 5 -viewonly" .
85 " +noresetroot %%PPM%% -quit";
87 my $ppm_to_root_window_cmd = undef; # initialized by x_output()
89 my $filter_cmd = undef;
90 my $post_filter_cmd = undef;
91 my $background = undef;
96 my $wordlist = "/usr/dict/words";
99 $wordlist = "/usr/share/lib/dict/words"; # irix
101 die "$wordlist doesn't exist!\n" unless (-r $wordlist);
111 my @tripwire_words = ("aberrate", "abode", "amorphous", "antioch",
112 "arrhenius", "arteriole", "blanket", "brainchild",
113 "burdensome", "carnival", "cherub", "chord", "clever",
114 "dedicate", "dilogarithm", "dolan", "dryden",
120 ##############################################################################
124 ##############################################################################
126 # returns three values: the HTTP response line; the document headers;
127 # and the document body.
130 my ( $url, $referer, $timeout ) = @_;
132 if (!defined($timeout)) { $timeout = $http_timeout; }
133 if ($timeout <= 0) { return (); }
134 if ($timeout > $http_timeout) { $timeout = $http_timeout; }
136 if ( $verbose > 3 ) {
137 print STDERR "$progname: get_document_1 $url " .
138 ($referer ? $referer : "") . "\n";
141 my($url_proto, $dummy, $serverstring, $path) = split(/\//, $url, 4);
142 if (! ($url_proto && $url_proto =~ m/^http:$/i)) {
143 if ($verbose) { print STDERR "$progname: not an HTTP URL: $url\n"; }
147 $path = "" unless $path;
149 my($them,$port) = split(/:/, $serverstring);
150 $port = 80 unless $port;
155 $serverstring = $http_proxy if $http_proxy;
156 ($them2,$port2) = split(/:/, $serverstring);
157 $port2 = 80 unless $port2;
160 my ($remote, $iaddr, $paddr, $proto, $line);
162 if ($port2 =~ /\D/) { $port2 = getservbyname($port2, 'tcp') }
163 return unless $port2;
164 $iaddr = inet_aton($remote) || return;
165 $paddr = sockaddr_in($port2, $iaddr);
173 local $SIG{ALRM} = sub {
175 print STDERR "$progname: timed out ($timeout) for $url\n";
181 $proto = getprotobyname('tcp');
182 if (!socket(S, PF_INET, SOCK_STREAM, $proto)) {
183 print STDERR "$progname: socket: $!\n" if ($verbose);
186 if (!connect(S, $paddr)) {
187 print STDERR "$progname: connect($serverstring): $!\n"
192 select(S); $| = 1; select(STDOUT);
195 if ($remote =~ m/\baltavista\.com$/i) {
196 # kludge to tell the various altavista sites to be uncensored.
197 $cookie = "AV_ALL=1";
200 print S ("GET " . ($http_proxy ? $url : "/$path") . " HTTP/1.0\r\n" .
202 "User-Agent: $progname/$version\r\n" .
203 ($referer ? "Referer: $referer\r\n" : "") .
204 ($cookie ? "Cookie: $cookie\r\n" : "") .
218 if ( $verbose > 3 ) {
219 print STDERR "$progname: ==> $http\n";
222 return ( $http, $head, $body );
224 die if ($@ && $@ ne "alarm\n"); # propagate errors
238 # returns two values: the document headers; and the document body.
239 # if the given URL did a redirect, returns the redirected-to document.
242 my ( $url, $referer, $timeout ) = @_;
247 my $max_loop_count = 4;
250 if (defined($timeout) && $timeout <= 0) { return (); }
252 my ( $http, $head, $body ) = get_document_1 ($url, $referer, $timeout);
254 if (defined ($timeout)) {
256 my $elapsed = $now - $start;
257 $timeout -= $elapsed;
261 return () if ( ! $body );
263 if ( $http =~ m@HTTP/[0-9.]+ 30[23]@ ) {
265 my ( $location ) = m@^location:[ \t]*(.*)$@im;
267 $location =~ s/[\r\n]$//;
269 if ( $verbose > 3 ) {
270 print STDERR "$progname: redirect from " .
271 "$url to $location\n";
277 $referer =~ m@^(http://[^/]+)@i;
279 } elsif (! ($url =~ m@^[a-z]+:@i)) {
281 s@[^/]+$@@g if m@^http://[^/]+/@i;
282 $_ .= "/" if m@^http://[^/]+$@i;
287 return ( $url, $body );
290 if ($loop_count++ > $max_loop_count) {
291 if ( $verbose > 1 ) {
292 print STDERR "$progname: too many redirects " .
293 "($max_loop_count) from $orig_url\n";
299 } elsif ( $http =~ m@HTTP/[0-9.]+ [4-9][0-9][0-9]@ ) {
300 # http errors -- return nothing.
306 return ( $url, $body );
313 # given a URL and the body text at that URL, selects and returns a random
314 # image from it. returns () if no suitable images found.
316 sub pick_image_from_body {
317 my ( $url, $body ) = @_;
322 # if there's at least one slash after the host, take off the last
324 if ( m@^http://[^/]+/@io ) {
325 $base =~ s@[^/]+$@@go;
328 # if there are no slashes after the host at all, put one on the end.
329 if ( m@^http://[^/]+$@io ) {
333 if ( $verbose > 3 ) {
334 print STDERR "$progname: base is $base\n";
340 # strip out newlines, compress whitespace
347 # There are certain web sites that list huge numbers of dictionary
348 # words in their bodies or in their <META NAME=KEYWORDS> tags (surprise!
349 # Porn sites tend not to be reputable!)
351 # I do not want webcollage to filter on content: I want it to select
352 # randomly from the set of images on the web. All the logic here for
353 # rejecting some images is really a set of heuristics for rejecting
354 # images that are not really images: for rejecting *text* that is in
355 # GIF/JPEG form. I don't want text, I want pictures, and I want the
356 # content of the pictures to be randomly selected from among all the
359 # So, filtering out "dirty" pictures by looking for "dirty" keywords
360 # would be wrong: dirty pictures exist, like it or not, so webcollage
361 # should be able to select them.
363 # However, picking a random URL is a hard thing to do. The mechanism I'm
364 # using is to search for a selection of random words. This is not
365 # perfect, but works ok most of the time. The way it breaks down is when
366 # some URLs get precedence because their pages list *every word* as
367 # related -- those URLs come up more often than others.
369 # So, after we've retrieved a URL, if it has too many keywords, reject
370 # it. We reject it not on the basis of what those keywords are, but on
371 # the basis that by having so many, the page has gotten an unfair
372 # advantage against our randomizer.
375 foreach my $trip (@tripwire_words) {
376 $trip_count++ if m/$trip/i;
378 if ($trip_count >= $#tripwire_words - 2) {
380 print STDERR "$progname: there is probably a dictionary in" .
381 " \"$url\": rejecting.\n";
383 $rejected_urls{$url} = -1;
393 foreach (split(/ *</)) {
396 # Likewise, reject any web pages that have a KEYWORDS meta tag
399 if (m/name ?= ?\"?keywords\"?/i &&
400 m/content ?= ?\"([^\"]+)\"/) {
404 print STDERR "$progname: keywords of" .
405 " length $L in $url: rejecting.\n";
407 $rejected_urls{$url} = $L;
411 } elsif ( $verbose > 2 ) {
412 print STDERR "$progname: keywords of length $L" .
417 } elsif ( m/^(img|a) .*(src|href) ?= ?\"? ?(.*?)[ >\"]/io ) {
419 my $was_inline = ( "$1" eq "a" || "$1" eq "A" );
421 my ( $width ) = m/width ?=[ \"]*(\d+)/oi;
422 my ( $height ) = m/height ?=[ \"]*(\d+)/oi;
427 ( $site = $base ) =~ s@^(http://[^/]*).*@$1@gio;
429 } elsif ( ! m@^[^/:?]+:@ ) {
432 while (s@/\.\./@/@g) {
437 if ( ! m@^http://@io ) {
442 if ( ! m@[.](gif|jpg|jpeg|pjpg|pjpeg)$@io ) {
446 # skip really short or really narrow images
447 if ( $width && $width < $min_width) {
448 if ( $verbose > 2 ) {
449 if (!$height) { $height = "?"; }
450 print STDERR "$progname: skip narrow image " .
451 "$_ (${width}x$height)\n";
456 if ( $height && $height < $min_height) {
457 if ( $verbose > 2 ) {
458 if (!$width) { $width = "?"; }
459 print STDERR "$progname: skip short image " .
460 "$_ (${width}x$height)\n";
465 # skip images with ratios that make them look like banners.
466 if ( $min_ratio && $width && $height &&
467 ($width * $min_ratio ) > $height ) {
468 if ( $verbose > 2 ) {
469 if (!$height) { $height = "?"; }
470 print STDERR "$progname: skip bad ratio " .
471 "$_ (${width}x$height)\n";
478 if ( $unique_urls{$url} ) {
479 if ( $verbose > 2 ) {
480 print STDERR "$progname: skip duplicate image $_\n";
485 if ( $verbose > 2 ) {
486 print STDERR "$progname: got $url" .
487 ($width && $height ? " (${width}x${height})" : "") .
488 ($was_inline ? " (inline)" : "") . "\n";
491 $urls[++$#urls] = $url;
492 $unique_urls{$url}++;
494 # jpegs are preferable to gifs.
496 if ( ! m@[.]gif$@io ) {
497 $urls[++$#urls] = $url;
500 # pointers to images are preferable to inlined images.
501 if ( ! $was_inline ) {
502 $urls[++$#urls] = $url;
503 $urls[++$#urls] = $url;
512 if ( $verbose > 2 ) {
513 print STDERR "$progname: no images on $base\n";
518 return () if ( $#urls < 1 );
520 # pick a random element of the table
521 my $i = ((rand() * 99999) % $#urls);
524 if ( $verbose > 2 ) {
525 print STDERR "$progname: picked $url\n";
532 # Using the URL-randomizer, picks a random image on a random page, and
533 # returns two URLs: the page containing the image, and the image.
534 # Returns () if nothing found this time.
536 sub pick_from_url_randomizer {
537 my ( $timeout ) = @_;
539 if ( $verbose > 3 ) {
540 print STDERR "\n\n$progname: picking from $random_redirector...\n\n";
543 my ( $base, $body ) = get_document ($random_redirector, undef, $timeout);
545 if (!$base || !$body) {
549 my $img = pick_image_from_body ($base, $body);
553 return ($base, $img, "yahoo");
563 if (open (IN, "<$wordlist")) {
564 my $size = (stat(IN))[7];
565 my $pos = rand $size;
566 if (seek (IN, $pos, 0)) {
567 $word = <IN>; # toss partial line
568 $word = <IN>; # keep next line
577 return 0 if (!$word);
579 $word =~ s/^[ \t\n\r]+//;
580 $word =~ s/[ \t\n\r]+$//;
585 $word =~ s/ally$/al/;
586 $word =~ s/izes$/ize/;
587 $word =~ tr/A-Z/a-z/;
589 if ( $word =~ s/[ \t\n\r]/\+/g ) { # convert intra-word spaces to "+".
590 $word = "\%22$word\%22"; # And put quotes (%22) around it.
598 # Using the image-randomizer, picks a random image on a random page, and
599 # returns two URLs: the page containing the image, and the image.
600 # Returns () if nothing found this time.
602 sub pick_from_image_randomizer {
603 my ( $timeout, $which ) = @_;
605 my $words = random_word;
606 $words .= "%20" . random_word;
607 $words .= "%20" . random_word;
608 $words .= "%20" . random_word;
609 $words .= "%20" . random_word;
611 my $search_url = ($which == 0 ? $image_randomizer_1 :
612 $which == 1 ? $image_randomizer_2 :
613 $which == 2 ? $image_randomizer_3 :
614 $image_randomizer_4) .
617 # Pick a random search-result page instead of always taking the first.
618 # This assumes there are at least 10 pages...
620 $search_url .= "&pgno=" . (int(rand(9)) + 1);
621 } elsif ($which == 2) {
622 $search_url .= "&stq=" . (10 * (int(rand(9)) + 1));
625 if ( $verbose > 3 ) {
626 $_ = $words; s/%20/ /g; print STDERR "$progname: search words: $_\n";
629 if ( $verbose > 3 ) {
630 print STDERR "\n\n$progname: picking from $search_url\n";
634 my ( $base, $body ) = get_document ($search_url, undef, $timeout);
635 if (defined ($timeout)) {
636 $timeout -= (time - $start);
643 return () if (! $body);
649 my $search_count = "?";
651 $body =~ m@found (approximately |about )?(<B>)?(\d+)(</B>)? image@) {
653 } elsif ($which == 1 && $body =~ m@<NOBR>((\d{1,3})(,\d{3})*) @i) {
655 } elsif ($which == 2 && $body =~ m@found ((\d{1,3})(,\d{3})*|\d+) Web p@) {
658 1 while ($search_count =~ s/^(\d+)(\d{3})/$1,$2/);
660 my $length = length($body);
665 # s/Result [Pp]ages:.*$//s; # trim off page footer
666 # s/^.*?IMAGE RESULTS//s; # trim off page header
671 foreach (split(/\n/)) {
673 my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
675 if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; } # quoted string
676 elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; } # or token
679 # Kludge to decode HotBot pages
680 next unless ($u =~ m@/director\.asp\?target=(http%3A[^&>]+)@);
684 next unless ($u =~ m@^http://@i); # skip non-http and relative urls.
686 next if ($u =~ m@[/.]altavista\.com@i); # skip altavista builtins
687 next if ($u =~ m@[/.]av\.com@i);
688 next if ($u =~ m@[/.]virage\.com@i);
689 next if ($u =~ m@[/.]photoloft\.com@i);
690 next if ($u =~ m@[/.]shopping\.com@i);
691 next if ($u =~ m@[/.]thetrip\.com@i);
692 next if ($u =~ m@[/.]cmgi\.com@i);
693 next if ($u =~ m@[/.]intelihealth\.com@i);
694 next if ($u =~ m@[/.]wildweb\.com@i);
695 next if ($u =~ m@[/.]digital\.com@i);
696 next if ($u =~ m@[/.]doubleclick\.net@i);
697 next if ($u =~ m@[/.]freeim\.org@i);
698 next if ($u =~ m@[/.]clicktomarket\.com@i); # you cretins
700 if ($which == 0 && $u =~ m@[/.]corbis\.com@) {
702 if ( $verbose > 3 ) {
703 print STDERR "$progname: skipping corbis URL: $u\n";
707 } elsif ($which == 3 &&
708 ($u =~ m@^http://[^/]+$@ || # no slashes
709 $u =~ m@/$@ || # ends in /
710 ! ($u =~ m@dailynews\.yahoo\.com@))) { # not dailynews
712 if ( $verbose > 3 ) {
713 print STDERR "$progname: skipping non-AP URL: $u\n";
717 } elsif ( $rejected_urls{$u} ) {
718 if ( $verbose > 3 ) {
719 my $L = $rejected_urls{$u};
720 print STDERR "$progname: pre-rejecting sub-page: $u\n";
724 } elsif ( $verbose > 3 ) {
725 print STDERR "$progname: sub-page: $u\n";
728 $subpages[++$#subpages] = $u;
731 if ( $#subpages < 0 ) {
732 if (!$skipped && $verbose > 1) {
733 print STDERR "$progname: found nothing on $base " .
734 "($length bytes, $href_count links).\n";
741 # pick a random element of the table
742 my $i = ((rand() * 99999) % ($#subpages + 1));
743 my $subpage = $subpages[$i];
745 if ( $verbose > 3 ) {
746 print STDERR "$progname: picked page $subpage\n";
753 my ( $base2, $body2 ) = get_document ($subpage, $base, $timeout);
755 if (!$base2 || !$body2) {
760 my $img = pick_image_from_body ($base2, $body2);
764 return ($base2, $img,
765 ($which == 0 ? "imagevista" :
766 $which == 1 ? "hotbot" :
767 $which == 2 ? "altavista" :
776 # Using the photo site, generate a random URL that will hopefully point
777 # to an image. Returns two URLs, both of which are the URL of the image.
778 # Returns () if nothing found this time.
780 #sub pick_from_photo_randomizer {
781 # my ( $timeout ) = @_;
782 # my $n = ($photo_randomizer_lo +
783 # int(rand() * ($photo_randomizer_hi - $photo_randomizer_lo)));
784 # my $url = $photo_randomizer . $n;
785 # return ( $url, $url, "photopoint" );
789 # Picks a random image on a random page, and returns two URLs:
790 # the page containing the image, and the image.
791 # Returns () if nothing found this time.
792 # Uses the url-randomizer 1 time in 5, else the image randomizer.
806 my ( $timeout ) = @_;
808 my $r = int(rand(100));
810 my ($base, $img, $source, $total, $count);
813 ($base, $img, $source) = pick_from_url_randomizer ($timeout);
815 $count = ++$count_0 if $img;
818 ($base, $img, $source) = pick_from_image_randomizer ($timeout, 0);
820 $count = ++$count_1 if $img;
823 ($base, $img, $source) = pick_from_image_randomizer ($timeout, 3);
825 $count = ++$count_4 if $img;
827 # } elsif ($r < 70) {
828 # ($base, $img, $source) = pick_from_photo_randomizer ($timeout);
829 # $total = ++$total_4;
830 # $count = ++$count_4 if $img;
832 # } elsif ($r < 80) {
833 # # HotBot sucks: 98% of the time, it says "no pages match your
834 # # search", and then if I load the URL again by hand, it works.
835 # # I don't understand what's going wrong here, but we're not getting
836 # # any good data back from them, so forget it for now.
838 # ($base, $img, $source) = pick_from_image_randomizer ($timeout, 1);
839 # $total = ++$total_2;
840 # $count = ++$count_2 if $img;
843 ($base, $img, $source) = pick_from_image_randomizer ($timeout, 2);
845 $count = ++$count_3 if $img;
848 if ($source && $total > 0) {
849 $source .= " " . int(($count / $total) * 100) . "%";
851 return ($base, $img, $source);
860 s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
865 # Given the raw body of a GIF document, returns the dimensions of the image.
869 my $type = substr($body, 0, 6);
871 return () unless ($type =~ /GIF8[7,9]a/);
872 $s = substr ($body, 6, 10);
873 my ($a,$b,$c,$d) = unpack ("C"x4, $s);
874 return (($b<<8|$a), ($d<<8|$c));
877 # Given the raw body of a JPEG document, returns the dimensions of the image.
882 my $L = length($body);
884 my $c1 = substr($body, $i, 1); $i++;
885 my $c2 = substr($body, $i, 1); $i++;
886 return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
889 while (ord($ch) != 0xDA && $i < $L) {
890 # Find next marker, beginning with 0xFF.
891 while (ord($ch) != 0xFF) {
892 $ch = substr($body, $i, 1); $i++;
894 # markers can be padded with any number of 0xFF.
895 while (ord($ch) == 0xFF) {
896 $ch = substr($body, $i, 1); $i++;
899 # $ch contains the value of the marker.
900 my $marker = ord($ch);
902 if (($marker >= 0xC0) &&
905 ($marker != 0xCC)) { # it's a SOFn marker
907 my $s = substr($body, $i, 4); $i += 4;
908 my ($a,$b,$c,$d) = unpack("C"x4, $s);
909 return (($c<<8|$d), ($a<<8|$b));
912 # We must skip variables, since FFs in variable names aren't
913 # valid JPEG markers.
914 my $s = substr($body, $i, 2); $i += 2;
915 my ($c1, $c2) = unpack ("C"x2, $s);
916 my $length = ($c1 << 8) | $c2;
917 return () if ($length < 2);
924 # Given the raw body of a GIF or JPEG document, returns the dimensions of
929 my ($w, $h) = gif_size ($body);
930 if ($w && $h) { return ($w, $h); }
931 return jpeg_size ($body);
935 # returns the full path of the named program, or undef.
939 foreach (split (/:/, $ENV{PATH})) {
948 # Like rand(), but chooses numbers with a bell curve distribution.
951 $_ = 1.0 unless defined($_);
953 return (rand($_) + rand($_) + rand($_));
957 ##############################################################################
959 # Generating a list of urls only
961 ##############################################################################
963 sub url_only_output {
965 my ($base, $img) = pick_image;
969 print "$img $base\n";
974 ##############################################################################
976 # Running as an xscreensaver module
978 ##############################################################################
982 if ($verbose > 0) { print STDERR "$progname: caught signal $sig.\n"; }
983 unlink $image_ppm, $image_tmp1, $image_tmp2;
988 # Like system, but prints status about exit codes, and kills this process
989 # with whatever signal killed the sub-process, if any.
991 sub nontrapping_system {
996 s/\"[^\"]+\"/\"...\"/g;
997 print STDERR "$progname: executing \"$_\"\n";
1004 print STDERR "$progname: subproc exited normally.\n";
1006 } elsif (($rc & 0xff) == 0) {
1009 print "$progname: subproc exited with status $rc.\n";
1014 print "$progname: subproc dumped core.\n";
1019 print "$progname: subproc died with signal $rc.\n";
1021 # die that way ourselves.
1029 # Given the URL of a GIF or JPEG image, and the body of that image, writes a
1030 # PPM to the given output file. Returns the width/height of the image if
1034 my ($url, $body, $output) = @_;
1035 my ($cmd, $cmd2, $w, $h);
1037 if ((@_ = gif_size ($body))) {
1040 } elsif ((@_ = jpeg_size ($body))) {
1047 $cmd2 = "exec $cmd"; # yes, this really is necessary. if we don't
1048 # do this, the process doesn't die properly.
1049 if ($verbose <= 1) {
1051 # We get a "giftopnm: got a 'Application Extension' extension"
1052 # warning any time it's an animgif.
1054 # Note that "giftopnm: EOF / read error on image data" is not
1055 # always a fatal error -- sometimes the image looks fine anyway.
1057 $cmd2 .= " 2>/dev/null";
1060 # There exist corrupted GIF and JPEG files that can make giftopnm and
1061 # djpeg lose their minds and go into a loop. So this gives those programs
1062 # a small timeout -- if they don't complete in time, kill them.
1068 local $SIG{ALRM} = sub {
1070 print STDERR "$progname: timed out ($cvt_timeout) for " .
1071 "$cmd on \"$url\" in pid $pid\n";
1073 kill ('TERM', $pid) if ($pid);
1078 if (($pid = open(PIPE, "| $cmd2 > $output"))) {
1085 if ($verbose > 3) { print STDERR "$progname: awaiting $pid\n"; }
1087 if ($verbose > 3) { print STDERR "$progname: $pid completed\n"; }
1090 my $size = (stat($output))[7];
1093 print STDERR "$progname: $cmd on ${w}x$h \"$url\" failed" .
1100 print STDERR "$progname: created ${w}x$h $output ($cmd)\n";
1104 print STDERR "$progname: $cmd failed: $!\n";
1108 die if ($@ && $@ ne "alarm\n"); # propagate errors
1123 my $win_cmd_1 = $ppm_to_root_window_cmd_1;
1124 my $win_cmd_2 = $ppm_to_root_window_cmd_2;
1125 my $win_cmd_3 = $ppm_to_root_window_cmd_3;
1126 $win_cmd_1 =~ s/^([^ \t\r\n]+).*$/$1/;
1127 $win_cmd_2 =~ s/^([^ \t\r\n]+).*$/$1/;
1128 $win_cmd_3 =~ s/^([^ \t\r\n]+).*$/$1/;
1130 # make sure the various programs we execute exist, right up front.
1131 foreach ("ppmmake", "giftopnm", "djpeg", "pnmpaste", "pnmscale",
1133 which ($_) || die "$progname: $_ not found on \$PATH.\n";
1136 if (which($win_cmd_1)) {
1137 $ppm_to_root_window_cmd = $ppm_to_root_window_cmd_1;
1138 } elsif (which($win_cmd_2)) {
1139 $ppm_to_root_window_cmd = $ppm_to_root_window_cmd_2;
1140 } elsif (which($win_cmd_3)) {
1141 $ppm_to_root_window_cmd = $ppm_to_root_window_cmd_3;
1143 die "$progname: didn't find $win_cmd_1, $win_cmd_2, or $win_cmd_3 on \$PATH.\n";
1146 $SIG{HUP} = \&x_cleanup;
1147 $SIG{INT} = \&x_cleanup;
1148 $SIG{QUIT} = \&x_cleanup;
1149 $SIG{ABRT} = \&x_cleanup;
1150 $SIG{KILL} = \&x_cleanup;
1151 $SIG{TERM} = \&x_cleanup;
1153 # Need this so that if giftopnm dies, we don't die.
1154 $SIG{PIPE} = 'IGNORE';
1156 if (!$img_width || !$img_height) {
1158 which ($_) || die "$progname: $_ not found on \$PATH.\n";
1160 ($img_width, $img_height) = m/dimensions: *(\d+)x(\d+) /;
1161 if (!defined($img_height)) {
1162 die "$progname: xdpyinfo failed.\n";
1166 my $bgcolor = "#000000";
1167 my $bgimage = undef;
1170 if ($background =~ m/^\#[0-9a-f]+$/i) {
1171 $bgcolor = $background;
1172 } elsif (-r $background) {
1173 $bgimage = $background;
1175 } elsif (! $background =~ m@^[-a-z0-9 ]+$@i) {
1176 print STDERR "$progname: not a color or readable file: " .
1180 # default to assuming it's a color
1181 $bgcolor = $background;
1185 # Create the sold-colored base image.
1187 $_ = "ppmmake '$bgcolor' $img_width $img_height";
1189 print STDERR "$progname: creating base image: $_\n";
1191 nontrapping_system "$_ > $image_ppm";
1193 # Paste the default background image in the middle of it.
1200 open(IMG, "<$bgimage") || die ("couldn't open $bgimage: $!\n");
1202 while (<IMG>) { $body .= $_; }
1204 if ((@_ = gif_size ($body))) {
1206 $cmd = "giftopnm |";
1207 } elsif ((@_ = jpeg_size ($body))) {
1210 } elsif ($body =~ "^P\d\n(\d+) (\d+)\n") {
1215 die "$progname: $bgimage is not a GIF, JPEG, or PPM.\n";
1218 my $x = int (($img_width - $iw) / 2);
1219 my $y = int (($img_height - $ih) / 2);
1221 print STDERR "$progname: pasting $bgimage (${iw}x$ih) into base ".
1225 $cmd .= "pnmpaste - $x $y $image_ppm > $image_tmp1";
1226 open (IMG, "| $cmd") || die ("running $cmd: $!\n");
1231 print STDERR "$progname: subproc exited normally.\n";
1233 rename ($image_tmp1, $image_ppm) ||
1234 die ("renaming $image_tmp1 to $image_ppm: $!\n");
1238 my ($base, $img, $source) = pick_image();
1240 my ($headers, $body) = get_document ($img, $base);
1242 handle_image ($base, $img, $body, $source);
1246 unlink $image_tmp1, $image_tmp2;
1252 my ($base, $img, $body, $source) = @_;
1255 print STDERR "$progname: got $img (" . length($body) . ")\n";
1258 my ($iw, $ih) = image_to_pnm ($img, $body, $image_tmp1);
1260 return 0 unless ($iw && $ih);
1262 my $ow = $iw; # used only for error messages
1265 # don't just tack this onto the front of the pipeline -- we want it to
1266 # be able to change the size of the input image.
1270 print STDERR "$progname: running $filter_cmd\n";
1273 my $rc = nontrapping_system "($filter_cmd) < $image_tmp1 >$image_tmp2";
1276 print STDERR "$progname: failed command: \"$filter_cmd\"\n";
1277 print STDERR "$progname: failed url: \"$img\" (${ow}x$oh)\n";
1281 rename ($image_tmp2, $image_tmp1);
1283 # re-get the width/height in case the filter resized it.
1285 open(IMG, "<$image_tmp1") || return 0;
1288 ($iw, $ih) = m/^(\d+) (\d+)$/;
1290 return 0 unless ($iw && $ih);
1293 my $target_w = $img_width;
1294 my $target_h = $img_height;
1299 # Usually scale the image to fit on the screen -- but sometimes scale it
1300 # to fit on half or a quarter of the screen. Note that we don't merely
1301 # scale it to fit, we instead cut it in half until it fits -- that should
1302 # give a wider distribution of sizes.
1304 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
1305 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
1307 if ($iw > $target_w || $ih > $target_h) {
1308 while ($iw > $target_w ||
1313 if ($iw <= 10 || $ih <= 10) {
1315 print STDERR "$progname: scaling to ${iw}x$ih would " .
1316 "have been bogus.\n";
1322 print STDERR "$progname: scaling to ${iw}x$ih\n";
1325 $cmd .= " | pnmscale -xsize $iw -ysize $ih";
1329 my $src = $image_tmp1;
1331 my $crop_x = 0; # the sub-rectangle of the image
1332 my $crop_y = 0; # that we will actually paste.
1336 # The chance that we will randomly crop out a section of an image starts
1337 # out fairly low, but goes up for images that are very large, or images
1338 # that have ratios that make them look like banners (we try to avoid
1339 # banner images entirely, but they slip through when the IMG tags didn't
1340 # have WIDTH and HEIGHT specified.)
1342 my $crop_chance = 0.2;
1343 if ($iw > $img_width * 0.4 || $ih > $img_height * 0.4) {
1344 $crop_chance += 0.2;
1346 if ($iw > $img_width * 0.7 || $ih > $img_height * 0.7) {
1347 $crop_chance += 0.2;
1349 if ($min_ratio && ($iw * $min_ratio) > $ih) {
1350 $crop_chance += 0.7;
1353 if ($verbose > 2 && $crop_chance > 0.1) {
1354 print STDERR "$progname: crop chance: $crop_chance\n";
1357 if (rand() < $crop_chance) {
1362 if ($crop_w > $min_width) {
1363 # if it's a banner, select the width linearly.
1364 # otherwise, select a bell.
1365 my $r = (($min_ratio && ($iw * $min_ratio) > $ih)
1368 $crop_w = $min_width + int ($r * ($crop_w - $min_width));
1369 $crop_x = int (rand() * ($ow - $crop_w));
1371 if ($crop_h > $min_height) {
1372 # height always selects as a bell.
1373 $crop_h = $min_height + int (bellrand() * ($crop_h - $min_height));
1374 $crop_y = int (rand() * ($oh - $crop_h));
1378 ($crop_x != 0 || $crop_y != 0 ||
1379 $crop_w != $iw || $crop_h != $ih)) {
1380 print STDERR "$progname: randomly cropping to " .
1381 "${crop_w}x$crop_h \@ $crop_x,$crop_y\n";
1385 # Where the image should logically land -- this might be negative.
1387 my $x = int((rand() * ($img_width + $crop_w/2)) - $crop_w*3/4);
1388 my $y = int((rand() * ($img_height + $crop_h/2)) - $crop_h*3/4);
1390 # if we have chosen to paste the image outside of the rectangle of the
1391 # screen, then we need to crop it.
1395 $x + $crop_w > $img_width ||
1396 $y + $crop_h > $img_height) {
1399 print STDERR "$progname: cropping for effective paste of " .
1400 "${crop_w}x$crop_h \@ $x,$y\n";
1403 if ($x < 0) { $crop_x -= $x; $crop_w += $x; $x = 0; }
1404 if ($y < 0) { $crop_y -= $y; $crop_h += $y; $y = 0; }
1406 if ($x + $crop_w >= $img_width) { $crop_w = $img_width - $x - 1; }
1407 if ($y + $crop_h >= $img_height) { $crop_h = $img_height - $y - 1; }
1410 # If any cropping needs to happen, add pnmcut.
1412 if ($crop_x != 0 || $crop_y != 0 ||
1413 $crop_w != $iw || $crop_h != $ih) {
1416 $cmd .= " | pnmcut $crop_x $crop_y $iw $ih";
1418 print STDERR "$progname: cropping to ${crop_w}x$crop_h \@ " .
1419 "$crop_x,$crop_y\n";
1424 print STDERR "$progname: pasting ${iw}x$ih \@ $x,$y in $image_ppm\n";
1427 $cmd .= " | pnmpaste - $x $y $image_ppm";
1429 $cmd =~ s@^ *\| *@@;
1430 my $rc = nontrapping_system "($cmd) < $image_tmp1 > $image_tmp2";
1434 print STDERR "$progname: failed command: \"$cmd\"\n";
1435 print STDERR "$progname: failed url: \"$img\" (${ow}x$oh)\n";
1440 rename ($image_tmp2, $image_ppm) || return;
1442 my $target = "$image_ppm";
1444 # don't just tack this onto the end of the pipeline -- we don't want it
1445 # to end up in $image_ppm, because we don't want the results to be
1448 if ($post_filter_cmd) {
1449 $target = $image_tmp1;
1450 $rc = nontrapping_system "($post_filter_cmd) < $image_ppm > $target";
1453 print STDERR "$progname: filter failed: " .
1454 "\"$post_filter_cmd\"\n";
1460 if (!$no_output_p) {
1461 my $tsize = (stat($target))[7];
1463 $cmd = $ppm_to_root_window_cmd;
1464 $cmd =~ s/%%PPM%%/$target/;
1466 # xv seems to hate being killed. it tends to forget to clean
1467 # up after itself, and leaves windows around and colors allocated.
1468 # I had this same problem with vidwhacker, and I'm not entirely
1469 # sure what I did to fix it. But, let's try this: launch xv
1470 # in the background, so that killing this process doesn't kill it.
1471 # it will die of its own accord soon enough. So this means we
1472 # start pumping bits to the root window in parallel with starting
1473 # the next network retrieval, which is probably a better thing
1478 $rc = nontrapping_system ($cmd);
1482 print STDERR "$progname: display failed: \"$cmd\"\n";
1487 } elsif ($verbose > 1) {
1488 print STDERR "$progname: $target size is $tsize\n";
1493 print STDOUT "image: ${iw}x${ih} @ $x,$y $base $source\n";
1506 # historical suckage: the environment variable name is lower case.
1507 $http_proxy = $ENV{http_proxy} || $ENV{HTTP_PROXY};
1509 while ($_ = $ARGV[0]) {
1511 if ($_ eq "-display" ||
1517 $ENV{DISPLAY} = shift @ARGV;
1518 } elsif ($_ eq "-root") {
1520 } elsif ($_ eq "-no-output") {
1522 } elsif ($_ eq "-urls-only") {
1525 } elsif ($_ eq "-verbose") {
1527 } elsif (m/^-v+$/) {
1528 $verbose += length($_)-1;
1529 } elsif ($_ eq "-delay") {
1530 $delay = shift @ARGV;
1531 } elsif ($_ eq "-timeout") {
1532 $http_timeout = shift @ARGV;
1533 } elsif ($_ eq "-filter") {
1534 $filter_cmd = shift @ARGV;
1535 } elsif ($_ eq "-filter2") {
1536 $post_filter_cmd = shift @ARGV;
1537 } elsif ($_ eq "-background" || $_ eq "-bg") {
1538 $background = shift @ARGV;
1539 } elsif ($_ eq "-size") {
1541 if (m@^(\d+)x(\d+)$@) {
1545 die "$progname: argument to \"-size\" must be" .
1546 " of the form \"640x400\"\n";
1548 } elsif ($_ eq "-proxy" || $_ eq "-http-proxy") {
1549 $http_proxy = shift @ARGV;
1551 die "$copyright\nusage: $progname [-root]" .
1552 " [-display dpy] [-root] [-verbose] [-timeout secs]\n" .
1553 "\t\t [-delay secs] [-filter cmd] [-filter2 cmd]\n" .
1554 "\t\t [-http-proxy host[:port]]\n";
1558 if ($http_proxy && $http_proxy eq "") {
1559 $http_proxy = undef;
1561 if ($http_proxy && $http_proxy =~ m@^http://([^/]*)/?$@ ) {
1562 # historical suckage: allow "http://host:port" as well as "host:port".
1566 if (!$root_p && !$no_output_p) {
1568 "$progname: the -root argument is mandatory (for now.)\n";
1571 if (!$no_output_p && !$ENV{DISPLAY}) {
1572 die "$progname: \$DISPLAY is not set.\n";