From http://www.jwz.org/xscreensaver/xscreensaver-5.15.tar.gz
[xscreensaver] / driver / xscreensaver-getimage-file
1 #!/usr/bin/perl -w
2 # Copyright © 2001-2011 Jamie Zawinski <jwz@jwz.org>.
3 #
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 
10 # implied warranty.
11 #
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.
15 #
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.
19 #
20 # The various xscreensaver hacks that manipulate images ("jigsaw", etc.) get
21 # the image to manipulate by running the "xscreensaver-getimage" program.
22 #
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.
28 #
29 # Under Cocoa, this script lives inside the .saver bundle, and is invoked
30 # directly from utils/grabclient.c.
31 #
32 # Created: 12-Apr-01.
33
34 require 5;
35 #use diagnostics;       # Fails on some MacOS 10.5 systems
36 use strict;
37
38 use POSIX;
39 use Fcntl;
40
41 use Fcntl ':flock'; # import LOCK_* constants
42
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?
47
48 use bytes;  # Larry can take Unicode and shove it up his ass sideways.
49             # Perl 5.8.0 causes us to start getting incomprehensible
50             # errors about UTF-8 all over the place without this.
51
52 use Digest::MD5 qw(md5_base64);
53 use LWP::Simple qw($ua);
54
55
56 my $progname = $0; $progname =~ s@.*/@@g;
57 my $version = q{ $Revision: 1.30 $ }; $version =~ s/^[^0-9]+([0-9.]+).*$/$1/;
58
59 my $verbose = 0;
60
61 # Whether to use MacOS X's Spotlight to generate the list of files.
62 # When set to -1, uses Spotlight if "mdfind" exists.
63 #
64 # (In my experience, this isn't actually any faster, and might not find
65 # everything if your Spotlight index is out of date, which happens often.)
66 #
67 my $use_spotlight_p = 0;
68
69 # Whether to cache the results of the last run.
70 #
71 my $cache_p = 1;
72
73 # Regenerate the cache if it is older than this many seconds.
74 #
75 my $cache_max_age = 60 * 60 * 3;   # 3 hours
76
77 # Re-poll RSS/Atom feeds when local copy is older than this many seconds.
78 #
79 my $feed_max_age = $cache_max_age;
80
81
82 # This matches files that we are allowed to use as images (case-insensitive.)
83 # Anything not matching this is ignored.  This is so you can point your
84 # imageDirectory at directory trees that have things other than images in
85 # them, but it assumes that you gave your images sensible file extensions.
86 #
87 my @good_extensions = ('jpg', 'jpeg', 'pjpeg', 'pjpg', 'png', 'gif',
88                        'tif', 'tiff', 'xbm', 'xpm');
89 my $good_file_re = '\.(' . join("|", @good_extensions) . ')$';
90
91 # This matches file extensions that might occur in an image directory,
92 # and that are never used in the name of a subdirectory.  This is an
93 # optimization that prevents us from having to stat() those files to
94 # tell whether they are directories or not.  (It speeds things up a
95 # lot.  Don't give your directories stupid names.)
96 #
97 my @nondir_extensions = ('ai', 'bmp', 'bz2', 'cr2', 'crw', 'db',
98    'dmg', 'eps', 'gz', 'hqx', 'htm', 'html', 'icns', 'ilbm', 'mov',
99    'nef', 'pbm', 'pdf', 'pl', 'ppm', 'ps', 'psd', 'sea', 'sh', 'shtml',
100    'tar', 'tgz', 'thb', 'txt', 'xcf', 'xmp', 'Z', 'zip' );
101 my $nondir_re = '\.(' . join("|", @nondir_extensions) . ')$';
102
103
104 # JPEG, GIF, and PNG files that are are smaller than this are rejected:
105 # this is so that you can use an image directory that contains both big
106 # images and thumbnails, and have it only select the big versions.
107 #
108 my $min_image_width  = 255;
109 my $min_image_height = 255;
110
111 my @all_files = ();         # list of "good" files we've collected
112 my %seen_inodes;            # for breaking recursive symlink loops
113
114 # For diagnostic messages:
115 #
116 my $dir_count = 1;          # number of directories seen
117 my $stat_count = 0;         # number of files/dirs stat'ed
118 my $skip_count_unstat = 0;  # number of files skipped without stat'ing
119 my $skip_count_stat = 0;    # number of files skipped after stat
120
121 sub find_all_files($);
122 sub find_all_files($) {
123   my ($dir) = @_;
124
125   print STDERR "$progname:  + reading dir $dir/...\n" if ($verbose > 1);
126
127   my $dd;
128   if (! opendir ($dd, $dir)) {
129     print STDERR "$progname: couldn't open $dir: $!\n" if ($verbose);
130     return;
131   }
132   my @files = readdir ($dd);
133   closedir ($dd);
134
135   my @dirs = ();
136
137   foreach my $file (@files) {
138     next if ($file =~ m/^\./);      # silently ignore dot files/dirs
139
140     if ($file =~ m/[~%\#]$/) {      # ignore backup files (and dirs...)
141       $skip_count_unstat++;
142       print STDERR "$progname:  - skip file  $file\n" if ($verbose > 1);
143     }
144
145     $file = "$dir/$file";
146
147     if ($file =~ m/$good_file_re/io) {
148       #
149       # Assume that files ending in .jpg exist and are not directories.
150       #
151       push @all_files, $file;
152       print STDERR "$progname:  - found file $file\n" if ($verbose > 1);
153
154     } elsif ($file =~ m/$nondir_re/io) {
155       #
156       # Assume that files ending in .html are not directories.
157       #
158       $skip_count_unstat++;
159       print STDERR "$progname: -- skip file  $file\n" if ($verbose > 1);
160
161     } else {
162       #
163       # Now we need to stat the file to see if it's a subdirectory.
164       #
165       # Note: we could use the trick of checking "nlinks" on the parent
166       # directory to see if this directory contains any subdirectories,
167       # but that would exclude any symlinks to directories.
168       #
169       my @st = stat($file);
170       my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
171           $atime,$mtime,$ctime,$blksize,$blocks) = @st;
172
173       $stat_count++;
174
175       if ($#st == -1) {
176         if ($verbose) {
177           my $ll = readlink $file;
178           if (defined ($ll)) {
179             print STDERR "$progname: + dangling symlink: $file -> $ll\n";
180           } else {
181             print STDERR "$progname: + unreadable: $file\n";
182           }
183         }
184         next;
185       }
186
187       next if ($seen_inodes{"$dev:$ino"}); # break symlink loops
188       $seen_inodes{"$dev:$ino"} = 1;
189
190       if (S_ISDIR($mode)) {
191         push @dirs, $file;
192         $dir_count++;
193         print STDERR "$progname:  + found dir  $file\n" if ($verbose > 1);
194
195       } else {
196         $skip_count_stat++;
197         print STDERR "$progname:  + skip file  $file\n" if ($verbose > 1);
198       }
199     }
200   }
201
202   foreach (@dirs) {
203     find_all_files ($_);
204   }
205 }
206
207
208 sub spotlight_all_files($) {
209   my ($dir) = @_;
210
211   my @terms = ();
212   # "public.image" matches all (indexed) images, including Photoshop, etc.
213 #  push @terms, "kMDItemContentTypeTree == 'public.image'";
214   foreach (@good_extensions) {
215
216     # kMDItemFSName hits the file system every time: much worse than "find".
217 #    push @terms, "kMDItemFSName == '*.$_'";
218
219     # kMDItemDisplayName matches against the name in the Spotlight index,
220     # but won't find files that (for whatever reason) didn't get indexed.
221     push @terms, "kMDItemDisplayName == '*.$_'";
222   }
223
224   $dir =~ s@([^-_/a-z\d.,])@\\$1@gsi;  # quote for sh
225   my $cmd = "mdfind -onlyin $dir \"" . join (' || ', @terms) . "\"";
226
227   print STDERR "$progname: executing: $cmd\n" if ($verbose > 1);
228   @all_files = split (/[\r\n]+/, `$cmd`);
229 }
230
231
232 # If we're using cacheing, read the cache file and return its contents,
233 # if any.  This also holds an exclusive lock on the cache file, which 
234 # has the additional benefit that if two copies of this program are
235 # running at once, one will wait for the other, instead of both of
236 # them spanking the same file system at the same time.
237 #
238 my $cache_fd = undef;
239 my $cache_file_name = undef;
240 my $read_cache_p = 0;
241
242 sub read_cache($) {
243   my ($dir) = @_;
244
245   return () unless ($cache_p);
246
247   my $dd = "$ENV{HOME}/Library/Caches";    # MacOS location
248   if (-d $dd) {
249     $cache_file_name = "$dd/org.jwz.xscreensaver.getimage.cache";
250   } elsif (-d "$ENV{HOME}/tmp") {
251     $cache_file_name = "$ENV{HOME}/tmp/.xscreensaver-getimage.cache";
252   } else {
253     $cache_file_name = "$ENV{HOME}/.xscreensaver-getimage.cache";
254   }
255
256   print STDERR "$progname: awaiting lock: $cache_file_name\n"
257     if ($verbose > 1);
258
259   my $file = $cache_file_name;
260   open ($cache_fd, '+>>', $file) || error ("unable to write $file: $!");
261   flock ($cache_fd, LOCK_EX)     || error ("unable to lock $file: $!");
262   seek ($cache_fd, 0, 0)         || error ("unable to rewind $file: $!");
263
264   my $mtime = (stat($cache_fd))[9];
265
266   if ($mtime + $cache_max_age < time) {
267     print STDERR "$progname: cache is too old\n" if ($verbose);
268     return ();
269   }
270
271   my $odir = <$cache_fd>;
272   $odir =~ s/[\r\n]+$//s if defined ($odir);
273   if (!defined ($odir) || ($dir ne $odir)) {
274     print STDERR "$progname: cache is for $odir, not $dir\n"
275       if ($verbose && $odir);
276     return ();
277   }
278
279   my @files = ();
280   while (<$cache_fd>) { 
281     s/[\r\n]+$//s;
282     push @files, "$odir/$_";
283   }
284
285   print STDERR "$progname: " . ($#files+1) . " files in cache\n"
286     if ($verbose);
287
288   $read_cache_p = 1;
289   return @files;
290 }
291
292
293 sub write_cache($) {
294   my ($dir) = @_;
295
296   return unless ($cache_p);
297
298   # If we read the cache, just close it without rewriting it.
299   # If we didn't read it, then write it now.
300
301   if (! $read_cache_p) {
302
303     truncate ($cache_fd, 0) ||
304       error ("unable to truncate $cache_file_name: $!");
305     seek ($cache_fd, 0, 0) ||
306       error ("unable to rewind $cache_file_name: $!");
307
308     if ($#all_files >= 0) {
309       print $cache_fd "$dir\n";
310       foreach (@all_files) {
311         my $f = $_; # stupid Perl. do this to avoid modifying @all_files!
312         $f =~ s@^\Q$dir\L/@@so || die;  # remove $dir from front
313         print $cache_fd "$f\n";
314       }
315     }
316
317     print STDERR "$progname: cached " . ($#all_files+1) . " files\n"
318       if ($verbose);
319   }
320
321   flock ($cache_fd, LOCK_UN) ||
322     error ("unable to unlock $cache_file_name: $!");
323   close ($cache_fd);
324   $cache_fd = undef;
325 }
326
327
328 # Returns a list of the image enclosures in the RSS or Atom feed.
329 # Elements of the list are references, [ "url", "guid" ].
330 #
331 sub parse_feed($) {
332   my ($url) = @_;
333
334   $ua->agent ("$progname/$version");
335   $ua->timeout (10);  # bail sooner than the default of 3 minutes
336
337   my $body = (LWP::Simple::get($url) || '');
338
339   error ("not an RSS or Atom feed: $url")
340     unless ($body =~ m@^<\?xml\s@si);
341
342   $body =~ s@(<ENTRY|<ITEM)@\001$1@gsi;
343   my @items = split(/\001/, $body);
344   shift @items;
345
346   my @imgs = ();
347   my %ids;
348
349   foreach my $item (@items) {
350     my $iurl = undef;
351     my $id = undef;
352
353     # First look for <link rel="enclosure" href="...">
354     #
355     if (! $iurl) {
356       $item =~ s!(<LINK[^<>]*>)!{
357         my $link = $1;
358         my ($rel)  = ($link =~ m/\bREL\s*=\s*[\"\']?([^<>\'\"]+)/si);
359         my ($type) = ($link =~ m/\bTYPE\s*=\s*[\"\']?([^<>\'\"]+)/si);
360         my ($href) = ($link =~ m/\bHREF\s*=\s*[\"\']([^<>\'\"]+)/si);
361
362         if ($rel && lc($rel) eq 'enclosure') {
363           if ($type) {
364             $href = undef unless ($type =~ m@^image/@si);  # omit videos
365           }
366           $iurl = $href if ($href);
367         }
368         $link;
369       }!gsexi;
370     }
371
372     # Then look for <media:content url="...">
373     #
374     if (! $iurl) {
375       $item =~ s!(<MEDIA:CONTENT[^<>]*>)!{
376         my $link = $1;
377         my ($href) = ($link =~ m/\bURL\s*=\s*[\"\']([^<>\'\"]+)/si);
378         $iurl = $href if $href;
379         $link;
380       }!gsexi;
381     }
382
383     # Then look for <description>... with an <img href="..."> inside.
384     #
385     if (! $iurl) {
386       $item =~ s!(<description[^<>]*>.*?</description>)!{
387         my $desc = $1;
388         $desc =~ s/&lt;/</gs;
389         $desc =~ s/&gt;/>/gs;
390         $desc =~ s/&quot;/\"/gs;
391         $desc =~ s/&apos;/\'/gs;
392         $desc =~ s/&amp;/&/gs;
393         my ($href) = ($desc =~ m@<IMG[^<>]*\bSRC=[\"\']?([^\"\'<>]+)@si);
394         $iurl = $href if ($href);
395         $desc;
396       }!gsexi;
397     }
398
399     # Could also do <content:encoded>, but the above probably covers all
400     # of the real-world possibilities.
401
402
403     # Find a unique ID for this image, to defeat image farms.
404     # First look for <id>...</id>
405     ($id) = ($item =~ m!<ID\b[^<>]*>\s*([^<>]+?)\s*</ID>!si) unless $id;
406
407     # Then look for <guid isPermaLink=...> ... </guid>
408     ($id) = ($item =~ m!<GUID\b[^<>]*>\s*([^<>]+?)\s*</GUID>!si) unless $id;
409
410     # Then look for <link> ... </link>
411     ($id) = ($item =~ m!<LINK\b[^<>]*>\s*([^<>]+?)\s*</LINK>!si) unless $id;
412
413
414     if ($iurl) {
415       $id = $iurl unless $id;
416       my $o = $ids{$id};
417       if (! $o) {
418         $ids{$id} = $iurl;
419         my @P = ($iurl, $id);
420         push @imgs, \@P;
421       } elsif ($iurl ne $o) {
422         print STDERR "$progname: WARNING: dup ID \"$id\"" .
423                      " for \"$o\" and \"$iurl\"\n";
424       }
425     }
426   }
427
428   return @imgs;
429 }
430
431
432 # Like md5_base64 but uses filename-safe characters.
433 #
434 sub md5_file($) {
435   my ($s) = @_;
436   $s = md5_base64($s);
437   $s =~ s@[/]@_@gs;
438   $s =~ s@[+]@-@gs;
439   return $s;
440 }
441
442
443 # Given the URL of an image, download it into the given directory
444 # and return the file name.
445 #
446 sub download_image($$$) {
447   my ($url, $uid, $dir) = @_;
448
449   my ($ext) = ($url =~ m@\.([a-z\d]+)$@si);
450   my $file = md5_file ($uid);
451   $file .= '.' . lc($ext) if $ext;
452
453   # Don't bother doing If-Modified-Since to see if the URL has changed.
454   # If we have already downloaded it, assume it's good.
455   if (-f "$dir/$file") {
456     print STDERR "$progname: exists: $dir/$file for $uid / $url\n" 
457       if ($verbose > 1);
458     return $file;
459   }
460
461   # Special-case kludge for Flickr:
462   # Their RSS feeds sometimes include only the small versions of the images.
463   # So if the URL ends in "s" (75x75), "t" (100x100) or "m" (240x240),then
464   # munge it to be "b" (1024x1024).
465   #
466   $url =~ s@_[stm](\.[a-z]+)$@_b$1@si
467     if ($url =~ m@^https?://[^/?#&]*?flickr\.com/@si);
468
469   print STDERR "$progname: downloading: $dir/$file for $uid / $url\n" 
470     if ($verbose > 1);
471   $ua->agent ("$progname/$version");
472   my $status = LWP::Simple::mirror ($url, "$dir/$file");
473   if (!LWP::Simple::is_success ($status)) {
474     print STDERR "$progname: error $status: $url\n";   # keep going
475   }
476
477   return $file;
478 }
479
480
481 sub mirror_feed($) {
482   my ($url) = @_;
483
484   if ($url !~ m/^https?:/si) {   # not a URL: local directory.
485     return (undef, $url);
486   }
487
488   my $dir = "$ENV{HOME}/Library/Caches";    # MacOS location
489   if (-d $dir) {
490     $dir = "$dir/org.jwz.xscreensaver.feeds";
491   } elsif (-d "$ENV{HOME}/tmp") {
492     $dir = "$ENV{HOME}/tmp/.xscreensaver-feeds";
493   } else {
494     $dir = "$ENV{HOME}/.xscreensaver-feeds";
495   }
496
497   if (! -d $dir) {
498     mkdir ($dir) || error ("mkdir $dir: $!");
499     print STDERR "$progname: mkdir $dir/\n" if ($verbose);
500   }
501
502   # MD5 for directory name to use for cache of a feed URL.
503   $dir .= '/' . md5_file ($url);
504
505   if (! -d $dir) {
506     mkdir ($dir) || error ("mkdir $dir: $!");
507     print STDERR "$progname: mkdir $dir/ for $url\n" if ($verbose);
508   }
509
510   # At this point, we have the directory corresponding to this URL.
511   # Now check to see if the files in it are up to date, and download
512   # them if not.
513
514   my $stamp = '.timestamp';
515   my $lock = "$dir/$stamp";
516
517   print STDERR "$progname: awaiting lock: $lock\n"
518     if ($verbose > 1);
519
520   my $mtime = ((stat($lock))[9]) || 0;
521
522   my $lock_fd;
523   open ($lock_fd, '+>>', $lock) || error ("unable to write $lock: $!");
524   flock ($lock_fd, LOCK_EX)     || error ("unable to lock $lock: $!");
525   seek ($lock_fd, 0, 0)         || error ("unable to rewind $lock: $!");
526
527   my $poll_p = ($mtime + $feed_max_age < time);
528
529   $poll_p = 1 unless ($cache_p);  # poll again now with --no-cache cmd line arg.
530
531   # Even if the cache is young, let's make sure there are at least
532   # a few files in it, and re-check if not.
533   #
534   if (! $poll_p) {
535     my $count = 0;
536     opendir (my $dirh, $dir) || error ("$dir: $!");
537     foreach my $f (readdir ($dirh)) {
538       next if ($f =~ m/^\./s);
539       $count++;
540       last;
541     }
542     closedir $dirh;
543
544     if ($count <= 0) {
545       print STDERR "$progname: no files in cache of $url\n" if ($verbose);
546       $poll_p = 1;
547     }
548   }
549
550   if ($poll_p) {
551
552     print STDERR "$progname: loading $url\n" if ($verbose);
553
554     my %files;
555     opendir (my $dirh, $dir) || error ("$dir: $!");
556     foreach my $f (readdir ($dirh)) {
557       next if ($f eq '.' || $f eq '..');
558       $files{$f} = 0;  # 0 means "file exists, should be deleted"
559     }
560     closedir $dirh;
561
562     $files{$stamp} = 1;
563
564     # Download each image currently in the feed.
565     #
566     my $count = 0;
567     my @urls = parse_feed ($url);
568     foreach my $p (@urls) {
569       my ($furl, $id) = @$p;
570       my $f = download_image ($furl, $id, $dir);
571       next unless $f;
572       $files{$f} = 1;    # Got it, don't delete
573       $count++;
574     }
575
576     print STDERR "$progname: empty feed: $url\n" if ($count <= 0);
577
578     # Now delete any files that are no longer in the feed.
579     # But if there was nothing in the feed (network failure?)
580     # then don't blow away the old files.
581     #
582     my $kept = 0;
583     foreach my $f (keys(%files)) {
584       if ($count <= 0) {
585         $kept++;
586       } elsif ($files{$f}) {
587         $kept++;
588       } else {
589         if (unlink ("$dir/$f")) {
590           print STDERR "$progname: rm $dir/$f\n" if ($verbose > 1);
591         } else {
592           print STDERR "$progname: rm $dir/$f: $!\n";   # don't bail
593         }
594       }
595     }
596
597     # Both feed and cache are empty. No files at all.
598     error ("empty feed: $url") if ($kept <= 1);
599
600     $mtime = time();    # update the timestamp
601
602   } else {
603
604     # Not yet time to re-check the URL.
605     print STDERR "$progname: using cache: $url\n" if ($verbose);
606
607   }
608
609   # Unlock and update the write date on the .timestamp file.
610   #
611   truncate ($lock_fd, 0) || error ("unable to truncate $lock: $!");
612   seek ($lock_fd, 0, 0)  || error ("unable to rewind $lock: $!");
613   utime ($mtime, $mtime, $lock_fd) || error ("unable to touch $lock: $!");
614   flock ($lock_fd, LOCK_UN) || error ("unable to unlock $lock: $!");
615   close ($lock_fd);
616   $lock_fd = undef;
617   print STDERR "$progname: unlocked $lock\n" if ($verbose > 1);
618
619   # Don't bother using the imageDirectory cache.  We know that this directory
620   # is flat, and we can assume that an RSS feed doesn't contain 100,000 images
621   # like ~/Pictures/ might.
622   #
623   $cache_p = 0;
624
625   # Return the URL and directory name of the files of that URL's local cache.
626   #
627   return ($url, $dir);
628 }
629
630
631 sub find_random_file($) {
632   my ($dir) = @_;
633
634   if ($use_spotlight_p == -1) {
635     $use_spotlight_p = 0;
636     if (-x '/usr/bin/mdfind') {
637       $use_spotlight_p = 1;
638     }
639   }
640
641   my $url;
642   ($url, $dir) = mirror_feed ($dir);
643
644   if ($url) {
645     $use_spotlight_p = 0;
646     print STDERR "$progname: $dir is cache for $url\n" if ($verbose > 1);
647   }
648
649   @all_files = read_cache ($dir);
650
651   if ($#all_files >= 0) {
652     # got it from the cache...
653
654   } elsif ($use_spotlight_p) {
655     print STDERR "$progname: spotlighting $dir...\n" if ($verbose);
656     spotlight_all_files ($dir);
657     print STDERR "$progname: found " . ($#all_files+1) .
658                  " file" . ($#all_files == 0 ? "" : "s") .
659                  " via Spotlight\n"
660       if ($verbose);
661   } else {
662     print STDERR "$progname: recursively reading $dir...\n" if ($verbose);
663     find_all_files ($dir);
664     print STDERR "$progname: " .
665                  "f=" . ($#all_files+1) . "; " .
666                  "d=$dir_count; " .
667                  "s=$stat_count; " .
668                  "skip=${skip_count_unstat}+$skip_count_stat=" .
669                   ($skip_count_unstat + $skip_count_stat) .
670                  ".\n"
671       if ($verbose);
672   }
673
674   write_cache ($dir);
675
676 #  @all_files = sort(@all_files);
677
678   if ($#all_files < 0) {
679     print STDERR "$progname: no files in $dir\n";
680     exit 1;
681   }
682
683   my $max_tries = 50;
684   for (my $i = 0; $i < $max_tries; $i++) {
685
686     my $n = int (rand ($#all_files + 1));
687     my $file = $all_files[$n];
688     if (large_enough_p ($file)) {
689       if (! $url) {
690         $file =~ s@^\Q$dir\L/@@so || die;  # remove $dir from front
691       }
692       return $file;
693     }
694   }
695
696   print STDERR "$progname: no suitable images in $dir " .
697                "(after $max_tries tries)\n";
698   exit 1;
699 }
700
701
702 sub large_enough_p($) {
703   my ($file) = @_;
704
705   my ($w, $h) = image_file_size ($file);
706
707   if (!defined ($h)) {
708     print STDERR "$progname: $file: unable to determine image size\n"
709       if ($verbose);
710     # Assume that unknown files are of good sizes: this will happen if
711     # they matched $good_file_re, but we don't have code to parse them.
712     # (This will also happen if the file is junk...)
713     return 1;
714   }
715
716   if ($w < $min_image_width || $h < $min_image_height) {
717     print STDERR "$progname: $file: too small ($w x $h)\n" if ($verbose);
718     return 0;
719   }
720
721   print STDERR "$progname: $file: $w x $h\n" if ($verbose);
722   return 1;
723 }
724
725
726
727 # Given the raw body of a GIF document, returns the dimensions of the image.
728 #
729 sub gif_size($) {
730   my ($body) = @_;
731   my $type = substr($body, 0, 6);
732   my $s;
733   return () unless ($type =~ /GIF8[7,9]a/);
734   $s = substr ($body, 6, 10);
735   my ($a,$b,$c,$d) = unpack ("C"x4, $s);
736   return (($b<<8|$a), ($d<<8|$c));
737 }
738
739 # Given the raw body of a JPEG document, returns the dimensions of the image.
740 #
741 sub jpeg_size($) {
742   my ($body) = @_;
743   my $i = 0;
744   my $L = length($body);
745
746   my $c1 = substr($body, $i, 1); $i++;
747   my $c2 = substr($body, $i, 1); $i++;
748   return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
749
750   my $ch = "0";
751   while (ord($ch) != 0xDA && $i < $L) {
752     # Find next marker, beginning with 0xFF.
753     while (ord($ch) != 0xFF) {
754       return () if (length($body) <= $i);
755       $ch = substr($body, $i, 1); $i++;
756     }
757     # markers can be padded with any number of 0xFF.
758     while (ord($ch) == 0xFF) {
759       return () if (length($body) <= $i);
760       $ch = substr($body, $i, 1); $i++;
761     }
762
763     # $ch contains the value of the marker.
764     my $marker = ord($ch);
765
766     if (($marker >= 0xC0) &&
767         ($marker <= 0xCF) &&
768         ($marker != 0xC4) &&
769         ($marker != 0xCC)) {  # it's a SOFn marker
770       $i += 3;
771       return () if (length($body) <= $i);
772       my $s = substr($body, $i, 4); $i += 4;
773       my ($a,$b,$c,$d) = unpack("C"x4, $s);
774       return (($c<<8|$d), ($a<<8|$b));
775
776     } else {
777       # We must skip variables, since FFs in variable names aren't
778       # valid JPEG markers.
779       return () if (length($body) <= $i);
780       my $s = substr($body, $i, 2); $i += 2;
781       my ($c1, $c2) = unpack ("C"x2, $s);
782       my $length = ($c1 << 8) | $c2;
783       return () if ($length < 2);
784       $i += $length-2;
785     }
786   }
787   return ();
788 }
789
790 # Given the raw body of a PNG document, returns the dimensions of the image.
791 #
792 sub png_size($) {
793   my ($body) = @_;
794   return () unless ($body =~ m/^\211PNG\r/s);
795   my ($bits) = ($body =~ m/^.{12}(.{12})/s);
796   return () unless defined ($bits);
797   return () unless ($bits =~ /^IHDR/);
798   my ($ign, $w, $h) = unpack("a4N2", $bits);
799   return ($w, $h);
800 }
801
802
803 # Given the raw body of a GIF, JPEG, or PNG document, returns the dimensions
804 # of the image.
805 #
806 sub image_size($) {
807   my ($body) = @_;
808   return () if (length($body) < 10);
809   my ($w, $h) = gif_size ($body);
810   if ($w && $h) { return ($w, $h); }
811   ($w, $h) = jpeg_size ($body);
812   if ($w && $h) { return ($w, $h); }
813   # #### TODO: need image parsers for TIFF, XPM, XBM.
814   return png_size ($body);
815 }
816
817 # Returns the dimensions of the image file.
818 #
819 sub image_file_size($) {
820   my ($file) = @_;
821   my $in;
822   if (! open ($in, '<', $file)) {
823     print STDERR "$progname: $file: $!\n" if ($verbose);
824     return undef;
825   }
826   binmode ($in);  # Larry can take Unicode and shove it up his ass sideways.
827   my $body = '';
828   sysread ($in, $body, 1024 * 50);  # The first 50k should be enough.
829   close $in;                        # (It's not for certain huge jpegs...
830   return image_size ($body);        # but we know they're huge!)
831 }
832
833
834 sub error($) {
835   my ($err) = @_;
836   print STDERR "$progname: $err\n";
837   exit 1;
838 }
839
840 sub usage() {
841   print STDERR "usage: $progname [--verbose] directory\n" .
842   "       Prints the name of a randomly-selected image file.  The directory\n" .
843   "       is searched recursively.  Images smaller than " .
844          "${min_image_width}x${min_image_height} are excluded.\n" .
845   "\n" .
846   "       The directory may also be the URL of an RSS/Atom feed.  Enclosed\n" .
847   "       images will be downloaded cached locally.\n" .
848   "\n";
849   exit 1;
850 }
851
852 sub main() {
853   my $dir = undef;
854
855   while ($_ = $ARGV[0]) {
856     shift @ARGV;
857     if ($_ eq "--verbose") { $verbose++; }
858     elsif (m/^-v+$/) { $verbose += length($_)-1; }
859     elsif ($_ eq "--name") { }     # ignored, for compatibility
860     elsif ($_ eq "--spotlight")    { $use_spotlight_p = 1; }
861     elsif ($_ eq "--no-spotlight") { $use_spotlight_p = 0; }
862     elsif ($_ eq "--cache")        { $cache_p = 1; }
863     elsif ($_ eq "--no-cache")     { $cache_p = 0; }
864     elsif (m/^-./) { usage; }
865     elsif (!defined($dir)) { $dir = $_; }
866     else { usage; }
867   }
868
869   usage unless (defined($dir));
870
871   $dir =~ s@^feed:@http:@si;
872
873   if ($dir =~ m/^https?:/si) {
874     # ok
875   } else {
876     $dir =~ s@^~/@$ENV{HOME}/@s;     # allow literal "~/"
877     $dir =~ s@/+$@@s;              # omit trailing /
878
879     if (! -d $dir) {
880       print STDERR "$progname: $dir: not a directory or URL\n";
881       usage;
882     }
883   }
884
885   my $file = find_random_file ($dir);
886   print STDOUT "$file\n";
887 }
888
889 main;
890 exit 0;