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.42 $ }; $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 # programs we can use to write to the root window (tried in ascending order.)
79 my $ppm_to_root_window_cmd_1 = "xloadimage -onroot -quiet %%PPM%%";
80 my $ppm_to_root_window_cmd_2 = "xli -quiet -onroot -center" .
81 " -border black %%PPM%%";
82 my $ppm_to_root_window_cmd_3 = "xv -root -rmode 5 -viewonly" .
83 " +noresetroot %%PPM%% -quit";
85 my $ppm_to_root_window_cmd = undef; # initialized by x_output()
87 my $filter_cmd = undef;
88 my $post_filter_cmd = undef;
89 my $background = undef;
94 my $wordlist = "/usr/dict/words";
97 $wordlist = "/usr/share/lib/dict/words"; # irix
99 die "$wordlist doesn't exist!\n" unless (-r $wordlist);
109 my @tripwire_words = ("aberrate", "abode", "amorphous", "antioch",
110 "arrhenius", "arteriole", "blanket", "brainchild",
111 "burdensome", "carnival", "cherub", "chord", "clever",
112 "dedicate", "dilogarithm", "dolan", "dryden",
118 ##############################################################################
122 ##############################################################################
124 # returns three values: the HTTP response line; the document headers;
125 # and the document body.
128 my ( $url, $referer, $timeout ) = @_;
130 if (!defined($timeout)) { $timeout = $http_timeout; }
131 if ($timeout <= 0) { return (); }
132 if ($timeout > $http_timeout) { $timeout = $http_timeout; }
134 if ( $verbose > 3 ) {
135 print STDERR "$progname: get_document_1 $url " .
136 ($referer ? $referer : "") . "\n";
139 my($url_proto, $dummy, $serverstring, $path) = split(/\//, $url, 4);
140 if (! ($url_proto && $url_proto =~ m/^http:$/i)) {
141 if ($verbose) { print STDERR "$progname: not an HTTP URL: $url\n"; }
145 $path = "" unless $path;
147 my($them,$port) = split(/:/, $serverstring);
148 $port = 80 unless $port;
153 $serverstring = $http_proxy if $http_proxy;
154 ($them2,$port2) = split(/:/, $serverstring);
155 $port2 = 80 unless $port2;
158 my ($remote, $iaddr, $paddr, $proto, $line);
160 if ($port2 =~ /\D/) { $port2 = getservbyname($port2, 'tcp') }
161 return unless $port2;
162 $iaddr = inet_aton($remote) || return;
163 $paddr = sockaddr_in($port2, $iaddr);
171 local $SIG{ALRM} = sub {
173 print STDERR "$progname: timed out ($timeout) for $url\n";
179 $proto = getprotobyname('tcp');
180 if (!socket(S, PF_INET, SOCK_STREAM, $proto)) {
181 print STDERR "$progname: socket: $!\n" if ($verbose);
184 if (!connect(S, $paddr)) {
185 print STDERR "$progname: connect($serverstring): $!\n"
190 select(S); $| = 1; select(STDOUT);
193 if ($remote =~ m/\baltavista\.com$/i) {
194 # kludge to tell the various altavista sites to be uncensored.
195 $cookie = "AV_ALL=1";
198 print S ("GET " . ($http_proxy ? $url : "/$path") . " HTTP/1.0\n" .
200 "User-Agent: $progname/$version\n" .
201 ($referer ? "Referer: $referer\n" : "") .
202 ($cookie ? "Cookie: $cookie\n" : "") .
216 if ( $verbose > 3 ) {
217 print STDERR "$progname: ==> $http\n";
220 return ( $http, $head, $body );
222 die if ($@ && $@ ne "alarm\n"); # propagate errors
236 # returns two values: the document headers; and the document body.
237 # if the given URL did a redirect, returns the redirected-to document.
240 my ( $url, $referer, $timeout ) = @_;
245 my $max_loop_count = 4;
248 if (defined($timeout) && $timeout <= 0) { return (); }
250 my ( $http, $head, $body ) = get_document_1 ($url, $referer, $timeout);
252 if (defined ($timeout)) {
254 my $elapsed = $now - $start;
255 $timeout -= $elapsed;
259 return () if ( ! $body );
261 if ( $http =~ m@HTTP/[0-9.]+ 30[23]@ ) {
263 my ( $location ) = m@^location:[ \t]*(.*)$@im;
265 $location =~ s/[\r\n]$//;
267 if ( $verbose > 3 ) {
268 print STDERR "$progname: redirect from " .
269 "$url to $location\n";
275 $referer =~ m@^(http://[^/]+)@i;
277 } elsif (! ($url =~ m@^[a-z]+:@i)) {
279 s@[^/]+$@@g if m@^http://[^/]+/@i;
280 $_ .= "/" if m@^http://[^/]+$@i;
285 return ( $url, $body );
288 if ($loop_count++ > $max_loop_count) {
289 if ( $verbose > 1 ) {
290 print STDERR "$progname: too many redirects " .
291 "($max_loop_count) from $orig_url\n";
297 } elsif ( $http =~ m@HTTP/[0-9.]+ [4-9][0-9][0-9]@ ) {
298 # http errors -- return nothing.
304 return ( $url, $body );
311 # given a URL and the body text at that URL, selects and returns a random
312 # image from it. returns () if no suitable images found.
314 sub pick_image_from_body {
315 my ( $url, $body ) = @_;
320 # if there's at least one slash after the host, take off the last
322 if ( m@^http://[^/]+/@io ) {
323 $base =~ s@[^/]+$@@go;
326 # if there are no slashes after the host at all, put one on the end.
327 if ( m@^http://[^/]+$@io ) {
331 if ( $verbose > 3 ) {
332 print STDERR "$progname: base is $base\n";
338 # strip out newlines, compress whitespace
345 # There are certain web sites that list huge numbers of dictionary
346 # words in their bodies or in their <META NAME=KEYWORDS> tags (surprise!
347 # Porn sites tend not to be reputable!)
349 # I do not want webcollage to filter on content: I want it to select
350 # randomly from the set of images on the web. All the logic here for
351 # rejecting some images is really a set of heuristics for rejecting
352 # images that are not really images: for rejecting *text* that is in
353 # GIF/JPEG form. I don't want text, I want pictures, and I want the
354 # content of the pictures to be randomly selected from among all the
357 # So, filtering out "dirty" pictures by looking for "dirty" keywords
358 # would be wrong: dirty pictures exist, like it or not, so webcollage
359 # should be able to select them.
361 # However, picking a random URL is a hard thing to do. The mechanism I'm
362 # using is to search for a selection of random words. This is not
363 # perfect, but works ok most of the time. The way it breaks down is when
364 # some URLs get precedence because their pages list *every word* as
365 # related -- those URLs come up more often than others.
367 # So, after we've retrieved a URL, if it has too many keywords, reject
368 # it. We reject it not on the basis of what those keywords are, but on
369 # the basis that by having so many, the page has gotten an unfair
370 # advantage against our randomizer.
373 foreach my $trip (@tripwire_words) {
374 $trip_count++ if m/$trip/i;
376 if ($trip_count >= $#tripwire_words - 2) {
378 print STDERR "$progname: there is probably a dictionary in" .
379 " \"$url\": rejecting.\n";
381 $rejected_urls{$url} = -1;
391 foreach (split(/ *</)) {
394 # Likewise, reject any web pages that have a KEYWORDS meta tag
397 if (m/name ?= ?\"?keywords\"?/i &&
398 m/content ?= ?\"([^\"]+)\"/) {
402 print STDERR "$progname: keywords of" .
403 " length $L in $url: rejecting.\n";
405 $rejected_urls{$url} = $L;
409 } elsif ( $verbose > 2 ) {
410 print STDERR "$progname: keywords of length $L" .
415 } elsif ( m/^(img|a) .*(src|href) ?= ?\"? ?(.*?)[ >\"]/io ) {
417 my $was_inline = ( "$1" eq "a" || "$1" eq "A" );
419 my ( $width ) = m/width ?=[ \"]*(\d+)/oi;
420 my ( $height ) = m/height ?=[ \"]*(\d+)/oi;
425 ( $site = $base ) =~ s@^(http://[^/]*).*@$1@gio;
427 } elsif ( ! m@^[^/:?]+:@ ) {
430 while (s@/\.\./@/@g) {
435 if ( ! m@^http://@io ) {
440 if ( ! m@[.](gif|jpg|jpeg|pjpg|pjpeg)$@io ) {
444 # skip really short or really narrow images
445 if ( $width && $width < $min_width) {
446 if ( $verbose > 2 ) {
447 if (!$height) { $height = "?"; }
448 print STDERR "$progname: skip narrow image " .
449 "$_ (${width}x$height)\n";
454 if ( $height && $height < $min_height) {
455 if ( $verbose > 2 ) {
456 if (!$width) { $width = "?"; }
457 print STDERR "$progname: skip short image " .
458 "$_ (${width}x$height)\n";
463 # skip images with ratios that make them look like banners.
464 if ( $min_ratio && $width && $height &&
465 ($width * $min_ratio ) > $height ) {
466 if ( $verbose > 2 ) {
467 if (!$height) { $height = "?"; }
468 print STDERR "$progname: skip bad ratio " .
469 "$_ (${width}x$height)\n";
476 if ( $unique_urls{$url} ) {
477 if ( $verbose > 2 ) {
478 print STDERR "$progname: skip duplicate image $_\n";
483 if ( $verbose > 2 ) {
484 print STDERR "$progname: got $url" .
485 ($width && $height ? " (${width}x${height})" : "") .
486 ($was_inline ? " (inline)" : "") . "\n";
489 $urls[++$#urls] = $url;
490 $unique_urls{$url}++;
492 # jpegs are preferable to gifs.
494 if ( ! m@[.]gif$@io ) {
495 $urls[++$#urls] = $url;
498 # pointers to images are preferable to inlined images.
499 if ( ! $was_inline ) {
500 $urls[++$#urls] = $url;
501 $urls[++$#urls] = $url;
510 if ( $verbose > 2 ) {
511 print STDERR "$progname: no images on $base\n";
516 return () if ( $#urls < 1 );
518 # pick a random element of the table
519 my $i = ((rand() * 99999) % $#urls);
522 if ( $verbose > 2 ) {
523 print STDERR "$progname: picked $url\n";
530 # Using the URL-randomizer, picks a random image on a random page, and
531 # returns two URLs: the page containing the image, and the image.
532 # Returns () if nothing found this time.
534 sub pick_from_url_randomizer {
535 my ( $timeout ) = @_;
537 if ( $verbose > 3 ) {
538 print STDERR "\n\n$progname: picking from $random_redirector...\n\n";
541 my ( $base, $body ) = get_document ($random_redirector, undef, $timeout);
543 if (!$base || !$body) {
547 my $img = pick_image_from_body ($base, $body);
551 return ($base, $img, "yahoo");
561 if (open (IN, "<$wordlist")) {
562 my $size = (stat(IN))[7];
563 my $pos = rand $size;
564 if (seek (IN, $pos, 0)) {
565 $word = <IN>; # toss partial line
566 $word = <IN>; # keep next line
571 return 0 if (!$word);
573 $word =~ s/^[ \t\n\r]+//;
574 $word =~ s/[ \t\n\r]+$//;
579 $word =~ s/ally$/al/;
580 $word =~ s/izes$/ize/;
581 $word =~ tr/A-Z/a-z/;
588 # Using the image-randomizer, picks a random image on a random page, and
589 # returns two URLs: the page containing the image, and the image.
590 # Returns () if nothing found this time.
592 sub pick_from_image_randomizer {
593 my ( $timeout, $which ) = @_;
595 my $words = random_word;
596 $words .= "%20" . random_word;
597 $words .= "%20" . random_word;
598 $words .= "%20" . random_word;
599 $words .= "%20" . random_word;
601 my $search_url = ($which == 0 ? $image_randomizer_1 :
602 $which == 1 ? $image_randomizer_2 :
603 $image_randomizer_3) .
606 # Pick a random search-result page instead of always taking the first.
607 # This assumes there are at least 10 pages...
609 $search_url .= "&pgno=" . (int(rand(9)) + 1);
610 } elsif ($which == 2) {
611 $search_url .= "&stq=" . (10 * (int(rand(9)) + 1));
614 if ( $verbose > 3 ) {
615 $_ = $words; s/%20/ /g; print STDERR "$progname: search words: $_\n";
618 if ( $verbose > 3 ) {
619 print STDERR "\n\n$progname: picking from $search_url\n";
623 my ( $base, $body ) = get_document ($search_url, undef, $timeout);
624 if (defined ($timeout)) {
625 $timeout -= (time - $start);
632 return () if (! $body);
638 my $search_count = "?";
640 $body =~ m@found (approximately |about )?(<B>)?(\d+)(</B>)? image@) {
642 } elsif ($which == 1 && $body =~ m@<NOBR>((\d{1,3})(,\d{3})*) @i) {
644 } elsif ($which == 2 && $body =~ m@found ((\d{1,3})(,\d{3})*|\d+) Web p@) {
647 1 while ($search_count =~ s/^(\d+)(\d{3})/$1,$2/);
649 my $length = length($body);
654 s/Result [Pp]ages:.*$//s; # trim off page footer
655 s/^.*?IMAGE RESULTS//s; # trim off page header
660 foreach (split(/\n/)) {
662 my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
664 if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; } # quoted string
665 elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; } # or token
668 # Kludge to decode HotBot pages
669 next unless ($u =~ m@/director\.asp\?target=(http%3A[^&>]+)@);
673 next unless ($u =~ m@^http://@i); # skip non-http and relative urls.
675 next if ($u =~ m@[/.]altavista\.com@i); # skip altavista builtins
676 next if ($u =~ m@[/.]av\.com@i);
677 next if ($u =~ m@[/.]virage\.com@i);
678 next if ($u =~ m@[/.]photoloft\.com@i);
679 next if ($u =~ m@[/.]shopping\.com@i);
680 next if ($u =~ m@[/.]thetrip\.com@i);
681 next if ($u =~ m@[/.]cmgi\.com@i);
682 next if ($u =~ m@[/.]intelihealth\.com@i);
683 next if ($u =~ m@[/.]wildweb\.com@i);
684 next if ($u =~ m@[/.]digital\.com@i);
685 next if ($u =~ m@[/.]doubleclick\.net@i);
687 if ($which == 0 && $u =~ m@[/.]corbis\.com@) {
689 if ( $verbose > 3 ) {
690 print STDERR "$progname: skipping corbis URL: $u\n";
694 } elsif ( $rejected_urls{$u} ) {
695 if ( $verbose > 3 ) {
696 my $L = $rejected_urls{$u};
697 print STDERR "$progname: pre-rejecting sub-page: $u\n";
701 } elsif ( $verbose > 3 ) {
702 print STDERR "$progname: sub-page: $u\n";
705 $subpages[++$#subpages] = $u;
708 if ( $#subpages < 0 ) {
709 if (!$skipped && $verbose > 1) {
710 print STDERR "$progname: found nothing on $base " .
711 "($length bytes, $href_count links).\n";
718 # pick a random element of the table
719 my $i = ((rand() * 99999) % ($#subpages + 1));
720 my $subpage = $subpages[$i];
722 if ( $verbose > 3 ) {
723 print STDERR "$progname: picked page $subpage\n";
730 my ( $base2, $body2 ) = get_document ($subpage, $base, $timeout);
732 if (!$base2 || !$body2) {
737 my $img = pick_image_from_body ($base2, $body2);
741 return ($base2, $img,
742 ($which == 0 ? "imagevista" :
743 $which == 1 ? "hotbot" : "altavista") .
751 # Using the photo site, generate a random URL that will hopefully point
752 # to an image. Returns two URLs, both of which are the URL of the image.
753 # Returns () if nothing found this time.
755 #sub pick_from_photo_randomizer {
756 # my ( $timeout ) = @_;
757 # my $n = ($photo_randomizer_lo +
758 # int(rand() * ($photo_randomizer_hi - $photo_randomizer_lo)));
759 # my $url = $photo_randomizer . $n;
760 # return ( $url, $url, "photopoint" );
764 # Picks a random image on a random page, and returns two URLs:
765 # the page containing the image, and the image.
766 # Returns () if nothing found this time.
767 # Uses the url-randomizer 1 time in 5, else the image randomizer.
781 my ( $timeout ) = @_;
783 my $r = int(rand(100));
784 my ($base, $img, $source, $total, $count);
787 ($base, $img, $source) = pick_from_url_randomizer ($timeout);
789 $count = ++$count_0 if $img;
792 ($base, $img, $source) = pick_from_image_randomizer ($timeout, 0);
794 $count = ++$count_1 if $img;
796 # } elsif ($r < 70) {
797 # ($base, $img, $source) = pick_from_photo_randomizer ($timeout);
798 # $total = ++$total_4;
799 # $count = ++$count_4 if $img;
801 # } elsif ($r < 80) {
802 # # HotBot sucks: 98% of the time, it says "no pages match your
803 # # search", and then if I load the URL again by hand, it works.
804 # # I don't understand what's going wrong here, but we're not getting
805 # # any good data back from them, so forget it for now.
807 # ($base, $img, $source) = pick_from_image_randomizer ($timeout, 1);
808 # $total = ++$total_2;
809 # $count = ++$count_2 if $img;
812 ($base, $img, $source) = pick_from_image_randomizer ($timeout, 2);
814 $count = ++$count_3 if $img;
817 if ($source && $total > 0) {
818 $source .= " " . int(($count / $total) * 100) . "%";
820 return ($base, $img, $source);
829 s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
834 # Given the raw body of a GIF document, returns the dimensions of the image.
838 my $type = substr($body, 0, 6);
840 return () unless ($type =~ /GIF8[7,9]a/);
841 $s = substr ($body, 6, 10);
842 my ($a,$b,$c,$d) = unpack ("C"x4, $s);
843 return (($b<<8|$a), ($d<<8|$c));
846 # Given the raw body of a JPEG document, returns the dimensions of the image.
851 my $L = length($body);
853 my $c1 = substr($body, $i, 1); $i++;
854 my $c2 = substr($body, $i, 1); $i++;
855 return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
858 while (ord($ch) != 0xDA && $i < $L) {
859 # Find next marker, beginning with 0xFF.
860 while (ord($ch) != 0xFF) {
861 $ch = substr($body, $i, 1); $i++;
863 # markers can be padded with any number of 0xFF.
864 while (ord($ch) == 0xFF) {
865 $ch = substr($body, $i, 1); $i++;
868 # $ch contains the value of the marker.
869 my $marker = ord($ch);
871 if (($marker >= 0xC0) &&
874 ($marker != 0xCC)) { # it's a SOFn marker
876 my $s = substr($body, $i, 4); $i += 4;
877 my ($a,$b,$c,$d) = unpack("C"x4, $s);
878 return (($c<<8|$d), ($a<<8|$b));
881 # We must skip variables, since FFs in variable names aren't
882 # valid JPEG markers.
883 my $s = substr($body, $i, 2); $i += 2;
884 my ($c1, $c2) = unpack ("C"x2, $s);
885 my $length = ($c1 << 8) | $c2;
886 return () if ($length < 2);
893 # Given the raw body of a GIF or JPEG document, returns the dimensions of
898 my ($w, $h) = gif_size ($body);
899 if ($w && $h) { return ($w, $h); }
900 return jpeg_size ($body);
904 # returns the full path of the named program, or undef.
908 foreach (split (/:/, $ENV{PATH})) {
917 # Like rand(), but chooses numbers with a bell curve distribution.
920 $_ = 1.0 unless defined($_);
922 return (rand($_) + rand($_) + rand($_));
926 ##############################################################################
928 # Generating a list of urls only
930 ##############################################################################
932 sub url_only_output {
934 my ($base, $img) = pick_image;
938 print "$img $base\n";
943 ##############################################################################
945 # Running as an xscreensaver module
947 ##############################################################################
951 if ($verbose > 0) { print STDERR "$progname: caught signal $sig.\n"; }
952 unlink $image_ppm, $image_tmp1, $image_tmp2;
957 # Like system, but prints status about exit codes, and kills this process
958 # with whatever signal killed the sub-process, if any.
960 sub nontrapping_system {
965 s/\"[^\"]+\"/\"...\"/g;
966 print STDERR "$progname: executing \"$_\"\n";
973 print STDERR "$progname: subproc exited normally.\n";
975 } elsif (($rc & 0xff) == 0) {
978 print "$progname: subproc exited with status $rc.\n";
983 print "$progname: subproc dumped core.\n";
988 print "$progname: subproc died with signal $rc.\n";
990 # die that way ourselves.
998 # Given the URL of a GIF or JPEG image, and the body of that image, writes a
999 # PPM to the given output file. Returns the width/height of the image if
1003 my ($url, $body, $output) = @_;
1004 my ($cmd, $cmd2, $w, $h);
1006 if ((@_ = gif_size ($body))) {
1009 } elsif ((@_ = jpeg_size ($body))) {
1016 $cmd2 = "exec $cmd"; # yes, this really is necessary. if we don't
1017 # do this, the process doesn't die properly.
1018 if ($verbose == 0) {
1019 $cmd2 .= " 2>/dev/null";
1022 # There exist corrupted GIF and JPEG files that can make giftopnm and
1023 # djpeg lose their minds and go into a loop. So this gives those programs
1024 # a small timeout -- if they don't complete in time, kill them.
1030 local $SIG{ALRM} = sub {
1032 print STDERR "$progname: timed out ($cvt_timeout) for " .
1033 "$cmd on \"$url\" in pid $pid\n";
1035 kill ('TERM', $pid) if ($pid);
1040 if (($pid = open(PIPE, "| $cmd2 > $output"))) {
1047 if ($verbose > 3) { print STDERR "$progname: awaiting $pid\n"; }
1049 if ($verbose > 3) { print STDERR "$progname: $pid completed\n"; }
1052 my $size = (stat($output))[7];
1055 print STDERR "$progname: $cmd on ${w}x$h \"$url\" failed" .
1062 print STDERR "$progname: created ${w}x$h $output ($cmd)\n";
1066 print STDERR "$progname: $cmd failed: $!\n";
1070 die if ($@ && $@ ne "alarm\n"); # propagate errors
1085 my $win_cmd_1 = $ppm_to_root_window_cmd_1;
1086 my $win_cmd_2 = $ppm_to_root_window_cmd_2;
1087 my $win_cmd_3 = $ppm_to_root_window_cmd_3;
1088 $win_cmd_1 =~ s/^([^ \t\r\n]+).*$/$1/;
1089 $win_cmd_2 =~ s/^([^ \t\r\n]+).*$/$1/;
1090 $win_cmd_3 =~ s/^([^ \t\r\n]+).*$/$1/;
1092 # make sure the various programs we execute exist, right up front.
1093 foreach ("ppmmake", "giftopnm", "djpeg", "pnmpaste", "pnmscale",
1095 which ($_) || die "$progname: $_ not found on \$PATH.\n";
1098 if (which($win_cmd_1)) {
1099 $ppm_to_root_window_cmd = $ppm_to_root_window_cmd_1;
1100 } elsif (which($win_cmd_2)) {
1101 $ppm_to_root_window_cmd = $ppm_to_root_window_cmd_2;
1102 } elsif (which($win_cmd_3)) {
1103 $ppm_to_root_window_cmd = $ppm_to_root_window_cmd_3;
1105 die "$progname: didn't find $win_cmd_1, $win_cmd_2, or $win_cmd_3 on \$PATH.\n";
1108 $SIG{HUP} = \&x_cleanup;
1109 $SIG{INT} = \&x_cleanup;
1110 $SIG{QUIT} = \&x_cleanup;
1111 $SIG{ABRT} = \&x_cleanup;
1112 $SIG{KILL} = \&x_cleanup;
1113 $SIG{TERM} = \&x_cleanup;
1115 # Need this so that if giftopnm dies, we don't die.
1116 $SIG{PIPE} = 'IGNORE';
1118 if (!$img_width || !$img_height) {
1120 which ($_) || die "$progname: $_ not found on \$PATH.\n";
1122 ($img_width, $img_height) = m/dimensions: *(\d+)x(\d+) /;
1123 if (!defined($img_height)) {
1124 die "$progname: xdpyinfo failed.\n";
1128 my $bgcolor = "#000000";
1129 my $bgimage = undef;
1132 if ($background =~ m/^\#[0-9a-f]+$/i) {
1133 $bgcolor = $background;
1134 } elsif (-r $background) {
1135 $bgimage = $background;
1137 } elsif (! $background =~ m@^[-a-z0-9 ]+$@i) {
1138 print STDERR "$progname: not a color or readable file: " .
1142 # default to assuming it's a color
1143 $bgcolor = $background;
1147 # Create the sold-colored base image.
1149 $_ = "ppmmake '$bgcolor' $img_width $img_height";
1151 print STDERR "$progname: creating base image: $_\n";
1153 nontrapping_system "$_ > $image_ppm";
1155 # Paste the default background image in the middle of it.
1162 open(IMG, "<$bgimage") || die ("couldn't open $bgimage: $!\n");
1164 while (<IMG>) { $body .= $_; }
1166 if ((@_ = gif_size ($body))) {
1168 $cmd = "giftopnm |";
1169 } elsif ((@_ = jpeg_size ($body))) {
1172 } elsif ($body =~ "^P\d\n(\d+) (\d+)\n") {
1177 die "$progname: $bgimage is not a GIF, JPEG, or PPM.\n";
1180 my $x = int (($img_width - $iw) / 2);
1181 my $y = int (($img_height - $ih) / 2);
1183 print STDERR "$progname: pasting $bgimage (${iw}x$ih) into base ".
1187 $cmd .= "pnmpaste - $x $y $image_ppm > $image_tmp1";
1188 open (IMG, "| $cmd") || die ("running $cmd: $!\n");
1193 print STDERR "$progname: subproc exited normally.\n";
1195 rename ($image_tmp1, $image_ppm) ||
1196 die ("renaming $image_tmp1 to $image_ppm: $!\n");
1200 my ($base, $img, $source) = pick_image();
1202 my ($headers, $body) = get_document ($img, $base);
1204 handle_image ($base, $img, $body, $source);
1208 unlink $image_tmp1, $image_tmp2;
1214 my ($base, $img, $body, $source) = @_;
1217 print STDERR "$progname: got $img (" . length($body) . ")\n";
1220 my ($iw, $ih) = image_to_pnm ($img, $body, $image_tmp1);
1222 return 0 unless ($iw && $ih);
1224 my $ow = $iw; # used only for error messages
1227 # don't just tack this onto the front of the pipeline -- we want it to
1228 # be able to change the size of the input image.
1232 print STDERR "$progname: running $filter_cmd\n";
1235 my $rc = nontrapping_system "($filter_cmd) < $image_tmp1 >$image_tmp2";
1238 print STDERR "$progname: failed command: \"$filter_cmd\"\n";
1239 print STDERR "$progname: failed url: \"$img\" (${ow}x$oh)\n";
1243 rename ($image_tmp2, $image_tmp1);
1245 # re-get the width/height in case the filter resized it.
1247 open(IMG, "<$image_tmp1") || return 0;
1250 ($iw, $ih) = m/^(\d+) (\d+)$/;
1252 return 0 unless ($iw && $ih);
1255 my $target_w = $img_width;
1256 my $target_h = $img_height;
1261 # Usually scale the image to fit on the screen -- but sometimes scale it
1262 # to fit on half or a quarter of the screen. Note that we don't merely
1263 # scale it to fit, we instead cut it in half until it fits -- that should
1264 # give a wider distribution of sizes.
1266 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
1267 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
1269 if ($iw > $target_w || $ih > $target_h) {
1270 while ($iw > $target_w ||
1275 if ($iw <= 10 || $ih <= 10) {
1277 print STDERR "$progname: scaling to ${iw}x$ih would " .
1278 "have been bogus.\n";
1284 print STDERR "$progname: scaling to ${iw}x$ih\n";
1287 $cmd .= " | pnmscale -xsize $iw -ysize $ih";
1291 my $src = $image_tmp1;
1293 my $crop_x = 0; # the sub-rectangle of the image
1294 my $crop_y = 0; # that we will actually paste.
1298 # The chance that we will randomly crop out a section of an image starts
1299 # out fairly low, but goes up for images that are very large, or images
1300 # that have ratios that make them look like banners (we try to avoid
1301 # banner images entirely, but they slip through when the IMG tags didn't
1302 # have WIDTH and HEIGHT specified.)
1304 my $crop_chance = 0.2;
1305 if ($iw > $img_width * 0.4 || $ih > $img_height * 0.4) {
1306 $crop_chance += 0.2;
1308 if ($iw > $img_width * 0.7 || $ih > $img_height * 0.7) {
1309 $crop_chance += 0.2;
1311 if ($min_ratio && ($iw * $min_ratio) > $ih) {
1312 $crop_chance += 0.7;
1315 if ($verbose > 2 && $crop_chance > 0.1) {
1316 print STDERR "$progname: crop chance: $crop_chance\n";
1319 if (rand() < $crop_chance) {
1324 if ($crop_w > $min_width) {
1325 # if it's a banner, select the width linearly.
1326 # otherwise, select a bell.
1327 my $r = (($min_ratio && ($iw * $min_ratio) > $ih)
1330 $crop_w = $min_width + int ($r * ($crop_w - $min_width));
1331 $crop_x = int (rand() * ($ow - $crop_w));
1333 if ($crop_h > $min_height) {
1334 # height always selects as a bell.
1335 $crop_h = $min_height + int (bellrand() * ($crop_h - $min_height));
1336 $crop_y = int (rand() * ($oh - $crop_h));
1340 ($crop_x != 0 || $crop_y != 0 ||
1341 $crop_w != $iw || $crop_h != $ih)) {
1342 print STDERR "$progname: randomly cropping to " .
1343 "${crop_w}x$crop_h \@ $crop_x,$crop_y\n";
1347 # Where the image should logically land -- this might be negative.
1349 my $x = int((rand() * ($img_width + $crop_w/2)) - $crop_w*3/4);
1350 my $y = int((rand() * ($img_height + $crop_h/2)) - $crop_h*3/4);
1352 # if we have chosen to paste the image outside of the rectangle of the
1353 # screen, then we need to crop it.
1357 $x + $crop_w > $img_width ||
1358 $y + $crop_h > $img_height) {
1361 print STDERR "$progname: cropping for effective paste of " .
1362 "${crop_w}x$crop_h \@ $x,$y\n";
1365 if ($x < 0) { $crop_x -= $x; $crop_w += $x; $x = 0; }
1366 if ($y < 0) { $crop_y -= $y; $crop_h += $y; $y = 0; }
1368 if ($x + $crop_w >= $img_width) { $crop_w = $img_width - $x - 1; }
1369 if ($y + $crop_h >= $img_height) { $crop_h = $img_height - $y - 1; }
1372 # If any cropping needs to happen, add pnmcut.
1374 if ($crop_x != 0 || $crop_y != 0 ||
1375 $crop_w != $iw || $crop_h != $ih) {
1378 $cmd .= " | pnmcut $crop_x $crop_y $iw $ih";
1380 print STDERR "$progname: cropping to ${crop_w}x$crop_h \@ " .
1381 "$crop_x,$crop_y\n";
1386 print STDERR "$progname: pasting ${iw}x$ih \@ $x,$y in $image_ppm\n";
1389 $cmd .= " | pnmpaste - $x $y $image_ppm";
1391 $cmd =~ s@^ *\| *@@;
1392 my $rc = nontrapping_system "($cmd) < $image_tmp1 > $image_tmp2";
1396 print STDERR "$progname: failed command: \"$cmd\"\n";
1397 print STDERR "$progname: failed url: \"$img\" (${ow}x$oh)\n";
1402 rename ($image_tmp2, $image_ppm) || return;
1404 my $target = "$image_ppm";
1406 # don't just tack this onto the end of the pipeline -- we don't want it
1407 # to end up in $image_ppm, because we don't want the results to be
1410 if ($post_filter_cmd) {
1411 $target = $image_tmp1;
1412 $rc = nontrapping_system "($post_filter_cmd) < $image_ppm > $target";
1415 print STDERR "$progname: filter failed: " .
1416 "\"$post_filter_cmd\"\n";
1422 if (!$no_output_p) {
1423 my $tsize = (stat($target))[7];
1425 $cmd = $ppm_to_root_window_cmd;
1426 $cmd =~ s/%%PPM%%/$target/;
1428 # xv seems to hate being killed. it tends to forget to clean
1429 # up after itself, and leaves windows around and colors allocated.
1430 # I had this same problem with vidwhacker, and I'm not entirely
1431 # sure what I did to fix it. But, let's try this: launch xv
1432 # in the background, so that killing this process doesn't kill it.
1433 # it will die of its own accord soon enough. So this means we
1434 # start pumping bits to the root window in parallel with starting
1435 # the next network retrieval, which is probably a better thing
1440 $rc = nontrapping_system ($cmd);
1444 print STDERR "$progname: display failed: \"$cmd\"\n";
1449 } elsif ($verbose > 1) {
1450 print STDERR "$progname: $target size is $tsize\n";
1455 print STDOUT "image: ${iw}x${ih} @ $x,$y $base $source\n";
1468 # historical suckage: the environment variable name is lower case.
1469 $http_proxy = $ENV{http_proxy} || $ENV{HTTP_PROXY};
1471 while ($_ = $ARGV[0]) {
1473 if ($_ eq "-display" ||
1479 $ENV{DISPLAY} = shift @ARGV;
1480 } elsif ($_ eq "-root") {
1482 } elsif ($_ eq "-no-output") {
1484 } elsif ($_ eq "-urls-only") {
1487 } elsif ($_ eq "-verbose") {
1489 } elsif (m/^-v+$/) {
1490 $verbose += length($_)-1;
1491 } elsif ($_ eq "-delay") {
1492 $delay = shift @ARGV;
1493 } elsif ($_ eq "-timeout") {
1494 $http_timeout = shift @ARGV;
1495 } elsif ($_ eq "-filter") {
1496 $filter_cmd = shift @ARGV;
1497 } elsif ($_ eq "-filter2") {
1498 $post_filter_cmd = shift @ARGV;
1499 } elsif ($_ eq "-background" || $_ eq "-bg") {
1500 $background = shift @ARGV;
1501 } elsif ($_ eq "-size") {
1503 if (m@^(\d+)x(\d+)$@) {
1507 die "$progname: argument to \"-size\" must be" .
1508 " of the form \"640x400\"\n";
1510 } elsif ($_ eq "-proxy" || $_ eq "-http-proxy") {
1511 $http_proxy = shift @ARGV;
1513 die "$copyright\nusage: $progname [-root]" .
1514 " [-display dpy] [-root] [-verbose] [-timeout secs]\n" .
1515 "\t\t [-delay secs] [-filter cmd] [-filter2 cmd]\n" .
1516 "\t\t [-http-proxy host[:port]]\n";
1520 if ($http_proxy && $http_proxy eq "") {
1521 $http_proxy = undef;
1523 if ($http_proxy && $http_proxy =~ m@^http://([^/]*)/?$@ ) {
1524 # historical suckage: allow "http://host:port" as well as "host:port".
1528 if (!$root_p && !$no_output_p) {
1530 "$progname: the -root argument is mandatory (for now.)\n";
1533 if (!$no_output_p && !$ENV{DISPLAY}) {
1534 die "$progname: \$DISPLAY is not set.\n";