3 # webcollage, Copyright (c) 1999-2001 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.82 $ }; $version =~ s/^[^0-9]+([0-9.]+).*$/$1/;
39 my $copyright = "WebCollage $version, Copyright (c) 1999-2001" .
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 #@search_methods=(100, "googleimgs",\&pick_from_google_images);
61 # programs we can use to write to the root window (tried in ascending order.)
63 my @root_displayers = (
64 "xloadimage -quiet -onroot -center -border black",
65 "xli -quiet -onroot -center -border black",
66 "xv -root -quit -viewonly +noresetroot -rmode 5" .
67 " -rfg black -rbg black",
68 "chbg -once -xscreensaver",
70 # this lame program wasn't built with vroot.h:
71 # "xsri -scale -keep-aspect -center-horizontal -center-vertical",
75 # Some sites need cookies to work properly. These are they.
78 "www.altavista.com" => "AV_ALL=1", # request uncensored searches
79 "web.altavista.com" => "AV_ALL=1",
81 # log in as "cipherpunk"
82 "www.nytimes.com" => 'NYT-S=18cHMIlJOn2Y1bu5xvEG3Ufuk6E1oJ.' .
83 'FMxWaQV0igaB5Yi/Q/guDnLeoL.pe7i1oakSb' .
84 '/VqfdUdb2Uo27Vzt1jmPn3cpYRlTw9',
88 # Some sites have managed to poison the search engines. These are they.
89 # (We auto-detect sites that have poisoned the search engines via excessive
90 # keywords or dictionary words, but these are ones that slip through
93 # This can contain full host names, or 2 or 3 component domains.
96 "die.net" => 1, # 'l33t h4ck3r d00dz.
97 "genforum.genealogy.com" => 1, # Cluttering altavista with human names.
98 "rootsweb.com" => 1, # Cluttering altavista with human names.
99 "akamai.net" => 1, # Lots of sites have their images on Akamai.
100 # But those are pretty much all banners.
101 # Since Akamai is super-expensive, let's
102 # go out on a limb and assume that all of
103 # their customers are rich-and-boring.
104 "bartleby.com" => 1, # Dictionary, cluttering altavista.
105 "encyclopedia.com" => 1, # Dictionary, cluttering altavista.
106 "onlinedictionary.datasegment.com" => 1, # Dictionary, cluttering altavista.
110 # When verbosity is turned on, we warn about sites that we seem to be hitting
111 # a lot: usually this means some new poisoner has made it into the search
112 # engines. But sometimes, the warning is just because that site has a lot
113 # of stuff on it. So these are the sites that are immune to the "frequent
114 # site" diagnostic message.
116 my %warningless_sites = (
117 "home.earthlink.net" => 1, # Lots of home pages here.
118 "www.geocities.com" => 1,
119 "www.angelfire.com" => 1,
120 "members.aol.com" => 1,
122 "yimg.com" => 1, # This is where dailynews.yahoo.com stores
123 "eimg.com" => 1, # its images, so pick_from_yahoo_news_text()
124 # hits this every time.
128 ##############################################################################
130 # Various global flags set by command line parameters, or computed
132 ##############################################################################
135 my $current_state = "???"; # for diagnostics
138 my $image_succeeded = -1;
139 my $suppress_audit = 0;
141 my $verbose_imgmap = 0; # print out rectangles and URLs only (stdout)
142 my $verbose_warnings = 0; # print out warnings when things go wrong
143 my $verbose_load = 0; # diagnostics about loading of URLs
144 my $verbose_filter = 0; # diagnostics about page selection/rejection
145 my $verbose_net = 0; # diagnostics about network I/O
146 my $verbose_pbm = 0; # diagnostics about PBM pipelines
147 my $verbose_http = 0; # diagnostics about all HTTP activity
148 my $verbose_exec = 0; # diagnostics about executing programs
150 my $report_performance_interval = 60 * 15; # print some stats every 15 minutes
152 my $http_proxy = undef;
153 my $http_timeout = 30;
154 my $cvt_timeout = 10;
160 my $min_gif_area = (120 * 120);
169 my @tripwire_words = ("aberrate", "abode", "amorphous", "antioch",
170 "arrhenius", "arteriole", "blanket", "brainchild",
171 "burdensome", "carnival", "cherub", "chord", "clever",
172 "dedicate", "dilogarithm", "dolan", "dryden",
176 ##############################################################################
180 ##############################################################################
182 # returns three values: the HTTP response line; the document headers;
183 # and the document body.
186 my ( $url, $referer, $timeout ) = @_;
188 if (!defined($timeout)) { $timeout = $http_timeout; }
189 if ($timeout > $http_timeout) { $timeout = $http_timeout; }
192 LOG (($verbose_net || $verbose_load), "timed out for $url");
196 LOG ($verbose_net, "get_document_1 $url " . ($referer ? $referer : ""));
198 if (! ($url =~ m@^http://@i)) {
199 LOG ($verbose_net, "not an HTTP URL: $url");
203 my ($url_proto, $dummy, $serverstring, $path) = split(/\//, $url, 4);
204 $path = "" unless $path;
206 my ($them,$port) = split(/:/, $serverstring);
207 $port = 80 unless $port;
212 $serverstring = $http_proxy if $http_proxy;
213 ($them2,$port2) = split(/:/, $serverstring);
214 $port2 = 80 unless $port2;
217 my ($remote, $iaddr, $paddr, $proto, $line);
219 if ($port2 =~ /\D/) { $port2 = getservbyname($port2, 'tcp') }
221 LOG (($verbose_net || $verbose_load), "unrecognised port in $url");
224 $iaddr = inet_aton($remote);
226 LOG (($verbose_net || $verbose_load), "host not found: $remote");
229 $paddr = sockaddr_in($port2, $iaddr);
237 local $SIG{ALRM} = sub {
238 LOG (($verbose_net || $verbose_load), "timed out ($timeout) for $url");
243 $proto = getprotobyname('tcp');
244 if (!socket(S, PF_INET, SOCK_STREAM, $proto)) {
245 LOG (($verbose_net || $verbose_load), "socket: $!");
248 if (!connect(S, $paddr)) {
249 LOG (($verbose_net || $verbose_load), "connect($serverstring): $!");
253 select(S); $| = 1; select(STDOUT);
255 my $cookie = $cookies{$them};
257 my $user_agent = "$progname/$version";
258 if ($url =~ m@^http://www\.altavista\.com/@) {
259 # block this, you turkeys.
260 $user_agent = "Mozilla/4.76 [en] (X11; U; Linux 2.2.16-22 i686; Nav)";
263 my $hdrs = "GET " . ($http_proxy ? $url : "/$path") . " HTTP/1.0\r\n" .
265 "User-Agent: $user_agent\r\n";
267 $hdrs .= "Referer: $referer\r\n";
270 my @cc = split(/\r?\n/, $cookie);
271 $hdrs .= "Cookie: " . join('; ', @cc) . "\r\n";
275 foreach (split('\r?\n', $hdrs)) {
276 LOG ($verbose_http, " ==> $_");
283 LOG ($verbose_http, " <== $_");
289 LOG ($verbose_http, " <== $_");
291 if (m@^Set-cookie:\s*([^;\r\n]+)@i) {
292 set_cookie($them, $1)
303 " <== [ body ]: $lines lines, " . length($body) . " bytes");
308 LOG (($verbose_net || $verbose_load), "null response: $url");
312 return ( $http, $head, $body );
314 die if ($@ && $@ ne "alarm\n"); # propagate errors
329 # returns two values: the document headers; and the document body.
330 # if the given URL did a redirect, returns the redirected-to document.
333 my ( $url, $referer, $timeout ) = @_;
338 my $max_loop_count = 4;
341 if (defined($timeout) && $timeout <= 0) {
342 LOG (($verbose_net || $verbose_load), "timed out for $url");
347 my ( $http, $head, $body ) = get_document_1 ($url, $referer, $timeout);
349 if (defined ($timeout)) {
351 my $elapsed = $now - $start;
352 $timeout -= $elapsed;
356 return () unless $http; # error message already printed
358 $http =~ s/[\r\n]+$//s;
360 if ( $http =~ m@^HTTP/[0-9.]+ 30[123]@ ) {
362 my ( $location ) = m@^location:[ \t]*(.*)$@im;
364 $location =~ s/[\r\n]$//;
366 LOG ($verbose_net, "redirect from $url to $location");
371 $referer =~ m@^(http://[^/]+)@i;
373 } elsif (! ($url =~ m@^[a-z]+:@i)) {
375 s@[^/]+$@@g if m@^http://[^/]+/@i;
376 $_ .= "/" if m@^http://[^/]+$@i;
381 LOG ($verbose_net, "no Location with \"$http\"");
382 return ( $url, $body );
385 if ($loop_count++ > $max_loop_count) {
387 "too many redirects ($max_loop_count) from $orig_url");
392 } elsif ( $http =~ m@^HTTP/[0-9.]+ ([4-9][0-9][0-9].*)$@ ) {
394 LOG (($verbose_net || $verbose_load), "failed: $1 ($url)");
396 # http errors -- return nothing.
402 LOG (($verbose_net || $verbose_load), "document contains no data: $url");
408 return ( $url, $body );
414 # If we already have a cookie defined for this site, and the site is trying
415 # to overwrite that very same cookie, let it do so. This is because nytimes
416 # expires its cookies - it lets you upgrade to a new cookie without logging
417 # in again, but you have to present the old cookie to get the new cookie.
418 # So, by doing this, the built-in cypherpunks cookie will never go "stale".
421 my ($host, $cookie) = @_;
422 my $oc = $cookies{$host};
425 my ($oc_name, $oc_value) = m@^([^= \t\r\n]+)=(.*)$@;
427 my ($nc_name, $nc_value) = m@^([^= \t\r\n]+)=(.*)$@;
429 if ($oc_name eq $nc_name &&
430 $oc_value ne $nc_value) {
431 $cookies{$host} = $cookie;
432 LOG ($verbose_net, "overwrote ${host}'s $oc_name cookie");
437 ############################################################################
439 # Extracting image URLs from HTML
441 ############################################################################
443 # given a URL and the body text at that URL, selects and returns a random
444 # image from it. returns () if no suitable images found.
446 sub pick_image_from_body {
447 my ( $url, $body ) = @_;
452 # if there's at least one slash after the host, take off the last
454 if ( m@^http://[^/]+/@io ) {
455 $base =~ s@[^/]+$@@go;
458 # if there are no slashes after the host at all, put one on the end.
459 if ( m@^http://[^/]+$@io ) {
465 # strip out newlines, compress whitespace
472 # There are certain web sites that list huge numbers of dictionary
473 # words in their bodies or in their <META NAME=KEYWORDS> tags (surprise!
474 # Porn sites tend not to be reputable!)
476 # I do not want webcollage to filter on content: I want it to select
477 # randomly from the set of images on the web. All the logic here for
478 # rejecting some images is really a set of heuristics for rejecting
479 # images that are not really images: for rejecting *text* that is in
480 # GIF/JPEG form. I don't want text, I want pictures, and I want the
481 # content of the pictures to be randomly selected from among all the
484 # So, filtering out "dirty" pictures by looking for "dirty" keywords
485 # would be wrong: dirty pictures exist, like it or not, so webcollage
486 # should be able to select them.
488 # However, picking a random URL is a hard thing to do. The mechanism I'm
489 # using is to search for a selection of random words. This is not
490 # perfect, but works ok most of the time. The way it breaks down is when
491 # some URLs get precedence because their pages list *every word* as
492 # related -- those URLs come up more often than others.
494 # So, after we've retrieved a URL, if it has too many keywords, reject
495 # it. We reject it not on the basis of what those keywords are, but on
496 # the basis that by having so many, the page has gotten an unfair
497 # advantage against our randomizer.
500 foreach my $trip (@tripwire_words) {
501 $trip_count++ if m/$trip/i;
504 if ($trip_count >= $#tripwire_words - 2) {
505 LOG (($verbose_filter || $verbose_load),
506 "there is probably a dictionary in \"$url\": rejecting.");
507 $rejected_urls{$url} = -1;
517 foreach (split(/ *</)) {
520 # Likewise, reject any web pages that have a KEYWORDS meta tag
523 if (m/name ?= ?\"?keywords\"?/i &&
524 m/content ?= ?\"([^\"]+)\"/) {
527 LOG (($verbose_filter || $verbose_load),
528 "excessive keywords ($L bytes) in $url: rejecting.");
529 $rejected_urls{$url} = $L;
534 LOG ($verbose_filter, " keywords ($L bytes) in $url (ok)");
538 } elsif ( m/^(img|a) .*(src|href) ?= ?\"? ?(.*?)[ >\"]/io ) {
540 my $was_inline = ( "$1" eq "a" || "$1" eq "A" );
542 my ( $width ) = m/width ?=[ \"]*(\d+)/oi;
543 my ( $height ) = m/height ?=[ \"]*(\d+)/oi;
548 ( $site = $base ) =~ s@^(http://[^/]*).*@$1@gio;
550 } elsif ( ! m@^[^/:?]+:@ ) {
553 while (s@/\.\./@/@g) {
558 if ( ! m@^http://@io ) {
563 if ( ! m@[.](gif|jpg|jpeg|pjpg|pjpeg)$@io ) {
567 # skip really short or really narrow images
568 if ( $width && $width < $min_width) {
569 if (!$height) { $height = "?"; }
570 LOG ($verbose_filter, " skip narrow image $_ (${width}x$height)");
574 if ( $height && $height < $min_height) {
575 if (!$width) { $width = "?"; }
576 LOG ($verbose_filter, " skip short image $_ (${width}x$height)");
580 # skip images with ratios that make them look like banners.
581 if ($min_ratio && $width && $height &&
582 ($width * $min_ratio ) > $height) {
583 if (!$height) { $height = "?"; }
584 LOG ($verbose_filter, " skip bad ratio $_ (${width}x$height)");
588 # skip GIFs with a small number of pixels -- those usually suck.
589 if ($width && $height &&
591 ($width * $height) < $min_gif_area) {
592 LOG ($verbose_filter, " skip small GIF $_ (${width}x$height)");
599 if ($unique_urls{$url}) {
600 LOG ($verbose_filter, " skip duplicate image $_");
604 LOG ($verbose_filter,
606 ($width && $height ? " (${width}x${height})" : "") .
607 ($was_inline ? " (inline)" : ""));
609 $urls[++$#urls] = $url;
610 $unique_urls{$url}++;
612 # jpegs are preferable to gifs.
614 if ( ! m@[.]gif$@io ) {
615 $urls[++$#urls] = $url;
618 # pointers to images are preferable to inlined images.
619 if ( ! $was_inline ) {
620 $urls[++$#urls] = $url;
621 $urls[++$#urls] = $url;
626 my $fsp = ($body =~ m@<frameset@i);
631 @urls = depoison (@urls);
634 LOG ($verbose_load, "no images on $base" . ($fsp ? " (frameset)" : ""));
638 # pick a random element of the table
639 my $i = int(rand($#urls+1));
642 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#urls+1) . ": $url");
649 ############################################################################
651 # Subroutines for getting pages and images out of search engines
653 ############################################################################
656 sub pick_dictionary {
657 my @dicts = ("/usr/dict/words",
658 "/usr/share/dict/words",
659 "/usr/share/lib/dict/words");
660 foreach my $f (@dicts) {
666 error ("$dicts[0] does not exist") unless defined($wordlist);
669 # returns a random word from the dictionary
673 if (open (IN, "<$wordlist")) {
674 my $size = (stat(IN))[7];
675 my $pos = rand $size;
676 if (seek (IN, $pos, 0)) {
677 $word = <IN>; # toss partial line
678 $word = <IN>; # keep next line
687 return 0 if (!$word);
689 $word =~ s/^[ \t\n\r]+//;
690 $word =~ s/[ \t\n\r]+$//;
695 $word =~ s/ally$/al/;
696 $word =~ s/izes$/ize/;
697 $word =~ tr/A-Z/a-z/;
699 if ( $word =~ s/[ \t\n\r]/\+/g ) { # convert intra-word spaces to "+".
700 $word = "\%22$word\%22"; # And put quotes (%22) around it.
707 return (random_word . "%20" .
708 random_word . "%20" .
709 random_word . "%20" .
710 random_word . "%20" .
717 $s =~ s|([^-a-zA-Z0-9.\@/_\r\n])|sprintf("%%%02X", ord($1))|ge;
724 $s =~ s/%([a-z0-9]{2})/chr(hex($1))/ige;
729 # Loads the given URL (a search on some search engine) and returns:
730 # - the total number of hits the search engine claimed it had;
731 # - a list of URLs from the page that the search engine returned;
732 # Note that this list contains all kinds of internal search engine
733 # junk URLs too -- caller must prune them.
735 sub pick_from_search_engine {
736 my ( $timeout, $search_url, $words ) = @_;
741 print STDERR "\n\n" if ($verbose_load);
743 LOG ($verbose_load, "words: $_");
744 LOG ($verbose_load, "URL: $search_url");
746 $last_search = $search_url; # for warnings
749 my ( $base, $body ) = get_document ($search_url, undef, $timeout);
750 if (defined ($timeout)) {
751 $timeout -= (time - $start);
754 LOG (($verbose_net || $verbose_load),
755 "timed out (late) for $search_url");
761 return () if (! $body);
766 my $search_count = "?";
767 if ($body =~ m@found (approximately |about )?(<B>)?(\d+)(</B>)? image@) {
769 } elsif ($body =~ m@<NOBR>((\d{1,3})(,\d{3})*) @i) {
771 } elsif ($body =~ m@found ((\d{1,3})(,\d{3})*|\d+) Web p@) {
773 } elsif ($body =~ m@found about ((\d{1,3})(,\d{3})*|\d+) results@) {
775 } elsif ($body =~ m@\b\d+ - \d+ of (\d+)\b@i) { # imagevista
777 } elsif ($body =~ m@About ((\d{1,3})(,\d{3})*) images@i) { # imagevista
779 } elsif ($body =~ m@We found ((\d{1,3})(,\d{3})*|\d+) results@i) { # *vista
781 } elsif ($body =~ m@ of about <B>((\d{1,3})(,\d{3})*)<@i) { # googleimages
783 } elsif ($body =~ m@<B>((\d{1,3})(,\d{3})*)</B> Web sites were found@i) {
784 $search_count = $1; # lycos
785 } elsif ($body =~ m@WEB.*?RESULTS.*?\b((\d{1,3})(,\d{3})*)\b.*?Matches@i) {
786 $search_count = $1; # hotbot
787 } elsif ($body =~ m@no photos were found containing@i) { # imagevista
789 } elsif ($body =~ m@found no document matching@i) { # altavista
792 1 while ($search_count =~ s/^(\d+)(\d{3})/$1,$2/);
794 # if ($search_count eq "?" || $search_count eq "0") {
796 # my $file = "/tmp/wc.html";
797 # open(OUT, ">$file") || error ("writing $file: $!");
800 # print STDERR blurb() . "###### wrote $file\n";
804 my $length = length($body);
813 foreach (split(/\n/)) {
815 my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
818 if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; } # quoted string
819 elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; } # or token
821 if ( $rejected_urls{$u} ) {
822 LOG ($verbose_filter, " pre-rejecting candidate: $u");
826 LOG ($verbose_http, " HREF: $u");
828 $subpages[++$#subpages] = $u;
831 if ( $#subpages < 0 ) {
832 LOG ($verbose_filter,
833 "found nothing on $base ($length bytes, $href_count links).");
837 LOG ($verbose_filter, "" . $#subpages+1 . " links on $search_url");
839 return ($search_count, @subpages);
847 my ($h) = m@^http://([^/: \t\r\n]+)@i;
849 next unless defined($h);
851 if ($poisoners{$h}) {
852 LOG (($verbose_filter), " rejecting poisoner: $_");
855 if ($h =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
857 LOG (($verbose_filter), " rejecting poisoner: $_");
860 if ($h =~ m@([^.]+\.[^.]+)$@ &&
862 LOG (($verbose_filter), " rejecting poisoner: $_");
872 # given a list of URLs, picks one at random; loads it; and returns a
873 # random image from it.
874 # returns the url of the page loaded; the url of the image chosen;
875 # and a debugging description string.
877 sub pick_image_from_pages {
878 my ($base, $total_hit_count, $unfiltered_link_count, $timeout, @pages) = @_;
880 $total_hit_count = "?" unless defined($total_hit_count);
882 @pages = depoison (@pages);
884 "" . ($#pages+1) . " candidates of $unfiltered_link_count links" .
885 " ($total_hit_count total)");
887 return () if ($#pages < 0);
889 my $i = int(rand($#pages+1));
890 my $page = $pages[$i];
892 LOG ($verbose_load, "picked page $page");
896 my ( $base2, $body2 ) = get_document ($page, $base, $timeout);
898 if (!$base2 || !$body2) {
903 my $img = pick_image_from_body ($base2, $body2);
907 return ($base2, $img);
914 ############################################################################
916 # Pick images from random pages returned by the Yahoo Random Link
918 ############################################################################
921 my $yahoo_random_link = "http://random.yahoo.com/bin/ryl";
924 # Picks a random page; picks a random image on that page;
925 # returns two URLs: the page containing the image, and the image.
926 # Returns () if nothing found this time.
928 sub pick_from_yahoo_random_link {
929 my ( $timeout ) = @_;
931 print STDERR "\n\n" if ($verbose_load);
932 LOG ($verbose_load, "URL: $yahoo_random_link");
934 $last_search = $yahoo_random_link; # for warnings
938 my ( $base, $body ) = get_document ($yahoo_random_link, undef, $timeout);
939 if (!$base || !$body) {
944 LOG ($verbose_load, "redirected to: $base");
946 my $img = pick_image_from_body ($base, $body);
950 return ($base, $img);
957 ############################################################################
959 # Pick images by feeding random words into Alta Vista Image Search
961 ############################################################################
964 my $alta_vista_images_url = "http://www.altavista.com/cgi-bin/query" .
966 "&igrph=1" . # graphics
969 "&micat=1" . # no partner sites
970 "&imgset=1" . # no partner sites
971 "&stype=simage" . # do image search
972 "&mmW=1" . # unknown, but required
976 sub pick_from_alta_vista_images {
977 my ( $timeout ) = @_;
979 my $words = random_words;
980 my $page = (int(rand(9)) + 1);
981 my $search_url = $alta_vista_images_url . $words;
984 $search_url .= "&pgno=" . $page; # page number
985 $search_url .= "&stq=" . (($page-1) * 12); # first hit result on page
988 my ($search_hit_count, @subpages) =
989 pick_from_search_engine ($timeout, $search_url, $words);
992 foreach my $u (@subpages) {
994 # altavista is encoding their URLs now.
996 m@^/r\?ck_sm=[a-zA-Z0-9]+\&ref=[a-zA-Z0-9]+(\&uid=[a-zA-Z0-9]+)?\&r=(.*)@);
997 $u = url_unquote($2);
999 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
1000 next if ($u =~ m@[/.]altavista\.com\b@i); # skip altavista builtins
1001 next if ($u =~ m@[/.]doubleclick\.net\b@i); # you cretins
1002 next if ($u =~ m@[/.]clicktomarket\.com\b@i); # more cretins
1004 next if ($u =~ m@[/.]viewimages\.com\b@i); # stacked deck
1005 next if ($u =~ m@[/.]gettyimages\.com\b@i);
1007 LOG ($verbose_filter, " candidate: $u");
1008 push @candidates, $u;
1011 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1012 $timeout, @candidates);
1017 ############################################################################
1019 # Pick images by feeding random words into Google Image Search
1020 # By Charles Gales <gales@us.ibm.com>
1022 ############################################################################
1025 my $google_images_url = "http://images.google.com/images" .
1026 "?site=images" . # photos
1027 "&btnG=Search" . # graphics
1028 "&safe=off" . # no screening
1033 sub pick_from_google_images {
1034 my ( $timeout ) = @_;
1036 my $words = random_word; # only one word for Google
1037 my $page = (int(rand(9)) + 1);
1038 my $num = 20; # 20 images per page
1039 my $search_url = $google_images_url . $words;
1042 $search_url .= "&start=" . $page*$num; # page number
1043 $search_url .= "&num=" . $num; #images per page
1046 my ($search_hit_count, @subpages) =
1047 pick_from_search_engine ($timeout, $search_url, $words);
1049 my @candidates = ();
1050 foreach my $u (@subpages) {
1051 next unless ($u =~ m@imgres\?imgurl@i); # All pics start with this
1052 next if ($u =~ m@[/.]google\.com\b@i); # skip google builtins
1054 if ($u =~ m@^/imgres\?imgurl=(.*?)\&imgrefurl=(.*?)\&@) {
1056 LOG ($verbose_filter, " candidate: $urlf");
1057 push @candidates, $urlf;
1061 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1062 $timeout, @candidates);
1067 ############################################################################
1069 # Pick images by feeding random words into Alta Vista Text Search
1071 ############################################################################
1074 my $alta_vista_url_1 = "http://www.altavista.com/cgi-bin/query?pg=q" .
1075 "&text=yes&kl=XX&stype=stext&q=";
1076 my $alta_vista_url_2 = "http://www.altavista.com/sites/search/web?pg=q" .
1077 "&kl=XX&search=Search&q=";
1079 my $alta_vista_url = $alta_vista_url_2;
1082 sub pick_from_alta_vista_text {
1083 my ( $timeout ) = @_;
1085 my $words = random_words;
1086 my $page = (int(rand(9)) + 1);
1087 my $search_url = $alta_vista_url . $words;
1090 $search_url .= "&pgno=" . $page;
1091 $search_url .= "&stq=" . (($page-1) * 10);
1094 my ($search_hit_count, @subpages) =
1095 pick_from_search_engine ($timeout, $search_url, $words);
1097 my @candidates = ();
1098 foreach my $u (@subpages) {
1100 # Those altavista fuckers are playing really nasty redirection games
1101 # these days: the filter your clicks through their site, but use
1102 # onMouseOver to make it look like they're not! Well, it makes it
1103 # easier for us to identify search results...
1106 m@^/r\?ck_sm=[a-zA-Z0-9]+\&ref=[a-zA-Z0-9]+\&uid=[a-zA-Z0-9]+\&r=(.*)@);
1107 $u = url_unquote($1);
1109 LOG ($verbose_filter, " candidate: $u");
1110 push @candidates, $u;
1113 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1114 $timeout, @candidates);
1119 ############################################################################
1121 # Pick images by feeding random words into Hotbot
1123 ############################################################################
1125 my $hotbot_search_url = "http://hotbot.lycos.com/" .
1137 sub pick_from_hotbot_text {
1138 my ( $timeout ) = @_;
1140 my $words = random_words;
1141 my $search_url = $hotbot_search_url . $words;
1143 my ($search_hit_count, @subpages) =
1144 pick_from_search_engine ($timeout, $search_url, $words);
1146 my @candidates = ();
1147 foreach my $u (@subpages) {
1149 # Hotbot plays redirection games too
1150 next unless ($u =~ m@^/director.asp\?target=([^&]+)@);
1151 $u = url_decode($1);
1153 LOG ($verbose_filter, " candidate: $u");
1154 push @candidates, $u;
1157 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1158 $timeout, @candidates);
1163 ############################################################################
1165 # Pick images by feeding random words into Lycos
1167 ############################################################################
1169 my $lycos_search_url = "http://lycospro.lycos.com/srchpro/" .
1174 sub pick_from_lycos_text {
1175 my ( $timeout ) = @_;
1177 my $words = random_words;
1178 my $start = int(rand(8)) * 10 + 1;
1179 my $search_url = $lycos_search_url . $words . "&start=$start";
1181 my ($search_hit_count, @subpages) =
1182 pick_from_search_engine ($timeout, $search_url, $words);
1184 my @candidates = ();
1185 foreach my $u (@subpages) {
1187 # Lycos plays exact the same redirection game as hotbot.
1188 # Note that "id=0" is used for internal advertising links,
1189 # and 1+ are used for search results.
1190 next unless ($u =~ m@^http://click.hotbot.com/director.asp\?id=[1-9]\d*&target=([^&]+)@);
1191 $u = url_decode($1);
1193 LOG ($verbose_filter, " candidate: $u");
1194 push @candidates, $u;
1197 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1198 $timeout, @candidates);
1203 ############################################################################
1205 # Pick images by feeding random words into news.yahoo.com
1207 ############################################################################
1209 my $yahoo_news_url = "http://search.news.yahoo.com/search/news_photos?" .
1210 "&z=&n=100&o=o&2=&3=&p=";
1213 sub pick_from_yahoo_news_text {
1214 my ( $timeout ) = @_;
1216 my $words = random_words;
1217 my $search_url = $yahoo_news_url . $words;
1219 my ($search_hit_count, @subpages) =
1220 pick_from_search_engine ($timeout, $search_url, $words);
1222 my @candidates = ();
1223 foreach my $u (@subpages) {
1224 # only accept URLs on Yahoo's news site
1225 next unless ($u =~ m@^http://dailynews.yahoo.com/@i);
1227 LOG ($verbose_filter, " candidate: $u");
1228 push @candidates, $u;
1231 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1232 $timeout, @candidates);
1238 ############################################################################
1240 # Pick a random image in a random way
1242 ############################################################################
1245 # Picks a random image on a random page, and returns two URLs:
1246 # the page containing the image, and the image.
1247 # Returns () if nothing found this time.
1248 # Uses the url-randomizer 1 time in 5, else the image randomizer.
1252 my ( $timeout ) = @_;
1254 $current_state = "select";
1255 $load_method = "none";
1257 my $n = int(rand(100));
1260 my @rest = @search_methods;
1263 my $pct = shift @rest;
1264 my $name = shift @rest;
1265 my $tfn = shift @rest;
1267 if ($total > $n && !defined($fn)) {
1269 $current_state = $name;
1270 $load_method = $current_state;
1274 if ($total != 100) {
1275 error ("internal error: \@search_methods totals to $total%!");
1278 record_attempt ($current_state);
1279 return $fn->($timeout);
1284 ############################################################################
1286 # Statistics and logging
1288 ############################################################################
1291 return strftime ("%H:%M:%S: ", localtime);
1295 return "$progname: " . timestr() . "$current_state: ";
1300 print STDERR blurb() . "$err\n";
1312 my $head = "$progname: DEBUG: ";
1313 foreach (split (/\n/, $lastlog)) {
1314 print STDERR "$head$_\n";
1320 my ($print, $msg) = @_;
1321 my $blurb = timestr() . "$current_state: ";
1322 $lastlog .= "$blurb$msg\n";
1323 print STDERR "$progname: $blurb$msg\n" if $print;
1328 my %stats_successes;
1331 my $last_state = undef;
1332 sub record_attempt {
1336 record_failure($last_state) unless ($image_succeeded > 0);
1338 $last_state = $name;
1341 report_performance();
1344 $image_succeeded = 0;
1345 $suppress_audit = 0;
1348 sub record_success {
1349 my ($name, $url, $base) = @_;
1350 if (defined($stats_successes{$name})) {
1351 $stats_successes{$name}++;
1353 $stats_successes{$name} = 1;
1356 stop_timer ($name, 1);
1357 my $o = $current_state;
1358 $current_state = $name;
1359 save_recent_url ($url, $base);
1360 $current_state = $o;
1361 $image_succeeded = 1;
1366 sub record_failure {
1369 return if $image_succeeded;
1371 stop_timer ($name, 0);
1372 if ($verbose_load && !$verbose_exec) {
1374 if ($suppress_audit) {
1375 print STDERR "$progname: " . timestr() . "(audit log suppressed)\n";
1379 my $o = $current_state;
1380 $current_state = "DEBUG";
1382 my $line = "#" x 78;
1383 print STDERR "\n\n\n";
1384 print STDERR ("#" x 78) . "\n";
1385 print STDERR blurb() . "failed to get an image. Full audit log:\n";
1388 print STDERR ("-" x 78) . "\n";
1389 print STDERR "\n\n";
1391 $current_state = $o;
1393 $image_succeeded = 0;
1400 my $i = $stats_successes{$name};
1401 my $j = $stats_attempts{$name};
1404 return "" . ($j ? int($i * 100 / $j) : "0") . "%";
1408 my $current_start_time = 0;
1412 $current_start_time = time;
1414 if (defined($stats_attempts{$name})) {
1415 $stats_attempts{$name}++;
1417 $stats_attempts{$name} = 1;
1419 if (!defined($stats_elapsed{$name})) {
1420 $stats_elapsed{$name} = 0;
1425 my ($name, $success) = @_;
1426 $stats_elapsed{$name} += time - $current_start_time;
1430 my $last_report_time = 0;
1431 sub report_performance {
1433 return unless $verbose_warnings;
1436 return unless ($now >= $last_report_time + $report_performance_interval);
1437 my $ot = $last_report_time;
1438 $last_report_time = $now;
1440 return if ($ot == 0);
1442 my $blurb = "$progname: " . timestr();
1445 print STDERR "${blurb}Current standings:\n";
1447 foreach my $name (sort keys (%stats_attempts)) {
1448 my $try = $stats_attempts{$name};
1449 my $suc = $stats_successes{$name} || 0;
1450 my $pct = int($suc * 100 / $try);
1451 my $secs = $stats_elapsed{$name};
1452 my $secs_link = int($secs / $try);
1453 print STDERR sprintf ("$blurb %-12s %4s (%d/%d);\t %2d secs/link\n",
1454 "$name:", "$pct%", $suc, $try, $secs_link);
1460 my $max_recent_images = 400;
1461 my $max_recent_sites = 20;
1462 my @recent_images = ();
1463 my @recent_sites = ();
1465 sub save_recent_url {
1466 my ($url, $base) = @_;
1468 return unless ($verbose_warnings);
1471 my ($site) = m@^http://([^ \t\n\r/:]+)@;
1474 foreach (@recent_images) {
1476 print STDERR blurb() . "WARNING: recently-duplicated image: $url" .
1477 " (on $base via $last_search)\n";
1483 # suppress "duplicate site" warning via %warningless_sites.
1485 if ($warningless_sites{$site}) {
1487 } elsif ($site =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
1488 $warningless_sites{$1}) {
1490 } elsif ($site =~ m@([^.]+\.[^.]+)$@ &&
1491 $warningless_sites{$1}) {
1496 foreach (@recent_sites) {
1498 print STDERR blurb() . "WARNING: recently-duplicated site: $site" .
1499 " ($url on $base via $last_search)\n";
1505 push @recent_images, $url;
1506 push @recent_sites, $site;
1507 shift @recent_images if ($#recent_images >= $max_recent_images);
1508 shift @recent_sites if ($#recent_sites >= $max_recent_sites);
1513 ##############################################################################
1517 ##############################################################################
1524 s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
1529 # Given the raw body of a GIF document, returns the dimensions of the image.
1533 my $type = substr($body, 0, 6);
1535 return () unless ($type =~ /GIF8[7,9]a/);
1536 $s = substr ($body, 6, 10);
1537 my ($a,$b,$c,$d) = unpack ("C"x4, $s);
1538 return (($b<<8|$a), ($d<<8|$c));
1541 # Given the raw body of a JPEG document, returns the dimensions of the image.
1546 my $L = length($body);
1548 my $c1 = substr($body, $i, 1); $i++;
1549 my $c2 = substr($body, $i, 1); $i++;
1550 return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
1553 while (ord($ch) != 0xDA && $i < $L) {
1554 # Find next marker, beginning with 0xFF.
1555 while (ord($ch) != 0xFF) {
1556 $ch = substr($body, $i, 1); $i++;
1558 # markers can be padded with any number of 0xFF.
1559 while (ord($ch) == 0xFF) {
1560 $ch = substr($body, $i, 1); $i++;
1563 # $ch contains the value of the marker.
1564 my $marker = ord($ch);
1566 if (($marker >= 0xC0) &&
1567 ($marker <= 0xCF) &&
1568 ($marker != 0xC4) &&
1569 ($marker != 0xCC)) { # it's a SOFn marker
1571 my $s = substr($body, $i, 4); $i += 4;
1572 my ($a,$b,$c,$d) = unpack("C"x4, $s);
1573 return (($c<<8|$d), ($a<<8|$b));
1576 # We must skip variables, since FFs in variable names aren't
1577 # valid JPEG markers.
1578 my $s = substr($body, $i, 2); $i += 2;
1579 my ($c1, $c2) = unpack ("C"x2, $s);
1580 my $length = ($c1 << 8) | $c2;
1581 return () if ($length < 2);
1588 # Given the raw body of a GIF or JPEG document, returns the dimensions of
1593 my ($w, $h) = gif_size ($body);
1594 if ($w && $h) { return ($w, $h); }
1595 return jpeg_size ($body);
1599 # returns the full path of the named program, or undef.
1603 foreach (split (/:/, $ENV{PATH})) {
1604 if (-x "$_/$prog") {
1612 # Like rand(), but chooses numbers with a bell curve distribution.
1615 $_ = 1.0 unless defined($_);
1617 return (rand($_) + rand($_) + rand($_));
1621 ##############################################################################
1623 # Generating a list of urls only
1625 ##############################################################################
1627 sub url_only_output {
1629 my ($base, $img) = pick_image;
1633 print "$img $base\n";
1638 ##############################################################################
1640 # Running as an xscreensaver module
1642 ##############################################################################
1644 my $image_ppm = ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp") . "/webcollage." . $$;
1645 my $image_tmp1 = $image_ppm . "-1";
1646 my $image_tmp2 = $image_ppm . "-2";
1648 my $filter_cmd = undef;
1649 my $post_filter_cmd = undef;
1650 my $background = undef;
1652 my $img_width; # size of the image being generated.
1660 print STDERR blurb() . "caught signal $sig.\n" if ($verbose_exec);
1661 unlink $image_ppm, $image_tmp1, $image_tmp2;
1666 # Like system, but prints status about exit codes, and kills this process
1667 # with whatever signal killed the sub-process, if any.
1669 sub nontrapping_system {
1673 s/\"[^\"]+\"/\"...\"/g;
1675 LOG ($verbose_exec, "executing \"$_\"");
1680 LOG ($verbose_exec, "subproc exited normally.");
1681 } elsif (($rc & 0xff) == 0) {
1683 LOG ($verbose_exec, "subproc exited with status $rc.");
1686 LOG ($verbose_exec, "subproc dumped core.");
1689 LOG ($verbose_exec, "subproc died with signal $rc.");
1690 # die that way ourselves.
1698 # Given the URL of a GIF or JPEG image, and the body of that image, writes a
1699 # PPM to the given output file. Returns the width/height of the image if
1703 my ($url, $body, $output) = @_;
1704 my ($cmd, $cmd2, $w, $h);
1706 if ((@_ = gif_size ($body))) {
1709 } elsif ((@_ = jpeg_size ($body))) {
1713 LOG (($verbose_pbm || $verbose_load),
1714 "not a GIF or JPG" .
1715 (($body =~ m@<(base|html|head|body|script|table|a href)>@i)
1716 ? " (looks like HTML)" : "") .
1718 $suppress_audit = 1;
1722 $cmd2 = "exec $cmd"; # yes, this really is necessary. if we don't
1723 # do this, the process doesn't die properly.
1724 if (!$verbose_pbm) {
1726 # We get a "giftopnm: got a 'Application Extension' extension"
1727 # warning any time it's an animgif.
1729 # Note that "giftopnm: EOF / read error on image data" is not
1730 # always a fatal error -- sometimes the image looks fine anyway.
1732 $cmd2 .= " 2>/dev/null";
1735 # There exist corrupted GIF and JPEG files that can make giftopnm and
1736 # djpeg lose their minds and go into a loop. So this gives those programs
1737 # a small timeout -- if they don't complete in time, kill them.
1743 local $SIG{ALRM} = sub {
1745 "timed out ($cvt_timeout) for $cmd on \"$url\" in pid $pid");
1746 kill ('TERM', $pid) if ($pid);
1751 if (($pid = open(PIPE, "| $cmd2 > $output"))) {
1758 LOG ($verbose_exec, "awaiting $pid");
1760 LOG ($verbose_exec, "$pid completed");
1762 my $size = (stat($output))[7];
1763 $size = -1 unless defined($size);
1765 LOG ($verbose_pbm, "$cmd on ${w}x$h \"$url\" failed ($size bytes)");
1769 LOG ($verbose_pbm, "created ${w}x$h $output ($cmd)");
1772 print STDERR blurb() . "$cmd failed: $!\n";
1776 die if ($@ && $@ ne "alarm\n"); # propagate errors
1789 sub pick_root_displayer {
1792 foreach my $cmd (@root_displayers) {
1794 my ($name) = m/^([^ ]+)/;
1795 push @names, "\"$name\"";
1796 LOG ($verbose_exec, "looking for $name...");
1797 foreach my $dir (split (/:/, $ENV{PATH})) {
1798 LOG ($verbose_exec, " checking $dir/$name");
1799 return $cmd if (-x "$dir/$name");
1803 $names[$#names] = "or " . $names[$#names];
1804 error "none of: " . join (", ", @names) . " were found on \$PATH.";
1808 my $ppm_to_root_window_cmd = undef;
1811 sub x_or_pbm_output {
1813 # make sure the various programs we execute exist, right up front.
1815 foreach ("ppmmake", "giftopnm", "djpeg", "pnmpaste", "pnmscale", "pnmcut") {
1816 which ($_) || error "$_ not found on \$PATH.";
1819 # find a root-window displayer program.
1821 $ppm_to_root_window_cmd = pick_root_displayer();
1824 $SIG{HUP} = \&x_cleanup;
1825 $SIG{INT} = \&x_cleanup;
1826 $SIG{QUIT} = \&x_cleanup;
1827 $SIG{ABRT} = \&x_cleanup;
1828 $SIG{KILL} = \&x_cleanup;
1829 $SIG{TERM} = \&x_cleanup;
1831 # Need this so that if giftopnm dies, we don't die.
1832 $SIG{PIPE} = 'IGNORE';
1834 if (!$img_width || !$img_height) {
1836 which ($_) || error "$_ not found on \$PATH.";
1838 ($img_width, $img_height) = m/dimensions: *(\d+)x(\d+) /;
1839 if (!defined($img_height)) {
1840 error "xdpyinfo failed.";
1844 my $bgcolor = "#000000";
1845 my $bgimage = undef;
1848 if ($background =~ m/^\#[0-9a-f]+$/i) {
1849 $bgcolor = $background;
1851 } elsif (-r $background) {
1852 $bgimage = $background;
1854 } elsif (! $background =~ m@^[-a-z0-9 ]+$@i) {
1855 error "not a color or readable file: $background";
1858 # default to assuming it's a color
1859 $bgcolor = $background;
1863 # Create the sold-colored base image.
1865 $_ = "ppmmake '$bgcolor' $img_width $img_height";
1866 LOG ($verbose_pbm, "creating base image: $_");
1867 nontrapping_system "$_ > $image_ppm";
1869 # Paste the default background image in the middle of it.
1876 open(IMG, "<$bgimage") || error "couldn't open $bgimage: $!";
1878 while (<IMG>) { $body .= $_; }
1881 if ((@_ = gif_size ($body))) {
1883 $cmd = "giftopnm |";
1885 } elsif ((@_ = jpeg_size ($body))) {
1889 } elsif ($body =~ m/^P\d\n(\d+) (\d+)\n/) {
1895 error "$bgimage is not a GIF, JPEG, or PPM.";
1898 my $x = int (($img_width - $iw) / 2);
1899 my $y = int (($img_height - $ih) / 2);
1901 "pasting $bgimage (${iw}x$ih) into base image at $x,$y");
1903 $cmd .= "pnmpaste - $x $y $image_ppm > $image_tmp1";
1904 open (IMG, "| $cmd") || error "running $cmd: $!";
1908 LOG ($verbose_exec, "subproc exited normally.");
1909 rename ($image_tmp1, $image_ppm) ||
1910 error "renaming $image_tmp1 to $image_ppm: $!";
1916 my ($base, $img) = pick_image();
1917 my $source = $current_state;
1918 $current_state = "loadimage";
1920 my ($headers, $body) = get_document ($img, $base);
1922 paste_image ($base, $img, $body, $source);
1926 $current_state = "idle";
1927 $load_method = "none";
1929 unlink $image_tmp1, $image_tmp2;
1935 my ($base, $img, $body, $source) = @_;
1937 $current_state = "paste";
1939 $suppress_audit = 0;
1941 LOG ($verbose_pbm, "got $img (" . length($body) . ")");
1943 my ($iw, $ih) = image_to_pnm ($img, $body, $image_tmp1);
1946 LOG ($verbose_pbm, "unable to make PBM from $img");
1950 record_success ($load_method, $img, $base);
1953 my $ow = $iw; # used only for error messages
1956 # don't just tack this onto the front of the pipeline -- we want it to
1957 # be able to change the size of the input image.
1960 LOG ($verbose_pbm, "running $filter_cmd");
1962 my $rc = nontrapping_system "($filter_cmd) < $image_tmp1 >$image_tmp2";
1964 LOG(($verbose_pbm || $verbose_load), "failed command: \"$filter_cmd\"");
1965 LOG(($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
1968 rename ($image_tmp2, $image_tmp1);
1970 # re-get the width/height in case the filter resized it.
1972 open(IMG, "<$image_tmp1") || return 0;
1975 ($iw, $ih) = m/^(\d+) (\d+)$/;
1977 return 0 unless ($iw && $ih);
1980 my $target_w = $img_width;
1981 my $target_h = $img_height;
1986 # Usually scale the image to fit on the screen -- but sometimes scale it
1987 # to fit on half or a quarter of the screen. Note that we don't merely
1988 # scale it to fit, we instead cut it in half until it fits -- that should
1989 # give a wider distribution of sizes.
1991 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
1992 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
1994 if ($iw > $target_w || $ih > $target_h) {
1995 while ($iw > $target_w ||
2000 if ($iw <= 10 || $ih <= 10) {
2001 LOG ($verbose_pbm, "scaling to ${iw}x$ih would have been bogus.");
2005 LOG ($verbose_pbm, "scaling to ${iw}x$ih");
2007 $cmd .= " | pnmscale -xsize $iw -ysize $ih";
2011 my $src = $image_tmp1;
2013 my $crop_x = 0; # the sub-rectangle of the image
2014 my $crop_y = 0; # that we will actually paste.
2018 # The chance that we will randomly crop out a section of an image starts
2019 # out fairly low, but goes up for images that are very large, or images
2020 # that have ratios that make them look like banners (we try to avoid
2021 # banner images entirely, but they slip through when the IMG tags didn't
2022 # have WIDTH and HEIGHT specified.)
2024 my $crop_chance = 0.2;
2025 if ($iw > $img_width * 0.4 || $ih > $img_height * 0.4) {
2026 $crop_chance += 0.2;
2028 if ($iw > $img_width * 0.7 || $ih > $img_height * 0.7) {
2029 $crop_chance += 0.2;
2031 if ($min_ratio && ($iw * $min_ratio) > $ih) {
2032 $crop_chance += 0.7;
2035 if ($crop_chance > 0.1) {
2036 LOG ($verbose_pbm, "crop chance: $crop_chance");
2039 if (rand() < $crop_chance) {
2044 if ($crop_w > $min_width) {
2045 # if it's a banner, select the width linearly.
2046 # otherwise, select a bell.
2047 my $r = (($min_ratio && ($iw * $min_ratio) > $ih)
2050 $crop_w = $min_width + int ($r * ($crop_w - $min_width));
2051 $crop_x = int (rand() * ($ow - $crop_w));
2053 if ($crop_h > $min_height) {
2054 # height always selects as a bell.
2055 $crop_h = $min_height + int (bellrand() * ($crop_h - $min_height));
2056 $crop_y = int (rand() * ($oh - $crop_h));
2059 if ($crop_x != 0 || $crop_y != 0 ||
2060 $crop_w != $iw || $crop_h != $ih) {
2062 "randomly cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
2066 # Where the image should logically land -- this might be negative.
2068 my $x = int((rand() * ($img_width + $crop_w/2)) - $crop_w*3/4);
2069 my $y = int((rand() * ($img_height + $crop_h/2)) - $crop_h*3/4);
2071 # if we have chosen to paste the image outside of the rectangle of the
2072 # screen, then we need to crop it.
2076 $x + $crop_w > $img_width ||
2077 $y + $crop_h > $img_height) {
2080 "cropping for effective paste of ${crop_w}x$crop_h \@ $x,$y");
2082 if ($x < 0) { $crop_x -= $x; $crop_w += $x; $x = 0; }
2083 if ($y < 0) { $crop_y -= $y; $crop_h += $y; $y = 0; }
2085 if ($x + $crop_w >= $img_width) { $crop_w = $img_width - $x - 1; }
2086 if ($y + $crop_h >= $img_height) { $crop_h = $img_height - $y - 1; }
2089 # If any cropping needs to happen, add pnmcut.
2091 if ($crop_x != 0 || $crop_y != 0 ||
2092 $crop_w != $iw || $crop_h != $ih) {
2095 $cmd .= " | pnmcut $crop_x $crop_y $iw $ih";
2096 LOG ($verbose_pbm, "cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
2099 LOG ($verbose_pbm, "pasting ${iw}x$ih \@ $x,$y in $image_ppm");
2101 $cmd .= " | pnmpaste - $x $y $image_ppm";
2103 $cmd =~ s@^ *\| *@@;
2106 $_ .= " < $image_tmp1 > $image_tmp2";
2109 $_ = "($_) 2>&1 | sed s'/^/" . blurb() . "/'";
2111 $_ .= " 2> /dev/null";
2113 my $rc = nontrapping_system ($_);
2116 LOG (($verbose_pbm || $verbose_load), "failed command: \"$cmd\"");
2117 LOG (($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
2121 rename ($image_tmp2, $image_ppm) || return;
2123 my $target = "$image_ppm";
2125 # don't just tack this onto the end of the pipeline -- we don't want it
2126 # to end up in $image_ppm, because we don't want the results to be
2129 if ($post_filter_cmd) {
2130 $target = $image_tmp1;
2131 $rc = nontrapping_system "($post_filter_cmd) < $image_ppm > $target";
2133 LOG ($verbose_pbm, "filter failed: \"$post_filter_cmd\"\n");
2138 if (!$no_output_p) {
2139 my $tsize = (stat($target))[7];
2141 $cmd = "$ppm_to_root_window_cmd $target";
2143 # xv seems to hate being killed. it tends to forget to clean
2144 # up after itself, and leaves windows around and colors allocated.
2145 # I had this same problem with vidwhacker, and I'm not entirely
2146 # sure what I did to fix it. But, let's try this: launch xv
2147 # in the background, so that killing this process doesn't kill it.
2148 # it will die of its own accord soon enough. So this means we
2149 # start pumping bits to the root window in parallel with starting
2150 # the next network retrieval, which is probably a better thing
2155 $rc = nontrapping_system ($cmd);
2158 LOG (($verbose_pbm || $verbose_load), "display failed: \"$cmd\"");
2163 LOG ($verbose_pbm, "$target size is $tsize");
2167 $source .= "-" . stats_of($source);
2168 print STDOUT "image: ${iw}x${ih} @ $x,$y $base $source\n"
2169 if ($verbose_imgmap);
2184 $current_state = "init";
2185 $load_method = "none";
2189 # historical suckage: the environment variable name is lower case.
2190 $http_proxy = $ENV{http_proxy} || $ENV{HTTP_PROXY};
2192 while ($_ = $ARGV[0]) {
2194 if ($_ eq "-display" ||
2200 $ENV{DISPLAY} = shift @ARGV;
2201 } elsif ($_ eq "-root") {
2203 } elsif ($_ eq "-no-output") {
2205 } elsif ($_ eq "-urls-only") {
2208 } elsif ($_ eq "-verbose") {
2210 } elsif (m/^-v+$/) {
2211 $verbose += length($_)-1;
2212 } elsif ($_ eq "-delay") {
2213 $delay = shift @ARGV;
2214 } elsif ($_ eq "-timeout") {
2215 $http_timeout = shift @ARGV;
2216 } elsif ($_ eq "-filter") {
2217 $filter_cmd = shift @ARGV;
2218 } elsif ($_ eq "-filter2") {
2219 $post_filter_cmd = shift @ARGV;
2220 } elsif ($_ eq "-background" || $_ eq "-bg") {
2221 $background = shift @ARGV;
2222 } elsif ($_ eq "-size") {
2224 if (m@^(\d+)x(\d+)$@) {
2228 error "argument to \"-size\" must be of the form \"640x400\"";
2230 } elsif ($_ eq "-proxy" || $_ eq "-http-proxy") {
2231 $http_proxy = shift @ARGV;
2232 } elsif ($_ eq "-dictionary" || $_ eq "-dict") {
2233 $dict = shift @ARGV;
2235 print STDERR "$copyright\nusage: $progname [-root]" .
2236 " [-display dpy] [-root] [-verbose] [-timeout secs]\n" .
2237 "\t\t [-delay secs] [-filter cmd] [-filter2 cmd]\n" .
2238 "\t\t [-dictionary dictionary-file]\n" .
2239 "\t\t [-http-proxy host[:port]]\n";
2244 if ($http_proxy && $http_proxy eq "") {
2245 $http_proxy = undef;
2247 if ($http_proxy && $http_proxy =~ m@^http://([^/]*)/?$@ ) {
2248 # historical suckage: allow "http://host:port" as well as "host:port".
2252 if (!$root_p && !$no_output_p) {
2253 print STDERR $copyright;
2254 error "the -root argument is mandatory (for now.)";
2257 if (!$no_output_p && !$ENV{DISPLAY}) {
2258 error "\$DISPLAY is not set.";
2262 if ($verbose == 1) {
2263 $verbose_imgmap = 1;
2264 $verbose_warnings = 1;
2266 } elsif ($verbose == 2) {
2267 $verbose_imgmap = 1;
2268 $verbose_warnings = 1;
2271 } elsif ($verbose == 3) {
2272 $verbose_imgmap = 1;
2273 $verbose_warnings = 1;
2275 $verbose_filter = 1;
2277 } elsif ($verbose == 4) {
2278 $verbose_imgmap = 1;
2279 $verbose_warnings = 1;
2281 $verbose_filter = 1;
2284 } elsif ($verbose == 5) {
2285 $verbose_imgmap = 1;
2286 $verbose_warnings = 1;
2288 $verbose_filter = 1;
2292 } elsif ($verbose == 6) {
2293 $verbose_imgmap = 1;
2294 $verbose_warnings = 1;
2296 $verbose_filter = 1;
2301 } elsif ($verbose >= 7) {
2302 $verbose_imgmap = 1;
2303 $verbose_warnings = 1;
2305 $verbose_filter = 1;
2313 error ("$dict does not exist") unless (-f $dict);