http://www.jwz.org/xscreensaver/xscreensaver-5.13.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 # The various xscreensaver hacks that manipulate images ("jigsaw", etc.) get
17 # the image to manipulate by running the "xscreensaver-getimage" program.
18 #
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.
24 #
25 # Under Cocoa, this script lives inside the .saver bundle, and is invoked
26 # directly from utils/grabclient.c.
27 #
28 # Created: 12-Apr-01.
29
30 require 5;
31 #use diagnostics;       # Fails on some MacOS 10.5 systems
32 use strict;
33
34 use POSIX;
35 use Fcntl;
36
37 use Fcntl ':flock'; # import LOCK_* constants
38
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?
43
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.
47
48 my $progname = $0; $progname =~ s@.*/@@g;
49 my $version = q{ $Revision: 1.29 $ }; $version =~ s/^[^0-9]+([0-9.]+).*$/$1/;
50
51 my $verbose = 0;
52
53 # Whether to use MacOS X's Spotlight to generate the list of files.
54 # When set to -1, uses Spotlight if "mdfind" exists.
55 #
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.)
58 #
59 my $use_spotlight_p = 0;
60
61 # Whether to cache the results of the last run.
62 #
63 my $cache_p = 1;
64
65 # Regenerate the cache if it is older than this many seconds.
66 #
67 my $cache_max_age = 60 * 60 * 3;   # 3 hours
68
69
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.
74 #
75 my @good_extensions = ('jpg', 'jpeg', 'pjpeg', 'pjpg', 'png', 'gif',
76                        'tif', 'tiff', 'xbm', 'xpm');
77 my $good_file_re = '\.(' . join("|", @good_extensions) . ')$';
78
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.)
84 #
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) . ')$';
90
91
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.
95 #
96 my $min_image_width  = 255;
97 my $min_image_height = 255;
98
99 my @all_files = ();         # list of "good" files we've collected
100 my %seen_inodes;            # for breaking recursive symlink loops
101
102 # For diagnostic messages:
103 #
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
108
109 sub find_all_files($);
110 sub find_all_files($) {
111   my ($dir) = @_;
112
113   print STDERR "$progname:  + reading dir $dir/...\n" if ($verbose > 1);
114
115   my $dd;
116   if (! opendir ($dd, $dir)) {
117     print STDERR "$progname: couldn't open $dir: $!\n" if ($verbose);
118     return;
119   }
120   my @files = readdir ($dd);
121   closedir ($dd);
122
123   my @dirs = ();
124
125   foreach my $file (@files) {
126     next if ($file =~ m/^\./);      # silently ignore dot files/dirs
127
128     if ($file =~ m/[~%\#]$/) {      # ignore backup files (and dirs...)
129       $skip_count_unstat++;
130       print STDERR "$progname:  - skip file  $file\n" if ($verbose > 1);
131     }
132
133     $file = "$dir/$file";
134
135     if ($file =~ m/$good_file_re/io) {
136       #
137       # Assume that files ending in .jpg exist and are not directories.
138       #
139       push @all_files, $file;
140       print STDERR "$progname:  - found file $file\n" if ($verbose > 1);
141
142     } elsif ($file =~ m/$nondir_re/io) {
143       #
144       # Assume that files ending in .html are not directories.
145       #
146       $skip_count_unstat++;
147       print STDERR "$progname: -- skip file  $file\n" if ($verbose > 1);
148
149     } else {
150       #
151       # Now we need to stat the file to see if it's a subdirectory.
152       #
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.
156       #
157       my @st = stat($file);
158       my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
159           $atime,$mtime,$ctime,$blksize,$blocks) = @st;
160
161       $stat_count++;
162
163       if ($#st == -1) {
164         if ($verbose) {
165           my $ll = readlink $file;
166           if (defined ($ll)) {
167             print STDERR "$progname: + dangling symlink: $file -> $ll\n";
168           } else {
169             print STDERR "$progname: + unreadable: $file\n";
170           }
171         }
172         next;
173       }
174
175       next if ($seen_inodes{"$dev:$ino"}); # break symlink loops
176       $seen_inodes{"$dev:$ino"} = 1;
177
178       if (S_ISDIR($mode)) {
179         push @dirs, $file;
180         $dir_count++;
181         print STDERR "$progname:  + found dir  $file\n" if ($verbose > 1);
182
183       } else {
184         $skip_count_stat++;
185         print STDERR "$progname:  + skip file  $file\n" if ($verbose > 1);
186       }
187     }
188   }
189
190   foreach (@dirs) {
191     find_all_files ($_);
192   }
193 }
194
195
196 sub spotlight_all_files($) {
197   my ($dir) = @_;
198
199   my @terms = ();
200   # "public.image" matches all (indexed) images, including Photoshop, etc.
201 #  push @terms, "kMDItemContentTypeTree == 'public.image'";
202   foreach (@good_extensions) {
203
204     # kMDItemFSName hits the file system every time: much worse than "find".
205 #    push @terms, "kMDItemFSName == '*.$_'";
206
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 == '*.$_'";
210   }
211
212   $dir =~ s@([^-_/a-z\d.,])@\\$1@gsi;  # quote for sh
213   my $cmd = "mdfind -onlyin $dir \"" . join (' || ', @terms) . "\"";
214
215   print STDERR "$progname: executing: $cmd\n" if ($verbose > 1);
216   @all_files = split (/[\r\n]+/, `$cmd`);
217 }
218
219
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.
225 #
226 my $cache_fd = undef;
227 my $cache_file_name = undef;
228 my $read_cache_p = 0;
229
230 sub read_cache($) {
231   my ($dir) = @_;
232
233   return () unless ($cache_p);
234
235   my $dd = "$ENV{HOME}/Library/Caches";    # MacOS location
236   if (-d $dd) {
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";
240   } else {
241     $cache_file_name = "$ENV{HOME}/.xscreensaver-getimage.cache";
242   }
243
244   print STDERR "$progname: awaiting lock: $cache_file_name\n"
245     if ($verbose > 1);
246
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: $!");
251
252   my $mtime = (stat($cache_fd))[9];
253
254   if ($mtime + $cache_max_age < time) {
255     print STDERR "$progname: cache is too old\n" if ($verbose);
256     return ();
257   }
258
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);
264     return ();
265   }
266
267   my @files = ();
268   while (<$cache_fd>) { 
269     s/[\r\n]+$//s;
270     push @files, "$odir/$_";
271   }
272
273   print STDERR "$progname: " . ($#files+1) . " files in cache\n"
274     if ($verbose);
275
276   $read_cache_p = 1;
277   return @files;
278 }
279
280
281 sub write_cache($) {
282   my ($dir) = @_;
283
284   return unless ($cache_p);
285
286   # If we read the cache, just close it without rewriting it.
287   # If we didn't read it, then write it now.
288
289   if (! $read_cache_p) {
290
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: $!");
295
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";
302       }
303     }
304
305     print STDERR "$progname: cached " . ($#all_files+1) . " files\n"
306       if ($verbose);
307   }
308
309   flock ($cache_fd, LOCK_UN) ||
310     error ("unable to unlock $cache_file_name: $!");
311   close ($cache_fd);
312   $cache_fd = undef;
313 }
314
315
316 sub find_random_file($) {
317   my ($dir) = @_;
318
319   if ($use_spotlight_p == -1) {
320     $use_spotlight_p = 0;
321     if (-x '/usr/bin/mdfind') {
322       $use_spotlight_p = 1;
323     }
324   }
325
326   @all_files = read_cache ($dir);
327
328   if ($#all_files >= 0) {
329     # got it from the cache...
330
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") .
336                  " via Spotlight\n"
337       if ($verbose);
338   } else {
339     print STDERR "$progname: recursively reading $dir...\n" if ($verbose);
340     find_all_files ($dir);
341     print STDERR "$progname: " .
342                  "f=" . ($#all_files+1) . "; " .
343                  "d=$dir_count; " .
344                  "s=$stat_count; " .
345                  "skip=${skip_count_unstat}+$skip_count_stat=" .
346                   ($skip_count_unstat + $skip_count_stat) .
347                  ".\n"
348       if ($verbose);
349   }
350
351   write_cache ($dir);
352
353 #  @all_files = sort(@all_files);
354
355   if ($#all_files < 0) {
356     print STDERR "$progname: no files in $dir\n";
357     exit 1;
358   }
359
360   my $max_tries = 50;
361   for (my $i = 0; $i < $max_tries; $i++) {
362
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
367       return $file;
368     }
369   }
370
371   print STDERR "$progname: no suitable images in $dir " .
372                "(after $max_tries tries)\n";
373   exit 1;
374 }
375
376
377 sub large_enough_p($) {
378   my ($file) = @_;
379
380   my ($w, $h) = image_file_size ($file);
381
382   if (!defined ($h)) {
383     print STDERR "$progname: $file: unable to determine image size\n"
384       if ($verbose);
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...)
388     return 1;
389   }
390
391   if ($w < $min_image_width || $h < $min_image_height) {
392     print STDERR "$progname: $file: too small ($w x $h)\n" if ($verbose);
393     return 0;
394   }
395
396   print STDERR "$progname: $file: $w x $h\n" if ($verbose);
397   return 1;
398 }
399
400
401
402 # Given the raw body of a GIF document, returns the dimensions of the image.
403 #
404 sub gif_size($) {
405   my ($body) = @_;
406   my $type = substr($body, 0, 6);
407   my $s;
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));
412 }
413
414 # Given the raw body of a JPEG document, returns the dimensions of the image.
415 #
416 sub jpeg_size($) {
417   my ($body) = @_;
418   my $i = 0;
419   my $L = length($body);
420
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);
424
425   my $ch = "0";
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++;
431     }
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++;
436     }
437
438     # $ch contains the value of the marker.
439     my $marker = ord($ch);
440
441     if (($marker >= 0xC0) &&
442         ($marker <= 0xCF) &&
443         ($marker != 0xC4) &&
444         ($marker != 0xCC)) {  # it's a SOFn marker
445       $i += 3;
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));
450
451     } else {
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);
459       $i += $length-2;
460     }
461   }
462   return ();
463 }
464
465 # Given the raw body of a PNG document, returns the dimensions of the image.
466 #
467 sub png_size($) {
468   my ($body) = @_;
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);
474   return ($w, $h);
475 }
476
477
478 # Given the raw body of a GIF, JPEG, or PNG document, returns the dimensions
479 # of the image.
480 #
481 sub image_size($) {
482   my ($body) = @_;
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);
490 }
491
492 # Returns the dimensions of the image file.
493 #
494 sub image_file_size($) {
495   my ($file) = @_;
496   my $in;
497   if (! open ($in, '<', $file)) {
498     print STDERR "$progname: $file: $!\n" if ($verbose);
499     return undef;
500   }
501   binmode ($in);  # Larry can take Unicode and shove it up his ass sideways.
502   my $body = '';
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!)
506 }
507
508
509 sub error($) {
510   my ($err) = @_;
511   print STDERR "$progname: $err\n";
512   exit 1;
513 }
514
515 sub usage() {
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";
520   exit 1;
521 }
522
523 sub main() {
524   my $dir = undef;
525
526   while ($_ = $ARGV[0]) {
527     shift @ARGV;
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 = $_; }
537     else { usage; }
538   }
539
540   usage unless (defined($dir));
541
542   $dir =~ s@^~/@$ENV{HOME}/@s;     # allow literal "~/"
543   $dir =~ s@/+$@@s;                # omit trailing /
544
545   if (! -d $dir) {
546     print STDERR "$progname: $dir: not a directory\n";
547     usage;
548   }
549
550   my $file = find_random_file ($dir);
551   print STDOUT "$file\n";
552 }
553
554 main;
555 exit 0;