3 # webcollage, Copyright (c) 1999-2002 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\
24 # We can't "use diagnostics" here, because that library malfunctions if
25 # you signal and catch alarms: it says "Uncaught exception from user code"
26 # and exits, even though I damned well AM catching it!
33 use Fcntl ':flock'; # import LOCK_* constants
34 use POSIX qw(strftime);
37 my $progname = $0; $progname =~ s@.*/@@g;
38 my $version = q{ $Revision: 1.87 $ }; $version =~ s/^[^0-9]+([0-9.]+).*$/$1/;
39 my $copyright = "WebCollage $version, Copyright (c) 1999-2002" .
40 " Jamie Zawinski <jwz\@jwz.org>\n" .
41 " http://www.jwz.org/xscreensaver/\n";
45 my @search_methods = ( 30, "imagevista", \&pick_from_alta_vista_images,
46 28, "altavista", \&pick_from_alta_vista_text,
47 18, "yahoorand", \&pick_from_yahoo_random_link,
48 14, "googleimgs", \&pick_from_google_images,
49 2, "yahoonews", \&pick_from_yahoo_news_text,
50 8, "lycos", \&pick_from_lycos_text,
52 # Hotbot gives me "no matches" just about every time.
53 # Then I try the same URL again, and it works. I guess
54 # it caches searches, and webcollage always busts its
55 # cache and time out? Or it just sucks.
56 # 0, "hotbot", \&pick_from_hotbot_text,
59 # programs we can use to write to the root window (tried in ascending order.)
61 my @root_displayers = (
62 "chbg -once -xscreensaver -max_size 100",
63 "xv -root -quit -viewonly -noresetroot -quick24 -rmode 5" .
64 " -rfg black -rbg black",
65 "xli -quiet -onroot -center -border black",
66 "xloadimage -quiet -onroot -center -border black",
68 # this lame program wasn't built with vroot.h:
69 # "xsri -scale -keep-aspect -center-horizontal -center-vertical",
73 # Some sites need cookies to work properly. These are they.
76 "www.altavista.com" => "AV_ALL=1", # request uncensored searches
77 "web.altavista.com" => "AV_ALL=1",
79 # log in as "cipherpunk"
80 "www.nytimes.com" => 'NYT-S=18cHMIlJOn2Y1bu5xvEG3Ufuk6E1oJ.' .
81 'FMxWaQV0igaB5Yi/Q/guDnLeoL.pe7i1oakSb' .
82 '/VqfdUdb2Uo27Vzt1jmPn3cpYRlTw9',
86 # If this is set, it's a helper program to use for pasting images together:
87 # this is a lot faster and more efficient than using PPM pipelines, which is
88 # what we do if this program doesn't exist. (We check for "webcollage-helper"
89 # on $PATH at startup, and set this variable appropriately.)
91 my $webcollage_helper = undef;
94 # If we have the webcollage-helper program, then it will paste the images
95 # together with transparency! 0.0 is invisible, 1.0 is totally opaque.
100 # Some sites have managed to poison the search engines. These are they.
101 # (We auto-detect sites that have poisoned the search engines via excessive
102 # keywords or dictionary words, but these are ones that slip through
105 # This can contain full host names, or 2 or 3 component domains.
108 "die.net" => 1, # 'l33t h4ck3r d00dz.
109 "genforum.genealogy.com" => 1, # Cluttering altavista with human names.
110 "rootsweb.com" => 1, # Cluttering altavista with human names.
111 "akamai.net" => 1, # Lots of sites have their images on Akamai.
112 # But those are pretty much all banners.
113 # Since Akamai is super-expensive, let's
114 # go out on a limb and assume that all of
115 # their customers are rich-and-boring.
116 "bartleby.com" => 1, # Dictionary, cluttering altavista.
117 "encyclopedia.com" => 1, # Dictionary, cluttering altavista.
118 "onlinedictionary.datasegment.com" => 1, # Dictionary, cluttering altavista.
119 "hotlinkpics.com" => 1, # Porn site that has poisoned imagevista
120 # (I don't see how they did it, though!)
121 "alwayshotels.com" => 1, # Poisoned Lycos pretty heavily.
125 # When verbosity is turned on, we warn about sites that we seem to be hitting
126 # a lot: usually this means some new poisoner has made it into the search
127 # engines. But sometimes, the warning is just because that site has a lot
128 # of stuff on it. So these are the sites that are immune to the "frequent
129 # site" diagnostic message.
131 my %warningless_sites = (
132 "home.earthlink.net" => 1, # Lots of home pages here.
133 "www.geocities.com" => 1,
134 "www.angelfire.com" => 1,
135 "members.aol.com" => 1,
137 "yimg.com" => 1, # This is where dailynews.yahoo.com stores
138 "eimg.com" => 1, # its images, so pick_from_yahoo_news_text()
139 # hits this every time.
143 ##############################################################################
145 # Various global flags set by command line parameters, or computed
147 ##############################################################################
150 my $current_state = "???"; # for diagnostics
153 my $image_succeeded = -1;
154 my $suppress_audit = 0;
156 my $verbose_imgmap = 0; # print out rectangles and URLs only (stdout)
157 my $verbose_warnings = 0; # print out warnings when things go wrong
158 my $verbose_load = 0; # diagnostics about loading of URLs
159 my $verbose_filter = 0; # diagnostics about page selection/rejection
160 my $verbose_net = 0; # diagnostics about network I/O
161 my $verbose_pbm = 0; # diagnostics about PBM pipelines
162 my $verbose_http = 0; # diagnostics about all HTTP activity
163 my $verbose_exec = 0; # diagnostics about executing programs
165 my $report_performance_interval = 60 * 15; # print some stats every 15 minutes
167 my $http_proxy = undef;
168 my $http_timeout = 30;
169 my $cvt_timeout = 10;
175 my $min_gif_area = (120 * 120);
184 my @tripwire_words = ("aberrate", "abode", "amorphous", "antioch",
185 "arrhenius", "arteriole", "blanket", "brainchild",
186 "burdensome", "carnival", "cherub", "chord", "clever",
187 "dedicate", "dilogarithm", "dolan", "dryden",
191 ##############################################################################
195 ##############################################################################
197 # returns three values: the HTTP response line; the document headers;
198 # and the document body.
201 my ( $url, $referer, $timeout ) = @_;
203 if (!defined($timeout)) { $timeout = $http_timeout; }
204 if ($timeout > $http_timeout) { $timeout = $http_timeout; }
207 LOG (($verbose_net || $verbose_load), "timed out for $url");
211 LOG ($verbose_net, "get_document_1 $url " . ($referer ? $referer : ""));
213 if (! ($url =~ m@^http://@i)) {
214 LOG ($verbose_net, "not an HTTP URL: $url");
218 my ($url_proto, $dummy, $serverstring, $path) = split(/\//, $url, 4);
219 $path = "" unless $path;
221 my ($them,$port) = split(/:/, $serverstring);
222 $port = 80 unless $port;
227 $serverstring = $http_proxy if $http_proxy;
228 ($them2,$port2) = split(/:/, $serverstring);
229 $port2 = 80 unless $port2;
232 my ($remote, $iaddr, $paddr, $proto, $line);
234 if ($port2 =~ /\D/) { $port2 = getservbyname($port2, 'tcp') }
236 LOG (($verbose_net || $verbose_load), "unrecognised port in $url");
239 $iaddr = inet_aton($remote);
241 LOG (($verbose_net || $verbose_load), "host not found: $remote");
244 $paddr = sockaddr_in($port2, $iaddr);
252 local $SIG{ALRM} = sub {
253 LOG (($verbose_net || $verbose_load), "timed out ($timeout) for $url");
258 $proto = getprotobyname('tcp');
259 if (!socket(S, PF_INET, SOCK_STREAM, $proto)) {
260 LOG (($verbose_net || $verbose_load), "socket: $!");
263 if (!connect(S, $paddr)) {
264 LOG (($verbose_net || $verbose_load), "connect($serverstring): $!");
268 select(S); $| = 1; select(STDOUT);
270 my $cookie = $cookies{$them};
272 my $user_agent = "$progname/$version";
273 if ($url =~ m@^http://www\.altavista\.com/@) {
274 # block this, you turkeys.
275 $user_agent = "Mozilla/4.76 [en] (X11; U; Linux 2.2.16-22 i686; Nav)";
278 my $hdrs = "GET " . ($http_proxy ? $url : "/$path") . " HTTP/1.0\r\n" .
280 "User-Agent: $user_agent\r\n";
282 $hdrs .= "Referer: $referer\r\n";
285 my @cc = split(/\r?\n/, $cookie);
286 $hdrs .= "Cookie: " . join('; ', @cc) . "\r\n";
290 foreach (split('\r?\n', $hdrs)) {
291 LOG ($verbose_http, " ==> $_");
294 my $http = <S> || "";
298 LOG ($verbose_http, " <== $_");
304 LOG ($verbose_http, " <== $_");
306 if (m@^Set-cookie:\s*([^;\r\n]+)@i) {
307 set_cookie($them, $1)
318 " <== [ body ]: $lines lines, " . length($body) . " bytes");
323 LOG (($verbose_net || $verbose_load), "null response: $url");
327 return ( $http, $head, $body );
329 die if ($@ && $@ ne "alarm\n"); # propagate errors
344 # returns two values: the document headers; and the document body.
345 # if the given URL did a redirect, returns the redirected-to document.
348 my ( $url, $referer, $timeout ) = @_;
353 my $max_loop_count = 4;
356 if (defined($timeout) && $timeout <= 0) {
357 LOG (($verbose_net || $verbose_load), "timed out for $url");
362 my ( $http, $head, $body ) = get_document_1 ($url, $referer, $timeout);
364 if (defined ($timeout)) {
366 my $elapsed = $now - $start;
367 $timeout -= $elapsed;
371 return () unless $http; # error message already printed
373 $http =~ s/[\r\n]+$//s;
375 if ( $http =~ m@^HTTP/[0-9.]+ 30[123]@ ) {
377 my ( $location ) = m@^location:[ \t]*(.*)$@im;
379 $location =~ s/[\r\n]$//;
381 LOG ($verbose_net, "redirect from $url to $location");
386 $referer =~ m@^(http://[^/]+)@i;
388 } elsif (! ($url =~ m@^[a-z]+:@i)) {
390 s@[^/]+$@@g if m@^http://[^/]+/@i;
391 $_ .= "/" if m@^http://[^/]+$@i;
396 LOG ($verbose_net, "no Location with \"$http\"");
397 return ( $url, $body );
400 if ($loop_count++ > $max_loop_count) {
402 "too many redirects ($max_loop_count) from $orig_url");
407 } elsif ( $http =~ m@^HTTP/[0-9.]+ ([4-9][0-9][0-9].*)$@ ) {
409 LOG (($verbose_net || $verbose_load), "failed: $1 ($url)");
411 # http errors -- return nothing.
417 LOG (($verbose_net || $verbose_load), "document contains no data: $url");
423 return ( $url, $body );
429 # If we already have a cookie defined for this site, and the site is trying
430 # to overwrite that very same cookie, let it do so. This is because nytimes
431 # expires its cookies - it lets you upgrade to a new cookie without logging
432 # in again, but you have to present the old cookie to get the new cookie.
433 # So, by doing this, the built-in cypherpunks cookie will never go "stale".
436 my ($host, $cookie) = @_;
437 my $oc = $cookies{$host};
440 my ($oc_name, $oc_value) = m@^([^= \t\r\n]+)=(.*)$@;
442 my ($nc_name, $nc_value) = m@^([^= \t\r\n]+)=(.*)$@;
444 if ($oc_name eq $nc_name &&
445 $oc_value ne $nc_value) {
446 $cookies{$host} = $cookie;
447 LOG ($verbose_net, "overwrote ${host}'s $oc_name cookie");
452 ############################################################################
454 # Extracting image URLs from HTML
456 ############################################################################
458 # given a URL and the body text at that URL, selects and returns a random
459 # image from it. returns () if no suitable images found.
461 sub pick_image_from_body {
462 my ( $url, $body ) = @_;
467 # if there's at least one slash after the host, take off the last
469 if ( m@^http://[^/]+/@io ) {
470 $base =~ s@[^/]+$@@go;
473 # if there are no slashes after the host at all, put one on the end.
474 if ( m@^http://[^/]+$@io ) {
480 # strip out newlines, compress whitespace
487 # There are certain web sites that list huge numbers of dictionary
488 # words in their bodies or in their <META NAME=KEYWORDS> tags (surprise!
489 # Porn sites tend not to be reputable!)
491 # I do not want webcollage to filter on content: I want it to select
492 # randomly from the set of images on the web. All the logic here for
493 # rejecting some images is really a set of heuristics for rejecting
494 # images that are not really images: for rejecting *text* that is in
495 # GIF/JPEG form. I don't want text, I want pictures, and I want the
496 # content of the pictures to be randomly selected from among all the
499 # So, filtering out "dirty" pictures by looking for "dirty" keywords
500 # would be wrong: dirty pictures exist, like it or not, so webcollage
501 # should be able to select them.
503 # However, picking a random URL is a hard thing to do. The mechanism I'm
504 # using is to search for a selection of random words. This is not
505 # perfect, but works ok most of the time. The way it breaks down is when
506 # some URLs get precedence because their pages list *every word* as
507 # related -- those URLs come up more often than others.
509 # So, after we've retrieved a URL, if it has too many keywords, reject
510 # it. We reject it not on the basis of what those keywords are, but on
511 # the basis that by having so many, the page has gotten an unfair
512 # advantage against our randomizer.
515 foreach my $trip (@tripwire_words) {
516 $trip_count++ if m/$trip/i;
519 if ($trip_count >= $#tripwire_words - 2) {
520 LOG (($verbose_filter || $verbose_load),
521 "there is probably a dictionary in \"$url\": rejecting.");
522 $rejected_urls{$url} = -1;
532 foreach (split(/ *</)) {
535 # Likewise, reject any web pages that have a KEYWORDS meta tag
538 if (m/name ?= ?\"?keywords\"?/i &&
539 m/content ?= ?\"([^\"]+)\"/) {
542 LOG (($verbose_filter || $verbose_load),
543 "excessive keywords ($L bytes) in $url: rejecting.");
544 $rejected_urls{$url} = $L;
549 LOG ($verbose_filter, " keywords ($L bytes) in $url (ok)");
553 } elsif ( m/^(img|a) .*(src|href) ?= ?\"? ?(.*?)[ >\"]/io ) {
555 my $was_inline = ( "$1" eq "a" || "$1" eq "A" );
557 my ( $width ) = m/width ?=[ \"]*(\d+)/oi;
558 my ( $height ) = m/height ?=[ \"]*(\d+)/oi;
563 ( $site = $base ) =~ s@^(http://[^/]*).*@$1@gio;
565 } elsif ( ! m@^[^/:?]+:@ ) {
568 while (s@/\.\./@/@g) {
573 if ( ! m@^http://@io ) {
578 if ( ! m@[.](gif|jpg|jpeg|pjpg|pjpeg)$@io ) {
582 # skip really short or really narrow images
583 if ( $width && $width < $min_width) {
584 if (!$height) { $height = "?"; }
585 LOG ($verbose_filter, " skip narrow image $_ (${width}x$height)");
589 if ( $height && $height < $min_height) {
590 if (!$width) { $width = "?"; }
591 LOG ($verbose_filter, " skip short image $_ (${width}x$height)");
595 # skip images with ratios that make them look like banners.
596 if ($min_ratio && $width && $height &&
597 ($width * $min_ratio ) > $height) {
598 if (!$height) { $height = "?"; }
599 LOG ($verbose_filter, " skip bad ratio $_ (${width}x$height)");
603 # skip GIFs with a small number of pixels -- those usually suck.
604 if ($width && $height &&
606 ($width * $height) < $min_gif_area) {
607 LOG ($verbose_filter, " skip small GIF $_ (${width}x$height)");
614 if ($unique_urls{$url}) {
615 LOG ($verbose_filter, " skip duplicate image $_");
619 LOG ($verbose_filter,
621 ($width && $height ? " (${width}x${height})" : "") .
622 ($was_inline ? " (inline)" : ""));
624 $urls[++$#urls] = $url;
625 $unique_urls{$url}++;
627 # jpegs are preferable to gifs.
629 if ( ! m@[.]gif$@io ) {
630 $urls[++$#urls] = $url;
633 # pointers to images are preferable to inlined images.
634 if ( ! $was_inline ) {
635 $urls[++$#urls] = $url;
636 $urls[++$#urls] = $url;
641 my $fsp = ($body =~ m@<frameset@i);
646 @urls = depoison (@urls);
649 LOG ($verbose_load, "no images on $base" . ($fsp ? " (frameset)" : ""));
653 # pick a random element of the table
654 my $i = int(rand($#urls+1));
657 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#urls+1) . ": $url");
664 ############################################################################
666 # Subroutines for getting pages and images out of search engines
668 ############################################################################
671 sub pick_dictionary {
672 my @dicts = ("/usr/dict/words",
673 "/usr/share/dict/words",
674 "/usr/share/lib/dict/words");
675 foreach my $f (@dicts) {
681 error ("$dicts[0] does not exist") unless defined($wordlist);
684 # returns a random word from the dictionary
688 if (open (IN, "<$wordlist")) {
689 my $size = (stat(IN))[7];
690 my $pos = rand $size;
691 if (seek (IN, $pos, 0)) {
692 $word = <IN>; # toss partial line
693 $word = <IN>; # keep next line
702 return 0 if (!$word);
704 $word =~ s/^[ \t\n\r]+//;
705 $word =~ s/[ \t\n\r]+$//;
710 $word =~ s/ally$/al/;
711 $word =~ s/izes$/ize/;
712 $word =~ tr/A-Z/a-z/;
714 if ( $word =~ s/[ \t\n\r]/\+/g ) { # convert intra-word spaces to "+".
715 $word = "\%22$word\%22"; # And put quotes (%22) around it.
723 my $sep = ($or_p ? "%20OR%20" : "%20");
724 return (random_word . $sep .
734 $s =~ s|([^-a-zA-Z0-9.\@/_\r\n])|sprintf("%%%02X", ord($1))|ge;
741 $s =~ s/%([a-z0-9]{2})/chr(hex($1))/ige;
746 # Loads the given URL (a search on some search engine) and returns:
747 # - the total number of hits the search engine claimed it had;
748 # - a list of URLs from the page that the search engine returned;
749 # Note that this list contains all kinds of internal search engine
750 # junk URLs too -- caller must prune them.
752 sub pick_from_search_engine {
753 my ( $timeout, $search_url, $words ) = @_;
758 print STDERR "\n\n" if ($verbose_load);
760 LOG ($verbose_load, "words: $_");
761 LOG ($verbose_load, "URL: $search_url");
763 $last_search = $search_url; # for warnings
766 my ( $base, $body ) = get_document ($search_url, undef, $timeout);
767 if (defined ($timeout)) {
768 $timeout -= (time - $start);
771 LOG (($verbose_net || $verbose_load),
772 "timed out (late) for $search_url");
778 return () if (! $body);
783 my $search_count = "?";
784 if ($body =~ m@found (approximately |about )?(<B>)?(\d+)(</B>)? image@) {
786 } elsif ($body =~ m@<NOBR>((\d{1,3})(,\d{3})*) @i) {
788 } elsif ($body =~ m@found ((\d{1,3})(,\d{3})*|\d+) Web p@) {
790 } elsif ($body =~ m@found about ((\d{1,3})(,\d{3})*|\d+) results@) {
792 } elsif ($body =~ m@\b\d+ - \d+ of (\d+)\b@i) { # imagevista
794 } elsif ($body =~ m@About ((\d{1,3})(,\d{3})*) images@i) { # imagevista
796 } elsif ($body =~ m@We found ((\d{1,3})(,\d{3})*|\d+) results@i) { # *vista
798 } elsif ($body =~ m@ of about <B>((\d{1,3})(,\d{3})*)<@i) { # googleimages
800 } elsif ($body =~ m@<B>((\d{1,3})(,\d{3})*)</B> Web sites were found@i) {
801 $search_count = $1; # lycos
802 } elsif ($body =~ m@WEB.*?RESULTS.*?\b((\d{1,3})(,\d{3})*)\b.*?Matches@i) {
803 $search_count = $1; # hotbot
804 } elsif ($body =~ m@no photos were found containing@i) { # imagevista
806 } elsif ($body =~ m@found no document matching@i) { # altavista
809 1 while ($search_count =~ s/^(\d+)(\d{3})/$1,$2/);
811 # if ($search_count eq "?" || $search_count eq "0") {
813 # my $file = "/tmp/wc.html";
814 # open(OUT, ">$file") || error ("writing $file: $!");
817 # print STDERR blurb() . "###### wrote $file\n";
821 my $length = length($body);
830 foreach (split(/\n/)) {
832 my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
835 if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; } # quoted string
836 elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; } # or token
838 if ( $rejected_urls{$u} ) {
839 LOG ($verbose_filter, " pre-rejecting candidate: $u");
843 LOG ($verbose_http, " HREF: $u");
845 $subpages[++$#subpages] = $u;
848 if ( $#subpages < 0 ) {
849 LOG ($verbose_filter,
850 "found nothing on $base ($length bytes, $href_count links).");
854 LOG ($verbose_filter, "" . $#subpages+1 . " links on $search_url");
856 return ($search_count, @subpages);
864 my ($h) = m@^http://([^/: \t\r\n]+)@i;
866 next unless defined($h);
868 if ($poisoners{$h}) {
869 LOG (($verbose_filter), " rejecting poisoner: $_");
872 if ($h =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
874 LOG (($verbose_filter), " rejecting poisoner: $_");
877 if ($h =~ m@([^.]+\.[^.]+)$@ &&
879 LOG (($verbose_filter), " rejecting poisoner: $_");
889 # given a list of URLs, picks one at random; loads it; and returns a
890 # random image from it.
891 # returns the url of the page loaded; the url of the image chosen;
892 # and a debugging description string.
894 sub pick_image_from_pages {
895 my ($base, $total_hit_count, $unfiltered_link_count, $timeout, @pages) = @_;
897 $total_hit_count = "?" unless defined($total_hit_count);
899 @pages = depoison (@pages);
901 "" . ($#pages+1) . " candidates of $unfiltered_link_count links" .
902 " ($total_hit_count total)");
904 return () if ($#pages < 0);
906 my $i = int(rand($#pages+1));
907 my $page = $pages[$i];
909 LOG ($verbose_load, "picked page $page");
913 my ( $base2, $body2 ) = get_document ($page, $base, $timeout);
915 if (!$base2 || !$body2) {
920 my $img = pick_image_from_body ($base2, $body2);
924 return ($base2, $img);
931 ############################################################################
933 # Pick images from random pages returned by the Yahoo Random Link
935 ############################################################################
938 my $yahoo_random_link = "http://random.yahoo.com/bin/ryl";
941 # Picks a random page; picks a random image on that page;
942 # returns two URLs: the page containing the image, and the image.
943 # Returns () if nothing found this time.
945 sub pick_from_yahoo_random_link {
946 my ( $timeout ) = @_;
948 print STDERR "\n\n" if ($verbose_load);
949 LOG ($verbose_load, "URL: $yahoo_random_link");
951 $last_search = $yahoo_random_link; # for warnings
955 my ( $base, $body ) = get_document ($yahoo_random_link, undef, $timeout);
956 if (!$base || !$body) {
961 LOG ($verbose_load, "redirected to: $base");
963 my $img = pick_image_from_body ($base, $body);
967 return ($base, $img);
974 ############################################################################
976 # Pick images by feeding random words into Alta Vista Image Search
978 ############################################################################
981 my $alta_vista_images_url = "http://www.altavista.com/cgi-bin/query" .
983 "&igrph=1" . # graphics
986 "&micat=1" . # no partner sites
987 "&imgset=1" . # no partner sites
988 "&stype=simage" . # do image search
989 "&mmW=1" . # unknown, but required
993 sub pick_from_alta_vista_images {
994 my ( $timeout ) = @_;
996 my $words = random_words(1);
997 my $page = (int(rand(9)) + 1);
998 my $search_url = $alta_vista_images_url . $words;
1001 $search_url .= "&pgno=" . $page; # page number
1002 $search_url .= "&stq=" . (($page-1) * 12); # first hit result on page
1005 my ($search_hit_count, @subpages) =
1006 pick_from_search_engine ($timeout, $search_url, $words);
1008 my @candidates = ();
1009 foreach my $u (@subpages) {
1011 # altavista is encoding their URLs now.
1013 m@^/r\?ck_sm=[a-zA-Z0-9]+\&ref=[a-zA-Z0-9]+(\&uid=[a-zA-Z0-9]+)?\&r=(.*)@);
1014 $u = url_unquote($2);
1016 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1017 next if ($u =~ m@[/.]altavista\.com\b@i); # skip altavista builtins
1018 next if ($u =~ m@[/.]doubleclick\.net\b@i); # you cretins
1019 next if ($u =~ m@[/.]clicktomarket\.com\b@i); # more cretins
1021 next if ($u =~ m@[/.]viewimages\.com\b@i); # stacked deck
1022 next if ($u =~ m@[/.]gettyimages\.com\b@i);
1024 LOG ($verbose_filter, " candidate: $u");
1025 push @candidates, $u;
1028 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1029 $timeout, @candidates);
1034 ############################################################################
1036 # Pick images by feeding random words into Google Image Search
1037 # By Charles Gales <gales@us.ibm.com>
1039 ############################################################################
1042 my $google_images_url = "http://images.google.com/images" .
1043 "?site=images" . # photos
1044 "&btnG=Search" . # graphics
1045 "&safe=off" . # no screening
1050 sub pick_from_google_images {
1051 my ( $timeout ) = @_;
1053 my $words = random_word; # only one word for Google
1054 my $page = (int(rand(9)) + 1);
1055 my $num = 20; # 20 images per page
1056 my $search_url = $google_images_url . $words;
1059 $search_url .= "&start=" . $page*$num; # page number
1060 $search_url .= "&num=" . $num; #images per page
1063 my ($search_hit_count, @subpages) =
1064 pick_from_search_engine ($timeout, $search_url, $words);
1066 my @candidates = ();
1067 foreach my $u (@subpages) {
1068 next unless ($u =~ m@imgres\?imgurl@i); # All pics start with this
1069 next if ($u =~ m@[/.]google\.com\b@i); # skip google builtins
1071 if ($u =~ m@^/imgres\?imgurl=(.*?)\&imgrefurl=(.*?)\&@) {
1073 LOG ($verbose_filter, " candidate: $urlf");
1074 push @candidates, $urlf;
1078 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1079 $timeout, @candidates);
1084 ############################################################################
1086 # Pick images by feeding random words into Alta Vista Text Search
1088 ############################################################################
1091 my $alta_vista_url_1 = "http://www.altavista.com/cgi-bin/query?pg=q" .
1092 "&text=yes&kl=XX&stype=stext&q=";
1093 my $alta_vista_url_2 = "http://www.altavista.com/sites/search/web?pg=q" .
1094 "&kl=XX&search=Search&q=";
1096 my $alta_vista_url = $alta_vista_url_2;
1099 sub pick_from_alta_vista_text {
1100 my ( $timeout ) = @_;
1102 my $words = random_words(1);
1103 my $page = (int(rand(9)) + 1);
1104 my $search_url = $alta_vista_url . $words;
1107 $search_url .= "&pgno=" . $page;
1108 $search_url .= "&stq=" . (($page-1) * 10);
1111 my ($search_hit_count, @subpages) =
1112 pick_from_search_engine ($timeout, $search_url, $words);
1114 my @candidates = ();
1115 foreach my $u (@subpages) {
1117 # Those altavista fuckers are playing really nasty redirection games
1118 # these days: the filter your clicks through their site, but use
1119 # onMouseOver to make it look like they're not! Well, it makes it
1120 # easier for us to identify search results...
1123 m@^/r\?ck_sm=[a-zA-Z0-9]+\&ref=[a-zA-Z0-9]+\&uid=[a-zA-Z0-9]+\&r=(.*)@);
1124 $u = url_unquote($1);
1126 LOG ($verbose_filter, " candidate: $u");
1127 push @candidates, $u;
1130 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1131 $timeout, @candidates);
1136 ############################################################################
1138 # Pick images by feeding random words into Hotbot
1140 ############################################################################
1142 my $hotbot_search_url = "http://hotbot.lycos.com/" .
1154 sub pick_from_hotbot_text {
1155 my ( $timeout ) = @_;
1157 my $words = random_words(0);
1158 my $search_url = $hotbot_search_url . $words;
1160 my ($search_hit_count, @subpages) =
1161 pick_from_search_engine ($timeout, $search_url, $words);
1163 my @candidates = ();
1164 foreach my $u (@subpages) {
1166 # Hotbot plays redirection games too
1167 next unless ($u =~ m@^/director.asp\?target=([^&]+)@);
1168 $u = url_decode($1);
1170 LOG ($verbose_filter, " candidate: $u");
1171 push @candidates, $u;
1174 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1175 $timeout, @candidates);
1180 ############################################################################
1182 # Pick images by feeding random words into Lycos
1184 ############################################################################
1186 my $lycos_search_url = "http://lycospro.lycos.com/srchpro/" .
1191 sub pick_from_lycos_text {
1192 my ( $timeout ) = @_;
1194 my $words = random_words(0);
1195 my $start = int(rand(8)) * 10 + 1;
1196 my $search_url = $lycos_search_url . $words . "&start=$start";
1198 my ($search_hit_count, @subpages) =
1199 pick_from_search_engine ($timeout, $search_url, $words);
1201 my @candidates = ();
1202 foreach my $u (@subpages) {
1204 # Lycos plays exact the same redirection game as hotbot.
1205 # Note that "id=0" is used for internal advertising links,
1206 # and 1+ are used for search results.
1207 next unless ($u =~ m@^http://click.hotbot.com/director.asp\?id=[1-9]\d*&target=([^&]+)@);
1208 $u = url_decode($1);
1210 LOG ($verbose_filter, " candidate: $u");
1211 push @candidates, $u;
1214 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1215 $timeout, @candidates);
1220 ############################################################################
1222 # Pick images by feeding random words into news.yahoo.com
1224 ############################################################################
1226 my $yahoo_news_url = "http://search.news.yahoo.com/search/news_photos?" .
1227 "&z=&n=100&o=o&2=&3=&p=";
1230 sub pick_from_yahoo_news_text {
1231 my ( $timeout ) = @_;
1233 my $words = random_words(1);
1234 my $search_url = $yahoo_news_url . $words;
1236 my ($search_hit_count, @subpages) =
1237 pick_from_search_engine ($timeout, $search_url, $words);
1239 my @candidates = ();
1240 foreach my $u (@subpages) {
1241 # only accept URLs on Yahoo's news site
1242 next unless ($u =~ m@^http://dailynews\.yahoo\.com/@i ||
1243 $u =~ m@^http://story\.news\.yahoo\.com/@i);
1245 LOG ($verbose_filter, " candidate: $u");
1246 push @candidates, $u;
1249 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1250 $timeout, @candidates);
1256 ############################################################################
1258 # Pick a random image in a random way
1260 ############################################################################
1263 # Picks a random image on a random page, and returns two URLs:
1264 # the page containing the image, and the image.
1265 # Returns () if nothing found this time.
1266 # Uses the url-randomizer 1 time in 5, else the image randomizer.
1270 my ( $timeout ) = @_;
1272 $current_state = "select";
1273 $load_method = "none";
1275 my $n = int(rand(100));
1278 my @rest = @search_methods;
1281 my $pct = shift @rest;
1282 my $name = shift @rest;
1283 my $tfn = shift @rest;
1285 if ($total > $n && !defined($fn)) {
1287 $current_state = $name;
1288 $load_method = $current_state;
1292 if ($total != 100) {
1293 error ("internal error: \@search_methods totals to $total%!");
1296 record_attempt ($current_state);
1297 return $fn->($timeout);
1302 ############################################################################
1304 # Statistics and logging
1306 ############################################################################
1309 return strftime ("%H:%M:%S: ", localtime);
1313 return "$progname: " . timestr() . "$current_state: ";
1318 print STDERR blurb() . "$err\n";
1330 my $head = "$progname: DEBUG: ";
1331 foreach (split (/\n/, $lastlog)) {
1332 print STDERR "$head$_\n";
1338 my ($print, $msg) = @_;
1339 my $blurb = timestr() . "$current_state: ";
1340 $lastlog .= "$blurb$msg\n";
1341 print STDERR "$progname: $blurb$msg\n" if $print;
1346 my %stats_successes;
1349 my $last_state = undef;
1350 sub record_attempt {
1354 record_failure($last_state) unless ($image_succeeded > 0);
1356 $last_state = $name;
1359 report_performance();
1362 $image_succeeded = 0;
1363 $suppress_audit = 0;
1366 sub record_success {
1367 my ($name, $url, $base) = @_;
1368 if (defined($stats_successes{$name})) {
1369 $stats_successes{$name}++;
1371 $stats_successes{$name} = 1;
1374 stop_timer ($name, 1);
1375 my $o = $current_state;
1376 $current_state = $name;
1377 save_recent_url ($url, $base);
1378 $current_state = $o;
1379 $image_succeeded = 1;
1384 sub record_failure {
1387 return if $image_succeeded;
1389 stop_timer ($name, 0);
1390 if ($verbose_load && !$verbose_exec) {
1392 if ($suppress_audit) {
1393 print STDERR "$progname: " . timestr() . "(audit log suppressed)\n";
1397 my $o = $current_state;
1398 $current_state = "DEBUG";
1400 my $line = "#" x 78;
1401 print STDERR "\n\n\n";
1402 print STDERR ("#" x 78) . "\n";
1403 print STDERR blurb() . "failed to get an image. Full audit log:\n";
1406 print STDERR ("-" x 78) . "\n";
1407 print STDERR "\n\n";
1409 $current_state = $o;
1411 $image_succeeded = 0;
1418 my $i = $stats_successes{$name};
1419 my $j = $stats_attempts{$name};
1422 return "" . ($j ? int($i * 100 / $j) : "0") . "%";
1426 my $current_start_time = 0;
1430 $current_start_time = time;
1432 if (defined($stats_attempts{$name})) {
1433 $stats_attempts{$name}++;
1435 $stats_attempts{$name} = 1;
1437 if (!defined($stats_elapsed{$name})) {
1438 $stats_elapsed{$name} = 0;
1443 my ($name, $success) = @_;
1444 $stats_elapsed{$name} += time - $current_start_time;
1448 my $last_report_time = 0;
1449 sub report_performance {
1451 return unless $verbose_warnings;
1454 return unless ($now >= $last_report_time + $report_performance_interval);
1455 my $ot = $last_report_time;
1456 $last_report_time = $now;
1458 return if ($ot == 0);
1460 my $blurb = "$progname: " . timestr();
1463 print STDERR "${blurb}Current standings:\n";
1465 foreach my $name (sort keys (%stats_attempts)) {
1466 my $try = $stats_attempts{$name};
1467 my $suc = $stats_successes{$name} || 0;
1468 my $pct = int($suc * 100 / $try);
1469 my $secs = $stats_elapsed{$name};
1470 my $secs_link = int($secs / $try);
1471 print STDERR sprintf ("$blurb %-12s %4s (%d/%d);\t %2d secs/link\n",
1472 "$name:", "$pct%", $suc, $try, $secs_link);
1478 my $max_recent_images = 400;
1479 my $max_recent_sites = 20;
1480 my @recent_images = ();
1481 my @recent_sites = ();
1483 sub save_recent_url {
1484 my ($url, $base) = @_;
1486 return unless ($verbose_warnings);
1489 my ($site) = m@^http://([^ \t\n\r/:]+)@;
1492 foreach (@recent_images) {
1494 print STDERR blurb() . "WARNING: recently-duplicated image: $url" .
1495 " (on $base via $last_search)\n";
1501 # suppress "duplicate site" warning via %warningless_sites.
1503 if ($warningless_sites{$site}) {
1505 } elsif ($site =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
1506 $warningless_sites{$1}) {
1508 } elsif ($site =~ m@([^.]+\.[^.]+)$@ &&
1509 $warningless_sites{$1}) {
1514 foreach (@recent_sites) {
1516 print STDERR blurb() . "WARNING: recently-duplicated site: $site" .
1517 " ($url on $base via $last_search)\n";
1523 push @recent_images, $url;
1524 push @recent_sites, $site;
1525 shift @recent_images if ($#recent_images >= $max_recent_images);
1526 shift @recent_sites if ($#recent_sites >= $max_recent_sites);
1531 ##############################################################################
1535 ##############################################################################
1542 s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
1547 # Given the raw body of a GIF document, returns the dimensions of the image.
1551 my $type = substr($body, 0, 6);
1553 return () unless ($type =~ /GIF8[7,9]a/);
1554 $s = substr ($body, 6, 10);
1555 my ($a,$b,$c,$d) = unpack ("C"x4, $s);
1556 return (($b<<8|$a), ($d<<8|$c));
1559 # Given the raw body of a JPEG document, returns the dimensions of the image.
1564 my $L = length($body);
1566 my $c1 = substr($body, $i, 1); $i++;
1567 my $c2 = substr($body, $i, 1); $i++;
1568 return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
1571 while (ord($ch) != 0xDA && $i < $L) {
1572 # Find next marker, beginning with 0xFF.
1573 while (ord($ch) != 0xFF) {
1574 $ch = substr($body, $i, 1); $i++;
1576 # markers can be padded with any number of 0xFF.
1577 while (ord($ch) == 0xFF) {
1578 $ch = substr($body, $i, 1); $i++;
1581 # $ch contains the value of the marker.
1582 my $marker = ord($ch);
1584 if (($marker >= 0xC0) &&
1585 ($marker <= 0xCF) &&
1586 ($marker != 0xC4) &&
1587 ($marker != 0xCC)) { # it's a SOFn marker
1589 my $s = substr($body, $i, 4); $i += 4;
1590 my ($a,$b,$c,$d) = unpack("C"x4, $s);
1591 return (($c<<8|$d), ($a<<8|$b));
1594 # We must skip variables, since FFs in variable names aren't
1595 # valid JPEG markers.
1596 my $s = substr($body, $i, 2); $i += 2;
1597 my ($c1, $c2) = unpack ("C"x2, $s);
1598 my $length = ($c1 << 8) | $c2;
1599 return () if ($length < 2);
1606 # Given the raw body of a GIF or JPEG document, returns the dimensions of
1611 my ($w, $h) = gif_size ($body);
1612 if ($w && $h) { return ($w, $h); }
1613 return jpeg_size ($body);
1617 # returns the full path of the named program, or undef.
1621 foreach (split (/:/, $ENV{PATH})) {
1622 if (-x "$_/$prog") {
1630 # Like rand(), but chooses numbers with a bell curve distribution.
1633 $_ = 1.0 unless defined($_);
1635 return (rand($_) + rand($_) + rand($_));
1639 ##############################################################################
1641 # Generating a list of urls only
1643 ##############################################################################
1645 sub url_only_output {
1647 my ($base, $img) = pick_image;
1651 print "$img $base\n";
1656 ##############################################################################
1658 # Running as an xscreensaver module
1660 ##############################################################################
1662 my $image_ppm = ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp") . "/webcollage." . $$;
1663 my $image_tmp1 = $image_ppm . "-1";
1664 my $image_tmp2 = $image_ppm . "-2";
1666 my $filter_cmd = undef;
1667 my $post_filter_cmd = undef;
1668 my $background = undef;
1670 my $img_width; # size of the image being generated.
1678 print STDERR blurb() . "caught signal $sig.\n" if ($verbose_exec);
1679 unlink $image_ppm, $image_tmp1, $image_tmp2;
1684 # Like system, but prints status about exit codes, and kills this process
1685 # with whatever signal killed the sub-process, if any.
1687 sub nontrapping_system {
1691 s/\"[^\"]+\"/\"...\"/g;
1693 LOG ($verbose_exec, "executing \"$_\"");
1698 LOG ($verbose_exec, "subproc exited normally.");
1699 } elsif (($rc & 0xff) == 0) {
1701 LOG ($verbose_exec, "subproc exited with status $rc.");
1704 LOG ($verbose_exec, "subproc dumped core.");
1707 LOG ($verbose_exec, "subproc died with signal $rc.");
1708 # die that way ourselves.
1716 # Given the URL of a GIF or JPEG image, and the body of that image, writes a
1717 # PPM to the given output file. Returns the width/height of the image if
1721 my ($url, $body, $output) = @_;
1722 my ($cmd, $cmd2, $w, $h);
1724 if ((@_ = gif_size ($body))) {
1727 } elsif ((@_ = jpeg_size ($body))) {
1731 LOG (($verbose_pbm || $verbose_load),
1732 "not a GIF or JPG" .
1733 (($body =~ m@<(base|html|head|body|script|table|a href)>@i)
1734 ? " (looks like HTML)" : "") .
1736 $suppress_audit = 1;
1740 $cmd2 = "exec $cmd"; # yes, this really is necessary. if we don't
1741 # do this, the process doesn't die properly.
1742 if (!$verbose_pbm) {
1744 # We get a "giftopnm: got a 'Application Extension' extension"
1745 # warning any time it's an animgif.
1747 # Note that "giftopnm: EOF / read error on image data" is not
1748 # always a fatal error -- sometimes the image looks fine anyway.
1750 $cmd2 .= " 2>/dev/null";
1753 # There exist corrupted GIF and JPEG files that can make giftopnm and
1754 # djpeg lose their minds and go into a loop. So this gives those programs
1755 # a small timeout -- if they don't complete in time, kill them.
1761 local $SIG{ALRM} = sub {
1763 "timed out ($cvt_timeout) for $cmd on \"$url\" in pid $pid");
1764 kill ('TERM', $pid) if ($pid);
1769 if (($pid = open(PIPE, "| $cmd2 > $output"))) {
1776 LOG ($verbose_exec, "awaiting $pid");
1778 LOG ($verbose_exec, "$pid completed");
1780 my $size = (stat($output))[7];
1781 $size = -1 unless defined($size);
1783 LOG ($verbose_pbm, "$cmd on ${w}x$h \"$url\" failed ($size bytes)");
1787 LOG ($verbose_pbm, "created ${w}x$h $output ($cmd)");
1790 print STDERR blurb() . "$cmd failed: $!\n";
1794 die if ($@ && $@ ne "alarm\n"); # propagate errors
1807 sub pick_root_displayer {
1810 foreach my $cmd (@root_displayers) {
1812 my ($name) = m/^([^ ]+)/;
1813 push @names, "\"$name\"";
1814 LOG ($verbose_exec, "looking for $name...");
1815 foreach my $dir (split (/:/, $ENV{PATH})) {
1816 LOG ($verbose_exec, " checking $dir/$name");
1817 return $cmd if (-x "$dir/$name");
1821 $names[$#names] = "or " . $names[$#names];
1822 error "none of: " . join (", ", @names) . " were found on \$PATH.";
1826 my $ppm_to_root_window_cmd = undef;
1829 sub x_or_pbm_output {
1831 # Check for our helper program, to see whether we need to use PPM pipelines.
1833 $_ = "webcollage-helper";
1834 if (defined ($webcollage_helper) || which ($_)) {
1835 $webcollage_helper = $_ unless (defined($webcollage_helper));
1836 LOG ($verbose_pbm, "found \"$webcollage_helper\"");
1837 $webcollage_helper .= " -v";
1839 LOG (($verbose_pbm || $verbose_load), "no $_ program");
1842 # make sure the various programs we execute exist, right up front.
1844 my @progs = ("ppmmake"); # always need this one
1846 if (!defined($webcollage_helper)) {
1847 # Only need these others if we don't have the helper.
1848 @progs = (@progs, "giftopnm", "djpeg", "pnmpaste", "pnmscale", "pnmcut");
1852 which ($_) || error "$_ not found on \$PATH.";
1855 # find a root-window displayer program.
1857 $ppm_to_root_window_cmd = pick_root_displayer();
1860 $SIG{HUP} = \&x_cleanup;
1861 $SIG{INT} = \&x_cleanup;
1862 $SIG{QUIT} = \&x_cleanup;
1863 $SIG{ABRT} = \&x_cleanup;
1864 $SIG{KILL} = \&x_cleanup;
1865 $SIG{TERM} = \&x_cleanup;
1867 # Need this so that if giftopnm dies, we don't die.
1868 $SIG{PIPE} = 'IGNORE';
1870 if (!$img_width || !$img_height) {
1872 which ($_) || error "$_ not found on \$PATH.";
1874 ($img_width, $img_height) = m/dimensions: *(\d+)x(\d+) /;
1875 if (!defined($img_height)) {
1876 error "xdpyinfo failed.";
1880 my $bgcolor = "#000000";
1881 my $bgimage = undef;
1884 if ($background =~ m/^\#[0-9a-f]+$/i) {
1885 $bgcolor = $background;
1887 } elsif (-r $background) {
1888 $bgimage = $background;
1890 } elsif (! $background =~ m@^[-a-z0-9 ]+$@i) {
1891 error "not a color or readable file: $background";
1894 # default to assuming it's a color
1895 $bgcolor = $background;
1899 # Create the sold-colored base image.
1901 $_ = "ppmmake '$bgcolor' $img_width $img_height";
1902 LOG ($verbose_pbm, "creating base image: $_");
1903 nontrapping_system "$_ > $image_ppm";
1905 # Paste the default background image in the middle of it.
1912 open(IMG, "<$bgimage") || error "couldn't open $bgimage: $!";
1914 while (<IMG>) { $body .= $_; }
1917 if ((@_ = gif_size ($body))) {
1919 $cmd = "giftopnm |";
1921 } elsif ((@_ = jpeg_size ($body))) {
1925 } elsif ($body =~ m/^P\d\n(\d+) (\d+)\n/) {
1931 error "$bgimage is not a GIF, JPEG, or PPM.";
1934 my $x = int (($img_width - $iw) / 2);
1935 my $y = int (($img_height - $ih) / 2);
1937 "pasting $bgimage (${iw}x$ih) into base image at $x,$y");
1939 $cmd .= "pnmpaste - $x $y $image_ppm > $image_tmp1";
1940 open (IMG, "| $cmd") || error "running $cmd: $!";
1944 LOG ($verbose_exec, "subproc exited normally.");
1945 rename ($image_tmp1, $image_ppm) ||
1946 error "renaming $image_tmp1 to $image_ppm: $!";
1952 my ($base, $img) = pick_image();
1953 my $source = $current_state;
1954 $current_state = "loadimage";
1956 my ($headers, $body) = get_document ($img, $base);
1958 paste_image ($base, $img, $body, $source);
1962 $current_state = "idle";
1963 $load_method = "none";
1965 unlink $image_tmp1, $image_tmp2;
1971 my ($base, $img, $body, $source) = @_;
1973 $current_state = "paste";
1975 $suppress_audit = 0;
1977 LOG ($verbose_pbm, "got $img (" . length($body) . ")");
1981 if (defined ($webcollage_helper)) {
1983 ($iw, $ih) = image_size ($body);
1985 LOG (($verbose_pbm || $verbose_load),
1986 "not a GIF or JPG" .
1987 (($body =~ m@<(base|html|head|body|script|table|a href)>@i)
1988 ? " (looks like HTML)" : "") .
1990 $suppress_audit = 1;
1996 open (OUT, ">$image_tmp1") || error ("writing $image_tmp1: $!");
1997 print OUT $body || error ("writing $image_tmp1: $!");
1998 close OUT || error ("writing $image_tmp1: $!");
2001 ($iw, $ih) = image_to_pnm ($img, $body, $image_tmp1);
2004 LOG ($verbose_pbm, "unable to make PBM from $img");
2009 record_success ($load_method, $img, $base);
2012 my $ow = $iw; # used only for error messages
2015 # don't just tack this onto the front of the pipeline -- we want it to
2016 # be able to change the size of the input image.
2019 LOG ($verbose_pbm, "running $filter_cmd");
2021 my $rc = nontrapping_system "($filter_cmd) < $image_tmp1 >$image_tmp2";
2023 LOG(($verbose_pbm || $verbose_load), "failed command: \"$filter_cmd\"");
2024 LOG(($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
2027 rename ($image_tmp2, $image_tmp1);
2029 # re-get the width/height in case the filter resized it.
2031 open(IMG, "<$image_tmp1") || return 0;
2034 ($iw, $ih) = m/^(\d+) (\d+)$/;
2036 return 0 unless ($iw && $ih);
2039 my $target_w = $img_width;
2040 my $target_h = $img_height;
2046 # Usually scale the image to fit on the screen -- but sometimes scale it
2047 # to fit on half or a quarter of the screen. Note that we don't merely
2048 # scale it to fit, we instead cut it in half until it fits -- that should
2049 # give a wider distribution of sizes.
2051 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; $scale /= 2; }
2052 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; $scale /= 2; }
2054 if ($iw > $target_w || $ih > $target_h) {
2055 while ($iw > $target_w ||
2060 if ($iw <= 10 || $ih <= 10) {
2061 LOG ($verbose_pbm, "scaling to ${iw}x$ih would have been bogus.");
2065 LOG ($verbose_pbm, "scaling to ${iw}x$ih");
2067 $cmd .= " | pnmscale -xsize $iw -ysize $ih";
2071 my $src = $image_tmp1;
2073 my $crop_x = 0; # the sub-rectangle of the image
2074 my $crop_y = 0; # that we will actually paste.
2078 # The chance that we will randomly crop out a section of an image starts
2079 # out fairly low, but goes up for images that are very large, or images
2080 # that have ratios that make them look like banners (we try to avoid
2081 # banner images entirely, but they slip through when the IMG tags didn't
2082 # have WIDTH and HEIGHT specified.)
2084 my $crop_chance = 0.2;
2085 if ($iw > $img_width * 0.4 || $ih > $img_height * 0.4) {
2086 $crop_chance += 0.2;
2088 if ($iw > $img_width * 0.7 || $ih > $img_height * 0.7) {
2089 $crop_chance += 0.2;
2091 if ($min_ratio && ($iw * $min_ratio) > $ih) {
2092 $crop_chance += 0.7;
2095 if ($crop_chance > 0.1) {
2096 LOG ($verbose_pbm, "crop chance: $crop_chance");
2099 if (rand() < $crop_chance) {
2104 if ($crop_w > $min_width) {
2105 # if it's a banner, select the width linearly.
2106 # otherwise, select a bell.
2107 my $r = (($min_ratio && ($iw * $min_ratio) > $ih)
2110 $crop_w = $min_width + int ($r * ($crop_w - $min_width));
2111 $crop_x = int (rand() * ($ow - $crop_w));
2113 if ($crop_h > $min_height) {
2114 # height always selects as a bell.
2115 $crop_h = $min_height + int (bellrand() * ($crop_h - $min_height));
2116 $crop_y = int (rand() * ($oh - $crop_h));
2119 if ($crop_x != 0 || $crop_y != 0 ||
2120 $crop_w != $iw || $crop_h != $ih) {
2122 "randomly cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
2126 # Where the image should logically land -- this might be negative.
2128 my $x = int((rand() * ($img_width + $crop_w/2)) - $crop_w*3/4);
2129 my $y = int((rand() * ($img_height + $crop_h/2)) - $crop_h*3/4);
2131 # if we have chosen to paste the image outside of the rectangle of the
2132 # screen, then we need to crop it.
2136 $x + $crop_w > $img_width ||
2137 $y + $crop_h > $img_height) {
2140 "cropping for effective paste of ${crop_w}x$crop_h \@ $x,$y");
2142 if ($x < 0) { $crop_x -= $x; $crop_w += $x; $x = 0; }
2143 if ($y < 0) { $crop_y -= $y; $crop_h += $y; $y = 0; }
2145 if ($x + $crop_w >= $img_width) { $crop_w = $img_width - $x - 1; }
2146 if ($y + $crop_h >= $img_height) { $crop_h = $img_height - $y - 1; }
2149 # If any cropping needs to happen, add pnmcut.
2151 if ($crop_x != 0 || $crop_y != 0 ||
2152 $crop_w != $iw || $crop_h != $ih) {
2155 $cmd .= " | pnmcut $crop_x $crop_y $iw $ih";
2156 LOG ($verbose_pbm, "cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
2159 LOG ($verbose_pbm, "pasting ${iw}x$ih \@ $x,$y in $image_ppm");
2161 $cmd .= " | pnmpaste - $x $y $image_ppm";
2163 $cmd =~ s@^ *\| *@@;
2165 if (defined ($webcollage_helper)) {
2166 $cmd = "$webcollage_helper $image_tmp1 $image_ppm " .
2167 "$scale $opacity " .
2168 "$crop_x $crop_y $x $y " .
2173 # use a PPM pipeline
2175 $_ .= " < $image_tmp1 > $image_tmp2";
2179 $_ = "($_) 2>&1 | sed s'/^/" . blurb() . "/'";
2181 $_ .= " 2> /dev/null";
2184 my $rc = nontrapping_system ($_);
2186 if (defined ($webcollage_helper) && -z $image_ppm) {
2187 LOG (1, "failed command: \"$cmd\"");
2188 print STDERR "\naudit log:\n\n\n";
2189 print STDERR ("#" x 78) . "\n";
2190 print STDERR blurb() . "$image_ppm has zero size\n";
2192 print STDERR "\n\n";
2197 LOG (($verbose_pbm || $verbose_load), "failed command: \"$cmd\"");
2198 LOG (($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
2202 if (!defined ($webcollage_helper)) {
2203 rename ($image_tmp2, $image_ppm) || return;
2206 my $target = "$image_ppm";
2208 # don't just tack this onto the end of the pipeline -- we don't want it
2209 # to end up in $image_ppm, because we don't want the results to be
2212 if ($post_filter_cmd) {
2213 $target = $image_tmp1;
2214 $rc = nontrapping_system "($post_filter_cmd) < $image_ppm > $target";
2216 LOG ($verbose_pbm, "filter failed: \"$post_filter_cmd\"\n");
2221 if (!$no_output_p) {
2222 my $tsize = (stat($target))[7];
2224 $cmd = "$ppm_to_root_window_cmd $target";
2226 # xv seems to hate being killed. it tends to forget to clean
2227 # up after itself, and leaves windows around and colors allocated.
2228 # I had this same problem with vidwhacker, and I'm not entirely
2229 # sure what I did to fix it. But, let's try this: launch xv
2230 # in the background, so that killing this process doesn't kill it.
2231 # it will die of its own accord soon enough. So this means we
2232 # start pumping bits to the root window in parallel with starting
2233 # the next network retrieval, which is probably a better thing
2238 $rc = nontrapping_system ($cmd);
2241 LOG (($verbose_pbm || $verbose_load), "display failed: \"$cmd\"");
2246 LOG ($verbose_pbm, "$target size is $tsize");
2250 $source .= "-" . stats_of($source);
2251 print STDOUT "image: ${iw}x${ih} @ $x,$y $base $source\n"
2252 if ($verbose_imgmap);
2267 $current_state = "init";
2268 $load_method = "none";
2272 # historical suckage: the environment variable name is lower case.
2273 $http_proxy = $ENV{http_proxy} || $ENV{HTTP_PROXY};
2275 while ($_ = $ARGV[0]) {
2277 if ($_ eq "-display" ||
2283 $ENV{DISPLAY} = shift @ARGV;
2284 } elsif ($_ eq "-root") {
2286 } elsif ($_ eq "-no-output") {
2288 } elsif ($_ eq "-urls-only") {
2291 } elsif ($_ eq "-verbose") {
2293 } elsif (m/^-v+$/) {
2294 $verbose += length($_)-1;
2295 } elsif ($_ eq "-delay") {
2296 $delay = shift @ARGV;
2297 } elsif ($_ eq "-timeout") {
2298 $http_timeout = shift @ARGV;
2299 } elsif ($_ eq "-filter") {
2300 $filter_cmd = shift @ARGV;
2301 } elsif ($_ eq "-filter2") {
2302 $post_filter_cmd = shift @ARGV;
2303 } elsif ($_ eq "-background" || $_ eq "-bg") {
2304 $background = shift @ARGV;
2305 } elsif ($_ eq "-size") {
2307 if (m@^(\d+)x(\d+)$@) {
2311 error "argument to \"-size\" must be of the form \"640x400\"";
2313 } elsif ($_ eq "-proxy" || $_ eq "-http-proxy") {
2314 $http_proxy = shift @ARGV;
2315 } elsif ($_ eq "-dictionary" || $_ eq "-dict") {
2316 $dict = shift @ARGV;
2317 } elsif ($_ eq "-debug" || $_ eq "--debug") {
2318 my $which = shift @ARGV;
2319 my @rest = @search_methods;
2322 my $pct = shift @rest;
2323 my $name = shift @rest;
2324 my $tfn = shift @rest;
2326 if ($name eq $which) {
2327 @search_methods = (100, $name, $tfn);
2332 error "no such search method as \"$which\"" unless ($ok);
2333 LOG (1, "DEBUG: using only \"$which\"");
2336 print STDERR "$copyright\nusage: $progname [-root]" .
2337 " [-display dpy] [-root] [-verbose] [-timeout secs]\n" .
2338 "\t\t [-delay secs] [-filter cmd] [-filter2 cmd]\n" .
2339 "\t\t [-dictionary dictionary-file]\n" .
2340 "\t\t [-http-proxy host[:port]]\n";
2345 if ($http_proxy && $http_proxy eq "") {
2346 $http_proxy = undef;
2348 if ($http_proxy && $http_proxy =~ m@^http://([^/]*)/?$@ ) {
2349 # historical suckage: allow "http://host:port" as well as "host:port".
2353 if (!$root_p && !$no_output_p) {
2354 print STDERR $copyright;
2355 error "the -root argument is mandatory (for now.)";
2358 if (!$no_output_p && !$ENV{DISPLAY}) {
2359 error "\$DISPLAY is not set.";
2363 if ($verbose == 1) {
2364 $verbose_imgmap = 1;
2365 $verbose_warnings = 1;
2367 } elsif ($verbose == 2) {
2368 $verbose_imgmap = 1;
2369 $verbose_warnings = 1;
2372 } elsif ($verbose == 3) {
2373 $verbose_imgmap = 1;
2374 $verbose_warnings = 1;
2376 $verbose_filter = 1;
2378 } elsif ($verbose == 4) {
2379 $verbose_imgmap = 1;
2380 $verbose_warnings = 1;
2382 $verbose_filter = 1;
2385 } elsif ($verbose == 5) {
2386 $verbose_imgmap = 1;
2387 $verbose_warnings = 1;
2389 $verbose_filter = 1;
2393 } elsif ($verbose == 6) {
2394 $verbose_imgmap = 1;
2395 $verbose_warnings = 1;
2397 $verbose_filter = 1;
2402 } elsif ($verbose >= 7) {
2403 $verbose_imgmap = 1;
2404 $verbose_warnings = 1;
2406 $verbose_filter = 1;
2414 error ("$dict does not exist") unless (-f $dict);