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.32 $ }; $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://image.altavista.com/cgi-bin/avncgi" .
44 "&ophoto=1&oart=1&ocolor=1&obw=1" .
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 my $image_ppm = ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp") . "/webcollage." . $$;
61 my $image_tmp1 = $image_ppm . "-1";
62 my $image_tmp2 = $image_ppm . "-2";
64 my $img_width; # size of the image being generated.
67 my $http_proxy = undef;
68 my $http_timeout = 30;
70 my $ppm_to_root_window_cmd = "xv -root -rmode 5 -viewonly" .
71 " +noresetroot %%PPM%% -quit";
72 my $filter_cmd = undef;
73 my $post_filter_cmd = undef;
74 my $background = undef;
79 my $wordlist = "/usr/dict/words";
82 $wordlist = "/usr/share/lib/dict/words"; # irix
84 die "$wordlist doesn't exist!\n" unless (-r $wordlist);
94 my @tripwire_words = ("aberrate", "abode", "amorphous", "antioch",
95 "arrhenius", "arteriole", "blanket", "brainchild",
96 "burdensome", "carnival", "cherub", "chord", "clever",
97 "dedicate", "dilogarithm", "dolan", "dryden",
103 ##############################################################################
107 ##############################################################################
109 # returns three values: the HTTP response line; the document headers;
110 # and the document body.
113 my ( $url, $referer, $timeout ) = @_;
115 if (!defined($timeout)) { $timeout = $http_timeout; }
116 if ($timeout <= 0) { return (); }
117 if ($timeout > $http_timeout) { $timeout = $http_timeout; }
119 if ( $verbose > 3 ) {
120 print STDERR "$progname: get_document_1 $url " .
121 ($referer ? $referer : "") . "\n";
124 my($url_proto, $dummy, $serverstring, $path) = split(/\//, $url, 4);
125 if (! ($url_proto && $url_proto =~ m/^http:$/i)) {
126 if ($verbose) { print STDERR "$progname: not an HTTP URL: $url\n"; }
130 $path = "" unless $path;
132 my($them,$port) = split(/:/, $serverstring);
133 $port = 80 unless $port;
138 $serverstring = $http_proxy if $http_proxy;
139 ($them2,$port2) = split(/:/, $serverstring);
140 $port2 = 80 unless $port2;
143 my ($remote, $iaddr, $paddr, $proto, $line);
145 if ($port2 =~ /\D/) { $port2 = getservbyname($port2, 'tcp') }
146 return unless $port2;
147 $iaddr = inet_aton($remote) || return;
148 $paddr = sockaddr_in($port2, $iaddr);
153 local $SIG{ALRM} = sub {
155 print STDERR "$progname: timed out ($timeout) for $url\n";
161 $proto = getprotobyname('tcp');
162 if (!socket(S, PF_INET, SOCK_STREAM, $proto)) {
163 print STDERR "$progname: socket: $!\n" if ($verbose);
166 if (!connect(S, $paddr)) {
167 print STDERR "$progname: connect($serverstring): $!\n"
172 select(S); $| = 1; select(STDOUT);
175 if ($remote =~ m/\baltavista\.com$/i) {
176 # kludge to tell the various altavista sites to be uncensored.
177 $cookie = "AV_ALL=1";
180 print S ("GET " . ($http_proxy ? $url : "/$path") . " HTTP/1.0\n" .
182 "User-Agent: $progname/$version\n" .
183 ($referer ? "Referer: $referer\n" : "") .
184 ($cookie ? "Cookie: $cookie\n" : "") .
200 if ( $verbose > 3 ) {
201 print STDERR "$progname: ==> $http\n";
204 return ( $http, $head, $body );
206 die if ($@ && $@ ne "alarm\n"); # propagate errors
218 # returns two values: the document headers; and the document body.
219 # if the given URL did a redirect, returns the redirected-to document.
222 my ( $url, $referer, $timeout ) = @_;
227 my $max_loop_count = 4;
230 if (defined($timeout) && $timeout <= 0) { return (); }
232 my ( $http, $head, $body ) = get_document_1 ($url, $referer, $timeout);
234 if (defined ($timeout)) {
236 my $elapsed = $now - $start;
237 $timeout -= $elapsed;
241 return () if ( ! $body );
243 if ( $http =~ m@HTTP/[0-9.]+ 30[23]@ ) {
245 my ( $location ) = m@^location:[ \t]*(.*)$@im;
247 $location =~ s/[\r\n]$//;
249 if ( $verbose > 3 ) {
250 print STDERR "$progname: redirect from " .
251 "$url to $location\n";
257 $referer =~ m@^(http://[^/]+)@i;
259 } elsif (! ($url =~ m@^[a-z]+:@i)) {
261 s@[^/]+$@@g if m@^http://[^/]+/@i;
262 $_ .= "/" if m@^http://[^/]+$@i;
267 return ( $url, $body );
270 if ($loop_count++ > $max_loop_count) {
271 if ( $verbose > 1 ) {
272 print STDERR "$progname: too many redirects " .
273 "($max_loop_count) from $orig_url\n";
278 } elsif ( $http =~ m@HTTP/[0-9.]+ [4-9][0-9][0-9]@ ) {
279 # http errors -- return nothing.
284 return ( $url, $body );
291 # given a URL and the body text at that URL, selects and returns a random
292 # image from it. returns () if no suitable images found.
294 sub pick_image_from_body {
295 my ( $url, $body ) = @_;
300 # if there's at least one slash after the host, take off the last
302 if ( m@^http://[^/]+/@io ) {
303 $base =~ s@[^/]+$@@go;
306 # if there are no slashes after the host at all, put one on the end.
307 if ( m@^http://[^/]+$@io ) {
311 if ( $verbose > 3 ) {
312 print STDERR "$progname: base is $base\n";
318 # strip out newlines, compress whitespace
325 # There are certain web sites that list huge numbers of dictionary
326 # words in their bodies or in their <META NAME=KEYWORDS> tags (surprise!
327 # Porn sites tend not to be reputable!)
329 # I do not want webcollage to filter on content: I want it to select
330 # randomly from the set of images on the web. All the logic here for
331 # rejecting some images is really a set of heuristics for rejecting
332 # images that are not really images: for rejecting *text* that is in
333 # GIF/JPEG form. I don't want text, I want pictures, and I want the
334 # content of the pictures to be randomly selected from among all the
337 # So, filtering out "dirty" pictures by looking for "dirty" keywords
338 # would be wrong: dirty pictures exist, like it or not, so webcollage
339 # should be able to select them.
341 # However, picking a random URL is a hard thing to do. The mechanism I'm
342 # using is to search for a selection of random words. This is not
343 # perfect, but works ok most of the time. The way it breaks down is when
344 # some URLs get precedence because their pages list *every word* as
345 # related -- those URLs come up more often than others.
347 # So, after we've retrieved a URL, if it has too many keywords, reject
348 # it. We reject it not on the basis of what those keywords are, but on
349 # the basis that by having so many, the page has gotten an unfair
350 # advantage against our randomizer.
353 foreach my $trip (@tripwire_words) {
354 $trip_count++ if m/$trip/i;
356 if ($trip_count >= $#tripwire_words - 2) {
358 print STDERR "$progname: there is probably a dictionary in" .
359 " \"$url\": rejecting.\n";
361 $rejected_urls{$url} = -1;
369 foreach (split(/ *</)) {
372 # Likewise, reject any web pages that have a KEYWORDS meta tag
375 if (m/name ?= ?\"?keywords\"?/i &&
376 m/content ?= ?\"([^\"]+)\"/) {
380 print STDERR "$progname: keywords of" .
381 " length $L in $url: rejecting.\n";
383 $rejected_urls{$url} = $L;
385 } elsif ( $verbose > 2 ) {
386 print STDERR "$progname: keywords of length $L" .
391 } elsif ( m/^(img|a) .*(src|href) ?= ?\"? ?(.*?)[ >\"]/io ) {
393 my $was_inline = ( "$1" eq "a" || "$1" eq "A" );
395 my ( $width ) = m/width ?=[ \"]*(\d+)/oi;
396 my ( $height ) = m/height ?=[ \"]*(\d+)/oi;
401 ( $site = $base ) =~ s@^(http://[^/]*).*@$1@gio;
403 } elsif ( ! m@^[^/:?]+:@ ) {
406 while (s@/\.\./@/@g) {
411 if ( ! m@^http://@io ) {
416 if ( ! m@[.](gif|jpg|jpeg|pjpg|pjpeg)$@io ) {
420 # skip really short or really narrow images
421 if ( $width && $width < $min_width) {
422 if ( $verbose > 2 ) {
423 if (!$height) { $height = "?"; }
424 print STDERR "$progname: skip narrow image " .
425 "$_ (${width}x$height)\n";
430 if ( $height && $height < $min_height) {
431 if ( $verbose > 2 ) {
432 if (!$width) { $width = "?"; }
433 print STDERR "$progname: skip short image " .
434 "$_ (${width}x$height)\n";
439 # skip images with ratios that make them look like banners.
440 if ( $min_ratio && $width && $height &&
441 ($width * $min_ratio ) > $height ) {
442 if ( $verbose > 2 ) {
443 if (!$height) { $height = "?"; }
444 print STDERR "$progname: skip bad ratio " .
445 "$_ (${width}x$height)\n";
452 if ( $unique_urls{$url} ) {
453 if ( $verbose > 2 ) {
454 print STDERR "$progname: skip duplicate image $_\n";
459 if ( $verbose > 2 ) {
460 print STDERR "$progname: got $url" .
461 ($width && $height ? " (${width}x${height})" : "") .
462 ($was_inline ? " (inline)" : "") . "\n";
465 $urls[++$#urls] = $url;
466 $unique_urls{$url}++;
468 # jpegs are preferable to gifs.
470 if ( ! m@[.]gif$@io ) {
471 $urls[++$#urls] = $url;
474 # pointers to images are preferable to inlined images.
475 if ( ! $was_inline ) {
476 $urls[++$#urls] = $url;
477 $urls[++$#urls] = $url;
483 if ( $verbose > 2 ) {
484 print STDERR "$progname: no images on $base\n";
489 return () if ( $#urls < 1 );
491 # pick a random element of the table
492 my $i = ((rand() * 99999) % $#urls);
495 if ( $verbose > 2 ) {
496 print STDERR "$progname: picked $url\n";
503 # Using the URL-randomizer, picks a random image on a random page, and
504 # returns two URLs: the page containing the image, and the image.
505 # Returns () if nothing found this time.
507 sub pick_from_url_randomizer {
508 my ( $timeout ) = @_;
510 if ( $verbose > 3 ) {
511 print STDERR "\n\n$progname: picking from $random_redirector...\n\n";
514 my ( $base, $body ) = get_document ($random_redirector, undef, $timeout);
516 return if (!$base || !$body);
517 my $img = pick_image_from_body ($base, $body);
520 return ($base, $img, "yahoo");
530 if (open (IN, "<$wordlist")) {
531 my $size = (stat(IN))[7];
532 my $pos = rand $size;
533 if (seek (IN, $pos, 0)) {
534 $word = <IN>; # toss partial line
535 $word = <IN>; # keep next line
540 return 0 if (!$word);
542 $word =~ s/^[ \t\n\r]+//;
543 $word =~ s/[ \t\n\r]+$//;
548 $word =~ s/ally$/al/;
549 $word =~ s/izes$/ize/;
550 $word =~ tr/A-Z/a-z/;
557 # Using the image-randomizer, picks a random image on a random page, and
558 # returns two URLs: the page containing the image, and the image.
559 # Returns () if nothing found this time.
561 sub pick_from_image_randomizer {
562 my ( $timeout, $which ) = @_;
564 my $words = random_word;
565 $words .= "%20" . random_word;
566 $words .= "%20" . random_word;
567 $words .= "%20" . random_word;
568 $words .= "%20" . random_word;
570 my $search_url = ($which == 0 ? $image_randomizer_1 :
571 $which == 1 ? $image_randomizer_2 :
572 $image_randomizer_3) .
575 # Pick a random search-result page instead of always taking the first.
576 # This assumes there are at least 10 pages...
578 $search_url .= "&pgno=" . (int(rand(9)) + 1);
579 } elsif ($which == 2) {
580 $search_url .= "&stq=" . (10 * (int(rand(9)) + 1));
583 if ( $verbose > 3 ) {
584 $_ = $words; s/%20/ /g; print STDERR "$progname: search words: $_\n";
587 if ( $verbose > 3 ) {
588 print STDERR "\n\n$progname: picking from $search_url\n";
592 my ( $base, $body ) = get_document ($search_url, undef, $timeout);
593 if (defined ($timeout)) {
594 $timeout -= (time - $start);
595 return () if ($timeout <= 0);
598 return () if (! $body);
604 my $search_count = "?";
606 $body =~ m@found (approximately |about )?(<B>)?(\d+)(</B>)? image@) {
608 } elsif ($which == 1 && $body =~ m@<NOBR>((\d{1,3})(,\d{3})*) @i) {
610 } elsif ($which == 2 && $body =~ m@found ((\d{1,3})(,\d{3})*|\d+) Web p@) {
613 1 while ($search_count =~ s/^(\d+)(\d{3})/$1,$2/);
615 my $length = length($body);
621 s/Result Pages:.*$//; # trim off page footer
624 foreach (split(/\n/)) {
626 my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
628 if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; } # quoted string
629 elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; } # or token
632 # Kludge to decode HotBot pages
633 next unless ($u =~ m@/director\.asp\?target=(http%3A[^&>]+)@);
637 next unless ($u =~ m@^http://@i); # skip non-http and relative urls.
639 next if ($u =~ m@[/.]altavista\.com@i); # skip altavista builtins
640 next if ($u =~ m@[/.]digital\.com@i);
641 next if ($u =~ m@[/.]doubleclick\.net@i);
643 if ($which == 0 && $u =~ m@[/.]corbis\.com/@) {
645 if ( $verbose > 3 ) {
646 print STDERR "$progname: skipping corbis URL: $u\n";
650 } elsif ( $rejected_urls{$u} ) {
651 if ( $verbose > 3 ) {
652 my $L = $rejected_urls{$u};
653 print STDERR "$progname: pre-rejecting sub-page: $u\n";
657 } elsif ( $verbose > 3 ) {
658 print STDERR "$progname: sub-page: $u\n";
661 $subpages[++$#subpages] = $u;
664 if ( $#subpages < 0 ) {
665 if (!$skipped && $verbose > 1) {
666 print STDERR "$progname: found nothing on $base " .
667 "($length bytes, $href_count links).\n";
672 # pick a random element of the table
673 my $i = ((rand() * 99999) % ($#subpages + 1));
674 my $subpage = $subpages[$i];
676 if ( $verbose > 3 ) {
677 print STDERR "$progname: picked page $subpage\n";
682 my ( $base2, $body2 ) = get_document ($subpage, $base, $timeout);
684 return () if (!$base2 || !$body2);
686 my $img = pick_image_from_body ($base2, $body2);
689 return ($base2, $img,
690 ($which == 0 ? "imagevista" :
691 $which == 1 ? "hotbot" : "altavista") .
699 # Picks a random image on a random page, and returns two URLs:
700 # the page containing the image, and the image.
701 # Returns () if nothing found this time.
702 # Uses the url-randomizer 1 time in 5, else the image randomizer.
714 my ( $timeout ) = @_;
716 my $r = int(rand(100));
717 my ($base, $img, $source, $total, $count);
720 ($base, $img, $source) = pick_from_url_randomizer ($timeout);
722 $count = ++$count_0 if $img;
725 ($base, $img, $source) = pick_from_image_randomizer ($timeout, 0);
727 $count = ++$count_1 if $img;
729 # } elsif ($r < 80) {
730 # # HotBot sucks: 98% of the time, it says "no pages match your
731 # # search", and then if I load the URL again by hand, it works.
732 # # I don't understand what's going wrong here, but we're not getting
733 # # any good data back from them, so forget it for now.
735 # ($base, $img, $source) = pick_from_image_randomizer ($timeout, 1);
736 # $total = ++$total_2;
737 # $count = ++$count_2 if $img;
740 ($base, $img, $source) = pick_from_image_randomizer ($timeout, 2);
742 $count = ++$count_3 if $img;
745 if ($source && $total > 0) {
746 $source .= " " . int(($count / $total) * 100) . "%";
748 return ($base, $img, $source);
757 s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
762 # Given the raw body of a GIF document, returns the dimensions of the image.
766 my $type = substr($body, 0, 6);
768 return () unless ($type =~ /GIF8[7,9]a/);
769 $s = substr ($body, 6, 10);
770 my ($a,$b,$c,$d) = unpack ("C"x4, $s);
771 return (($b<<8|$a), ($d<<8|$c));
774 # Given the raw body of a JPEG document, returns the dimensions of the image.
779 my $L = length($body);
781 my $c1 = substr($body, $i, 1); $i++;
782 my $c2 = substr($body, $i, 1); $i++;
783 return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
786 while (ord($ch) != 0xDA && $i < $L) {
787 # Find next marker, beginning with 0xFF.
788 while (ord($ch) != 0xFF) {
789 $ch = substr($body, $i, 1); $i++;
791 # markers can be padded with any number of 0xFF.
792 while (ord($ch) == 0xFF) {
793 $ch = substr($body, $i, 1); $i++;
796 # $ch contains the value of the marker.
797 my $marker = ord($ch);
799 if (($marker >= 0xC0) &&
802 ($marker != 0xCC)) { # it's a SOFn marker
804 my $s = substr($body, $i, 4); $i += 4;
805 my ($a,$b,$c,$d) = unpack("C"x4, $s);
806 return (($c<<8|$d), ($a<<8|$b));
809 # We must skip variables, since FFs in variable names aren't
810 # valid JPEG markers.
811 my $s = substr($body, $i, 2); $i += 2;
812 my ($c1, $c2) = unpack ("C"x2, $s);
813 my $length = ($c1 << 8) | $c2;
814 return () if ($length < 2);
821 # Given the raw body of a GIF or JPEG document, returns the dimensions of
826 my ($w, $h) = gif_size ($body);
827 if ($w && $h) { return ($w, $h); }
828 return jpeg_size ($body);
832 # returns the full path of the named program, or undef.
836 foreach (split (/:/, $ENV{PATH})) {
845 # Like rand(), but chooses numbers with a bell curve distribution.
848 $_ = 1.0 unless defined($_);
850 return (rand($_) + rand($_) + rand($_));
854 ##############################################################################
856 # Generating a list of urls only
858 ##############################################################################
860 sub url_only_output {
862 my ($base, $img) = pick_image;
866 print "$img $base\n";
871 ##############################################################################
873 # Running as an xscreensaver module
875 ##############################################################################
879 if ($verbose > 0) { print STDERR "$progname: caught signal $sig.\n"; }
880 unlink $image_ppm, $image_tmp1, $image_tmp2;
885 # Like system, but prints status about exit codes, and kills this process
886 # with whatever signal killed the sub-process, if any.
888 sub nontrapping_system {
893 s/\"[^\"]+\"/\"...\"/g;
894 print STDERR "$progname: executing \"$_\"\n";
901 print STDERR "$progname: subproc exited normally.\n";
903 } elsif (($rc & 0xff) == 0) {
906 print "$progname: subproc exited with status $rc.\n";
911 print "$progname: subproc dumped core.\n";
916 print "$progname: subproc died with signal $rc.\n";
918 # die that way ourselves.
926 # Given the URL of a GIF or JPEG image, and the body of that image, writes a
927 # PPM to the given output file. Returns the width/height of the image if
931 my ($url, $body, $output) = @_;
932 my ($cmd, $cmd2, $w, $h);
934 if ((@_ = gif_size ($body))) {
937 } elsif ((@_ = jpeg_size ($body))) {
944 $cmd2 = "exec $cmd"; # yes, this really is necessary. if we don't
945 # do this, the process doesn't die properly.
947 $cmd2 .= " 2>/dev/null";
950 # There exist corrupted GIF and JPEG files that can make giftopnm and
951 # djpeg lose their minds and go into a loop. So this gives those programs
952 # a small timeout -- if they don't complete in time, kill them.
958 local $SIG{ALRM} = sub {
960 print STDERR "$progname: timed out ($cvt_timeout) for " .
961 "$cmd on \"$url\" in pid $pid\n";
963 kill ('TERM', $pid) if ($pid);
967 if (($pid = open(PIPE, "| $cmd2 > $output"))) {
973 if ($verbose > 3) { print STDERR "$progname: awaiting $pid\n"; }
975 if ($verbose > 3) { print STDERR "$progname: $pid completed\n"; }
978 my $size = (stat($output))[7];
981 print STDERR "$progname: $cmd on ${w}x$h \"$url\" failed" .
988 print STDERR "$progname: created ${w}x$h $output ($cmd)\n";
992 print STDERR "$progname: $cmd failed: $!\n";
996 die if ($@ && $@ ne "alarm\n"); # propagate errors
1009 my $win_cmd = $ppm_to_root_window_cmd;
1010 $win_cmd =~ s/^([^ \t\r\n]+).*$/$1/;
1012 # make sure the various programs we execute exist, right up front.
1013 foreach ("ppmmake", "giftopnm", "djpeg", "pnmpaste", "pnmscale",
1014 "pnmcut", $win_cmd) {
1015 which ($_) || die "$progname: $_ not found on \$PATH.\n";
1018 $SIG{HUP} = \&x_cleanup;
1019 $SIG{INT} = \&x_cleanup;
1020 $SIG{QUIT} = \&x_cleanup;
1021 $SIG{ABRT} = \&x_cleanup;
1022 $SIG{KILL} = \&x_cleanup;
1023 $SIG{TERM} = \&x_cleanup;
1025 # Need this so that if giftopnm dies, we don't die.
1026 $SIG{PIPE} = 'IGNORE';
1028 if (!$img_width || !$img_height) {
1030 which ($_) || die "$progname: $_ not found on \$PATH.\n";
1032 ($img_width, $img_height) = m/dimensions: *(\d+)x(\d+) /;
1035 my $bgcolor = "#000000";
1036 my $bgimage = undef;
1039 if ($background =~ m/^\#[0-9a-f]+$/i) {
1040 $bgcolor = $background;
1041 } elsif (-r $background) {
1042 $bgimage = $background;
1044 } elsif (! $background =~ m@^[-a-z0-9 ]+$@i) {
1045 print STDERR "$progname: not a color or readable file: " .
1049 # default to assuming it's a color
1050 $bgcolor = $background;
1054 # Create the sold-colored base image.
1056 $_ = "ppmmake '$bgcolor' $img_width $img_height";
1058 print STDERR "$progname: creating base image: $_\n";
1060 nontrapping_system "$_ > $image_ppm";
1062 # Paste the default background image in the middle of it.
1069 open(IMG, "<$bgimage") || die ("couldn't open $bgimage: $!\n");
1071 while (<IMG>) { $body .= $_; }
1073 if ((@_ = gif_size ($body))) {
1075 $cmd = "giftopnm |";
1076 } elsif ((@_ = jpeg_size ($body))) {
1079 } elsif ($body =~ "^P\d\n(\d+) (\d+)\n") {
1084 die "$progname: $bgimage is not a GIF, JPEG, or PPM.\n";
1087 my $x = int (($img_width - $iw) / 2);
1088 my $y = int (($img_height - $ih) / 2);
1090 print STDERR "$progname: pasting $bgimage (${iw}x$ih) into base ".
1094 $cmd .= "pnmpaste - $x $y $image_ppm > $image_tmp1";
1095 open (IMG, "| $cmd") || die ("running $cmd: $!\n");
1099 print STDERR "$progname: subproc exited normally.\n";
1101 rename ($image_tmp1, $image_ppm) ||
1102 die ("renaming $image_tmp1 to $image_ppm: $!\n");
1106 my ($base, $img, $source) = pick_image();
1108 my ($headers, $body) = get_document ($img, $base);
1110 handle_image ($base, $img, $body, $source);
1113 unlink $image_tmp1, $image_tmp2;
1119 my ($base, $img, $body, $source) = @_;
1122 print STDERR "$progname: got $img (" . length($body) . ")\n";
1125 my ($iw, $ih) = image_to_pnm ($img, $body, $image_tmp1);
1126 return 0 unless ($iw && $ih);
1128 my $ow = $iw; # used only for error messages
1131 # don't just tack this onto the front of the pipeline -- we want it to
1132 # be able to change the size of the input image.
1136 print STDERR "$progname: running $filter_cmd\n";
1139 my $rc = nontrapping_system "($filter_cmd) < $image_tmp1 >$image_tmp2";
1142 print STDERR "$progname: failed command: \"$filter_cmd\"\n";
1143 print STDERR "$progname: failed url: \"$img\" (${ow}x$oh)\n";
1147 rename ($image_tmp2, $image_tmp1);
1149 # re-get the width/height in case the filter resized it.
1151 open(IMG, "<$image_tmp1") || return 0;
1154 ($iw, $ih) = m/^(\d+) (\d+)$/;
1156 return 0 unless ($iw && $ih);
1159 my $target_w = $img_width;
1160 my $target_h = $img_height;
1165 # Usually scale the image to fit on the screen -- but sometimes scale it
1166 # to fit on half or a quarter of the screen. Note that we don't merely
1167 # scale it to fit, we instead cut it in half until it fits -- that should
1168 # give a wider distribution of sizes.
1170 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
1171 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
1173 if ($iw > $target_w || $ih > $target_h) {
1174 while ($iw > $target_w ||
1179 if ($iw <= 10 || $ih <= 10) {
1181 print STDERR "$progname: scaling to ${iw}x$ih would " .
1182 "have been bogus.\n";
1188 print STDERR "$progname: scaling to ${iw}x$ih\n";
1191 $cmd .= " | pnmscale -xsize $iw -ysize $ih";
1195 my $src = $image_tmp1;
1197 my $crop_x = 0; # the sub-rectangle of the image
1198 my $crop_y = 0; # that we will actually paste.
1202 # The chance that we will randomly crop out a section of an image starts
1203 # out fairly low, but goes up for images that are very large, or images
1204 # that have ratios that make them look like banners (we try to avoid
1205 # banner images entirely, but they slip through when the IMG tags didn't
1206 # have WIDTH and HEIGHT specified.)
1208 my $crop_chance = 0.2;
1209 if ($iw > $img_width * 0.4 || $ih > $img_height * 0.4) {
1210 $crop_chance += 0.2;
1212 if ($iw > $img_width * 0.7 || $ih > $img_height * 0.7) {
1213 $crop_chance += 0.2;
1215 if ($min_ratio && ($iw * $min_ratio) > $ih) {
1216 $crop_chance += 0.7;
1219 if ($verbose > 2 && $crop_chance > 0.1) {
1220 print STDERR "$progname: crop chance: $crop_chance\n";
1223 if (rand() < $crop_chance) {
1228 if ($crop_w > $min_width) {
1229 # if it's a banner, select the width linearly.
1230 # otherwise, select a bell.
1231 my $r = (($min_ratio && ($iw * $min_ratio) > $ih)
1234 $crop_w = $min_width + int ($r * ($crop_w - $min_width));
1235 $crop_x = int (rand() * ($ow - $crop_w));
1237 if ($crop_h > $min_height) {
1238 # height always selects as a bell.
1239 $crop_h = $min_height + int (bellrand() * ($crop_h - $min_height));
1240 $crop_y = int (rand() * ($oh - $crop_h));
1244 ($crop_x != 0 || $crop_y != 0 ||
1245 $crop_w != $iw || $crop_h != $ih)) {
1246 print STDERR "$progname: randomly cropping to " .
1247 "${crop_w}x$crop_h \@ $crop_x,$crop_y\n";
1251 # Where the image should logically land -- this might be negative.
1253 my $x = int((rand() * ($img_width + $crop_w/2)) - $crop_w*3/4);
1254 my $y = int((rand() * ($img_height + $crop_h/2)) - $crop_h*3/4);
1256 # if we have chosen to paste the image outside of the rectangle of the
1257 # screen, then we need to crop it.
1261 $x + $crop_w > $img_width ||
1262 $y + $crop_h > $img_height) {
1265 print STDERR "$progname: cropping for effective paste of " .
1266 "${crop_w}x$crop_h \@ $x,$y\n";
1269 if ($x < 0) { $crop_x -= $x; $crop_w += $x; $x = 0; }
1270 if ($y < 0) { $crop_y -= $y; $crop_h += $y; $y = 0; }
1272 if ($x + $crop_w >= $img_width) { $crop_w = $img_width - $x - 1; }
1273 if ($y + $crop_h >= $img_height) { $crop_h = $img_height - $y - 1; }
1276 # If any cropping needs to happen, add pnmcut.
1278 if ($crop_x != 0 || $crop_y != 0 ||
1279 $crop_w != $iw || $crop_h != $ih) {
1282 $cmd .= " | pnmcut $crop_x $crop_y $iw $ih";
1284 print STDERR "$progname: cropping to ${crop_w}x$crop_h \@ " .
1285 "$crop_x,$crop_y\n";
1290 print STDERR "$progname: pasting ${iw}x$ih \@ $x,$y in $image_ppm\n";
1293 $cmd .= " | pnmpaste - $x $y $image_ppm";
1295 $cmd =~ s@^ *\| *@@;
1296 my $rc = nontrapping_system "($cmd) < $image_tmp1 > $image_tmp2";
1300 print STDERR "$progname: failed command: \"$cmd\"\n";
1301 print STDERR "$progname: failed url: \"$img\" (${ow}x$oh)\n";
1306 rename ($image_tmp2, $image_ppm) || return;
1308 my $target = "$image_ppm";
1310 # don't just tack this onto the end of the pipeline -- we don't want it
1311 # to end up in $image_ppm, because we don't want the results to be
1314 if ($post_filter_cmd) {
1315 $target = $image_tmp1;
1316 $rc = nontrapping_system "($post_filter_cmd) < $image_ppm > $target";
1319 print STDERR "$progname: filter failed: " .
1320 "\"$post_filter_cmd\"\n";
1326 if (!$no_output_p) {
1327 my $tsize = (stat($target))[7];
1329 $cmd = $ppm_to_root_window_cmd;
1330 $cmd =~ s/%%PPM%%/$target/;
1332 # xv seems to hate being killed. it tends to forget to clean
1333 # up after itself, and leaves windows around and colors allocated.
1334 # I had this same problem with vidwhacker, and I'm not entirely
1335 # sure what I did to fix it. But, let's try this: launch xv
1336 # in the background, so that killing this process doesn't kill it.
1337 # it will die of its own accord soon enough. So this means we
1338 # start pumping bits to the root window in parallel with starting
1339 # the next network retrieval, which is probably a better thing
1344 $rc = nontrapping_system ($cmd);
1348 print STDERR "$progname: display failed: \"$cmd\"\n";
1353 } elsif ($verbose > 1) {
1354 print STDERR "$progname: $target size is $tsize\n";
1359 print STDOUT "image: ${iw}x${ih} @ $x,$y $base $source\n";
1372 # historical suckage: the environment variable name is lower case.
1373 $http_proxy = $ENV{http_proxy} || $ENV{HTTP_PROXY};
1375 while ($_ = $ARGV[0]) {
1377 if ($_ eq "-display" ||
1383 $ENV{DISPLAY} = shift @ARGV;
1384 } elsif ($_ eq "-root") {
1386 } elsif ($_ eq "-no-output") {
1388 } elsif ($_ eq "-urls-only") {
1391 } elsif ($_ eq "-verbose") {
1393 } elsif (m/^-v+$/) {
1394 $verbose += length($_)-1;
1395 } elsif ($_ eq "-delay") {
1396 $delay = shift @ARGV;
1397 } elsif ($_ eq "-timeout") {
1398 $http_timeout = shift @ARGV;
1399 } elsif ($_ eq "-filter") {
1400 $filter_cmd = shift @ARGV;
1401 } elsif ($_ eq "-filter2") {
1402 $post_filter_cmd = shift @ARGV;
1403 } elsif ($_ eq "-background" || $_ eq "-bg") {
1404 $background = shift @ARGV;
1405 } elsif ($_ eq "-size") {
1407 if (m@^(\d+)x(\d+)$@) {
1411 die "$progname: argument to \"-size\" must be" .
1412 " of the form \"640x400\"\n";
1414 } elsif ($_ eq "-proxy" || $_ eq "-http-proxy") {
1415 $http_proxy = shift @ARGV;
1417 die "$copyright\nusage: $progname [-root]" .
1418 " [-display dpy] [-root] [-verbose] [-timeout secs]\n" .
1419 "\t\t [-delay secs] [-filter cmd] [-filter2 cmd]\n" .
1420 "\t\t [-http-proxy host[:port]]\n";
1424 if ($http_proxy && $http_proxy eq "") {
1425 $http_proxy = undef;
1427 if ($http_proxy && $http_proxy =~ m@^http://([^/]*)/?$@ ) {
1428 # historical suckage: allow "http://host:port" as well as "host:port".
1432 if (!$root_p && !$no_output_p) {
1434 "$progname: the -root argument is manditory (for now.)\n";
1437 if (!$no_output_p && !$ENV{DISPLAY}) {
1438 die "$progname: \$DISPLAY is not set.\n";