2 # Copyright © 2001-2017 Jamie Zawinski <jwz@jwz.org>.
4 # Permission to use, copy, modify, distribute, and sell this software and its
5 # documentation for any purpose is hereby granted without fee, provided that
6 # the above copyright notice appear in all copies and that both that
7 # copyright notice and this permission notice appear in supporting
8 # documentation. No representations are made about the suitability of this
9 # software for any purpose. It is provided "as is" without express or
12 # This program chooses a random file from under the given directory, and
13 # prints its name. The file will be an image file whose dimensions are
14 # larger than a certain minimum size.
16 # If the directory is a URL, it is assumed to be an RSS or Atom feed.
17 # The images from that feed will be downloaded, cached, and selected from
18 # at random. The feed will be re-polled periodically, as needed.
20 # The various xscreensaver hacks that manipulate images ("jigsaw", etc.) get
21 # the image to manipulate by running the "xscreensaver-getimage" program.
23 # Under X11, the "xscreensaver-getimage" program invokes this script,
24 # depending on the value of the "chooseRandomImages" and "imageDirectory"
25 # settings in the ~/.xscreensaver file (or .../app-defaults/XScreenSaver).
26 # The screen savers invoke "xscreensaver-getimage" via utils/grabclient.c,
27 # which then invokes this script.
29 # Under Cocoa, this script lives inside the .saver bundle, and is invoked
30 # directly from utils/grabclient.c.
35 #use diagnostics; # Fails on some MacOS 10.5 systems
41 use Fcntl ':flock'; # import LOCK_* constants
43 use POSIX ':fcntl_h'; # S_ISDIR was here in Perl 5.6
44 import Fcntl ':mode' unless defined &S_ISUID; # but it is here in Perl 5.8
45 # but in Perl 5.10, both of these load, and cause errors!
46 # So we have to check for S_ISUID instead of S_ISDIR? WTF?
48 use Digest::MD5 qw(md5_base64);
50 # Some Linux systems don't install LWP by default!
51 # Only error out if we're actually loading a URL instead of local data.
52 BEGIN { eval 'use LWP::Simple;' }
55 my $progname = $0; $progname =~ s@.*/@@g;
56 my ($version) = ('$Revision: 1.43 $' =~ m/\s(\d[.\d]+)\s/s);
60 # Whether to use MacOS X's Spotlight to generate the list of files.
61 # When set to -1, uses Spotlight if "mdfind" exists.
63 # (In my experience, this isn't actually any faster, and might not find
64 # everything if your Spotlight index is out of date, which happens often.)
66 my $use_spotlight_p = 0;
68 # Whether to cache the results of the last run.
72 # Regenerate the cache if it is older than this many seconds.
74 my $cache_max_age = 60 * 60 * 3; # 3 hours
76 # Re-poll RSS/Atom feeds when local copy is older than this many seconds.
78 my $feed_max_age = $cache_max_age;
81 # This matches files that we are allowed to use as images (case-insensitive.)
82 # Anything not matching this is ignored. This is so you can point your
83 # imageDirectory at directory trees that have things other than images in
84 # them, but it assumes that you gave your images sensible file extensions.
86 my @good_extensions = ('jpg', 'jpeg', 'pjpeg', 'pjpg', 'png', 'gif',
87 'tif', 'tiff', 'xbm', 'xpm');
88 my $good_file_re = '\.(' . join("|", @good_extensions) . ')$';
90 # This matches file extensions that might occur in an image directory,
91 # and that are never used in the name of a subdirectory. This is an
92 # optimization that prevents us from having to stat() those files to
93 # tell whether they are directories or not. (It speeds things up a
94 # lot. Don't give your directories stupid names.)
96 my @nondir_extensions = ('ai', 'bmp', 'bz2', 'cr2', 'crw', 'db',
97 'dmg', 'eps', 'gz', 'hqx', 'htm', 'html', 'icns', 'ilbm', 'mov',
98 'nef', 'pbm', 'pdf', 'pl', 'ppm', 'ps', 'psd', 'sea', 'sh', 'shtml',
99 'tar', 'tgz', 'thb', 'txt', 'xcf', 'xmp', 'Z', 'zip' );
100 my $nondir_re = '\.(' . join("|", @nondir_extensions) . ')$';
103 # JPEG, GIF, and PNG files that are are smaller than this are rejected:
104 # this is so that you can use an image directory that contains both big
105 # images and thumbnails, and have it only select the big versions.
107 my $min_image_width = 255;
108 my $min_image_height = 255;
110 my @all_files = (); # list of "good" files we've collected
111 my %seen_inodes; # for breaking recursive symlink loops
113 # For diagnostic messages:
115 my $dir_count = 1; # number of directories seen
116 my $stat_count = 0; # number of files/dirs stat'ed
117 my $skip_count_unstat = 0; # number of files skipped without stat'ing
118 my $skip_count_stat = 0; # number of files skipped after stat
120 sub find_all_files($);
121 sub find_all_files($) {
124 print STDERR "$progname: + reading dir $dir/...\n" if ($verbose > 1);
127 if (! opendir ($dd, $dir)) {
128 print STDERR "$progname: couldn't open $dir: $!\n" if ($verbose);
131 my @files = readdir ($dd);
136 foreach my $file (@files) {
137 next if ($file =~ m/^\./); # silently ignore dot files/dirs
139 if ($file =~ m/[~%\#]$/) { # ignore backup files (and dirs...)
140 $skip_count_unstat++;
141 print STDERR "$progname: - skip file $file\n" if ($verbose > 1);
144 $file = "$dir/$file";
146 if ($file =~ m/$good_file_re/io) {
148 # Assume that files ending in .jpg exist and are not directories.
150 push @all_files, $file;
151 print STDERR "$progname: - found file $file\n" if ($verbose > 1);
153 } elsif ($file =~ m/$nondir_re/io) {
155 # Assume that files ending in .html are not directories.
157 $skip_count_unstat++;
158 print STDERR "$progname: -- skip file $file\n" if ($verbose > 1);
162 # Now we need to stat the file to see if it's a subdirectory.
164 # Note: we could use the trick of checking "nlinks" on the parent
165 # directory to see if this directory contains any subdirectories,
166 # but that would exclude any symlinks to directories.
168 my @st = stat($file);
169 my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
170 $atime,$mtime,$ctime,$blksize,$blocks) = @st;
176 my $ll = readlink $file;
178 print STDERR "$progname: + dangling symlink: $file -> $ll\n";
180 print STDERR "$progname: + unreadable: $file\n";
186 next if ($seen_inodes{"$dev:$ino"}); # break symlink loops
187 $seen_inodes{"$dev:$ino"} = 1;
189 if (S_ISDIR($mode)) {
192 print STDERR "$progname: + found dir $file\n" if ($verbose > 1);
196 print STDERR "$progname: + skip file $file\n" if ($verbose > 1);
207 sub spotlight_all_files($) {
211 # "public.image" matches all (indexed) images, including Photoshop, etc.
212 # push @terms, "kMDItemContentTypeTree == 'public.image'";
213 foreach (@good_extensions) {
215 # kMDItemFSName hits the file system every time: much worse than "find".
216 # push @terms, "kMDItemFSName == '*.$_'";
218 # kMDItemDisplayName matches against the name in the Spotlight index,
219 # but won't find files that (for whatever reason) didn't get indexed.
220 push @terms, "kMDItemDisplayName == '*.$_'";
223 $dir =~ s@([^-_/a-z\d.,])@\\$1@gsi; # quote for sh
224 my $cmd = "mdfind -onlyin $dir \"" . join (' || ', @terms) . "\"";
226 print STDERR "$progname: executing: $cmd\n" if ($verbose > 1);
227 @all_files = split (/[\r\n]+/, `$cmd`);
231 # If we're using cacheing, read the cache file and return its contents,
232 # if any. This also holds an exclusive lock on the cache file, which
233 # has the additional benefit that if two copies of this program are
234 # running at once, one will wait for the other, instead of both of
235 # them spanking the same file system at the same time.
237 my $cache_fd = undef;
238 my $cache_file_name = undef;
239 my $read_cache_p = 0;
244 return () unless ($cache_p);
246 my $dd = "$ENV{HOME}/Library/Caches"; # MacOS location
248 $cache_file_name = "$dd/org.jwz.xscreensaver.getimage.cache";
249 } elsif (-d "$ENV{HOME}/.cache") { # Gnome "FreeDesktop XDG" location
250 $dd = "$ENV{HOME}/.cache/xscreensaver";
251 if (! -d $dd) { mkdir ($dd) || error ("mkdir $dd: $!"); }
252 $cache_file_name = "$dd/xscreensaver-getimage.cache"
253 } elsif (-d "$ENV{HOME}/tmp") { # If ~/tmp/ exists, use it.
254 $cache_file_name = "$ENV{HOME}/tmp/.xscreensaver-getimage.cache";
256 $cache_file_name = "$ENV{HOME}/.xscreensaver-getimage.cache";
259 print STDERR "$progname: awaiting lock: $cache_file_name\n"
262 my $file = $cache_file_name;
263 open ($cache_fd, '+>>', $file) || error ("unable to write $file: $!");
264 flock ($cache_fd, LOCK_EX) || error ("unable to lock $file: $!");
265 seek ($cache_fd, 0, 0) || error ("unable to rewind $file: $!");
267 my $mtime = (stat($cache_fd))[9];
269 if ($mtime + $cache_max_age < time) {
270 print STDERR "$progname: cache is too old\n" if ($verbose);
274 my $odir = <$cache_fd>;
275 $odir =~ s/[\r\n]+$//s if defined ($odir);
276 if (!defined ($odir) || ($dir ne $odir)) {
277 print STDERR "$progname: cache is for $odir, not $dir\n"
278 if ($verbose && $odir);
283 while (<$cache_fd>) {
285 push @files, "$odir/$_";
288 print STDERR "$progname: " . ($#files+1) . " files in cache\n"
299 return unless ($cache_p);
301 # If we read the cache, just close it without rewriting it.
302 # If we didn't read it, then write it now.
304 if (! $read_cache_p) {
306 truncate ($cache_fd, 0) ||
307 error ("unable to truncate $cache_file_name: $!");
308 seek ($cache_fd, 0, 0) ||
309 error ("unable to rewind $cache_file_name: $!");
311 if ($#all_files >= 0) {
312 print $cache_fd "$dir\n";
313 foreach (@all_files) {
314 my $f = $_; # stupid Perl. do this to avoid modifying @all_files!
315 $f =~ s@^\Q$dir/@@so || die; # remove $dir from front
316 print $cache_fd "$f\n";
320 print STDERR "$progname: cached " . ($#all_files+1) . " files\n"
324 flock ($cache_fd, LOCK_UN) ||
325 error ("unable to unlock $cache_file_name: $!");
331 sub html_unquote($) {
334 # This only needs to handle entities that occur in RSS, not full HTML.
335 my %ent = ( 'amp' => '&', 'lt' => '<', 'gt' => '>',
336 'quot' => '"', 'apos' => "'" );
337 $h =~ s/(&(\#)?([[:alpha:]\d]+);?)/
339 my ($o, $c) = ($1, $3);
341 $c = $ent{$c}; # for <
343 if ($c =~ m@^x([\dA-F]+)$@si) { # for A
345 } elsif ($c =~ m@^\d+$@si) { # for A
359 # Figure out what the proxy server should be, either from environment
360 # variables or by parsing the output of the (MacOS) program "scutil",
361 # which tells us what the system-wide proxy settings are.
366 my $proxy_data = `scutil --proxy 2>/dev/null`;
367 foreach my $proto ('http', 'https') {
368 my ($server) = ($proxy_data =~ m/\b${proto}Proxy\s*:\s*([^\s]+)/si);
369 my ($port) = ($proxy_data =~ m/\b${proto}Port\s*:\s*([^\s]+)/si);
370 my ($enable) = ($proxy_data =~ m/\b${proto}Enable\s*:\s*([^\s]+)/si);
372 if ($server && $enable) {
373 # Note: this ignores the "ExceptionsList".
375 $ENV{"${proto}_proxy"} = ("${proto2}://" . $server .
376 ($port ? ":$port" : "") . "/");
377 print STDERR "$progname: MacOS $proto proxy: " .
378 $ENV{"${proto}_proxy"} . "\n"
388 if (! defined ($LWP::Simple::ua)) {
389 error ("\n\n\tPerl is broken. Do this to repair it:\n" .
390 "\n\tsudo cpan LWP::Simple LWP::Protocol::https Mozilla::CA\n");
392 set_proxy ($LWP::Simple::ua);
396 # Returns a list of the image enclosures in the RSS or Atom feed.
397 # Elements of the list are references, [ "url", "guid" ].
404 $LWP::Simple::ua->agent ("$progname/$version");
405 $LWP::Simple::ua->timeout (10); # bail sooner than the default of 3 minutes
408 # Half the time, random Linux systems don't have Mozilla::CA installed,
409 # which results in "Can't verify SSL peers without knowning which
410 # Certificate Authorities to trust".
412 # In xscreensaver-text we just disabled certificate checks. However,
413 # malicious images really do exist, so for xscreensaver-getimage-file,
414 # let's actually require that SSL be installed properly.
417 my $body = (LWP::Simple::get($url) || '');
419 if ($body !~ m@^\s*<(\?xml|rss)\b@si) {
420 # Not an RSS/Atom feed. Try RSS autodiscovery.
422 # (Great news, everybody: Flickr no longer provides RSS for "Sets",
423 # only for "Photostreams", and only the first 20 images of those.
426 error ("null response: $url")
427 if ($body =~ m/^\s*$/s);
429 error ("not an RSS or Atom feed, or HTML: $url")
430 unless ($body =~ m@<(HEAD|BODY|A|IMG)\b@si);
432 # Find the first <link> with RSS or Atom in it, and use that instead.
434 $body =~ s@<LINK\s+([^<>]*)>@{
436 if ($p =~ m! \b REL \s* = \s* ['"]? alternate \b!six &&
437 $p =~ m! \b TYPE \s* = \s* ['"]? application/(atom|rss) !six &&
438 $p =~ m! \b HREF \s* = \s* ['"] ( [^<>'"]+ ) !six
440 my $u2 = html_unquote ($1);
442 my ($h) = ($url =~ m!^([a-z]+://[^/]+)!si);
445 print STDERR "$progname: found feed: $u2\n"
447 return parse_feed ($u2);
452 error ("no RSS or Atom feed for HTML page: $url");
456 $body =~ s@(<ENTRY|<ITEM)@\001$1@gsi;
457 my @items = split(/\001/, $body);
463 foreach my $item (@items) {
467 # First look for <link rel="enclosure" href="...">
470 $item =~ s!(<LINK[^<>]*>)!{
472 my ($rel) = ($link =~ m/\bREL\s*=\s*[\"\']?([^<>\'\"]+)/si);
473 my ($type) = ($link =~ m/\bTYPE\s*=\s*[\"\']?([^<>\'\"]+)/si);
474 my ($href) = ($link =~ m/\bHREF\s*=\s*[\"\']([^<>\'\"]+)/si);
476 if ($rel && lc($rel) eq 'enclosure') {
478 $href = undef unless ($type =~ m@^image/@si); # omit videos
480 $iurl = html_unquote($href) if $href;
486 # Then look for <media:content url="...">
489 $item =~ s!(<MEDIA:CONTENT[^<>]*>)!{
491 my ($href) = ($link =~ m/\bURL\s*=\s*[\"\']([^<>\'\"]+)/si);
492 $iurl = html_unquote($href) if $href;
497 # Then look for <enclosure url="..."/>
500 $item =~ s!(<ENCLOSURE[^<>]*>)!{
502 my ($type) = ($link =~ m/\bTYPE\s*=\s*[\"\']?([^<>\'\"]+)/si);
503 my ($href) = ($link =~ m/\bURL\s*=\s*[\"\']([^<>\'\"]+)/si);
504 $iurl = html_unquote($href)
505 if ($href && $type && $type =~ m@^image/@si); # omit videos
510 # Ok, maybe there's an image in the <url> field?
513 $item =~ s!((<URL\b[^<>]*>)([^<>]*))!{
514 my ($all, $u2) = ($1, $3);
515 $iurl = html_unquote($u2) if ($u2 =~ m/$good_file_re/io);
520 # Then look for <description>... with an <img src="..."> inside.
523 $item =~ s!(<description[^<>]*>.*?</description>)!{
525 $desc = html_unquote($desc);
526 my ($href) = ($desc =~ m@<IMG[^<>]*\bSRC=[\"\']?([^\"\'<>]+)@si);
527 $iurl = $href if ($href);
532 # Could also do <content:encoded>, but the above probably covers all
533 # of the real-world possibilities.
536 # Find a unique ID for this image, to defeat image farms.
537 # First look for <id>...</id>
538 ($id) = ($item =~ m!<ID\b[^<>]*>\s*([^<>]+?)\s*</ID>!si) unless $id;
540 # Then look for <guid isPermaLink=...> ... </guid>
541 ($id) = ($item =~ m!<GUID\b[^<>]*>\s*([^<>]+?)\s*</GUID>!si) unless $id;
543 # Then look for <link> ... </link>
544 ($id) = ($item =~ m!<LINK\b[^<>]*>\s*([^<>]+?)\s*</LINK>!si) unless $id;
548 $id = $iurl unless $id;
552 my @P = ($iurl, $id);
554 } elsif ($iurl ne $o) {
555 print STDERR "$progname: WARNING: dup ID \"$id\"" .
556 " for \"$o\" and \"$iurl\"\n";
565 # Like md5_base64 but uses filename-safe characters.
576 # Given the URL of an image, download it into the given directory
577 # and return the file name.
579 sub download_image($$$) {
580 my ($url, $uid, $dir) = @_;
583 $url2 =~ s/\#.*$//s; # Omit search terms after file extension
585 my ($ext) = ($url2 =~ m@\.([a-z\d]+)$@si);
587 # If the feed hasn't put a sane extension on their URLs, nothing's going
588 # to work. This code assumes that file names have extensions, even the
589 # ones in the cache directory.
592 print STDERR "$progname: skipping extensionless URL: $url\n"
597 # Don't bother downloading files that we will reject anyway.
599 if (! ($url2 =~ m/$good_file_re/io)) {
600 print STDERR "$progname: skipping non-image URL: $url\n"
605 my $file = md5_file ($uid);
606 $file .= '.' . lc($ext) if $ext;
608 # Don't bother doing If-Modified-Since to see if the URL has changed.
609 # If we have already downloaded it, assume it's good.
610 if (-f "$dir/$file") {
611 print STDERR "$progname: exists: $dir/$file for $uid / $url\n"
616 # Special-case kludge for Flickr:
617 # Their RSS feeds sometimes include only the small versions of the images.
618 # So if the URL ends in one of the "small-size" letters, change it to "b".
633 # Note: if we wanted to get the _k or _o version instead of the _b or _h
634 # version, we'd need to crack the DRM -- which is easy: see crack_secret
635 # in "https://www.jwz.org/hacks/galdown".
637 $url =~ s@_[sqtmnzc](\.[a-z]+)$@_b$1@si
638 if ($url =~ m@^https?://[^/?#&]*?flickr\.com/@si);
640 print STDERR "$progname: downloading: $dir/$file for $uid / $url\n"
643 $LWP::Simple::ua->agent ("$progname/$version");
644 my $status = LWP::Simple::mirror ($url, "$dir/$file");
645 if (!LWP::Simple::is_success ($status)) {
646 print STDERR "$progname: error $status: $url\n"; # keep going
656 if ($url !~ m/^https?:/si) { # not a URL: local directory.
657 return (undef, $url);
660 my $dir = "$ENV{HOME}/Library/Caches"; # MacOS location
662 $dir = "$dir/org.jwz.xscreensaver.feeds";
663 } elsif (-d "$ENV{HOME}/.cache") { # Gnome "FreeDesktop XDG" location
664 $dir = "$ENV{HOME}/.cache/xscreensaver";
665 if (! -d $dir) { mkdir ($dir) || error ("mkdir $dir: $!"); }
667 if (! -d $dir) { mkdir ($dir) || error ("mkdir $dir: $!"); }
668 } elsif (-d "$ENV{HOME}/tmp") { # If ~/tmp/ exists, use it.
669 $dir = "$ENV{HOME}/tmp/.xscreensaver-feeds";
671 $dir = "$ENV{HOME}/.xscreensaver-feeds";
675 mkdir ($dir) || error ("mkdir $dir: $!");
676 print STDERR "$progname: mkdir $dir/\n" if ($verbose);
679 # MD5 for directory name to use for cache of a feed URL.
680 $dir .= '/' . md5_file ($url);
683 mkdir ($dir) || error ("mkdir $dir: $!");
684 print STDERR "$progname: mkdir $dir/ for $url\n" if ($verbose);
687 # At this point, we have the directory corresponding to this URL.
688 # Now check to see if the files in it are up to date, and download
691 my $stamp = '.timestamp';
692 my $lock = "$dir/$stamp";
694 print STDERR "$progname: awaiting lock: $lock\n"
697 my $mtime = ((stat($lock))[9]) || 0;
700 open ($lock_fd, '+>>', $lock) || error ("unable to write $lock: $!");
701 flock ($lock_fd, LOCK_EX) || error ("unable to lock $lock: $!");
702 seek ($lock_fd, 0, 0) || error ("unable to rewind $lock: $!");
704 my $poll_p = ($mtime + $feed_max_age < time);
706 # --no-cache cmd line arg means poll again right now.
707 $poll_p = 1 unless ($cache_p);
709 # Even if the cache is young, make sure there is at least one file,
710 # and re-check if not.
714 opendir (my $dirh, $dir) || error ("$dir: $!");
715 foreach my $f (readdir ($dirh)) {
716 next if ($f =~ m/^\./s);
723 print STDERR "$progname: no files in cache of $url\n" if ($verbose);
730 print STDERR "$progname: loading $url\n" if ($verbose);
733 opendir (my $dirh, $dir) || error ("$dir: $!");
734 foreach my $f (readdir ($dirh)) {
735 next if ($f eq '.' || $f eq '..');
736 $files{$f} = 0; # 0 means "file exists, should be deleted"
742 # Download each image currently in the feed.
745 my @urls = parse_feed ($url);
746 print STDERR "$progname: " . ($#urls + 1) . " images\n"
748 foreach my $p (@urls) {
749 my ($furl, $id) = @$p;
750 my $f = download_image ($furl, $id, $dir);
752 $files{$f} = 1; # Got it, don't delete
756 my $empty_p = ($count <= 0);
758 # Now delete any files that are no longer in the feed.
759 # But if there was nothing in the feed (network failure?)
760 # then don't blow away the old files.
763 foreach my $f (keys(%files)) {
766 } elsif ($files{$f}) {
769 if (unlink ("$dir/$f")) {
770 print STDERR "$progname: rm $dir/$f\n" if ($verbose > 1);
772 print STDERR "$progname: rm $dir/$f: $!\n"; # don't bail
777 # Both feed and cache are empty. No files at all. Bail.
778 error ("empty feed: $url") if ($kept <= 1);
780 # Feed is empty, but we have some files from last time. Warn.
781 print STDERR "$progname: empty feed: using cache: $url\n"
784 $mtime = time(); # update the timestamp
788 # Not yet time to re-check the URL.
789 print STDERR "$progname: using cache: $url\n" if ($verbose);
793 # Unlock and update the write date on the .timestamp file.
795 truncate ($lock_fd, 0) || error ("unable to truncate $lock: $!");
796 seek ($lock_fd, 0, 0) || error ("unable to rewind $lock: $!");
797 utime ($mtime, $mtime, $lock_fd) || error ("unable to touch $lock: $!");
798 flock ($lock_fd, LOCK_UN) || error ("unable to unlock $lock: $!");
801 print STDERR "$progname: unlocked $lock\n" if ($verbose > 1);
803 # Don't bother using the imageDirectory cache. We know that this directory
804 # is flat, and we can assume that an RSS feed doesn't contain 100,000 images
805 # like ~/Pictures/ might.
809 # Return the URL and directory name of the files of that URL's local cache.
815 sub find_random_file($) {
818 if ($use_spotlight_p == -1) {
819 $use_spotlight_p = 0;
820 if (-x '/usr/bin/mdfind') {
821 $use_spotlight_p = 1;
826 ($url, $dir) = mirror_feed ($dir);
829 $use_spotlight_p = 0;
830 print STDERR "$progname: $dir is cache for $url\n" if ($verbose > 1);
833 @all_files = read_cache ($dir);
835 if ($#all_files >= 0) {
836 # got it from the cache...
838 } elsif ($use_spotlight_p) {
839 print STDERR "$progname: spotlighting $dir...\n" if ($verbose);
840 spotlight_all_files ($dir);
841 print STDERR "$progname: found " . ($#all_files+1) .
842 " file" . ($#all_files == 0 ? "" : "s") .
846 print STDERR "$progname: recursively reading $dir...\n" if ($verbose);
847 find_all_files ($dir);
848 print STDERR "$progname: " .
849 "f=" . ($#all_files+1) . "; " .
852 "skip=${skip_count_unstat}+$skip_count_stat=" .
853 ($skip_count_unstat + $skip_count_stat) .
860 if ($#all_files < 0) {
861 print STDERR "$progname: no files in $dir\n";
866 for (my $i = 0; $i < $max_tries; $i++) {
868 my $n = int (rand ($#all_files + 1));
869 my $file = $all_files[$n];
870 if (large_enough_p ($file)) {
872 $file =~ s@^\Q$dir/@@so || die; # remove $dir from front
878 print STDERR "$progname: no suitable images in $dir " .
879 "(after $max_tries tries)\n";
881 # If we got here, blow away the cache. Maybe it's stale.
882 unlink $cache_file_name if $cache_file_name;
888 sub large_enough_p($) {
891 my ($w, $h) = image_file_size ($file);
895 # Nonexistent files are obviously too small!
896 # Already printed $verbose message about the file not existing.
897 return 0 unless -f $file;
899 print STDERR "$progname: $file: unable to determine image size\n"
901 # Assume that unknown files are of good sizes: this will happen if
902 # they matched $good_file_re, but we don't have code to parse them.
903 # (This will also happen if the file is junk...)
907 if ($w < $min_image_width || $h < $min_image_height) {
908 print STDERR "$progname: $file: too small ($w x $h)\n" if ($verbose);
912 print STDERR "$progname: $file: $w x $h\n" if ($verbose);
918 # Given the raw body of a GIF document, returns the dimensions of the image.
922 my $type = substr($body, 0, 6);
924 return () unless ($type =~ /GIF8[7,9]a/);
925 $s = substr ($body, 6, 10);
926 my ($a,$b,$c,$d) = unpack ("C"x4, $s);
927 return (($b<<8|$a), ($d<<8|$c));
930 # Given the raw body of a JPEG document, returns the dimensions of the image.
935 my $L = length($body);
937 my $c1 = substr($body, $i, 1); $i++;
938 my $c2 = substr($body, $i, 1); $i++;
939 return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
942 while (ord($ch) != 0xDA && $i < $L) {
943 # Find next marker, beginning with 0xFF.
944 while (ord($ch) != 0xFF) {
945 return () if (length($body) <= $i);
946 $ch = substr($body, $i, 1); $i++;
948 # markers can be padded with any number of 0xFF.
949 while (ord($ch) == 0xFF) {
950 return () if (length($body) <= $i);
951 $ch = substr($body, $i, 1); $i++;
954 # $ch contains the value of the marker.
955 my $marker = ord($ch);
957 if (($marker >= 0xC0) &&
960 ($marker != 0xCC)) { # it's a SOFn marker
962 return () if (length($body) <= $i);
963 my $s = substr($body, $i, 4); $i += 4;
964 my ($a,$b,$c,$d) = unpack("C"x4, $s);
965 return (($c<<8|$d), ($a<<8|$b));
968 # We must skip variables, since FFs in variable names aren't
969 # valid JPEG markers.
970 return () if (length($body) <= $i);
971 my $s = substr($body, $i, 2); $i += 2;
972 my ($c1, $c2) = unpack ("C"x2, $s);
973 my $length = ($c1 << 8) | $c2;
974 return () if ($length < 2);
981 # Given the raw body of a PNG document, returns the dimensions of the image.
985 return () unless ($body =~ m/^\211PNG\r/s);
986 my ($bits) = ($body =~ m/^.{12}(.{12})/s);
987 return () unless defined ($bits);
988 return () unless ($bits =~ /^IHDR/);
989 my ($ign, $w, $h) = unpack("a4N2", $bits);
994 # Given the raw body of a GIF, JPEG, or PNG document, returns the dimensions
999 return () if (length($body) < 10);
1000 my ($w, $h) = gif_size ($body);
1001 if ($w && $h) { return ($w, $h); }
1002 ($w, $h) = jpeg_size ($body);
1003 if ($w && $h) { return ($w, $h); }
1004 # #### TODO: need image parsers for TIFF, XPM, XBM.
1005 return png_size ($body);
1008 # Returns the dimensions of the image file.
1010 sub image_file_size($) {
1013 if (! open ($in, '<:raw', $file)) {
1014 print STDERR "$progname: $file: $!\n" if ($verbose);
1018 sysread ($in, $body, 1024 * 50); # The first 50k should be enough.
1019 close $in; # (It's not for certain huge jpegs...
1020 return image_size ($body); # but we know they're huge!)
1026 print STDERR "$progname: $err\n";
1031 print STDERR "usage: $progname [--verbose] directory-or-feed-url\n\n" .
1032 " Prints the name of a randomly-selected image file. The directory\n" .
1033 " is searched recursively. Images smaller than " .
1034 "${min_image_width}x${min_image_height} are excluded.\n" .
1036 " The directory may also be the URL of an RSS/Atom feed. Enclosed\n" .
1037 " images will be downloaded and cached locally.\n" .
1045 while ($_ = $ARGV[0]) {
1047 if (m/^--?verbose$/s) { $verbose++; }
1048 elsif (m/^-v+$/s) { $verbose += length($_)-1; }
1049 elsif (m/^--?name$/s) { } # ignored, for compatibility
1050 elsif (m/^--?spotlight$/s) { $use_spotlight_p = 1; }
1051 elsif (m/^--?no-spotlight$/s) { $use_spotlight_p = 0; }
1052 elsif (m/^--?cache$/s) { $cache_p = 1; }
1053 elsif (m/^--?no-?cache$/s) { $cache_p = 0; }
1054 elsif (m/^-./) { usage; }
1055 elsif (!defined($dir)) { $dir = $_; }
1059 usage unless (defined($dir));
1061 $dir =~ s@^feed:@http:@si;
1063 if ($dir =~ m/^https?:/si) {
1066 $dir =~ s@^~/@$ENV{HOME}/@s; # allow literal "~/"
1067 $dir =~ s@/+$@@s; # omit trailing /
1070 print STDERR "$progname: $dir: not a directory or URL\n";
1075 my $file = find_random_file ($dir);
1076 print STDOUT "$file\n";