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.78 $ }; $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, "lycos", \&pick_from_lycos_text);
60 @search_methods=(100, "googleimgs",\&pick_from_google_images);
62 # programs we can use to write to the root window (tried in ascending order.)
64 my @root_displayers = (
65 "xloadimage -quiet -onroot -center -border black",
66 "xli -quiet -onroot -center -border black",
67 "xv -root -quit -viewonly +noresetroot -rmode 5" .
68 " -rfg black -rbg black",
69 "chbg -once -xscreensaver",
71 # this lame program wasn't built with vroot.h:
72 # "xsri -scale -keep-aspect -center-horizontal -center-vertical",
76 # Some sites need cookies to work properly. These are they.
79 "www.altavista.com" => "AV_ALL=1", # request uncensored searches
80 "web.altavista.com" => "AV_ALL=1",
83 "www.nytimes.com" => "NYT-S=104nv1sChNnnWAvTLGx6eiDhzQcbSoN" .
84 "6zOMB7s0Qm8MlMaa8It.2/BlXTrpbBk" .
85 "jinV68IcqxOvAABDyKdciIJ8O000",
89 # Some sites have managed to poison the search engines. These are they.
90 # (We auto-detect sites that have poisoned the search engines via excessive
91 # keywords or dictionary words, but these are ones that slip through
94 # This can contain full host names, or 2 or 3 component domains.
97 "die.net" => 1, # 'l33t h4ck3r d00dz.
98 "genforum.genealogy.com" => 1, # Cluttering altavista with human names.
99 "rootsweb.com" => 1, # Cluttering altavista with human names.
100 "akamai.net" => 1, # Lots of sites have their images on Akamai.
101 # But those are pretty much all banners.
102 # Since Akamai is super-expensive, let's
103 # go out on a limb and assume that all of
104 # their customers are rich-and-boring.
108 # When verbosity is turned on, we warn about sites that we seem to be hitting
109 # a lot: usually this means some new poisoner has made it into the search
110 # engines. But sometimes, the warning is just because that site has a lot
111 # of stuff on it. So these are the sites that are immune to the "frequent
112 # site" diagnostic message.
114 my %warningless_sites = (
115 "home.earthlink.net" => 1, # Lots of home pages here.
116 "www.geocities.com" => 1,
117 "www.angelfire.com" => 1,
118 "members.aol.com" => 1,
120 "yimg.com" => 1, # This is where dailynews.yahoo.com stores
121 "eimg.com" => 1, # its images, so pick_from_yahoo_news_text()
122 # hits this every time.
126 ##############################################################################
128 # Various global flags set by command line parameters, or computed
130 ##############################################################################
133 my $current_state = "???"; # for diagnostics
136 my $image_succeeded = -1;
137 my $suppress_audit = 0;
139 my $verbose_imgmap = 0; # print out rectangles and URLs only (stdout)
140 my $verbose_warnings = 0; # print out warnings when things go wrong
141 my $verbose_load = 0; # diagnostics about loading of URLs
142 my $verbose_filter = 0; # diagnostics about page selection/rejection
143 my $verbose_net = 0; # diagnostics about network I/O
144 my $verbose_pbm = 0; # diagnostics about PBM pipelines
145 my $verbose_http = 0; # diagnostics about all HTTP activity
146 my $verbose_exec = 0; # diagnostics about executing programs
148 my $report_performance_interval = 60 * 15; # print some stats every 15 minutes
150 my $http_proxy = undef;
151 my $http_timeout = 30;
152 my $cvt_timeout = 10;
164 my @tripwire_words = ("aberrate", "abode", "amorphous", "antioch",
165 "arrhenius", "arteriole", "blanket", "brainchild",
166 "burdensome", "carnival", "cherub", "chord", "clever",
167 "dedicate", "dilogarithm", "dolan", "dryden",
171 ##############################################################################
175 ##############################################################################
177 # returns three values: the HTTP response line; the document headers;
178 # and the document body.
181 my ( $url, $referer, $timeout ) = @_;
183 if (!defined($timeout)) { $timeout = $http_timeout; }
184 if ($timeout > $http_timeout) { $timeout = $http_timeout; }
187 LOG (($verbose_net || $verbose_load), "timed out for $url");
191 LOG ($verbose_net, "get_document_1 $url " . ($referer ? $referer : ""));
193 if (! ($url =~ m@^http://@i)) {
194 LOG ($verbose_net, "not an HTTP URL: $url");
198 my ($url_proto, $dummy, $serverstring, $path) = split(/\//, $url, 4);
199 $path = "" unless $path;
201 my ($them,$port) = split(/:/, $serverstring);
202 $port = 80 unless $port;
207 $serverstring = $http_proxy if $http_proxy;
208 ($them2,$port2) = split(/:/, $serverstring);
209 $port2 = 80 unless $port2;
212 my ($remote, $iaddr, $paddr, $proto, $line);
214 if ($port2 =~ /\D/) { $port2 = getservbyname($port2, 'tcp') }
216 LOG (($verbose_net || $verbose_load), "unrecognised port in $url");
219 $iaddr = inet_aton($remote);
221 LOG (($verbose_net || $verbose_load), "host not found: $remote");
224 $paddr = sockaddr_in($port2, $iaddr);
232 local $SIG{ALRM} = sub {
233 LOG (($verbose_net || $verbose_load), "timed out ($timeout) for $url");
238 $proto = getprotobyname('tcp');
239 if (!socket(S, PF_INET, SOCK_STREAM, $proto)) {
240 LOG (($verbose_net || $verbose_load), "socket: $!");
243 if (!connect(S, $paddr)) {
244 LOG (($verbose_net || $verbose_load), "connect($serverstring): $!");
248 select(S); $| = 1; select(STDOUT);
250 my $cookie = $cookies{$them};
252 my $user_agent = "$progname/$version";
253 if ($url =~ m@^http://www\.altavista\.com/@) {
254 # block this, you turkeys.
255 $user_agent = "Mozilla/4.76 [en] (X11; U; Linux 2.2.16-22 i686; Nav)";
258 my $hdrs = "GET " . ($http_proxy ? $url : "/$path") . " HTTP/1.0\r\n" .
260 "User-Agent: $user_agent\r\n";
262 $hdrs .= "Referer: $referer\r\n";
265 foreach (split(/\r?\n/, $cookie)) {
266 $hdrs .= "Cookie: $_\r\n";
271 foreach (split('\r?\n', $hdrs)) {
272 LOG ($verbose_http, " ==> $_");
279 LOG ($verbose_http, " <== $_");
285 LOG ($verbose_http, " <== $_");
287 if (m@^Set-cookie:\s*([^;\r\n]+)@i) {
288 set_cookie($them, $1)
299 " <== [ body ]: $lines lines, " . length($body) . " bytes");
304 LOG (($verbose_net || $verbose_load), "null response: $url");
308 return ( $http, $head, $body );
310 die if ($@ && $@ ne "alarm\n"); # propagate errors
325 # returns two values: the document headers; and the document body.
326 # if the given URL did a redirect, returns the redirected-to document.
329 my ( $url, $referer, $timeout ) = @_;
334 my $max_loop_count = 4;
337 if (defined($timeout) && $timeout <= 0) {
338 LOG (($verbose_net || $verbose_load), "timed out for $url");
343 my ( $http, $head, $body ) = get_document_1 ($url, $referer, $timeout);
345 if (defined ($timeout)) {
347 my $elapsed = $now - $start;
348 $timeout -= $elapsed;
352 return () unless $http; # error message already printed
354 $http =~ s/[\r\n]+$//s;
356 if ( $http =~ m@^HTTP/[0-9.]+ 30[123]@ ) {
358 my ( $location ) = m@^location:[ \t]*(.*)$@im;
360 $location =~ s/[\r\n]$//;
362 LOG ($verbose_net, "redirect from $url to $location");
367 $referer =~ m@^(http://[^/]+)@i;
369 } elsif (! ($url =~ m@^[a-z]+:@i)) {
371 s@[^/]+$@@g if m@^http://[^/]+/@i;
372 $_ .= "/" if m@^http://[^/]+$@i;
377 LOG ($verbose_net, "no Location with \"$http\"");
378 return ( $url, $body );
381 if ($loop_count++ > $max_loop_count) {
383 "too many redirects ($max_loop_count) from $orig_url");
388 } elsif ( $http =~ m@^HTTP/[0-9.]+ ([4-9][0-9][0-9].*)$@ ) {
390 LOG (($verbose_net || $verbose_load), "failed: $1 ($url)");
392 # http errors -- return nothing.
398 LOG (($verbose_net || $verbose_load), "document contains no data: $url");
404 return ( $url, $body );
410 # If we already have a cookie defined for this site, and the site is trying
411 # to overwrite that very same cookie, let it do so. This is because nytimes
412 # expires its cookies - it lets you upgrade to a new cookie without logging
413 # in again, but you have to present the old cookie to get the new cookie.
414 # So, by doing this, the built-in cypherpunks cookie will never go "stale".
417 my ($host, $cookie) = @_;
418 my $oc = $cookies{$host};
421 my ($oc_name, $oc_value) = m@^([^= \t\r\n]+)=(.*)$@;
423 my ($nc_name, $nc_value) = m@^([^= \t\r\n]+)=(.*)$@;
425 if ($oc_name eq $nc_name &&
426 $oc_value ne $nc_value) {
427 $cookies{$host} = $cookie;
428 LOG ($verbose_net, "overwrote ${host}'s $oc_name cookie");
433 ############################################################################
435 # Extracting image URLs from HTML
437 ############################################################################
439 # given a URL and the body text at that URL, selects and returns a random
440 # image from it. returns () if no suitable images found.
442 sub pick_image_from_body {
443 my ( $url, $body ) = @_;
448 # if there's at least one slash after the host, take off the last
450 if ( m@^http://[^/]+/@io ) {
451 $base =~ s@[^/]+$@@go;
454 # if there are no slashes after the host at all, put one on the end.
455 if ( m@^http://[^/]+$@io ) {
461 # strip out newlines, compress whitespace
468 # There are certain web sites that list huge numbers of dictionary
469 # words in their bodies or in their <META NAME=KEYWORDS> tags (surprise!
470 # Porn sites tend not to be reputable!)
472 # I do not want webcollage to filter on content: I want it to select
473 # randomly from the set of images on the web. All the logic here for
474 # rejecting some images is really a set of heuristics for rejecting
475 # images that are not really images: for rejecting *text* that is in
476 # GIF/JPEG form. I don't want text, I want pictures, and I want the
477 # content of the pictures to be randomly selected from among all the
480 # So, filtering out "dirty" pictures by looking for "dirty" keywords
481 # would be wrong: dirty pictures exist, like it or not, so webcollage
482 # should be able to select them.
484 # However, picking a random URL is a hard thing to do. The mechanism I'm
485 # using is to search for a selection of random words. This is not
486 # perfect, but works ok most of the time. The way it breaks down is when
487 # some URLs get precedence because their pages list *every word* as
488 # related -- those URLs come up more often than others.
490 # So, after we've retrieved a URL, if it has too many keywords, reject
491 # it. We reject it not on the basis of what those keywords are, but on
492 # the basis that by having so many, the page has gotten an unfair
493 # advantage against our randomizer.
496 foreach my $trip (@tripwire_words) {
497 $trip_count++ if m/$trip/i;
500 if ($trip_count >= $#tripwire_words - 2) {
501 LOG (($verbose_filter || $verbose_load),
502 "there is probably a dictionary in \"$url\": rejecting.");
503 $rejected_urls{$url} = -1;
513 foreach (split(/ *</)) {
516 # Likewise, reject any web pages that have a KEYWORDS meta tag
519 if (m/name ?= ?\"?keywords\"?/i &&
520 m/content ?= ?\"([^\"]+)\"/) {
523 LOG (($verbose_filter || $verbose_load),
524 "excessive keywords ($L bytes) in $url: rejecting.");
525 $rejected_urls{$url} = $L;
530 LOG ($verbose_filter, " keywords ($L bytes) in $url (ok)");
534 } elsif ( m/^(img|a) .*(src|href) ?= ?\"? ?(.*?)[ >\"]/io ) {
536 my $was_inline = ( "$1" eq "a" || "$1" eq "A" );
538 my ( $width ) = m/width ?=[ \"]*(\d+)/oi;
539 my ( $height ) = m/height ?=[ \"]*(\d+)/oi;
544 ( $site = $base ) =~ s@^(http://[^/]*).*@$1@gio;
546 } elsif ( ! m@^[^/:?]+:@ ) {
549 while (s@/\.\./@/@g) {
554 if ( ! m@^http://@io ) {
559 if ( ! m@[.](gif|jpg|jpeg|pjpg|pjpeg)$@io ) {
563 # skip really short or really narrow images
564 if ( $width && $width < $min_width) {
565 if (!$height) { $height = "?"; }
566 LOG ($verbose_filter, " skip narrow image $_ (${width}x$height)");
570 if ( $height && $height < $min_height) {
571 if (!$width) { $width = "?"; }
572 LOG ($verbose_filter, " skip short image $_ (${width}x$height)");
576 # skip images with ratios that make them look like banners.
577 if ($min_ratio && $width && $height &&
578 ($width * $min_ratio ) > $height) {
579 if (!$height) { $height = "?"; }
580 LOG ($verbose_filter, " skip bad ratio $_ (${width}x$height)");
586 if ($unique_urls{$url}) {
587 LOG ($verbose_filter, " skip duplicate image $_");
591 LOG ($verbose_filter,
593 ($width && $height ? " (${width}x${height})" : "") .
594 ($was_inline ? " (inline)" : ""));
596 $urls[++$#urls] = $url;
597 $unique_urls{$url}++;
599 # jpegs are preferable to gifs.
601 if ( ! m@[.]gif$@io ) {
602 $urls[++$#urls] = $url;
605 # pointers to images are preferable to inlined images.
606 if ( ! $was_inline ) {
607 $urls[++$#urls] = $url;
608 $urls[++$#urls] = $url;
613 my $fsp = ($body =~ m@<frameset@i);
619 LOG ($verbose_load, "no images on $base" . ($fsp ? " (frameset)" : ""));
623 @urls = depoison (@urls);
625 # pick a random element of the table
626 my $i = int(rand($#urls+1));
629 LOG ($verbose_load, "picked image " .($i+1) . "/" . ($#urls+1) . ": $url");
636 ############################################################################
638 # Subroutines for getting pages and images out of search engines
640 ############################################################################
643 sub pick_dictionary {
644 my @dicts = ("/usr/dict/words",
645 "/usr/share/dict/words",
646 "/usr/share/lib/dict/words");
647 foreach my $f (@dicts) {
653 error ("$dicts[0] does not exist") unless defined($wordlist);
656 # returns a random word from the dictionary
661 if (open (IN, "<$wordlist")) {
662 my $size = (stat(IN))[7];
663 my $pos = rand $size;
664 if (seek (IN, $pos, 0)) {
665 $word = <IN>; # toss partial line
666 $word = <IN>; # keep next line
675 return 0 if (!$word);
677 $word =~ s/^[ \t\n\r]+//;
678 $word =~ s/[ \t\n\r]+$//;
683 $word =~ s/ally$/al/;
684 $word =~ s/izes$/ize/;
685 $word =~ tr/A-Z/a-z/;
687 if ( $word =~ s/[ \t\n\r]/\+/g ) { # convert intra-word spaces to "+".
688 $word = "\%22$word\%22"; # And put quotes (%22) around it.
695 return (random_word . "%20" .
696 random_word . "%20" .
697 random_word . "%20" .
698 random_word . "%20" .
703 # Loads the given URL (a search on some search engine) and returns:
704 # - the total number of hits the search engine claimed it had;
705 # - a list of URLs from the page that the search engine returned;
706 # Note that this list contains all kinds of internal search engine
707 # junk URLs too -- caller must prune them.
709 sub pick_from_search_engine {
710 my ( $timeout, $search_url, $words ) = @_;
715 print STDERR "\n\n" if ($verbose_load);
717 LOG ($verbose_load, "words: $_");
718 LOG ($verbose_load, "URL: $search_url");
720 $last_search = $search_url; # for warnings
723 my ( $base, $body ) = get_document ($search_url, undef, $timeout);
724 if (defined ($timeout)) {
725 $timeout -= (time - $start);
728 LOG (($verbose_net || $verbose_load),
729 "timed out (late) for $search_url");
735 return () if (! $body);
740 my $search_count = "?";
741 if ($body =~ m@found (approximately |about )?(<B>)?(\d+)(</B>)? image@) {
743 } elsif ($body =~ m@<NOBR>((\d{1,3})(,\d{3})*) @i) {
745 } elsif ($body =~ m@found ((\d{1,3})(,\d{3})*|\d+) Web p@) {
747 } elsif ($body =~ m@found about ((\d{1,3})(,\d{3})*|\d+) results@) {
749 } elsif ($body =~ m@\b\d+ - \d+ of (\d+)\b@i) { # imagevista
751 } elsif ($body =~ m@About ((\d{1,3})(,\d{3})*) images@i) { # imagevista
753 } elsif ($body =~ m@WEB.*?RESULTS.*?\b((\d{1,3})(,\d{3})*)\b.*?Matches@i) {
754 $search_count = $1; # hotbot
755 } elsif ($body =~ m@no photos were found containing@i) { # imagevista
757 } elsif ($body =~ m@found no document matching@i) { # altavista
760 1 while ($search_count =~ s/^(\d+)(\d{3})/$1,$2/);
762 # if ($search_count eq "?" || $search_count eq "0") {
764 # my $file = "/tmp/wc.html";
765 # open(OUT, ">$file") || error ("writing $file: $!");
768 # print STDERR blurb() . "###### wrote $file\n";
772 my $length = length($body);
781 foreach (split(/\n/)) {
783 my ($u) = m@<A\s.*\bHREF\s*=\s*([^>]+)>@i;
786 if ($u =~ m/^\"([^\"]*)\"/) { $u = $1; } # quoted string
787 elsif ($u =~ m/^([^\s]*)\s/) { $u = $1; } # or token
789 if ( $rejected_urls{$u} ) {
790 LOG ($verbose_filter, " pre-rejecting candidate: $u");
794 LOG ($verbose_http, " HREF: $u");
796 $subpages[++$#subpages] = $u;
799 if ( $#subpages < 0 ) {
800 LOG ($verbose_filter,
801 "found nothing on $base ($length bytes, $href_count links).");
805 LOG ($verbose_filter, "" . $#subpages+1 . " links on $search_url");
807 return ($search_count, @subpages);
815 my ($h) = m@^http://([^/: \t\r\n]+)@i;
817 next unless defined($h);
819 if ($poisoners{$h}) {
820 LOG (($verbose_filter), " rejecting poisoner: $_");
823 if ($h =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
825 LOG (($verbose_filter), " rejecting poisoner: $_");
828 if ($h =~ m@([^.]+\.[^.]+)$@ &&
830 LOG (($verbose_filter), " rejecting poisoner: $_");
840 # given a list of URLs, picks one at random; loads it; and returns a
841 # random image from it.
842 # returns the url of the page loaded; the url of the image chosen;
843 # and a debugging description string.
845 sub pick_image_from_pages {
846 my ($base, $total_hit_count, $unfiltered_link_count, $timeout, @pages) = @_;
848 $total_hit_count = "?" unless defined($total_hit_count);
850 @pages = depoison (@pages);
852 "" . ($#pages+1) . " candidates of $unfiltered_link_count links" .
853 " ($total_hit_count total)");
855 return () if ($#pages < 0);
857 my $i = int(rand($#pages+1));
858 my $page = $pages[$i];
860 LOG ($verbose_load, "picked page $page");
864 my ( $base2, $body2 ) = get_document ($page, $base, $timeout);
866 if (!$base2 || !$body2) {
871 my $img = pick_image_from_body ($base2, $body2);
875 return ($base2, $img);
882 ############################################################################
884 # Pick images from random pages returned by the Yahoo Random Link
886 ############################################################################
889 my $yahoo_random_link = "http://random.yahoo.com/bin/ryl";
892 # Picks a random page; picks a random image on that page;
893 # returns two URLs: the page containing the image, and the image.
894 # Returns () if nothing found this time.
896 sub pick_from_yahoo_random_link {
897 my ( $timeout ) = @_;
899 print STDERR "\n\n" if ($verbose_load);
900 LOG ($verbose_load, "URL: $yahoo_random_link");
902 $last_search = $yahoo_random_link; # for warnings
906 my ( $base, $body ) = get_document ($yahoo_random_link, undef, $timeout);
907 if (!$base || !$body) {
912 LOG ($verbose_load, "redirected to: $base");
914 my $img = pick_image_from_body ($base, $body);
918 return ($base, $img);
925 ############################################################################
927 # Pick images by feeding random words into Alta Vista Image Search
929 ############################################################################
932 my $alta_vista_images_url = "http://www.altavista.com/cgi-bin/query" .
934 "&igrph=1" . # graphics
937 "&micat=1" . # no partner sites
938 "&imgset=1" . # no partner sites
939 "&stype=simage" . # do image search
940 "&mmW=1" . # unknown, but required
945 sub pick_from_alta_vista_images {
946 my ( $timeout ) = @_;
948 my $words = random_words;
949 my $page = (int(rand(9)) + 1);
950 my $search_url = $alta_vista_images_url . $words;
953 $search_url .= "&pgno=" . $page; # page number
954 $search_url .= "&stq=" . (($page-1) * 12); # first hit result on page
957 my ($search_hit_count, @subpages) =
958 pick_from_search_engine ($timeout, $search_url, $words);
961 foreach my $u (@subpages) {
962 next unless ($u =~ m@^http://@i); # skip non-HTTP or relative URLs
963 next if ($u =~ m@[/.]altavista\.com\b@i); # skip altavista builtins
964 next if ($u =~ m@[/.]doubleclick\.net\b@i); # you cretins
965 next if ($u =~ m@[/.]clicktomarket\.com\b@i); # more cretins
967 next if ($u =~ m@[/.]viewimages\.com\b@i); # stacked deck
968 next if ($u =~ m@[/.]gettyimages\.com\b@i);
970 LOG ($verbose_filter, " candidate: $u");
971 push @candidates, $u;
974 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
975 $timeout, @candidates);
980 ############################################################################
982 # Pick images by feeding random words into Google Image Search
983 # By Charles Gales <gales@us.ibm.com>
985 ############################################################################
988 my $google_images_url = "http://images.google.com/images" .
989 "?site=images" . # photos
990 "&btnG=Search" . # graphics
991 "&safe=off" . # no screening
996 sub pick_from_google_images {
997 my ( $timeout ) = @_;
999 my $words = random_word; # only one word for Google
1000 my $page = (int(rand(9)) + 1);
1001 my $num = 20; # 20 images per page
1002 my $search_url = $google_images_url . $words;
1005 $search_url .= "&start=" . $page*$num; # page number
1006 $search_url .= "&num=" . $num; #images per page
1009 my ($search_hit_count, @subpages) =
1010 pick_from_search_engine ($timeout, $search_url, $words);
1012 my @candidates = ();
1013 foreach my $u (@subpages) {
1014 next unless ($u =~ m@imgres\?imgurl@i); # All pics start with this
1015 next if ($u =~ m@[/.]google\.com\b@i); # skip google builtins
1017 if ($u =~ m@^/imgres\?imgurl=(.*?)\&imgrefurl=(.*?)\&@) {
1019 LOG ($verbose_filter, " candidate: $urlf");
1020 push @candidates, $urlf;
1024 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1025 $timeout, @candidates);
1030 ############################################################################
1032 # Pick images by feeding random words into Alta Vista Text Search
1034 ############################################################################
1037 my $alta_vista_url = "http://www.altavista.com/cgi-bin/query?pg=q" .
1038 "&text=yes&kl=XX&stype=stext&q=";
1041 sub pick_from_alta_vista_text {
1042 my ( $timeout ) = @_;
1044 my $words = random_words;
1045 my $page = (int(rand(9)) + 1);
1046 my $search_url = $alta_vista_url . $words;
1049 $search_url .= "&pgno=" . $page;
1050 $search_url .= "&stq=" . (($page-1) * 10);
1053 my ($search_hit_count, @subpages) =
1054 pick_from_search_engine ($timeout, $search_url, $words);
1056 my @candidates = ();
1057 foreach my $u (@subpages) {
1059 # Those altavista fuckers are playing really nasty redirection games
1060 # these days: the filter your clicks through their site, but use
1061 # onMouseOver to make it look like they're not! Well, it makes it
1062 # easier for us to identify search results...
1064 next unless ($u =~ m@^/r\?ck_sm=[a-zA-Z0-9]+\&ref=[a-zA-Z0-9]+\&r=(.*)@);
1067 LOG ($verbose_filter, " candidate: $u");
1068 push @candidates, $u;
1071 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1072 $timeout, @candidates);
1077 ############################################################################
1079 # Pick images by feeding random words into Hotbot
1081 ############################################################################
1083 my $hotbot_search_url = "http://hotbot.lycos.com/" .
1095 sub pick_from_hotbot_text {
1096 my ( $timeout ) = @_;
1098 my $words = random_words;
1099 my $search_url = $hotbot_search_url . $words;
1101 my ($search_hit_count, @subpages) =
1102 pick_from_search_engine ($timeout, $search_url, $words);
1104 my @candidates = ();
1105 foreach my $u (@subpages) {
1107 # Hotbot plays redirection games too
1108 next unless ($u =~ m@^/director.asp\?target=([^&]+)@);
1109 $u = url_decode($1);
1111 LOG ($verbose_filter, " candidate: $u");
1112 push @candidates, $u;
1115 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1116 $timeout, @candidates);
1121 ############################################################################
1123 # Pick images by feeding random words into Lycos
1125 ############################################################################
1127 my $lycos_search_url = "http://lycospro.lycos.com/srchpro/" .
1132 sub pick_from_lycos_text {
1133 my ( $timeout ) = @_;
1135 my $words = random_words;
1136 my $start = int(rand(8)) * 10 + 1;
1137 my $search_url = $lycos_search_url . $words . "&start=$start";
1139 my ($search_hit_count, @subpages) =
1140 pick_from_search_engine ($timeout, $search_url, $words);
1142 my @candidates = ();
1143 foreach my $u (@subpages) {
1145 # Lycos plays exact the same redirection game as hotbot.
1146 # Note that "id=0" is used for internal advertising links,
1147 # and 1+ are used for search results.
1148 next unless ($u =~ m@^http://click.hotbot.com/director.asp\?id=[1-9]\d*&target=([^&]+)@);
1149 $u = url_decode($1);
1151 LOG ($verbose_filter, " candidate: $u");
1152 push @candidates, $u;
1155 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1156 $timeout, @candidates);
1161 ############################################################################
1163 # Pick images by feeding random words into news.yahoo.com
1165 ############################################################################
1167 my $yahoo_news_url = "http://search.news.yahoo.com/search/news_photos?" .
1168 "&z=&n=100&o=o&2=&3=&p=";
1171 sub pick_from_yahoo_news_text {
1172 my ( $timeout ) = @_;
1174 my $words = random_words;
1175 my $search_url = $yahoo_news_url . $words;
1177 my ($search_hit_count, @subpages) =
1178 pick_from_search_engine ($timeout, $search_url, $words);
1180 my @candidates = ();
1181 foreach my $u (@subpages) {
1182 # only accept URLs on Yahoo's news site
1183 next unless ($u =~ m@^http://dailynews.yahoo.com/@i);
1185 LOG ($verbose_filter, " candidate: $u");
1186 push @candidates, $u;
1189 return pick_image_from_pages ($search_url, $search_hit_count, $#subpages+1,
1190 $timeout, @candidates);
1196 ############################################################################
1198 # Pick a random image in a random way
1200 ############################################################################
1203 # Picks a random image on a random page, and returns two URLs:
1204 # the page containing the image, and the image.
1205 # Returns () if nothing found this time.
1206 # Uses the url-randomizer 1 time in 5, else the image randomizer.
1210 my ( $timeout ) = @_;
1212 $current_state = "select";
1213 $load_method = "none";
1215 my $n = int(rand(100));
1218 my @rest = @search_methods;
1221 my $pct = shift @rest;
1222 my $name = shift @rest;
1223 my $tfn = shift @rest;
1225 if ($total > $n && !defined($fn)) {
1227 $current_state = $name;
1228 $load_method = $current_state;
1232 if ($total != 100) {
1233 error ("internal error: \@search_methods totals to $total%!");
1236 record_attempt ($current_state);
1237 return $fn->($timeout);
1242 ############################################################################
1244 # Statistics and logging
1246 ############################################################################
1249 return strftime ("%H:%M:%S: ", localtime);
1253 return "$progname: " . timestr() . "$current_state: ";
1258 print STDERR blurb() . "$_\n";
1270 my $head = "$progname: DEBUG: ";
1271 foreach (split (/\n/, $lastlog)) {
1272 print STDERR "$head$_\n";
1278 my ($print, $msg) = @_;
1279 my $blurb = timestr() . "$current_state: ";
1280 $lastlog .= "$blurb$msg\n";
1281 print STDERR "$progname: $blurb$msg\n" if $print;
1286 my %stats_successes;
1289 my $last_state = undef;
1290 sub record_attempt {
1294 record_failure($last_state) unless ($image_succeeded > 0);
1296 $last_state = $name;
1299 report_performance();
1302 $image_succeeded = 0;
1303 $suppress_audit = 0;
1306 sub record_success {
1307 my ($name, $url, $base) = @_;
1308 if (defined($stats_successes{$name})) {
1309 $stats_successes{$name}++;
1311 $stats_successes{$name} = 1;
1314 stop_timer ($name, 1);
1315 my $o = $current_state;
1316 $current_state = $name;
1317 save_recent_url ($url, $base);
1318 $current_state = $o;
1319 $image_succeeded = 1;
1324 sub record_failure {
1327 return if $image_succeeded;
1329 stop_timer ($name, 0);
1330 if ($verbose_load && !$verbose_exec) {
1332 if ($suppress_audit) {
1333 print STDERR "$progname: " . timestr() . "(audit log suppressed)\n";
1337 my $o = $current_state;
1338 $current_state = "DEBUG";
1340 my $line = "#" x 78;
1341 print STDERR "\n\n\n";
1342 print STDERR ("#" x 78) . "\n";
1343 print STDERR blurb() . "failed to get an image. Full audit log:\n";
1346 print STDERR ("-" x 78) . "\n";
1347 print STDERR "\n\n";
1349 $current_state = $o;
1351 $image_succeeded = 0;
1358 my $i = $stats_successes{$name};
1359 my $j = $stats_attempts{$name};
1362 return "" . ($j ? int($i * 100 / $j) : "0") . "%";
1366 my $current_start_time = 0;
1370 $current_start_time = time;
1372 if (defined($stats_attempts{$name})) {
1373 $stats_attempts{$name}++;
1375 $stats_attempts{$name} = 1;
1377 if (!defined($stats_elapsed{$name})) {
1378 $stats_elapsed{$name} = 0;
1383 my ($name, $success) = @_;
1384 $stats_elapsed{$name} += time - $current_start_time;
1388 my $last_report_time = 0;
1389 sub report_performance {
1391 return unless $verbose_warnings;
1394 return unless ($now >= $last_report_time + $report_performance_interval);
1395 my $ot = $last_report_time;
1396 $last_report_time = $now;
1398 return if ($ot == 0);
1400 my $blurb = "$progname: " . timestr();
1403 print STDERR "${blurb}Current standings:\n";
1405 foreach my $name (sort keys (%stats_attempts)) {
1406 my $try = $stats_attempts{$name};
1407 my $suc = $stats_successes{$name} || 0;
1408 my $pct = int($suc * 100 / $try);
1409 my $secs = $stats_elapsed{$name};
1410 my $secs_link = int($secs / $try);
1411 print STDERR sprintf ("$blurb %-12s %4s (%d/%d);\t %2d secs/link\n",
1412 "$name:", "$pct%", $suc, $try, $secs_link);
1418 my $max_recent_images = 400;
1419 my $max_recent_sites = 20;
1420 my @recent_images = ();
1421 my @recent_sites = ();
1423 sub save_recent_url {
1424 my ($url, $base) = @_;
1426 return unless ($verbose_warnings);
1429 my ($site) = m@^http://([^ \t\n\r/:]+)@;
1432 foreach (@recent_images) {
1434 print STDERR blurb() . "WARNING: recently-duplicated image: $url" .
1435 " (on $base via $last_search)\n";
1441 # suppress "duplicate site" warning via %warningless_sites.
1443 if ($warningless_sites{$site}) {
1445 } elsif ($site =~ m@([^.]+\.[^.]+\.[^.]+)$@ &&
1446 $warningless_sites{$1}) {
1448 } elsif ($site =~ m@([^.]+\.[^.]+)$@ &&
1449 $warningless_sites{$1}) {
1454 foreach (@recent_sites) {
1456 print STDERR blurb() . "WARNING: recently-duplicated site: $site" .
1457 " ($url on $base via $last_search)\n";
1463 push @recent_images, $url;
1464 push @recent_sites, $site;
1465 shift @recent_images if ($#recent_images >= $max_recent_images);
1466 shift @recent_sites if ($#recent_sites >= $max_recent_sites);
1471 ##############################################################################
1475 ##############################################################################
1482 s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
1487 # Given the raw body of a GIF document, returns the dimensions of the image.
1491 my $type = substr($body, 0, 6);
1493 return () unless ($type =~ /GIF8[7,9]a/);
1494 $s = substr ($body, 6, 10);
1495 my ($a,$b,$c,$d) = unpack ("C"x4, $s);
1496 return (($b<<8|$a), ($d<<8|$c));
1499 # Given the raw body of a JPEG document, returns the dimensions of the image.
1504 my $L = length($body);
1506 my $c1 = substr($body, $i, 1); $i++;
1507 my $c2 = substr($body, $i, 1); $i++;
1508 return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
1511 while (ord($ch) != 0xDA && $i < $L) {
1512 # Find next marker, beginning with 0xFF.
1513 while (ord($ch) != 0xFF) {
1514 $ch = substr($body, $i, 1); $i++;
1516 # markers can be padded with any number of 0xFF.
1517 while (ord($ch) == 0xFF) {
1518 $ch = substr($body, $i, 1); $i++;
1521 # $ch contains the value of the marker.
1522 my $marker = ord($ch);
1524 if (($marker >= 0xC0) &&
1525 ($marker <= 0xCF) &&
1526 ($marker != 0xC4) &&
1527 ($marker != 0xCC)) { # it's a SOFn marker
1529 my $s = substr($body, $i, 4); $i += 4;
1530 my ($a,$b,$c,$d) = unpack("C"x4, $s);
1531 return (($c<<8|$d), ($a<<8|$b));
1534 # We must skip variables, since FFs in variable names aren't
1535 # valid JPEG markers.
1536 my $s = substr($body, $i, 2); $i += 2;
1537 my ($c1, $c2) = unpack ("C"x2, $s);
1538 my $length = ($c1 << 8) | $c2;
1539 return () if ($length < 2);
1546 # Given the raw body of a GIF or JPEG document, returns the dimensions of
1551 my ($w, $h) = gif_size ($body);
1552 if ($w && $h) { return ($w, $h); }
1553 return jpeg_size ($body);
1557 # returns the full path of the named program, or undef.
1561 foreach (split (/:/, $ENV{PATH})) {
1562 if (-x "$_/$prog") {
1570 # Like rand(), but chooses numbers with a bell curve distribution.
1573 $_ = 1.0 unless defined($_);
1575 return (rand($_) + rand($_) + rand($_));
1579 ##############################################################################
1581 # Generating a list of urls only
1583 ##############################################################################
1585 sub url_only_output {
1587 my ($base, $img) = pick_image;
1591 print "$img $base\n";
1596 ##############################################################################
1598 # Running as an xscreensaver module
1600 ##############################################################################
1602 my $image_ppm = ($ENV{TMPDIR} ? $ENV{TMPDIR} : "/tmp") . "/webcollage." . $$;
1603 my $image_tmp1 = $image_ppm . "-1";
1604 my $image_tmp2 = $image_ppm . "-2";
1606 my $filter_cmd = undef;
1607 my $post_filter_cmd = undef;
1608 my $background = undef;
1610 my $img_width; # size of the image being generated.
1618 print STDERR blurb() . "caught signal $sig.\n" if ($verbose_exec);
1619 unlink $image_ppm, $image_tmp1, $image_tmp2;
1624 # Like system, but prints status about exit codes, and kills this process
1625 # with whatever signal killed the sub-process, if any.
1627 sub nontrapping_system {
1631 s/\"[^\"]+\"/\"...\"/g;
1633 LOG ($verbose_exec, "executing \"$_\"");
1638 LOG ($verbose_exec, "subproc exited normally.");
1639 } elsif (($rc & 0xff) == 0) {
1641 LOG ($verbose_exec, "subproc exited with status $rc.");
1644 LOG ($verbose_exec, "subproc dumped core.");
1647 LOG ($verbose_exec, "subproc died with signal $rc.");
1648 # die that way ourselves.
1656 # Given the URL of a GIF or JPEG image, and the body of that image, writes a
1657 # PPM to the given output file. Returns the width/height of the image if
1661 my ($url, $body, $output) = @_;
1662 my ($cmd, $cmd2, $w, $h);
1664 if ((@_ = gif_size ($body))) {
1667 } elsif ((@_ = jpeg_size ($body))) {
1671 LOG (($verbose_pbm || $verbose_load),
1672 "not a GIF or JPG" .
1673 (($body =~ m@<(base|html|head|body|script|table|a href)>@i)
1674 ? " (looks like HTML)" : "") .
1676 $suppress_audit = 1;
1680 $cmd2 = "exec $cmd"; # yes, this really is necessary. if we don't
1681 # do this, the process doesn't die properly.
1682 if (!$verbose_pbm) {
1684 # We get a "giftopnm: got a 'Application Extension' extension"
1685 # warning any time it's an animgif.
1687 # Note that "giftopnm: EOF / read error on image data" is not
1688 # always a fatal error -- sometimes the image looks fine anyway.
1690 $cmd2 .= " 2>/dev/null";
1693 # There exist corrupted GIF and JPEG files that can make giftopnm and
1694 # djpeg lose their minds and go into a loop. So this gives those programs
1695 # a small timeout -- if they don't complete in time, kill them.
1701 local $SIG{ALRM} = sub {
1703 "timed out ($cvt_timeout) for $cmd on \"$url\" in pid $pid");
1704 kill ('TERM', $pid) if ($pid);
1709 if (($pid = open(PIPE, "| $cmd2 > $output"))) {
1716 LOG ($verbose_exec, "awaiting $pid");
1718 LOG ($verbose_exec, "$pid completed");
1720 my $size = (stat($output))[7];
1721 $size = -1 unless defined($size);
1723 LOG ($verbose_pbm, "$cmd on ${w}x$h \"$url\" failed ($size bytes)");
1727 LOG ($verbose_pbm, "created ${w}x$h $output ($cmd)");
1730 print STDERR blurb() . "$cmd failed: $!\n";
1734 die if ($@ && $@ ne "alarm\n"); # propagate errors
1747 sub pick_root_displayer {
1750 foreach my $cmd (@root_displayers) {
1752 my ($name) = m/^([^ ]+)/;
1753 push @names, "\"$name\"";
1754 LOG ($verbose_exec, "looking for $name...");
1755 foreach my $dir (split (/:/, $ENV{PATH})) {
1756 LOG ($verbose_exec, " checking $dir/$name");
1757 return $cmd if (-x "$dir/$name");
1761 $names[$#names] = "or " . $names[$#names];
1762 error "none of: " . join (", ", @names) . " were found on \$PATH.";
1766 my $ppm_to_root_window_cmd = undef;
1769 sub x_or_pbm_output {
1771 # make sure the various programs we execute exist, right up front.
1773 foreach ("ppmmake", "giftopnm", "djpeg", "pnmpaste", "pnmscale", "pnmcut") {
1774 which ($_) || error "$_ not found on \$PATH.";
1777 # find a root-window displayer program.
1779 $ppm_to_root_window_cmd = pick_root_displayer();
1782 $SIG{HUP} = \&x_cleanup;
1783 $SIG{INT} = \&x_cleanup;
1784 $SIG{QUIT} = \&x_cleanup;
1785 $SIG{ABRT} = \&x_cleanup;
1786 $SIG{KILL} = \&x_cleanup;
1787 $SIG{TERM} = \&x_cleanup;
1789 # Need this so that if giftopnm dies, we don't die.
1790 $SIG{PIPE} = 'IGNORE';
1792 if (!$img_width || !$img_height) {
1794 which ($_) || error "$_ not found on \$PATH.";
1796 ($img_width, $img_height) = m/dimensions: *(\d+)x(\d+) /;
1797 if (!defined($img_height)) {
1798 error "xdpyinfo failed.";
1802 my $bgcolor = "#000000";
1803 my $bgimage = undef;
1806 if ($background =~ m/^\#[0-9a-f]+$/i) {
1807 $bgcolor = $background;
1809 } elsif (-r $background) {
1810 $bgimage = $background;
1812 } elsif (! $background =~ m@^[-a-z0-9 ]+$@i) {
1813 error "not a color or readable file: $background";
1816 # default to assuming it's a color
1817 $bgcolor = $background;
1821 # Create the sold-colored base image.
1823 $_ = "ppmmake '$bgcolor' $img_width $img_height";
1824 LOG ($verbose_pbm, "creating base image: $_");
1825 nontrapping_system "$_ > $image_ppm";
1827 # Paste the default background image in the middle of it.
1834 open(IMG, "<$bgimage") || error "couldn't open $bgimage: $!";
1836 while (<IMG>) { $body .= $_; }
1839 if ((@_ = gif_size ($body))) {
1841 $cmd = "giftopnm |";
1843 } elsif ((@_ = jpeg_size ($body))) {
1847 } elsif ($body =~ m/^P\d\n(\d+) (\d+)\n/) {
1853 error "$bgimage is not a GIF, JPEG, or PPM.";
1856 my $x = int (($img_width - $iw) / 2);
1857 my $y = int (($img_height - $ih) / 2);
1859 "pasting $bgimage (${iw}x$ih) into base image at $x,$y");
1861 $cmd .= "pnmpaste - $x $y $image_ppm > $image_tmp1";
1862 open (IMG, "| $cmd") || error "running $cmd: $!";
1866 LOG ($verbose_exec, "subproc exited normally.");
1867 rename ($image_tmp1, $image_ppm) ||
1868 error "renaming $image_tmp1 to $image_ppm: $!";
1874 my ($base, $img) = pick_image();
1875 my $source = $current_state;
1876 $current_state = "loadimage";
1878 my ($headers, $body) = get_document ($img, $base);
1880 paste_image ($base, $img, $body, $source);
1884 $current_state = "idle";
1885 $load_method = "none";
1887 unlink $image_tmp1, $image_tmp2;
1893 my ($base, $img, $body, $source) = @_;
1895 $current_state = "paste";
1897 $suppress_audit = 0;
1899 LOG ($verbose_pbm, "got $img (" . length($body) . ")");
1901 my ($iw, $ih) = image_to_pnm ($img, $body, $image_tmp1);
1904 LOG ($verbose_pbm, "unable to make PBM from $img");
1908 record_success ($load_method, $img, $base);
1911 my $ow = $iw; # used only for error messages
1914 # don't just tack this onto the front of the pipeline -- we want it to
1915 # be able to change the size of the input image.
1918 LOG ($verbose_pbm, "running $filter_cmd");
1920 my $rc = nontrapping_system "($filter_cmd) < $image_tmp1 >$image_tmp2";
1922 LOG(($verbose_pbm || $verbose_load), "failed command: \"$filter_cmd\"");
1923 LOG(($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
1926 rename ($image_tmp2, $image_tmp1);
1928 # re-get the width/height in case the filter resized it.
1930 open(IMG, "<$image_tmp1") || return 0;
1933 ($iw, $ih) = m/^(\d+) (\d+)$/;
1935 return 0 unless ($iw && $ih);
1938 my $target_w = $img_width;
1939 my $target_h = $img_height;
1944 # Usually scale the image to fit on the screen -- but sometimes scale it
1945 # to fit on half or a quarter of the screen. Note that we don't merely
1946 # scale it to fit, we instead cut it in half until it fits -- that should
1947 # give a wider distribution of sizes.
1949 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
1950 if (rand() < 0.3) { $target_w /= 2; $target_h /= 2; }
1952 if ($iw > $target_w || $ih > $target_h) {
1953 while ($iw > $target_w ||
1958 if ($iw <= 10 || $ih <= 10) {
1959 LOG ($verbose_pbm, "scaling to ${iw}x$ih would have been bogus.");
1963 LOG ($verbose_pbm, "scaling to ${iw}x$ih");
1965 $cmd .= " | pnmscale -xsize $iw -ysize $ih";
1969 my $src = $image_tmp1;
1971 my $crop_x = 0; # the sub-rectangle of the image
1972 my $crop_y = 0; # that we will actually paste.
1976 # The chance that we will randomly crop out a section of an image starts
1977 # out fairly low, but goes up for images that are very large, or images
1978 # that have ratios that make them look like banners (we try to avoid
1979 # banner images entirely, but they slip through when the IMG tags didn't
1980 # have WIDTH and HEIGHT specified.)
1982 my $crop_chance = 0.2;
1983 if ($iw > $img_width * 0.4 || $ih > $img_height * 0.4) {
1984 $crop_chance += 0.2;
1986 if ($iw > $img_width * 0.7 || $ih > $img_height * 0.7) {
1987 $crop_chance += 0.2;
1989 if ($min_ratio && ($iw * $min_ratio) > $ih) {
1990 $crop_chance += 0.7;
1993 if ($crop_chance > 0.1) {
1994 LOG ($verbose_pbm, "crop chance: $crop_chance");
1997 if (rand() < $crop_chance) {
2002 if ($crop_w > $min_width) {
2003 # if it's a banner, select the width linearly.
2004 # otherwise, select a bell.
2005 my $r = (($min_ratio && ($iw * $min_ratio) > $ih)
2008 $crop_w = $min_width + int ($r * ($crop_w - $min_width));
2009 $crop_x = int (rand() * ($ow - $crop_w));
2011 if ($crop_h > $min_height) {
2012 # height always selects as a bell.
2013 $crop_h = $min_height + int (bellrand() * ($crop_h - $min_height));
2014 $crop_y = int (rand() * ($oh - $crop_h));
2017 if ($crop_x != 0 || $crop_y != 0 ||
2018 $crop_w != $iw || $crop_h != $ih) {
2020 "randomly cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
2024 # Where the image should logically land -- this might be negative.
2026 my $x = int((rand() * ($img_width + $crop_w/2)) - $crop_w*3/4);
2027 my $y = int((rand() * ($img_height + $crop_h/2)) - $crop_h*3/4);
2029 # if we have chosen to paste the image outside of the rectangle of the
2030 # screen, then we need to crop it.
2034 $x + $crop_w > $img_width ||
2035 $y + $crop_h > $img_height) {
2038 "cropping for effective paste of ${crop_w}x$crop_h \@ $x,$y");
2040 if ($x < 0) { $crop_x -= $x; $crop_w += $x; $x = 0; }
2041 if ($y < 0) { $crop_y -= $y; $crop_h += $y; $y = 0; }
2043 if ($x + $crop_w >= $img_width) { $crop_w = $img_width - $x - 1; }
2044 if ($y + $crop_h >= $img_height) { $crop_h = $img_height - $y - 1; }
2047 # If any cropping needs to happen, add pnmcut.
2049 if ($crop_x != 0 || $crop_y != 0 ||
2050 $crop_w != $iw || $crop_h != $ih) {
2053 $cmd .= " | pnmcut $crop_x $crop_y $iw $ih";
2054 LOG ($verbose_pbm, "cropping to ${crop_w}x$crop_h \@ $crop_x,$crop_y");
2057 LOG ($verbose_pbm, "pasting ${iw}x$ih \@ $x,$y in $image_ppm");
2059 $cmd .= " | pnmpaste - $x $y $image_ppm";
2061 $cmd =~ s@^ *\| *@@;
2064 $_ .= " < $image_tmp1 > $image_tmp2";
2067 $_ = "($_) 2>&1 | sed s'/^/" . blurb() . "/'";
2069 $_ .= " 2> /dev/null";
2071 my $rc = nontrapping_system ($_);
2074 LOG (($verbose_pbm || $verbose_load), "failed command: \"$cmd\"");
2075 LOG (($verbose_pbm || $verbose_load), "failed URL: \"$img\" (${ow}x$oh)");
2079 rename ($image_tmp2, $image_ppm) || return;
2081 my $target = "$image_ppm";
2083 # don't just tack this onto the end of the pipeline -- we don't want it
2084 # to end up in $image_ppm, because we don't want the results to be
2087 if ($post_filter_cmd) {
2088 $target = $image_tmp1;
2089 $rc = nontrapping_system "($post_filter_cmd) < $image_ppm > $target";
2091 LOG ($verbose_pbm, "filter failed: \"$post_filter_cmd\"\n");
2096 if (!$no_output_p) {
2097 my $tsize = (stat($target))[7];
2099 $cmd = "$ppm_to_root_window_cmd $target";
2101 # xv seems to hate being killed. it tends to forget to clean
2102 # up after itself, and leaves windows around and colors allocated.
2103 # I had this same problem with vidwhacker, and I'm not entirely
2104 # sure what I did to fix it. But, let's try this: launch xv
2105 # in the background, so that killing this process doesn't kill it.
2106 # it will die of its own accord soon enough. So this means we
2107 # start pumping bits to the root window in parallel with starting
2108 # the next network retrieval, which is probably a better thing
2113 $rc = nontrapping_system ($cmd);
2116 LOG (($verbose_pbm || $verbose_load), "display failed: \"$cmd\"");
2121 LOG ($verbose_pbm, "$target size is $tsize");
2125 $source .= "-" . stats_of($source);
2126 print STDOUT "image: ${iw}x${ih} @ $x,$y $base $source\n"
2127 if ($verbose_imgmap);
2142 $current_state = "init";
2143 $load_method = "none";
2147 # historical suckage: the environment variable name is lower case.
2148 $http_proxy = $ENV{http_proxy} || $ENV{HTTP_PROXY};
2150 while ($_ = $ARGV[0]) {
2152 if ($_ eq "-display" ||
2158 $ENV{DISPLAY} = shift @ARGV;
2159 } elsif ($_ eq "-root") {
2161 } elsif ($_ eq "-no-output") {
2163 } elsif ($_ eq "-urls-only") {
2166 } elsif ($_ eq "-verbose") {
2168 } elsif (m/^-v+$/) {
2169 $verbose += length($_)-1;
2170 } elsif ($_ eq "-delay") {
2171 $delay = shift @ARGV;
2172 } elsif ($_ eq "-timeout") {
2173 $http_timeout = shift @ARGV;
2174 } elsif ($_ eq "-filter") {
2175 $filter_cmd = shift @ARGV;
2176 } elsif ($_ eq "-filter2") {
2177 $post_filter_cmd = shift @ARGV;
2178 } elsif ($_ eq "-background" || $_ eq "-bg") {
2179 $background = shift @ARGV;
2180 } elsif ($_ eq "-size") {
2182 if (m@^(\d+)x(\d+)$@) {
2186 error "argument to \"-size\" must be of the form \"640x400\"";
2188 } elsif ($_ eq "-proxy" || $_ eq "-http-proxy") {
2189 $http_proxy = shift @ARGV;
2190 } elsif ($_ eq "-dictionary" || $_ eq "-dict") {
2191 $dict = shift @ARGV;
2193 print STDERR "$copyright\nusage: $progname [-root]" .
2194 " [-display dpy] [-root] [-verbose] [-timeout secs]\n" .
2195 "\t\t [-delay secs] [-filter cmd] [-filter2 cmd]\n" .
2196 "\t\t [-dictionary dictionary-file]\n" .
2197 "\t\t [-http-proxy host[:port]]\n";
2202 if ($http_proxy && $http_proxy eq "") {
2203 $http_proxy = undef;
2205 if ($http_proxy && $http_proxy =~ m@^http://([^/]*)/?$@ ) {
2206 # historical suckage: allow "http://host:port" as well as "host:port".
2210 if (!$root_p && !$no_output_p) {
2211 print STDERR $copyright;
2212 error "the -root argument is mandatory (for now.)";
2215 if (!$no_output_p && !$ENV{DISPLAY}) {
2216 error "\$DISPLAY is not set.";
2220 if ($verbose == 1) {
2221 $verbose_imgmap = 1;
2222 $verbose_warnings = 1;
2224 } elsif ($verbose == 2) {
2225 $verbose_imgmap = 1;
2226 $verbose_warnings = 1;
2229 } elsif ($verbose == 3) {
2230 $verbose_imgmap = 1;
2231 $verbose_warnings = 1;
2233 $verbose_filter = 1;
2235 } elsif ($verbose == 4) {
2236 $verbose_imgmap = 1;
2237 $verbose_warnings = 1;
2239 $verbose_filter = 1;
2242 } elsif ($verbose == 5) {
2243 $verbose_imgmap = 1;
2244 $verbose_warnings = 1;
2246 $verbose_filter = 1;
2250 } elsif ($verbose == 6) {
2251 $verbose_imgmap = 1;
2252 $verbose_warnings = 1;
2254 $verbose_filter = 1;
2259 } elsif ($verbose >= 7) {
2260 $verbose_imgmap = 1;
2261 $verbose_warnings = 1;
2263 $verbose_filter = 1;
2271 error ("$dict does not exist") unless (-f $dict);