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.36 $ }; $version =~ s/^[^0-9]+([0-9.]+).*$/$1/;
31 my $copyright = "WebCollage $version, Copyright (c) 1999" .
32 " Jamie Zawinski <jwz\@jwz.org>\n" .
33 " http://www.jwz.org/xscreensaver/\n";
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=";
59 my $photo_randomizer = "http://albums.photopoint.com/j/View?u=1&a=1&p=";
60 my $photo_randomizer_lo = 10000001;
61 my $photo_randomizer_hi = 12400000;
63 my $image_ppm = ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp") . "/webcollage." . $$;
64 my $image_tmp1 = $image_ppm . "-1";
65 my $image_tmp2 = $image_ppm . "-2";
67 my $img_width; # size of the image being generated.
70 my $http_proxy = undef;
71 my $http_timeout = 30;
74 # if we have xli, use it to write to the root window. else use xv.
75 my $ppm_to_root_window_cmd_1 = "xli -quiet -onroot -center" .
76 " -border black %%PPM%%";
77 my $ppm_to_root_window_cmd_2 = "xv -root -rmode 5 -viewonly" .
78 " +noresetroot %%PPM%% -quit";
80 my $ppm_to_root_window_cmd = undef; # initialized by x_output()
82 my $filter_cmd = undef;
83 my $post_filter_cmd = undef;
84 my $background = undef;
89 my $wordlist = "/usr/dict/words";
92 $wordlist = "/usr/share/lib/dict/words"; # irix
94 die "$wordlist doesn't exist!\n" unless (-r $wordlist);
104 my @tripwire_words = ("aberrate", "abode", "amorphous", "antioch",
105 "arrhenius", "arteriole", "blanket", "brainchild",
106 "burdensome", "carnival", "cherub", "chord", "clever",
107 "dedicate", "dilogarithm", "dolan", "dryden",
113 ##############################################################################
117 ##############################################################################
119 # returns three values: the HTTP response line; the document headers;
120 # and the document body.
123 my ( $url, $referer, $timeout ) = @_;
125 if (!defined($timeout)) { $timeout = $http_timeout; }
126 if ($timeout <= 0) { return (); }
127 if ($timeout > $http_timeout) { $timeout = $http_timeout; }
129 if ( $verbose > 3 ) {
130 print STDERR "$progname: get_document_1 $url " .
131 ($referer ? $referer : "") . "\n";
134 my($url_proto, $dummy, $serverstring, $path) = split(/\//, $url, 4);
135 if (! ($url_proto && $url_proto =~ m/^http:$/i)) {
136 if ($verbose) { print STDERR "$progname: not an HTTP URL: $url\n"; }
140 $path = "" unless $path;
142 my($them,$port) = split(/:/, $serverstring);
143 $port = 80 unless $port;
148 $serverstring = $http_proxy if $http_proxy;
149 ($them2,$port2) = split(/:/, $serverstring);
150 $port2 = 80 unless $port2;
153 my ($remote, $iaddr, $paddr, $proto, $line);
155 if ($port2 =~ /\D/) { $port2 = getservbyname($port2, 'tcp') }
156 return unless $port2;
157 $iaddr = inet_aton($remote) || return;
158 $paddr = sockaddr_in($port2, $iaddr);
163 local $SIG{ALRM} = sub {
165 print STDERR "$progname: timed out ($timeout) for $url\n";
171 $proto = getprotobyname('tcp');
172 if (!socket(S, PF_INET, SOCK_STREAM, $proto)) {
173 print STDERR "$progname: socket: $!\n" if ($verbose);
176 if (!connect(S, $paddr)) {
177 print STDERR "$progname: connect($serverstring): $!\n"
182 select(S); $| = 1; select(STDOUT);
185 if ($remote =~ m/\baltavista\.com$/i) {
186 # kludge to tell the various altavista sites to be uncensored.
187 $cookie = "AV_ALL=1";
190 print S ("GET " . ($http_proxy ? $url : "/$path") . " HTTP/1.0\n" .
192 "User-Agent: $progname/$version\n" .
193 ($referer ? "Referer: $referer\n" : "") .
194 ($cookie ? "Cookie: $cookie\n" : "") .
210 if ( $verbose > 3 ) {
211 print STDERR "$progname: ==> $http\n";
214 return ( $http, $head, $body );
216 die if ($@ && $@ ne "alarm\n"); # propagate errors
228 # returns two values: the document headers; and the document body.
229 # if the given URL did a redirect, returns the redirected-to document.
232 my ( $url, $referer, $timeout ) = @_;
237 my $max_loop_count = 4;
240 if (defined($timeout) && $timeout <= 0) { return (); }
242 my ( $http, $head, $body ) = get_document_1 ($url, $referer, $timeout);
244 if (defined ($timeout)) {
246 my $elapsed = $now - $start;
247 $timeout -= $elapsed;
251 return () if ( ! $body );
253 if ( $http =~ m@HTTP/[0-9.]+ 30[23]@ ) {
255 my ( $location ) = m@^location:[ \t]*(.*)$@im;
257 $location =~ s/[\r\n]$//;
259 if ( $verbose > 3 ) {
260 print STDERR "$progname: redirect from " .
261 "$url to $location\n";
267 $referer =~ m@^(http://[^/]+)@i;
269 } elsif (! ($url =~ m@^[a-z]+:@i)) {
271 s@[^/]+$@@g if m@^http://[^/]+/@i;
272 $_ .= "/" if m@^http://[^/]+$@i;
277 return ( $url, $body );
280 if ($loop_count++ > $max_loop_count) {
281 if ( $verbose > 1 ) {
282 print STDERR "$progname: too many redirects " .
283 "($max_loop_count) from $orig_url\n";
288 } elsif ( $http =~ m@HTTP/[0-9.]+ [4-9][0-9][0-9]@ ) {
289 # http errors -- return nothing.
294 return ( $url, $body );
301 # given a URL and the body text at that URL, selects and returns a random
302 # image from it. returns () if no suitable images found.
304 sub pick_image_from_body {
305 my ( $url, $body ) = @_;
310 # if there's at least one slash after the host, take off the last
312 if ( m@^http://[^/]+/@io ) {
313 $base =~ s@[^/]+$@@go;
316 # if there are no slashes after the host at all, put one on the end.
317 if ( m@^http://[^/]+$@io ) {
321 if ( $verbose > 3 ) {
322 print STDERR "$progname: base is $base\n";
328 # strip out newlines, compress whitespace
335 # There are certain web sites that list huge numbers of dictionary
336 # words in their bodies or in their <META NAME=KEYWORDS> tags (surprise!
337 # Porn sites tend not to be reputable!)
339 # I do not want webcollage to filter on content: I want it to select
340 # randomly from the set of images on the web. All the logic here for
341 # rejecting some images is really a set of heuristics for rejecting
342 # images that are not really images: for rejecting *text* that is in
343 # GIF/JPEG form. I don't want text, I want pictures, and I want the
344 # content of the pictures to be randomly selected from among all the
347 # So, filtering out "dirty" pictures by looking for "dirty" keywords
348 # would be wrong: dirty pictures exist, like it or not, so webcollage
349 # should be able to select them.
351 # However, picking a random URL is a hard thing to do. The mechanism I'm
352 # using is to search for a selection of random words. This is not
353 # perfect, but works ok most of the time. The way it breaks down is when
354 # some URLs get precedence because their pages list *every word* as
355 # related -- those URLs come up more often than others.
357 # So, after we've retrieved a URL, if it has too many keywords, reject
358 # it. We reject it not on the basis of what those keywords are, but on
359 # the basis that by having so many, the page has gotten an unfair
360 # advantage against our randomizer.
363 foreach my $trip (@tripwire_words) {
364 $trip_count++ if m/$trip/i;
366 if ($trip_count >= $#tripwire_words - 2) {
368 print STDERR "$progname: there is probably a dictionary in" .
369 " \"$url\": rejecting.\n";
371 $rejected_urls{$url} = -1;
379 foreach (split(/ *</)) {
382 # Likewise, reject any web pages that have a KEYWORDS meta tag
385 if (m/name ?= ?\"?keywords\"?/i &&
386 m/content ?= ?\"([^\"]+)\"/) {
390 print STDERR "$progname: keywords of" .
391 " length $L in $url: rejecting.\n";
393 $rejected_urls{$url} = $L;
395 } elsif ( $verbose > 2 ) {
396 print STDERR "$progname: keywords of length $L" .
401 } elsif ( m/^(img|a) .*(src|href) ?= ?\"? ?(.*?)[ >\"]/io ) {
403 my $was_inline = ( "$1" eq "a" || "$1" eq "A" );
405 my ( $width ) = m/width ?=[ \"]*(\d+)/oi;
406 my ( $height ) = m/height ?=[ \"]*(\d+)/oi;
411 ( $site = $base ) =~ s@^(http://[^/]*).*@$1@gio;
413 } elsif ( ! m@^[^/:?]+:@ ) {
416 while (s@/\.\./@/@g) {
421 if ( ! m@^http://@io ) {
426 if ( ! m@[.](gif|jpg|jpeg|pjpg|pjpeg)$@io ) {
430 # skip really short or really narrow images
431 if ( $width && $width < $min_width) {
432 if ( $verbose > 2 ) {
433 if (!$height) { $height = "?"; }
434 print STDERR "$progname: skip narrow image " .
435 "$_ (${width}x$height)\n";
440 if ( $height && $height < $min_height) {
441 if ( $verbose > 2 ) {
442 if (!$width) { $width = "?"; }
443 print STDERR "$progname: skip short image " .
444 "$_ (${width}x$height)\n";
449 # skip images with ratios that make them look like banners.
450 if ( $min_ratio && $width && $height &&
451 ($width * $min_ratio ) > $height ) {
452 if ( $verbose > 2 ) {
453 if (!$height) { $height = "?"; }
454 print STDERR "$progname: skip bad ratio " .
455 "$_ (${width}x$height)\n";
462 if ( $unique_urls{$url} ) {
463 if ( $verbose > 2 ) {
464 print STDERR "$progname: skip duplicate image $_\n";
469 if ( $verbose > 2 ) {
470 print STDERR "$progname: got $url" .
471 ($width && $height ? " (${width}x${height})" : "") .
472 ($was_inline ? " (inline)" : "") . "\n";
475 $urls[++$#urls] = $url;
476 $unique_urls{$url}++;
478 # jpegs are preferable to gifs.
480 if ( ! m@[.]gif$@io ) {
481 $urls[++$#urls] = $url;
484 # pointers to images are preferable to inlined images.
485 if ( ! $was_inline ) {
486 $urls[++$#urls] = $url;
487 $urls[++$#urls] = $url;
493 if ( $verbose > 2 ) {
494 print STDERR "$progname: no images on $base\n";
499 return () if ( $#urls < 1 );
501 # pick a random element of the table
502 my $i = ((rand() * 99999) % $#urls);
505 if ( $verbose > 2 ) {
506 print STDERR "$progname: picked $url\n";
513 # Using the URL-randomizer, picks a random image on a random page, and
514 # returns two URLs: the page containing the image, and the image.
515 # Returns () if nothing found this time.
517 sub pick_from_url_randomizer {
518 my ( $timeout ) = @_;
520 if ( $verbose > 3 ) {
521 print STDERR "\n\n$progname: picking from $random_redirector...\n\n";
524 my ( $base, $body ) = get_document ($random_redirector, undef, $timeout);
526 return if (!$base || !$body);
527 my $img = pick_image_from_body ($base, $body);
530 return ($base, $img, "yahoo");
540 if (open (IN, "<$wordlist")) {
541 my $size = (stat(IN))[7];
542 my $pos = rand $size;
543 if (seek (IN, $pos, 0)) {
544 $word = <IN>; # toss partial line
545 $word = <IN>; # keep next line
550 return 0 if (!$word);
552 $word =~ s/^[ \t\n\r]+//;
553 $word =~ s/[ \t\n\r]+$//;
558 $word =~ s/ally$/al/;
559 $word =~ s/izes$/ize/;
560 $word =~ tr/A-Z/a-z/;
567 # Using the image-randomizer, picks a random image on a random page, and
568 # returns two URLs: the page containing the image, and the image.
569 # Returns () if nothing found this time.
571 sub pick_from_image_randomizer {
572 my ( $timeout, $which ) = @_;
574 my $words = random_word;
575 $words .= "%20" . random_word;
576 $words .= "%20" . random_word;
577 $words .= "%20" . random_word;
578 $words .= "%20" . random_word;
580 my $search_url = ($which == 0 ? $image_randomizer_1 :
581 $which == 1 ? $image_randomizer_2 :
582 $image_randomizer_3) .
585 # Pick a random search-result page instead of always taking the first.
586 # This assumes there are at least 10 pages...
588 $search_url .= "&pgno=" . (int(rand(9)) + 1);
589 } elsif ($which == 2) {
590 $search_url .= "&stq=" . (10 * (int(rand(9)) + 1));
593 if ( $verbose > 3 ) {
594 $_ = $words; s/%20/ /g; print STDERR "$progname: search words: $_\n";
597 if ( $verbose > 3 ) {
598 print STDERR "\n\n$progname: picking from $search_url\n";
602 my ( $base, $body ) = get_document ($search_url, undef, $timeout);
603 if (defined ($timeout)) {
604 $timeout -= (time - $start);
605 return () if ($timeout <= 0);
608 return () if (! $body);
614 my $search_count = "?";
616 $body =~ m@found (approximately |about )?(<B>)?(\d+)(</B>)? image@) {
618 } elsif ($which == 1 && $body =~ m@<NOBR>((\d{1,3})(,\d{3})*) @i) {
620 } elsif ($which == 2 && $body =~ m@found ((\d{1,3})(,\d{3})*|\d+) Web p@) {
623 1 while ($search_count =~ s/^(\d+)(\d{3})/$1,$2/);
625 my $length = length($body);
631 s/Result Pages:.*$//; # trim off page footer
634 foreach (split(/\n/)) {
636 my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
638 if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; } # quoted string
639 elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; } # or token
642 # Kludge to decode HotBot pages
643 next unless ($u =~ m@/director\.asp\?target=(http%3A[^&>]+)@);
647 next unless ($u =~ m@^http://@i); # skip non-http and relative urls.
649 next if ($u =~ m@[/.]altavista\.com@i); # skip altavista builtins
650 next if ($u =~ m@[/.]digital\.com@i);
651 next if ($u =~ m@[/.]doubleclick\.net@i);
653 if ($which == 0 && $u =~ m@[/.]corbis\.com@) {
655 if ( $verbose > 3 ) {
656 print STDERR "$progname: skipping corbis URL: $u\n";
660 } elsif ( $rejected_urls{$u} ) {
661 if ( $verbose > 3 ) {
662 my $L = $rejected_urls{$u};
663 print STDERR "$progname: pre-rejecting sub-page: $u\n";
667 } elsif ( $verbose > 3 ) {
668 print STDERR "$progname: sub-page: $u\n";
671 $subpages[++$#subpages] = $u;
674 if ( $#subpages < 0 ) {
675 if (!$skipped && $verbose > 1) {
676 print STDERR "$progname: found nothing on $base " .
677 "($length bytes, $href_count links).\n";
682 # pick a random element of the table
683 my $i = ((rand() * 99999) % ($#subpages + 1));
684 my $subpage = $subpages[$i];
686 if ( $verbose > 3 ) {
687 print STDERR "$progname: picked page $subpage\n";
692 my ( $base2, $body2 ) = get_document ($subpage, $base, $timeout);
694 return () if (!$base2 || !$body2);
696 my $img = pick_image_from_body ($base2, $body2);
699 return ($base2, $img,
700 ($which == 0 ? "imagevista" :
701 $which == 1 ? "hotbot" : "altavista") .
709 # Using the photo site, generate a random URL that will hopefully point
710 # to an image. Returns two URLs, both of which are the URL of the image.
711 # Returns () if nothing found this time.
713 sub pick_from_photo_randomizer {
714 my ( $timeout ) = @_;
715 my $n = ($photo_randomizer_lo +
716 int(rand() * ($photo_randomizer_hi - $photo_randomizer_lo)));
717 my $url = $photo_randomizer . $n;
718 return ( $url, $url, "photopoint" );
722 # Picks a random image on a random page, and returns two URLs:
723 # the page containing the image, and the image.
724 # Returns () if nothing found this time.
725 # Uses the url-randomizer 1 time in 5, else the image randomizer.
739 my ( $timeout ) = @_;
741 my $r = int(rand(100));
742 my ($base, $img, $source, $total, $count);
745 ($base, $img, $source) = pick_from_url_randomizer ($timeout);
747 $count = ++$count_0 if $img;
750 ($base, $img, $source) = pick_from_image_randomizer ($timeout, 0);
752 $count = ++$count_1 if $img;
755 ($base, $img, $source) = pick_from_photo_randomizer ($timeout);
757 $count = ++$count_4 if $img;
759 # } elsif ($r < 80) {
760 # # HotBot sucks: 98% of the time, it says "no pages match your
761 # # search", and then if I load the URL again by hand, it works.
762 # # I don't understand what's going wrong here, but we're not getting
763 # # any good data back from them, so forget it for now.
765 # ($base, $img, $source) = pick_from_image_randomizer ($timeout, 1);
766 # $total = ++$total_2;
767 # $count = ++$count_2 if $img;
770 ($base, $img, $source) = pick_from_image_randomizer ($timeout, 2);
772 $count = ++$count_3 if $img;
775 if ($source && $total > 0) {
776 $source .= " " . int(($count / $total) * 100) . "%";
778 return ($base, $img, $source);
787 s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
792 # Given the raw body of a GIF document, returns the dimensions of the image.
796 my $type = substr($body, 0, 6);
798 return () unless ($type =~ /GIF8[7,9]a/);
799 $s = substr ($body, 6, 10);
800 my ($a,$b,$c,$d) = unpack ("C"x4, $s);
801 return (($b<<8|$a), ($d<<8|$c));
804 # Given the raw body of a JPEG document, returns the dimensions of the image.
809 my $L = length($body);
811 my $c1 = substr($body, $i, 1); $i++;
812 my $c2 = substr($body, $i, 1); $i++;
813 return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
816 while (ord($ch) != 0xDA && $i < $L) {
817 # Find next marker, beginning with 0xFF.
818 while (ord($ch) != 0xFF) {
819 $ch = substr($body, $i, 1); $i++;
821 # markers can be padded with any number of 0xFF.
822 while (ord($ch) == 0xFF) {
823 $ch = substr($body, $i, 1); $i++;
826 # $ch contains the value of the marker.
827 my $marker = ord($ch);
829 if (($marker >= 0xC0) &&
832 ($marker != 0xCC)) { # it's a SOFn marker
834 my $s = substr($body, $i, 4); $i += 4;
835 my ($a,$b,$c,$d) = unpack("C"x4, $s);
836 return (($c<<8|$d), ($a<<8|$b));
839 # We must skip variables, since FFs in variable names aren't
840 # valid JPEG markers.
841 my $s = substr($body, $i, 2); $i += 2;
842 my ($c1, $c2) = unpack ("C"x2, $s);
843 my $length = ($c1 << 8) | $c2;
844 return () if ($length < 2);
851 # Given the raw body of a GIF or JPEG document, returns the dimensions of
856 my ($w, $h) = gif_size ($body);
857 if ($w && $h) { return ($w, $h); }
858 return jpeg_size ($body);
862 # returns the full path of the named program, or undef.
866 foreach (split (/:/, $ENV{PATH})) {
875 # Like rand(), but chooses numbers with a bell curve distribution.
878 $_ = 1.0 unless defined($_);
880 return (rand($_) + rand($_) + rand($_));
884 ##############################################################################
886 # Generating a list of urls only
888 ##############################################################################
890 sub url_only_output {
892 my ($base, $img) = pick_image;
896 print "$img $base\n";
901 ##############################################################################
903 # Running as an xscreensaver module
905 ##############################################################################
909 if ($verbose > 0) { print STDERR "$progname: caught signal $sig.\n"; }
910 unlink $image_ppm, $image_tmp1, $image_tmp2;
915 # Like system, but prints status about exit codes, and kills this process
916 # with whatever signal killed the sub-process, if any.
918 sub nontrapping_system {
923 s/\"[^\"]+\"/\"...\"/g;
924 print STDERR "$progname: executing \"$_\"\n";
931 print STDERR "$progname: subproc exited normally.\n";
933 } elsif (($rc & 0xff) == 0) {
936 print "$progname: subproc exited with status $rc.\n";
941 print "$progname: subproc dumped core.\n";
946 print "$progname: subproc died with signal $rc.\n";
948 # die that way ourselves.
956 # Given the URL of a GIF or JPEG image, and the body of that image, writes a
957 # PPM to the given output file. Returns the width/height of the image if
961 my ($url, $body, $output) = @_;
962 my ($cmd, $cmd2, $w, $h);
964 if ((@_ = gif_size ($body))) {
967 } elsif ((@_ = jpeg_size ($body))) {
974 $cmd2 = "exec $cmd"; # yes, this really is necessary. if we don't
975 # do this, the process doesn't die properly.
977 $cmd2 .= " 2>/dev/null";
980 # There exist corrupted GIF and JPEG files that can make giftopnm and
981 # djpeg lose their minds and go into a loop. So this gives those programs
982 # a small timeout -- if they don't complete in time, kill them.
988 local $SIG{ALRM} = sub {
990 print STDERR "$progname: timed out ($cvt_timeout) for " .
991 "$cmd on \"$url\" in pid $pid\n";
993 kill ('TERM', $pid) if ($pid);
997 if (($pid = open(PIPE, "| $cmd2 > $output"))) {
1003 if ($verbose > 3) { print STDERR "$progname: awaiting $pid\n"; }
1005 if ($verbose > 3) { print STDERR "$progname: $pid completed\n"; }
1008 my $size = (stat($output))[7];
1011 print STDERR "$progname: $cmd on ${w}x$h \"$url\" failed" .
1018 print STDERR "$progname: created ${w}x$h $output ($cmd)\n";
1022 print STDERR "$progname: $cmd failed: $!\n";
1026 die if ($@ && $@ ne "alarm\n"); # propagate errors
1039 my $win_cmd_1 = $ppm_to_root_window_cmd_1;
1040 my $win_cmd_2 = $ppm_to_root_window_cmd_2;
1041 $win_cmd_1 =~ s/^([^ \t\r\n]+).*$/$1/;
1042 $win_cmd_2 =~ s/^([^ \t\r\n]+).*$/$1/;
1044 # make sure the various programs we execute exist, right up front.
1045 foreach ("ppmmake", "giftopnm", "djpeg", "pnmpaste", "pnmscale",
1047 which ($_) || die "$progname: $_ not found on \$PATH.\n";
1050 if (which($win_cmd_1)) {
1051 $ppm_to_root_window_cmd = $ppm_to_root_window_cmd_1;
1052 } elsif (which($win_cmd_2)) {
1053 $ppm_to_root_window_cmd = $ppm_to_root_window_cmd_2;
1055 die "$progname: neither $win_cmd_1 nor $win_cmd_2 found on \$PATH.\n";
1058 $SIG{HUP} = \&x_cleanup;
1059 $SIG{INT} = \&x_cleanup;
1060 $SIG{QUIT} = \&x_cleanup;
1061 $SIG{ABRT} = \&x_cleanup;
1062 $SIG{KILL} = \&x_cleanup;
1063 $SIG{TERM} = \&x_cleanup;
1065 # Need this so that if giftopnm dies, we don't die.
1066 $SIG{PIPE} = 'IGNORE';
1068 if (!$img_width || !$img_height) {
1070 which ($_) || die "$progname: $_ not found on \$PATH.\n";
1072 ($img_width, $img_height) = m/dimensions: *(\d+)x(\d+) /;
1075 my $bgcolor = "#000000";
1076 my $bgimage = undef;
1079 if ($background =~ m/^\#[0-9a-f]+$/i) {
1080 $bgcolor = $background;
1081 } elsif (-r $background) {
1082 $bgimage = $background;
1084 } elsif (! $background =~ m@^[-a-z0-9 ]+$@i) {
1085 print STDERR "$progname: not a color or readable file: " .
1089 # default to assuming it's a color
1090 $bgcolor = $background;
1094 # Create the sold-colored base image.
1096 $_ = "ppmmake '$bgcolor' $img_width $img_height";
1098 print STDERR "$progname: creating base image: $_\n";
1100 nontrapping_system "$_ > $image_ppm";
1102 # Paste the default background image in the middle of it.
1109 open(IMG, "<$bgimage") || die ("couldn't open $bgimage: $!\n");
1111 while (<IMG>) { $body .= $_; }
1113 if ((@_ = gif_size ($body))) {
1115 $cmd = "giftopnm |";
1116 } elsif ((@_ = jpeg_size ($body))) {
1119 } elsif ($body =~ "^P\d\n(\d+) (\d+)\n") {
1124 die "$progname: $bgimage is not a GIF, JPEG, or PPM.\n";
1127 my $x = int (($img_width - $iw) / 2);
1128 my $y = int (($img_height - $ih) / 2);
1130 print STDERR "$progname: pasting $bgimage (${iw}x$ih) into base ".
1134 $cmd .= "pnmpaste - $x $y $image_ppm > $image_tmp1";
1135 open (IMG, "| $cmd") || die ("running $cmd: $!\n");
1139 print STDERR "$progname: subproc exited normally.\n";
1141 rename ($image_tmp1, $image_ppm) ||
1142 die ("renaming $image_tmp1 to $image_ppm: $!\n");
1146 my ($base, $img, $source) = pick_image();
1148 my ($headers, $body) = get_document ($img, $base);
1150 handle_image ($base, $img, $body, $source);
1153 unlink $image_tmp1, $image_tmp2;
1159 my ($base, $img, $body, $source) = @_;
1162 print STDERR "$progname: got $img (" . length($body) . ")\n";
1165 my ($iw, $ih) = image_to_pnm ($img, $body, $image_tmp1);
1166 return 0 unless ($iw && $ih);
1168 my $ow = $iw; # used only for error messages
1171 # don't just tack this onto the front of the pipeline -- we want it to
1172 # be able to change the size of the input image.
1176 print STDERR "$progname: running $filter_cmd\n";
1179 my $rc = nontrapping_system "($filter_cmd) < $image_tmp1 >$image_tmp2";
1182 print STDERR "$progname: failed command: \"$filter_cmd\"\n";
1183 print STDERR "$progname: failed url: \"$img\" (${ow}x$oh)\n";
1187 rename ($image_tmp2, $image_tmp1);
1189 # re-get the width/height in case the filter resized it.
1191 open(IMG, "<$image_tmp1") || return 0;
1194 ($iw, $ih) = m/^(\d+) (\d+)$/;
1196 return 0 unless ($iw && $ih);
1199 my $target_w = $img_width;
1200 my $target_h = $img_height;
1205 # Usually scale the image to fit on the screen -- but sometimes scale it
1206 # to fit on half or a quarter of the screen. Note that we don't merely
1207 # scale it to fit, we instead cut it in half until it fits -- that should
1208 # give a wider distribution of sizes.
1210 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
1211 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
1213 if ($iw > $target_w || $ih > $target_h) {
1214 while ($iw > $target_w ||
1219 if ($iw <= 10 || $ih <= 10) {
1221 print STDERR "$progname: scaling to ${iw}x$ih would " .
1222 "have been bogus.\n";
1228 print STDERR "$progname: scaling to ${iw}x$ih\n";
1231 $cmd .= " | pnmscale -xsize $iw -ysize $ih";
1235 my $src = $image_tmp1;
1237 my $crop_x = 0; # the sub-rectangle of the image
1238 my $crop_y = 0; # that we will actually paste.
1242 # The chance that we will randomly crop out a section of an image starts
1243 # out fairly low, but goes up for images that are very large, or images
1244 # that have ratios that make them look like banners (we try to avoid
1245 # banner images entirely, but they slip through when the IMG tags didn't
1246 # have WIDTH and HEIGHT specified.)
1248 my $crop_chance = 0.2;
1249 if ($iw > $img_width * 0.4 || $ih > $img_height * 0.4) {
1250 $crop_chance += 0.2;
1252 if ($iw > $img_width * 0.7 || $ih > $img_height * 0.7) {
1253 $crop_chance += 0.2;
1255 if ($min_ratio && ($iw * $min_ratio) > $ih) {
1256 $crop_chance += 0.7;
1259 if ($verbose > 2 && $crop_chance > 0.1) {
1260 print STDERR "$progname: crop chance: $crop_chance\n";
1263 if (rand() < $crop_chance) {
1268 if ($crop_w > $min_width) {
1269 # if it's a banner, select the width linearly.
1270 # otherwise, select a bell.
1271 my $r = (($min_ratio && ($iw * $min_ratio) > $ih)
1274 $crop_w = $min_width + int ($r * ($crop_w - $min_width));
1275 $crop_x = int (rand() * ($ow - $crop_w));
1277 if ($crop_h > $min_height) {
1278 # height always selects as a bell.
1279 $crop_h = $min_height + int (bellrand() * ($crop_h - $min_height));
1280 $crop_y = int (rand() * ($oh - $crop_h));
1284 ($crop_x != 0 || $crop_y != 0 ||
1285 $crop_w != $iw || $crop_h != $ih)) {
1286 print STDERR "$progname: randomly cropping to " .
1287 "${crop_w}x$crop_h \@ $crop_x,$crop_y\n";
1291 # Where the image should logically land -- this might be negative.
1293 my $x = int((rand() * ($img_width + $crop_w/2)) - $crop_w*3/4);
1294 my $y = int((rand() * ($img_height + $crop_h/2)) - $crop_h*3/4);
1296 # if we have chosen to paste the image outside of the rectangle of the
1297 # screen, then we need to crop it.
1301 $x + $crop_w > $img_width ||
1302 $y + $crop_h > $img_height) {
1305 print STDERR "$progname: cropping for effective paste of " .
1306 "${crop_w}x$crop_h \@ $x,$y\n";
1309 if ($x < 0) { $crop_x -= $x; $crop_w += $x; $x = 0; }
1310 if ($y < 0) { $crop_y -= $y; $crop_h += $y; $y = 0; }
1312 if ($x + $crop_w >= $img_width) { $crop_w = $img_width - $x - 1; }
1313 if ($y + $crop_h >= $img_height) { $crop_h = $img_height - $y - 1; }
1316 # If any cropping needs to happen, add pnmcut.
1318 if ($crop_x != 0 || $crop_y != 0 ||
1319 $crop_w != $iw || $crop_h != $ih) {
1322 $cmd .= " | pnmcut $crop_x $crop_y $iw $ih";
1324 print STDERR "$progname: cropping to ${crop_w}x$crop_h \@ " .
1325 "$crop_x,$crop_y\n";
1330 print STDERR "$progname: pasting ${iw}x$ih \@ $x,$y in $image_ppm\n";
1333 $cmd .= " | pnmpaste - $x $y $image_ppm";
1335 $cmd =~ s@^ *\| *@@;
1336 my $rc = nontrapping_system "($cmd) < $image_tmp1 > $image_tmp2";
1340 print STDERR "$progname: failed command: \"$cmd\"\n";
1341 print STDERR "$progname: failed url: \"$img\" (${ow}x$oh)\n";
1346 rename ($image_tmp2, $image_ppm) || return;
1348 my $target = "$image_ppm";
1350 # don't just tack this onto the end of the pipeline -- we don't want it
1351 # to end up in $image_ppm, because we don't want the results to be
1354 if ($post_filter_cmd) {
1355 $target = $image_tmp1;
1356 $rc = nontrapping_system "($post_filter_cmd) < $image_ppm > $target";
1359 print STDERR "$progname: filter failed: " .
1360 "\"$post_filter_cmd\"\n";
1366 if (!$no_output_p) {
1367 my $tsize = (stat($target))[7];
1369 $cmd = $ppm_to_root_window_cmd;
1370 $cmd =~ s/%%PPM%%/$target/;
1372 # xv seems to hate being killed. it tends to forget to clean
1373 # up after itself, and leaves windows around and colors allocated.
1374 # I had this same problem with vidwhacker, and I'm not entirely
1375 # sure what I did to fix it. But, let's try this: launch xv
1376 # in the background, so that killing this process doesn't kill it.
1377 # it will die of its own accord soon enough. So this means we
1378 # start pumping bits to the root window in parallel with starting
1379 # the next network retrieval, which is probably a better thing
1384 $rc = nontrapping_system ($cmd);
1388 print STDERR "$progname: display failed: \"$cmd\"\n";
1393 } elsif ($verbose > 1) {
1394 print STDERR "$progname: $target size is $tsize\n";
1399 print STDOUT "image: ${iw}x${ih} @ $x,$y $base $source\n";
1412 # historical suckage: the environment variable name is lower case.
1413 $http_proxy = $ENV{http_proxy} || $ENV{HTTP_PROXY};
1415 while ($_ = $ARGV[0]) {
1417 if ($_ eq "-display" ||
1423 $ENV{DISPLAY} = shift @ARGV;
1424 } elsif ($_ eq "-root") {
1426 } elsif ($_ eq "-no-output") {
1428 } elsif ($_ eq "-urls-only") {
1431 } elsif ($_ eq "-verbose") {
1433 } elsif (m/^-v+$/) {
1434 $verbose += length($_)-1;
1435 } elsif ($_ eq "-delay") {
1436 $delay = shift @ARGV;
1437 } elsif ($_ eq "-timeout") {
1438 $http_timeout = shift @ARGV;
1439 } elsif ($_ eq "-filter") {
1440 $filter_cmd = shift @ARGV;
1441 } elsif ($_ eq "-filter2") {
1442 $post_filter_cmd = shift @ARGV;
1443 } elsif ($_ eq "-background" || $_ eq "-bg") {
1444 $background = shift @ARGV;
1445 } elsif ($_ eq "-size") {
1447 if (m@^(\d+)x(\d+)$@) {
1451 die "$progname: argument to \"-size\" must be" .
1452 " of the form \"640x400\"\n";
1454 } elsif ($_ eq "-proxy" || $_ eq "-http-proxy") {
1455 $http_proxy = shift @ARGV;
1457 die "$copyright\nusage: $progname [-root]" .
1458 " [-display dpy] [-root] [-verbose] [-timeout secs]\n" .
1459 "\t\t [-delay secs] [-filter cmd] [-filter2 cmd]\n" .
1460 "\t\t [-http-proxy host[:port]]\n";
1464 if ($http_proxy && $http_proxy eq "") {
1465 $http_proxy = undef;
1467 if ($http_proxy && $http_proxy =~ m@^http://([^/]*)/?$@ ) {
1468 # historical suckage: allow "http://host:port" as well as "host:port".
1472 if (!$root_p && !$no_output_p) {
1474 "$progname: the -root argument is manditory (for now.)\n";
1477 if (!$no_output_p && !$ENV{DISPLAY}) {
1478 die "$progname: \$DISPLAY is not set.\n";