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.40 $ }; $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=";
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.
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;
67 my $image_ppm = ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp") . "/webcollage." . $$;
68 my $image_tmp1 = $image_ppm . "-1";
69 my $image_tmp2 = $image_ppm . "-2";
71 my $img_width; # size of the image being generated.
74 my $http_proxy = undef;
75 my $http_timeout = 30;
78 # if we have xli, use it to write to the root window. else use xv.
79 my $ppm_to_root_window_cmd_1 = "xli -quiet -onroot -center" .
80 " -border black %%PPM%%";
81 my $ppm_to_root_window_cmd_2 = "xv -root -rmode 5 -viewonly" .
82 " +noresetroot %%PPM%% -quit";
84 my $ppm_to_root_window_cmd = undef; # initialized by x_output()
86 my $filter_cmd = undef;
87 my $post_filter_cmd = undef;
88 my $background = undef;
93 my $wordlist = "/usr/dict/words";
96 $wordlist = "/usr/share/lib/dict/words"; # irix
98 die "$wordlist doesn't exist!\n" unless (-r $wordlist);
108 my @tripwire_words = ("aberrate", "abode", "amorphous", "antioch",
109 "arrhenius", "arteriole", "blanket", "brainchild",
110 "burdensome", "carnival", "cherub", "chord", "clever",
111 "dedicate", "dilogarithm", "dolan", "dryden",
117 ##############################################################################
121 ##############################################################################
123 # returns three values: the HTTP response line; the document headers;
124 # and the document body.
127 my ( $url, $referer, $timeout ) = @_;
129 if (!defined($timeout)) { $timeout = $http_timeout; }
130 if ($timeout <= 0) { return (); }
131 if ($timeout > $http_timeout) { $timeout = $http_timeout; }
133 if ( $verbose > 3 ) {
134 print STDERR "$progname: get_document_1 $url " .
135 ($referer ? $referer : "") . "\n";
138 my($url_proto, $dummy, $serverstring, $path) = split(/\//, $url, 4);
139 if (! ($url_proto && $url_proto =~ m/^http:$/i)) {
140 if ($verbose) { print STDERR "$progname: not an HTTP URL: $url\n"; }
144 $path = "" unless $path;
146 my($them,$port) = split(/:/, $serverstring);
147 $port = 80 unless $port;
152 $serverstring = $http_proxy if $http_proxy;
153 ($them2,$port2) = split(/:/, $serverstring);
154 $port2 = 80 unless $port2;
157 my ($remote, $iaddr, $paddr, $proto, $line);
159 if ($port2 =~ /\D/) { $port2 = getservbyname($port2, 'tcp') }
160 return unless $port2;
161 $iaddr = inet_aton($remote) || return;
162 $paddr = sockaddr_in($port2, $iaddr);
167 local $SIG{ALRM} = sub {
169 print STDERR "$progname: timed out ($timeout) for $url\n";
175 $proto = getprotobyname('tcp');
176 if (!socket(S, PF_INET, SOCK_STREAM, $proto)) {
177 print STDERR "$progname: socket: $!\n" if ($verbose);
180 if (!connect(S, $paddr)) {
181 print STDERR "$progname: connect($serverstring): $!\n"
186 select(S); $| = 1; select(STDOUT);
189 if ($remote =~ m/\baltavista\.com$/i) {
190 # kludge to tell the various altavista sites to be uncensored.
191 $cookie = "AV_ALL=1";
194 print S ("GET " . ($http_proxy ? $url : "/$path") . " HTTP/1.0\n" .
196 "User-Agent: $progname/$version\n" .
197 ($referer ? "Referer: $referer\n" : "") .
198 ($cookie ? "Cookie: $cookie\n" : "") .
214 if ( $verbose > 3 ) {
215 print STDERR "$progname: ==> $http\n";
218 return ( $http, $head, $body );
220 die if ($@ && $@ ne "alarm\n"); # propagate errors
232 # returns two values: the document headers; and the document body.
233 # if the given URL did a redirect, returns the redirected-to document.
236 my ( $url, $referer, $timeout ) = @_;
241 my $max_loop_count = 4;
244 if (defined($timeout) && $timeout <= 0) { return (); }
246 my ( $http, $head, $body ) = get_document_1 ($url, $referer, $timeout);
248 if (defined ($timeout)) {
250 my $elapsed = $now - $start;
251 $timeout -= $elapsed;
255 return () if ( ! $body );
257 if ( $http =~ m@HTTP/[0-9.]+ 30[23]@ ) {
259 my ( $location ) = m@^location:[ \t]*(.*)$@im;
261 $location =~ s/[\r\n]$//;
263 if ( $verbose > 3 ) {
264 print STDERR "$progname: redirect from " .
265 "$url to $location\n";
271 $referer =~ m@^(http://[^/]+)@i;
273 } elsif (! ($url =~ m@^[a-z]+:@i)) {
275 s@[^/]+$@@g if m@^http://[^/]+/@i;
276 $_ .= "/" if m@^http://[^/]+$@i;
281 return ( $url, $body );
284 if ($loop_count++ > $max_loop_count) {
285 if ( $verbose > 1 ) {
286 print STDERR "$progname: too many redirects " .
287 "($max_loop_count) from $orig_url\n";
292 } elsif ( $http =~ m@HTTP/[0-9.]+ [4-9][0-9][0-9]@ ) {
293 # http errors -- return nothing.
298 return ( $url, $body );
305 # given a URL and the body text at that URL, selects and returns a random
306 # image from it. returns () if no suitable images found.
308 sub pick_image_from_body {
309 my ( $url, $body ) = @_;
314 # if there's at least one slash after the host, take off the last
316 if ( m@^http://[^/]+/@io ) {
317 $base =~ s@[^/]+$@@go;
320 # if there are no slashes after the host at all, put one on the end.
321 if ( m@^http://[^/]+$@io ) {
325 if ( $verbose > 3 ) {
326 print STDERR "$progname: base is $base\n";
332 # strip out newlines, compress whitespace
339 # There are certain web sites that list huge numbers of dictionary
340 # words in their bodies or in their <META NAME=KEYWORDS> tags (surprise!
341 # Porn sites tend not to be reputable!)
343 # I do not want webcollage to filter on content: I want it to select
344 # randomly from the set of images on the web. All the logic here for
345 # rejecting some images is really a set of heuristics for rejecting
346 # images that are not really images: for rejecting *text* that is in
347 # GIF/JPEG form. I don't want text, I want pictures, and I want the
348 # content of the pictures to be randomly selected from among all the
351 # So, filtering out "dirty" pictures by looking for "dirty" keywords
352 # would be wrong: dirty pictures exist, like it or not, so webcollage
353 # should be able to select them.
355 # However, picking a random URL is a hard thing to do. The mechanism I'm
356 # using is to search for a selection of random words. This is not
357 # perfect, but works ok most of the time. The way it breaks down is when
358 # some URLs get precedence because their pages list *every word* as
359 # related -- those URLs come up more often than others.
361 # So, after we've retrieved a URL, if it has too many keywords, reject
362 # it. We reject it not on the basis of what those keywords are, but on
363 # the basis that by having so many, the page has gotten an unfair
364 # advantage against our randomizer.
367 foreach my $trip (@tripwire_words) {
368 $trip_count++ if m/$trip/i;
370 if ($trip_count >= $#tripwire_words - 2) {
372 print STDERR "$progname: there is probably a dictionary in" .
373 " \"$url\": rejecting.\n";
375 $rejected_urls{$url} = -1;
383 foreach (split(/ *</)) {
386 # Likewise, reject any web pages that have a KEYWORDS meta tag
389 if (m/name ?= ?\"?keywords\"?/i &&
390 m/content ?= ?\"([^\"]+)\"/) {
394 print STDERR "$progname: keywords of" .
395 " length $L in $url: rejecting.\n";
397 $rejected_urls{$url} = $L;
399 } elsif ( $verbose > 2 ) {
400 print STDERR "$progname: keywords of length $L" .
405 } elsif ( m/^(img|a) .*(src|href) ?= ?\"? ?(.*?)[ >\"]/io ) {
407 my $was_inline = ( "$1" eq "a" || "$1" eq "A" );
409 my ( $width ) = m/width ?=[ \"]*(\d+)/oi;
410 my ( $height ) = m/height ?=[ \"]*(\d+)/oi;
415 ( $site = $base ) =~ s@^(http://[^/]*).*@$1@gio;
417 } elsif ( ! m@^[^/:?]+:@ ) {
420 while (s@/\.\./@/@g) {
425 if ( ! m@^http://@io ) {
430 if ( ! m@[.](gif|jpg|jpeg|pjpg|pjpeg)$@io ) {
434 # skip really short or really narrow images
435 if ( $width && $width < $min_width) {
436 if ( $verbose > 2 ) {
437 if (!$height) { $height = "?"; }
438 print STDERR "$progname: skip narrow image " .
439 "$_ (${width}x$height)\n";
444 if ( $height && $height < $min_height) {
445 if ( $verbose > 2 ) {
446 if (!$width) { $width = "?"; }
447 print STDERR "$progname: skip short image " .
448 "$_ (${width}x$height)\n";
453 # skip images with ratios that make them look like banners.
454 if ( $min_ratio && $width && $height &&
455 ($width * $min_ratio ) > $height ) {
456 if ( $verbose > 2 ) {
457 if (!$height) { $height = "?"; }
458 print STDERR "$progname: skip bad ratio " .
459 "$_ (${width}x$height)\n";
466 if ( $unique_urls{$url} ) {
467 if ( $verbose > 2 ) {
468 print STDERR "$progname: skip duplicate image $_\n";
473 if ( $verbose > 2 ) {
474 print STDERR "$progname: got $url" .
475 ($width && $height ? " (${width}x${height})" : "") .
476 ($was_inline ? " (inline)" : "") . "\n";
479 $urls[++$#urls] = $url;
480 $unique_urls{$url}++;
482 # jpegs are preferable to gifs.
484 if ( ! m@[.]gif$@io ) {
485 $urls[++$#urls] = $url;
488 # pointers to images are preferable to inlined images.
489 if ( ! $was_inline ) {
490 $urls[++$#urls] = $url;
491 $urls[++$#urls] = $url;
497 if ( $verbose > 2 ) {
498 print STDERR "$progname: no images on $base\n";
503 return () if ( $#urls < 1 );
505 # pick a random element of the table
506 my $i = ((rand() * 99999) % $#urls);
509 if ( $verbose > 2 ) {
510 print STDERR "$progname: picked $url\n";
517 # Using the URL-randomizer, picks a random image on a random page, and
518 # returns two URLs: the page containing the image, and the image.
519 # Returns () if nothing found this time.
521 sub pick_from_url_randomizer {
522 my ( $timeout ) = @_;
524 if ( $verbose > 3 ) {
525 print STDERR "\n\n$progname: picking from $random_redirector...\n\n";
528 my ( $base, $body ) = get_document ($random_redirector, undef, $timeout);
530 return if (!$base || !$body);
531 my $img = pick_image_from_body ($base, $body);
534 return ($base, $img, "yahoo");
544 if (open (IN, "<$wordlist")) {
545 my $size = (stat(IN))[7];
546 my $pos = rand $size;
547 if (seek (IN, $pos, 0)) {
548 $word = <IN>; # toss partial line
549 $word = <IN>; # keep next line
554 return 0 if (!$word);
556 $word =~ s/^[ \t\n\r]+//;
557 $word =~ s/[ \t\n\r]+$//;
562 $word =~ s/ally$/al/;
563 $word =~ s/izes$/ize/;
564 $word =~ tr/A-Z/a-z/;
571 # Using the image-randomizer, picks a random image on a random page, and
572 # returns two URLs: the page containing the image, and the image.
573 # Returns () if nothing found this time.
575 sub pick_from_image_randomizer {
576 my ( $timeout, $which ) = @_;
578 my $words = random_word;
579 $words .= "%20" . random_word;
580 $words .= "%20" . random_word;
581 $words .= "%20" . random_word;
582 $words .= "%20" . random_word;
584 my $search_url = ($which == 0 ? $image_randomizer_1 :
585 $which == 1 ? $image_randomizer_2 :
586 $image_randomizer_3) .
589 # Pick a random search-result page instead of always taking the first.
590 # This assumes there are at least 10 pages...
592 $search_url .= "&pgno=" . (int(rand(9)) + 1);
593 } elsif ($which == 2) {
594 $search_url .= "&stq=" . (10 * (int(rand(9)) + 1));
597 if ( $verbose > 3 ) {
598 $_ = $words; s/%20/ /g; print STDERR "$progname: search words: $_\n";
601 if ( $verbose > 3 ) {
602 print STDERR "\n\n$progname: picking from $search_url\n";
606 my ( $base, $body ) = get_document ($search_url, undef, $timeout);
607 if (defined ($timeout)) {
608 $timeout -= (time - $start);
609 return () if ($timeout <= 0);
612 return () if (! $body);
618 my $search_count = "?";
620 $body =~ m@found (approximately |about )?(<B>)?(\d+)(</B>)? image@) {
622 } elsif ($which == 1 && $body =~ m@<NOBR>((\d{1,3})(,\d{3})*) @i) {
624 } elsif ($which == 2 && $body =~ m@found ((\d{1,3})(,\d{3})*|\d+) Web p@) {
627 1 while ($search_count =~ s/^(\d+)(\d{3})/$1,$2/);
629 my $length = length($body);
634 s/Result [Pp]ages:.*$//s; # trim off page footer
635 s/^.*?IMAGE RESULTS//s; # trim off page header
640 foreach (split(/\n/)) {
642 my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
644 if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; } # quoted string
645 elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; } # or token
648 # Kludge to decode HotBot pages
649 next unless ($u =~ m@/director\.asp\?target=(http%3A[^&>]+)@);
653 next unless ($u =~ m@^http://@i); # skip non-http and relative urls.
655 next if ($u =~ m@[/.]altavista\.com@i); # skip altavista builtins
656 next if ($u =~ m@[/.]av\.com@i);
657 next if ($u =~ m@[/.]virage\.com@i);
658 next if ($u =~ m@[/.]photoloft\.com@i);
659 next if ($u =~ m@[/.]shopping\.com@i);
660 next if ($u =~ m@[/.]thetrip\.com@i);
661 next if ($u =~ m@[/.]cmgi\.com@i);
662 next if ($u =~ m@[/.]intelihealth\.com@i);
663 next if ($u =~ m@[/.]wildweb\.com@i);
664 next if ($u =~ m@[/.]digital\.com@i);
665 next if ($u =~ m@[/.]doubleclick\.net@i);
667 if ($which == 0 && $u =~ m@[/.]corbis\.com@) {
669 if ( $verbose > 3 ) {
670 print STDERR "$progname: skipping corbis URL: $u\n";
674 } elsif ( $rejected_urls{$u} ) {
675 if ( $verbose > 3 ) {
676 my $L = $rejected_urls{$u};
677 print STDERR "$progname: pre-rejecting sub-page: $u\n";
681 } elsif ( $verbose > 3 ) {
682 print STDERR "$progname: sub-page: $u\n";
685 $subpages[++$#subpages] = $u;
688 if ( $#subpages < 0 ) {
689 if (!$skipped && $verbose > 1) {
690 print STDERR "$progname: found nothing on $base " .
691 "($length bytes, $href_count links).\n";
696 # pick a random element of the table
697 my $i = ((rand() * 99999) % ($#subpages + 1));
698 my $subpage = $subpages[$i];
700 if ( $verbose > 3 ) {
701 print STDERR "$progname: picked page $subpage\n";
706 my ( $base2, $body2 ) = get_document ($subpage, $base, $timeout);
708 return () if (!$base2 || !$body2);
710 my $img = pick_image_from_body ($base2, $body2);
713 return ($base2, $img,
714 ($which == 0 ? "imagevista" :
715 $which == 1 ? "hotbot" : "altavista") .
723 # Using the photo site, generate a random URL that will hopefully point
724 # to an image. Returns two URLs, both of which are the URL of the image.
725 # Returns () if nothing found this time.
727 #sub pick_from_photo_randomizer {
728 # my ( $timeout ) = @_;
729 # my $n = ($photo_randomizer_lo +
730 # int(rand() * ($photo_randomizer_hi - $photo_randomizer_lo)));
731 # my $url = $photo_randomizer . $n;
732 # return ( $url, $url, "photopoint" );
736 # Picks a random image on a random page, and returns two URLs:
737 # the page containing the image, and the image.
738 # Returns () if nothing found this time.
739 # Uses the url-randomizer 1 time in 5, else the image randomizer.
753 my ( $timeout ) = @_;
755 my $r = int(rand(100));
756 my ($base, $img, $source, $total, $count);
759 ($base, $img, $source) = pick_from_url_randomizer ($timeout);
761 $count = ++$count_0 if $img;
764 ($base, $img, $source) = pick_from_image_randomizer ($timeout, 0);
766 $count = ++$count_1 if $img;
768 # } elsif ($r < 70) {
769 # ($base, $img, $source) = pick_from_photo_randomizer ($timeout);
770 # $total = ++$total_4;
771 # $count = ++$count_4 if $img;
773 # } elsif ($r < 80) {
774 # # HotBot sucks: 98% of the time, it says "no pages match your
775 # # search", and then if I load the URL again by hand, it works.
776 # # I don't understand what's going wrong here, but we're not getting
777 # # any good data back from them, so forget it for now.
779 # ($base, $img, $source) = pick_from_image_randomizer ($timeout, 1);
780 # $total = ++$total_2;
781 # $count = ++$count_2 if $img;
784 ($base, $img, $source) = pick_from_image_randomizer ($timeout, 2);
786 $count = ++$count_3 if $img;
789 if ($source && $total > 0) {
790 $source .= " " . int(($count / $total) * 100) . "%";
792 return ($base, $img, $source);
801 s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
806 # Given the raw body of a GIF document, returns the dimensions of the image.
810 my $type = substr($body, 0, 6);
812 return () unless ($type =~ /GIF8[7,9]a/);
813 $s = substr ($body, 6, 10);
814 my ($a,$b,$c,$d) = unpack ("C"x4, $s);
815 return (($b<<8|$a), ($d<<8|$c));
818 # Given the raw body of a JPEG document, returns the dimensions of the image.
823 my $L = length($body);
825 my $c1 = substr($body, $i, 1); $i++;
826 my $c2 = substr($body, $i, 1); $i++;
827 return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
830 while (ord($ch) != 0xDA && $i < $L) {
831 # Find next marker, beginning with 0xFF.
832 while (ord($ch) != 0xFF) {
833 $ch = substr($body, $i, 1); $i++;
835 # markers can be padded with any number of 0xFF.
836 while (ord($ch) == 0xFF) {
837 $ch = substr($body, $i, 1); $i++;
840 # $ch contains the value of the marker.
841 my $marker = ord($ch);
843 if (($marker >= 0xC0) &&
846 ($marker != 0xCC)) { # it's a SOFn marker
848 my $s = substr($body, $i, 4); $i += 4;
849 my ($a,$b,$c,$d) = unpack("C"x4, $s);
850 return (($c<<8|$d), ($a<<8|$b));
853 # We must skip variables, since FFs in variable names aren't
854 # valid JPEG markers.
855 my $s = substr($body, $i, 2); $i += 2;
856 my ($c1, $c2) = unpack ("C"x2, $s);
857 my $length = ($c1 << 8) | $c2;
858 return () if ($length < 2);
865 # Given the raw body of a GIF or JPEG document, returns the dimensions of
870 my ($w, $h) = gif_size ($body);
871 if ($w && $h) { return ($w, $h); }
872 return jpeg_size ($body);
876 # returns the full path of the named program, or undef.
880 foreach (split (/:/, $ENV{PATH})) {
889 # Like rand(), but chooses numbers with a bell curve distribution.
892 $_ = 1.0 unless defined($_);
894 return (rand($_) + rand($_) + rand($_));
898 ##############################################################################
900 # Generating a list of urls only
902 ##############################################################################
904 sub url_only_output {
906 my ($base, $img) = pick_image;
910 print "$img $base\n";
915 ##############################################################################
917 # Running as an xscreensaver module
919 ##############################################################################
923 if ($verbose > 0) { print STDERR "$progname: caught signal $sig.\n"; }
924 unlink $image_ppm, $image_tmp1, $image_tmp2;
929 # Like system, but prints status about exit codes, and kills this process
930 # with whatever signal killed the sub-process, if any.
932 sub nontrapping_system {
937 s/\"[^\"]+\"/\"...\"/g;
938 print STDERR "$progname: executing \"$_\"\n";
945 print STDERR "$progname: subproc exited normally.\n";
947 } elsif (($rc & 0xff) == 0) {
950 print "$progname: subproc exited with status $rc.\n";
955 print "$progname: subproc dumped core.\n";
960 print "$progname: subproc died with signal $rc.\n";
962 # die that way ourselves.
970 # Given the URL of a GIF or JPEG image, and the body of that image, writes a
971 # PPM to the given output file. Returns the width/height of the image if
975 my ($url, $body, $output) = @_;
976 my ($cmd, $cmd2, $w, $h);
978 if ((@_ = gif_size ($body))) {
981 } elsif ((@_ = jpeg_size ($body))) {
988 $cmd2 = "exec $cmd"; # yes, this really is necessary. if we don't
989 # do this, the process doesn't die properly.
991 $cmd2 .= " 2>/dev/null";
994 # There exist corrupted GIF and JPEG files that can make giftopnm and
995 # djpeg lose their minds and go into a loop. So this gives those programs
996 # a small timeout -- if they don't complete in time, kill them.
1002 local $SIG{ALRM} = sub {
1004 print STDERR "$progname: timed out ($cvt_timeout) for " .
1005 "$cmd on \"$url\" in pid $pid\n";
1007 kill ('TERM', $pid) if ($pid);
1011 if (($pid = open(PIPE, "| $cmd2 > $output"))) {
1017 if ($verbose > 3) { print STDERR "$progname: awaiting $pid\n"; }
1019 if ($verbose > 3) { print STDERR "$progname: $pid completed\n"; }
1022 my $size = (stat($output))[7];
1025 print STDERR "$progname: $cmd on ${w}x$h \"$url\" failed" .
1032 print STDERR "$progname: created ${w}x$h $output ($cmd)\n";
1036 print STDERR "$progname: $cmd failed: $!\n";
1040 die if ($@ && $@ ne "alarm\n"); # propagate errors
1053 my $win_cmd_1 = $ppm_to_root_window_cmd_1;
1054 my $win_cmd_2 = $ppm_to_root_window_cmd_2;
1055 $win_cmd_1 =~ s/^([^ \t\r\n]+).*$/$1/;
1056 $win_cmd_2 =~ s/^([^ \t\r\n]+).*$/$1/;
1058 # make sure the various programs we execute exist, right up front.
1059 foreach ("ppmmake", "giftopnm", "djpeg", "pnmpaste", "pnmscale",
1061 which ($_) || die "$progname: $_ not found on \$PATH.\n";
1064 if (which($win_cmd_1)) {
1065 $ppm_to_root_window_cmd = $ppm_to_root_window_cmd_1;
1066 } elsif (which($win_cmd_2)) {
1067 $ppm_to_root_window_cmd = $ppm_to_root_window_cmd_2;
1069 die "$progname: neither $win_cmd_1 nor $win_cmd_2 found on \$PATH.\n";
1072 $SIG{HUP} = \&x_cleanup;
1073 $SIG{INT} = \&x_cleanup;
1074 $SIG{QUIT} = \&x_cleanup;
1075 $SIG{ABRT} = \&x_cleanup;
1076 $SIG{KILL} = \&x_cleanup;
1077 $SIG{TERM} = \&x_cleanup;
1079 # Need this so that if giftopnm dies, we don't die.
1080 $SIG{PIPE} = 'IGNORE';
1082 if (!$img_width || !$img_height) {
1084 which ($_) || die "$progname: $_ not found on \$PATH.\n";
1086 ($img_width, $img_height) = m/dimensions: *(\d+)x(\d+) /;
1087 if (!defined($img_height)) {
1088 die "$progname: xdpyinfo failed.\n";
1092 my $bgcolor = "#000000";
1093 my $bgimage = undef;
1096 if ($background =~ m/^\#[0-9a-f]+$/i) {
1097 $bgcolor = $background;
1098 } elsif (-r $background) {
1099 $bgimage = $background;
1101 } elsif (! $background =~ m@^[-a-z0-9 ]+$@i) {
1102 print STDERR "$progname: not a color or readable file: " .
1106 # default to assuming it's a color
1107 $bgcolor = $background;
1111 # Create the sold-colored base image.
1113 $_ = "ppmmake '$bgcolor' $img_width $img_height";
1115 print STDERR "$progname: creating base image: $_\n";
1117 nontrapping_system "$_ > $image_ppm";
1119 # Paste the default background image in the middle of it.
1126 open(IMG, "<$bgimage") || die ("couldn't open $bgimage: $!\n");
1128 while (<IMG>) { $body .= $_; }
1130 if ((@_ = gif_size ($body))) {
1132 $cmd = "giftopnm |";
1133 } elsif ((@_ = jpeg_size ($body))) {
1136 } elsif ($body =~ "^P\d\n(\d+) (\d+)\n") {
1141 die "$progname: $bgimage is not a GIF, JPEG, or PPM.\n";
1144 my $x = int (($img_width - $iw) / 2);
1145 my $y = int (($img_height - $ih) / 2);
1147 print STDERR "$progname: pasting $bgimage (${iw}x$ih) into base ".
1151 $cmd .= "pnmpaste - $x $y $image_ppm > $image_tmp1";
1152 open (IMG, "| $cmd") || die ("running $cmd: $!\n");
1156 print STDERR "$progname: subproc exited normally.\n";
1158 rename ($image_tmp1, $image_ppm) ||
1159 die ("renaming $image_tmp1 to $image_ppm: $!\n");
1163 my ($base, $img, $source) = pick_image();
1165 my ($headers, $body) = get_document ($img, $base);
1167 handle_image ($base, $img, $body, $source);
1170 unlink $image_tmp1, $image_tmp2;
1176 my ($base, $img, $body, $source) = @_;
1179 print STDERR "$progname: got $img (" . length($body) . ")\n";
1182 my ($iw, $ih) = image_to_pnm ($img, $body, $image_tmp1);
1183 return 0 unless ($iw && $ih);
1185 my $ow = $iw; # used only for error messages
1188 # don't just tack this onto the front of the pipeline -- we want it to
1189 # be able to change the size of the input image.
1193 print STDERR "$progname: running $filter_cmd\n";
1196 my $rc = nontrapping_system "($filter_cmd) < $image_tmp1 >$image_tmp2";
1199 print STDERR "$progname: failed command: \"$filter_cmd\"\n";
1200 print STDERR "$progname: failed url: \"$img\" (${ow}x$oh)\n";
1204 rename ($image_tmp2, $image_tmp1);
1206 # re-get the width/height in case the filter resized it.
1208 open(IMG, "<$image_tmp1") || return 0;
1211 ($iw, $ih) = m/^(\d+) (\d+)$/;
1213 return 0 unless ($iw && $ih);
1216 my $target_w = $img_width;
1217 my $target_h = $img_height;
1222 # Usually scale the image to fit on the screen -- but sometimes scale it
1223 # to fit on half or a quarter of the screen. Note that we don't merely
1224 # scale it to fit, we instead cut it in half until it fits -- that should
1225 # give a wider distribution of sizes.
1227 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
1228 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
1230 if ($iw > $target_w || $ih > $target_h) {
1231 while ($iw > $target_w ||
1236 if ($iw <= 10 || $ih <= 10) {
1238 print STDERR "$progname: scaling to ${iw}x$ih would " .
1239 "have been bogus.\n";
1245 print STDERR "$progname: scaling to ${iw}x$ih\n";
1248 $cmd .= " | pnmscale -xsize $iw -ysize $ih";
1252 my $src = $image_tmp1;
1254 my $crop_x = 0; # the sub-rectangle of the image
1255 my $crop_y = 0; # that we will actually paste.
1259 # The chance that we will randomly crop out a section of an image starts
1260 # out fairly low, but goes up for images that are very large, or images
1261 # that have ratios that make them look like banners (we try to avoid
1262 # banner images entirely, but they slip through when the IMG tags didn't
1263 # have WIDTH and HEIGHT specified.)
1265 my $crop_chance = 0.2;
1266 if ($iw > $img_width * 0.4 || $ih > $img_height * 0.4) {
1267 $crop_chance += 0.2;
1269 if ($iw > $img_width * 0.7 || $ih > $img_height * 0.7) {
1270 $crop_chance += 0.2;
1272 if ($min_ratio && ($iw * $min_ratio) > $ih) {
1273 $crop_chance += 0.7;
1276 if ($verbose > 2 && $crop_chance > 0.1) {
1277 print STDERR "$progname: crop chance: $crop_chance\n";
1280 if (rand() < $crop_chance) {
1285 if ($crop_w > $min_width) {
1286 # if it's a banner, select the width linearly.
1287 # otherwise, select a bell.
1288 my $r = (($min_ratio && ($iw * $min_ratio) > $ih)
1291 $crop_w = $min_width + int ($r * ($crop_w - $min_width));
1292 $crop_x = int (rand() * ($ow - $crop_w));
1294 if ($crop_h > $min_height) {
1295 # height always selects as a bell.
1296 $crop_h = $min_height + int (bellrand() * ($crop_h - $min_height));
1297 $crop_y = int (rand() * ($oh - $crop_h));
1301 ($crop_x != 0 || $crop_y != 0 ||
1302 $crop_w != $iw || $crop_h != $ih)) {
1303 print STDERR "$progname: randomly cropping to " .
1304 "${crop_w}x$crop_h \@ $crop_x,$crop_y\n";
1308 # Where the image should logically land -- this might be negative.
1310 my $x = int((rand() * ($img_width + $crop_w/2)) - $crop_w*3/4);
1311 my $y = int((rand() * ($img_height + $crop_h/2)) - $crop_h*3/4);
1313 # if we have chosen to paste the image outside of the rectangle of the
1314 # screen, then we need to crop it.
1318 $x + $crop_w > $img_width ||
1319 $y + $crop_h > $img_height) {
1322 print STDERR "$progname: cropping for effective paste of " .
1323 "${crop_w}x$crop_h \@ $x,$y\n";
1326 if ($x < 0) { $crop_x -= $x; $crop_w += $x; $x = 0; }
1327 if ($y < 0) { $crop_y -= $y; $crop_h += $y; $y = 0; }
1329 if ($x + $crop_w >= $img_width) { $crop_w = $img_width - $x - 1; }
1330 if ($y + $crop_h >= $img_height) { $crop_h = $img_height - $y - 1; }
1333 # If any cropping needs to happen, add pnmcut.
1335 if ($crop_x != 0 || $crop_y != 0 ||
1336 $crop_w != $iw || $crop_h != $ih) {
1339 $cmd .= " | pnmcut $crop_x $crop_y $iw $ih";
1341 print STDERR "$progname: cropping to ${crop_w}x$crop_h \@ " .
1342 "$crop_x,$crop_y\n";
1347 print STDERR "$progname: pasting ${iw}x$ih \@ $x,$y in $image_ppm\n";
1350 $cmd .= " | pnmpaste - $x $y $image_ppm";
1352 $cmd =~ s@^ *\| *@@;
1353 my $rc = nontrapping_system "($cmd) < $image_tmp1 > $image_tmp2";
1357 print STDERR "$progname: failed command: \"$cmd\"\n";
1358 print STDERR "$progname: failed url: \"$img\" (${ow}x$oh)\n";
1363 rename ($image_tmp2, $image_ppm) || return;
1365 my $target = "$image_ppm";
1367 # don't just tack this onto the end of the pipeline -- we don't want it
1368 # to end up in $image_ppm, because we don't want the results to be
1371 if ($post_filter_cmd) {
1372 $target = $image_tmp1;
1373 $rc = nontrapping_system "($post_filter_cmd) < $image_ppm > $target";
1376 print STDERR "$progname: filter failed: " .
1377 "\"$post_filter_cmd\"\n";
1383 if (!$no_output_p) {
1384 my $tsize = (stat($target))[7];
1386 $cmd = $ppm_to_root_window_cmd;
1387 $cmd =~ s/%%PPM%%/$target/;
1389 # xv seems to hate being killed. it tends to forget to clean
1390 # up after itself, and leaves windows around and colors allocated.
1391 # I had this same problem with vidwhacker, and I'm not entirely
1392 # sure what I did to fix it. But, let's try this: launch xv
1393 # in the background, so that killing this process doesn't kill it.
1394 # it will die of its own accord soon enough. So this means we
1395 # start pumping bits to the root window in parallel with starting
1396 # the next network retrieval, which is probably a better thing
1401 $rc = nontrapping_system ($cmd);
1405 print STDERR "$progname: display failed: \"$cmd\"\n";
1410 } elsif ($verbose > 1) {
1411 print STDERR "$progname: $target size is $tsize\n";
1416 print STDOUT "image: ${iw}x${ih} @ $x,$y $base $source\n";
1429 # historical suckage: the environment variable name is lower case.
1430 $http_proxy = $ENV{http_proxy} || $ENV{HTTP_PROXY};
1432 while ($_ = $ARGV[0]) {
1434 if ($_ eq "-display" ||
1440 $ENV{DISPLAY} = shift @ARGV;
1441 } elsif ($_ eq "-root") {
1443 } elsif ($_ eq "-no-output") {
1445 } elsif ($_ eq "-urls-only") {
1448 } elsif ($_ eq "-verbose") {
1450 } elsif (m/^-v+$/) {
1451 $verbose += length($_)-1;
1452 } elsif ($_ eq "-delay") {
1453 $delay = shift @ARGV;
1454 } elsif ($_ eq "-timeout") {
1455 $http_timeout = shift @ARGV;
1456 } elsif ($_ eq "-filter") {
1457 $filter_cmd = shift @ARGV;
1458 } elsif ($_ eq "-filter2") {
1459 $post_filter_cmd = shift @ARGV;
1460 } elsif ($_ eq "-background" || $_ eq "-bg") {
1461 $background = shift @ARGV;
1462 } elsif ($_ eq "-size") {
1464 if (m@^(\d+)x(\d+)$@) {
1468 die "$progname: argument to \"-size\" must be" .
1469 " of the form \"640x400\"\n";
1471 } elsif ($_ eq "-proxy" || $_ eq "-http-proxy") {
1472 $http_proxy = shift @ARGV;
1474 die "$copyright\nusage: $progname [-root]" .
1475 " [-display dpy] [-root] [-verbose] [-timeout secs]\n" .
1476 "\t\t [-delay secs] [-filter cmd] [-filter2 cmd]\n" .
1477 "\t\t [-http-proxy host[:port]]\n";
1481 if ($http_proxy && $http_proxy eq "") {
1482 $http_proxy = undef;
1484 if ($http_proxy && $http_proxy =~ m@^http://([^/]*)/?$@ ) {
1485 # historical suckage: allow "http://host:port" as well as "host:port".
1489 if (!$root_p && !$no_output_p) {
1491 "$progname: the -root argument is manditory (for now.)\n";
1494 if (!$no_output_p && !$ENV{DISPLAY}) {
1495 die "$progname: \$DISPLAY is not set.\n";