2 # Copyright © 2001-2011 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 # The various xscreensaver hacks that manipulate images ("jigsaw", etc.) get
17 # the image to manipulate by running the "xscreensaver-getimage" program.
19 # Under X11, the "xscreensaver-getimage" program invokes this script,
20 # depending on the value of the "chooseRandomImages" and "imageDirectory"
21 # settings in the ~/.xscreensaver file (or .../app-defaults/XScreenSaver).
22 # The screen savers invoke "xscreensaver-getimage" via utils/grabclient.c,
23 # which then invokes this script.
25 # Under Cocoa, this script lives inside the .saver bundle, and is invoked
26 # directly from utils/grabclient.c.
31 #use diagnostics; # Fails on some MacOS 10.5 systems
37 use Fcntl ':flock'; # import LOCK_* constants
39 use POSIX ':fcntl_h'; # S_ISDIR was here in Perl 5.6
40 import Fcntl ':mode' unless defined &S_ISUID; # but it is here in Perl 5.8
41 # but in Perl 5.10, both of these load, and cause errors!
42 # So we have to check for S_ISUID instead of S_ISDIR? WTF?
44 use bytes; # Larry can take Unicode and shove it up his ass sideways.
45 # Perl 5.8.0 causes us to start getting incomprehensible
46 # errors about UTF-8 all over the place without this.
48 my $progname = $0; $progname =~ s@.*/@@g;
49 my $version = q{ $Revision: 1.29 $ }; $version =~ s/^[^0-9]+([0-9.]+).*$/$1/;
53 # Whether to use MacOS X's Spotlight to generate the list of files.
54 # When set to -1, uses Spotlight if "mdfind" exists.
56 # (In my experience, this isn't actually any faster, and might not find
57 # everything if your Spotlight index is out of date, which happens often.)
59 my $use_spotlight_p = 0;
61 # Whether to cache the results of the last run.
65 # Regenerate the cache if it is older than this many seconds.
67 my $cache_max_age = 60 * 60 * 3; # 3 hours
70 # This matches files that we are allowed to use as images (case-insensitive.)
71 # Anything not matching this is ignored. This is so you can point your
72 # imageDirectory at directory trees that have things other than images in
73 # them, but it assumes that you gave your images sensible file extensions.
75 my @good_extensions = ('jpg', 'jpeg', 'pjpeg', 'pjpg', 'png', 'gif',
76 'tif', 'tiff', 'xbm', 'xpm');
77 my $good_file_re = '\.(' . join("|", @good_extensions) . ')$';
79 # This matches file extensions that might occur in an image directory,
80 # and that are never used in the name of a subdirectory. This is an
81 # optimization that prevents us from having to stat() those files to
82 # tell whether they are directories or not. (It speeds things up a
83 # lot. Don't give your directories stupid names.)
85 my @nondir_extensions = ('ai', 'bmp', 'bz2', 'cr2', 'crw', 'db',
86 'dmg', 'eps', 'gz', 'hqx', 'htm', 'html', 'icns', 'ilbm', 'mov',
87 'nef', 'pbm', 'pdf', 'pl', 'ppm', 'ps', 'psd', 'sea', 'sh', 'shtml',
88 'tar', 'tgz', 'thb', 'txt', 'xcf', 'xmp', 'Z', 'zip' );
89 my $nondir_re = '\.(' . join("|", @nondir_extensions) . ')$';
92 # JPEG, GIF, and PNG files that are are smaller than this are rejected:
93 # this is so that you can use an image directory that contains both big
94 # images and thumbnails, and have it only select the big versions.
96 my $min_image_width = 255;
97 my $min_image_height = 255;
99 my @all_files = (); # list of "good" files we've collected
100 my %seen_inodes; # for breaking recursive symlink loops
102 # For diagnostic messages:
104 my $dir_count = 1; # number of directories seen
105 my $stat_count = 0; # number of files/dirs stat'ed
106 my $skip_count_unstat = 0; # number of files skipped without stat'ing
107 my $skip_count_stat = 0; # number of files skipped after stat
109 sub find_all_files($);
110 sub find_all_files($) {
113 print STDERR "$progname: + reading dir $dir/...\n" if ($verbose > 1);
116 if (! opendir ($dd, $dir)) {
117 print STDERR "$progname: couldn't open $dir: $!\n" if ($verbose);
120 my @files = readdir ($dd);
125 foreach my $file (@files) {
126 next if ($file =~ m/^\./); # silently ignore dot files/dirs
128 if ($file =~ m/[~%\#]$/) { # ignore backup files (and dirs...)
129 $skip_count_unstat++;
130 print STDERR "$progname: - skip file $file\n" if ($verbose > 1);
133 $file = "$dir/$file";
135 if ($file =~ m/$good_file_re/io) {
137 # Assume that files ending in .jpg exist and are not directories.
139 push @all_files, $file;
140 print STDERR "$progname: - found file $file\n" if ($verbose > 1);
142 } elsif ($file =~ m/$nondir_re/io) {
144 # Assume that files ending in .html are not directories.
146 $skip_count_unstat++;
147 print STDERR "$progname: -- skip file $file\n" if ($verbose > 1);
151 # Now we need to stat the file to see if it's a subdirectory.
153 # Note: we could use the trick of checking "nlinks" on the parent
154 # directory to see if this directory contains any subdirectories,
155 # but that would exclude any symlinks to directories.
157 my @st = stat($file);
158 my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
159 $atime,$mtime,$ctime,$blksize,$blocks) = @st;
165 my $ll = readlink $file;
167 print STDERR "$progname: + dangling symlink: $file -> $ll\n";
169 print STDERR "$progname: + unreadable: $file\n";
175 next if ($seen_inodes{"$dev:$ino"}); # break symlink loops
176 $seen_inodes{"$dev:$ino"} = 1;
178 if (S_ISDIR($mode)) {
181 print STDERR "$progname: + found dir $file\n" if ($verbose > 1);
185 print STDERR "$progname: + skip file $file\n" if ($verbose > 1);
196 sub spotlight_all_files($) {
200 # "public.image" matches all (indexed) images, including Photoshop, etc.
201 # push @terms, "kMDItemContentTypeTree == 'public.image'";
202 foreach (@good_extensions) {
204 # kMDItemFSName hits the file system every time: much worse than "find".
205 # push @terms, "kMDItemFSName == '*.$_'";
207 # kMDItemDisplayName matches against the name in the Spotlight index,
208 # but won't find files that (for whatever reason) didn't get indexed.
209 push @terms, "kMDItemDisplayName == '*.$_'";
212 $dir =~ s@([^-_/a-z\d.,])@\\$1@gsi; # quote for sh
213 my $cmd = "mdfind -onlyin $dir \"" . join (' || ', @terms) . "\"";
215 print STDERR "$progname: executing: $cmd\n" if ($verbose > 1);
216 @all_files = split (/[\r\n]+/, `$cmd`);
220 # If we're using cacheing, read the cache file and return its contents,
221 # if any. This also holds an exclusive lock on the cache file, which
222 # has the additional benefit that if two copies of this program are
223 # running at once, one will wait for the other, instead of both of
224 # them spanking the same file system at the same time.
226 my $cache_fd = undef;
227 my $cache_file_name = undef;
228 my $read_cache_p = 0;
233 return () unless ($cache_p);
235 my $dd = "$ENV{HOME}/Library/Caches"; # MacOS location
237 $cache_file_name = "$dd/org.jwz.xscreensaver.getimage.cache";
238 } elsif (-d "$ENV{HOME}/tmp") {
239 $cache_file_name = "$ENV{HOME}/tmp/.xscreensaver-getimage.cache";
241 $cache_file_name = "$ENV{HOME}/.xscreensaver-getimage.cache";
244 print STDERR "$progname: awaiting lock: $cache_file_name\n"
247 my $file = $cache_file_name;
248 open ($cache_fd, '+>>', $file) || error ("unable to write $file: $!");
249 flock ($cache_fd, LOCK_EX) || error ("unable to lock $file: $!");
250 seek ($cache_fd, 0, 0) || error ("unable to rewind $file: $!");
252 my $mtime = (stat($cache_fd))[9];
254 if ($mtime + $cache_max_age < time) {
255 print STDERR "$progname: cache is too old\n" if ($verbose);
259 my $odir = <$cache_fd>;
260 $odir =~ s/[\r\n]+$//s if defined ($odir);
261 if (!defined ($odir) || ($dir ne $odir)) {
262 print STDERR "$progname: cache is for $odir, not $dir\n"
263 if ($verbose && $odir);
268 while (<$cache_fd>) {
270 push @files, "$odir/$_";
273 print STDERR "$progname: " . ($#files+1) . " files in cache\n"
284 return unless ($cache_p);
286 # If we read the cache, just close it without rewriting it.
287 # If we didn't read it, then write it now.
289 if (! $read_cache_p) {
291 truncate ($cache_fd, 0) ||
292 error ("unable to truncate $cache_file_name: $!");
293 seek ($cache_fd, 0, 0) ||
294 error ("unable to rewind $cache_file_name: $!");
296 if ($#all_files >= 0) {
297 print $cache_fd "$dir\n";
298 foreach (@all_files) {
299 my $f = $_; # stupid Perl. do this to avoid modifying @all_files!
300 $f =~ s@^\Q$dir\L/@@so || die; # remove $dir from front
301 print $cache_fd "$f\n";
305 print STDERR "$progname: cached " . ($#all_files+1) . " files\n"
309 flock ($cache_fd, LOCK_UN) ||
310 error ("unable to unlock $cache_file_name: $!");
316 sub find_random_file($) {
319 if ($use_spotlight_p == -1) {
320 $use_spotlight_p = 0;
321 if (-x '/usr/bin/mdfind') {
322 $use_spotlight_p = 1;
326 @all_files = read_cache ($dir);
328 if ($#all_files >= 0) {
329 # got it from the cache...
331 } elsif ($use_spotlight_p) {
332 print STDERR "$progname: spotlighting $dir...\n" if ($verbose);
333 spotlight_all_files ($dir);
334 print STDERR "$progname: found " . ($#all_files+1) .
335 " file" . ($#all_files == 0 ? "" : "s") .
339 print STDERR "$progname: recursively reading $dir...\n" if ($verbose);
340 find_all_files ($dir);
341 print STDERR "$progname: " .
342 "f=" . ($#all_files+1) . "; " .
345 "skip=${skip_count_unstat}+$skip_count_stat=" .
346 ($skip_count_unstat + $skip_count_stat) .
353 # @all_files = sort(@all_files);
355 if ($#all_files < 0) {
356 print STDERR "$progname: no files in $dir\n";
361 for (my $i = 0; $i < $max_tries; $i++) {
363 my $n = int (rand ($#all_files + 1));
364 my $file = $all_files[$n];
365 if (large_enough_p ($file)) {
366 $file =~ s@^\Q$dir\L/@@so || die; # remove $dir from front
371 print STDERR "$progname: no suitable images in $dir " .
372 "(after $max_tries tries)\n";
377 sub large_enough_p($) {
380 my ($w, $h) = image_file_size ($file);
383 print STDERR "$progname: $file: unable to determine image size\n"
385 # Assume that unknown files are of good sizes: this will happen if
386 # they matched $good_file_re, but we don't have code to parse them.
387 # (This will also happen if the file is junk...)
391 if ($w < $min_image_width || $h < $min_image_height) {
392 print STDERR "$progname: $file: too small ($w x $h)\n" if ($verbose);
396 print STDERR "$progname: $file: $w x $h\n" if ($verbose);
402 # Given the raw body of a GIF document, returns the dimensions of the image.
406 my $type = substr($body, 0, 6);
408 return () unless ($type =~ /GIF8[7,9]a/);
409 $s = substr ($body, 6, 10);
410 my ($a,$b,$c,$d) = unpack ("C"x4, $s);
411 return (($b<<8|$a), ($d<<8|$c));
414 # Given the raw body of a JPEG document, returns the dimensions of the image.
419 my $L = length($body);
421 my $c1 = substr($body, $i, 1); $i++;
422 my $c2 = substr($body, $i, 1); $i++;
423 return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
426 while (ord($ch) != 0xDA && $i < $L) {
427 # Find next marker, beginning with 0xFF.
428 while (ord($ch) != 0xFF) {
429 return () if (length($body) <= $i);
430 $ch = substr($body, $i, 1); $i++;
432 # markers can be padded with any number of 0xFF.
433 while (ord($ch) == 0xFF) {
434 return () if (length($body) <= $i);
435 $ch = substr($body, $i, 1); $i++;
438 # $ch contains the value of the marker.
439 my $marker = ord($ch);
441 if (($marker >= 0xC0) &&
444 ($marker != 0xCC)) { # it's a SOFn marker
446 return () if (length($body) <= $i);
447 my $s = substr($body, $i, 4); $i += 4;
448 my ($a,$b,$c,$d) = unpack("C"x4, $s);
449 return (($c<<8|$d), ($a<<8|$b));
452 # We must skip variables, since FFs in variable names aren't
453 # valid JPEG markers.
454 return () if (length($body) <= $i);
455 my $s = substr($body, $i, 2); $i += 2;
456 my ($c1, $c2) = unpack ("C"x2, $s);
457 my $length = ($c1 << 8) | $c2;
458 return () if ($length < 2);
465 # Given the raw body of a PNG document, returns the dimensions of the image.
469 return () unless ($body =~ m/^\211PNG\r/s);
470 my ($bits) = ($body =~ m/^.{12}(.{12})/s);
471 return () unless defined ($bits);
472 return () unless ($bits =~ /^IHDR/);
473 my ($ign, $w, $h) = unpack("a4N2", $bits);
478 # Given the raw body of a GIF, JPEG, or PNG document, returns the dimensions
483 return () if (length($body) < 10);
484 my ($w, $h) = gif_size ($body);
485 if ($w && $h) { return ($w, $h); }
486 ($w, $h) = jpeg_size ($body);
487 if ($w && $h) { return ($w, $h); }
488 # #### TODO: need image parsers for TIFF, XPM, XBM.
489 return png_size ($body);
492 # Returns the dimensions of the image file.
494 sub image_file_size($) {
497 if (! open ($in, '<', $file)) {
498 print STDERR "$progname: $file: $!\n" if ($verbose);
501 binmode ($in); # Larry can take Unicode and shove it up his ass sideways.
503 sysread ($in, $body, 1024 * 50); # The first 50k should be enough.
504 close $in; # (It's not for certain huge jpegs...
505 return image_size ($body); # but we know they're huge!)
511 print STDERR "$progname: $err\n";
516 print STDERR "usage: $progname [--verbose] directory\n" .
517 " Prints the name of a randomly-selected image file. The directory\n" .
518 " is searched recursively. Images smaller than " .
519 "${min_image_width}x${min_image_height} are excluded.\n";
526 while ($_ = $ARGV[0]) {
528 if ($_ eq "--verbose") { $verbose++; }
529 elsif (m/^-v+$/) { $verbose += length($_)-1; }
530 elsif ($_ eq "--name") { } # ignored, for compatibility
531 elsif ($_ eq "--spotlight") { $use_spotlight_p = 1; }
532 elsif ($_ eq "--no-spotlight") { $use_spotlight_p = 0; }
533 elsif ($_ eq "--cache") { $cache_p = 1; }
534 elsif ($_ eq "--no-cache") { $cache_p = 0; }
535 elsif (m/^-./) { usage; }
536 elsif (!defined($dir)) { $dir = $_; }
540 usage unless (defined($dir));
542 $dir =~ s@^~/@$ENV{HOME}/@s; # allow literal "~/"
543 $dir =~ s@/+$@@s; # omit trailing /
546 print STDERR "$progname: $dir: not a directory\n";
550 my $file = find_random_file ($dir);
551 print STDOUT "$file\n";