2 # Copyright © 2001-2018 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.52 $' =~ 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', 'php', 'pl', 'ppm', 'ps', 'psd', 'sea', 'sh',
99 'shtml', '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.
106 # But, if all of your images are smaller than this, all will be rejected.
108 my $min_image_width = 500;
109 my $min_image_height = 500;
111 my @all_files = (); # list of "good" files we've collected
112 my %seen_inodes; # for breaking recursive symlink loops
114 # For diagnostic messages:
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
121 my $config_file = $ENV{HOME} . "/.xscreensaver";
122 my $image_directory = undef;
125 sub find_all_files($);
126 sub find_all_files($) {
129 print STDERR "$progname: + reading dir $dir/...\n" if ($verbose > 1);
132 if (! opendir ($dd, $dir)) {
133 print STDERR "$progname: couldn't open $dir: $!\n" if ($verbose);
136 my @files = readdir ($dd);
141 foreach my $file (@files) {
142 next if ($file =~ m/^\./); # silently ignore dot files/dirs
144 if ($file =~ m/[~%\#]$/) { # ignore backup files (and dirs...)
145 $skip_count_unstat++;
146 print STDERR "$progname: - skip file $file\n" if ($verbose > 1);
149 $file = "$dir/$file";
151 if ($file =~ m/$good_file_re/io) {
153 # Assume that files ending in .jpg exist and are not directories.
155 push @all_files, $file;
156 print STDERR "$progname: - found file $file\n" if ($verbose > 1);
158 } elsif ($file =~ m/$nondir_re/io) {
160 # Assume that files ending in .html are not directories.
162 $skip_count_unstat++;
163 print STDERR "$progname: -- skip file $file\n" if ($verbose > 1);
167 # Now we need to stat the file to see if it's a subdirectory.
169 # Note: we could use the trick of checking "nlinks" on the parent
170 # directory to see if this directory contains any subdirectories,
171 # but that would exclude any symlinks to directories.
173 my @st = stat($file);
174 my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
175 $atime,$mtime,$ctime,$blksize,$blocks) = @st;
181 my $ll = readlink $file;
183 print STDERR "$progname: + dangling symlink: $file -> $ll\n";
185 print STDERR "$progname: + unreadable: $file\n";
191 next if ($seen_inodes{"$dev:$ino"}); # break symlink loops
192 $seen_inodes{"$dev:$ino"} = 1;
194 if (S_ISDIR($mode)) {
197 print STDERR "$progname: + found dir $file\n" if ($verbose > 1);
201 print STDERR "$progname: + skip file $file\n" if ($verbose > 1);
212 sub spotlight_all_files($) {
216 # "public.image" matches all (indexed) images, including Photoshop, etc.
217 # push @terms, "kMDItemContentTypeTree == 'public.image'";
218 foreach (@good_extensions) {
220 # kMDItemFSName hits the file system every time: much worse than "find".
221 # push @terms, "kMDItemFSName == '*.$_'";
223 # kMDItemDisplayName matches against the name in the Spotlight index,
224 # but won't find files that (for whatever reason) didn't get indexed.
225 push @terms, "kMDItemDisplayName == '*.$_'";
228 $dir =~ s@([^-_/a-z\d.,])@\\$1@gsi; # quote for sh
229 my $cmd = "mdfind -onlyin $dir \"" . join (' || ', @terms) . "\"";
231 print STDERR "$progname: executing: $cmd\n" if ($verbose > 1);
232 @all_files = split (/[\r\n]+/, `$cmd`);
236 # If we're using cacheing, read the cache file and return its contents,
237 # if any. This also holds an exclusive lock on the cache file, which
238 # has the additional benefit that if two copies of this program are
239 # running at once, one will wait for the other, instead of both of
240 # them spanking the same file system at the same time.
242 my $cache_fd = undef;
243 my $cache_file_name = undef;
244 my $read_cache_p = 0;
249 return () unless ($cache_p);
251 my $dd = "$ENV{HOME}/Library/Caches"; # MacOS location
253 $cache_file_name = "$dd/org.jwz.xscreensaver.getimage.cache";
254 } elsif (-d "$ENV{HOME}/.cache") { # Gnome "FreeDesktop XDG" location
255 $dd = "$ENV{HOME}/.cache/xscreensaver";
256 if (! -d $dd) { mkdir ($dd) || error ("mkdir $dd: $!"); }
257 $cache_file_name = "$dd/xscreensaver-getimage.cache"
258 } elsif (-d "$ENV{HOME}/tmp") { # If ~/tmp/ exists, use it.
259 $cache_file_name = "$ENV{HOME}/tmp/.xscreensaver-getimage.cache";
261 $cache_file_name = "$ENV{HOME}/.xscreensaver-getimage.cache";
264 print STDERR "$progname: awaiting lock: $cache_file_name\n"
267 my $file = $cache_file_name;
268 open ($cache_fd, '+>>', $file) || error ("unable to write $file: $!");
269 flock ($cache_fd, LOCK_EX) || error ("unable to lock $file: $!");
270 seek ($cache_fd, 0, 0) || error ("unable to rewind $file: $!");
272 my $mtime = (stat($cache_fd))[9];
274 if ($mtime + $cache_max_age < time) {
275 print STDERR "$progname: cache is too old\n" if ($verbose);
279 my $odir = <$cache_fd>;
280 $odir =~ s/[\r\n]+$//s if defined ($odir);
281 if (!defined ($odir) || ($dir ne $odir)) {
282 print STDERR "$progname: cache is for $odir, not $dir\n"
283 if ($verbose && $odir);
288 while (<$cache_fd>) {
290 push @files, "$odir/$_";
293 print STDERR "$progname: " . ($#files+1) . " files in cache\n"
304 return unless ($cache_p);
306 # If we read the cache, just close it without rewriting it.
307 # If we didn't read it, then write it now.
309 if (! $read_cache_p) {
311 truncate ($cache_fd, 0) ||
312 error ("unable to truncate $cache_file_name: $!");
313 seek ($cache_fd, 0, 0) ||
314 error ("unable to rewind $cache_file_name: $!");
316 if ($#all_files >= 0) {
317 print $cache_fd "$dir\n";
318 foreach (@all_files) {
319 my $f = $_; # stupid Perl. do this to avoid modifying @all_files!
320 $f =~ s@^\Q$dir/@@so || die; # remove $dir from front
321 print $cache_fd "$f\n";
325 print STDERR "$progname: cached " . ($#all_files+1) . " files\n"
329 flock ($cache_fd, LOCK_UN) ||
330 error ("unable to unlock $cache_file_name: $!");
336 sub html_unquote($) {
339 # This only needs to handle entities that occur in RSS, not full HTML.
340 my %ent = ( 'amp' => '&', 'lt' => '<', 'gt' => '>',
341 'quot' => '"', 'apos' => "'" );
342 $h =~ s/(&(\#)?([[:alpha:]\d]+);?)/
344 my ($o, $c) = ($1, $3);
346 $c = $ent{$c}; # for <
348 if ($c =~ m@^x([\dA-F]+)$@si) { # for A
350 } elsif ($c =~ m@^\d+$@si) { # for A
364 # Figure out what the proxy server should be, either from environment
365 # variables or by parsing the output of the (MacOS) program "scutil",
366 # which tells us what the system-wide proxy settings are.
371 my $proxy_data = `scutil --proxy 2>/dev/null`;
372 foreach my $proto ('http', 'https') {
373 my ($server) = ($proxy_data =~ m/\b${proto}Proxy\s*:\s*([^\s]+)/si);
374 my ($port) = ($proxy_data =~ m/\b${proto}Port\s*:\s*([^\s]+)/si);
375 my ($enable) = ($proxy_data =~ m/\b${proto}Enable\s*:\s*([^\s]+)/si);
377 if ($server && $enable) {
378 # Note: this ignores the "ExceptionsList".
380 $ENV{"${proto}_proxy"} = ("${proto2}://" . $server .
381 ($port ? ":$port" : "") . "/");
382 print STDERR "$progname: MacOS $proto proxy: " .
383 $ENV{"${proto}_proxy"} . "\n"
393 if (! defined ($LWP::Simple::ua)) {
394 error ("\n\n\tPerl is broken. Do this to repair it:\n" .
395 "\n\tsudo cpan LWP::Simple LWP::Protocol::https Mozilla::CA\n");
397 set_proxy ($LWP::Simple::ua);
401 sub sanity_check_lwp() {
402 my $url1 = 'https://www.mozilla.org/';
403 my $url2 = 'http://www.mozilla.org/';
404 my $body = (LWP::Simple::get($url1) || '');
405 if (length($body) < 10240) {
407 $body = (LWP::Simple::get($url2) || '');
408 if (length($body) < 10240) {
409 $err = "Perl is broken: neither HTTP nor HTTPS URLs work.";
411 $err = "Perl is broken: HTTP URLs work but HTTPS URLs don't.";
413 $err .= "\nMaybe try: sudo cpan -f Mozilla::CA LWP::Protocol::https";
415 error ("\n\n$err\n");
420 # If the URL does not already end with an extension appropriate for the
421 # content-type, add it after a "#" search.
423 # This is for when we know the content type of the URL, but the URL is
424 # some crazy thing without an extension. The files on disk need to have
427 sub force_extension($$) {
429 return $url unless (defined($url) && defined($ct));
430 my ($ext) = ($ct =~ m@^image/([-a-z\d]+)@si);
431 return $url unless $ext;
433 $ext = 'jpg' if ($ext eq 'jpeg');
434 return $url if ($url =~ m/\.$ext$/si);
439 # Returns a list of the image enclosures in the RSS or Atom feed.
440 # Elements of the list are references, [ "url", "guid" ].
447 $LWP::Simple::ua->agent ("$progname/$version");
448 $LWP::Simple::ua->timeout (10); # bail sooner than the default of 3 minutes
451 # Half the time, random Linux systems don't have Mozilla::CA installed,
452 # which results in "Can't verify SSL peers without knowning which
453 # Certificate Authorities to trust".
455 # In xscreensaver-text we just disabled certificate checks. However,
456 # malicious images really do exist, so for xscreensaver-getimage-file,
457 # let's actually require that SSL be installed properly.
459 print STDERR "$progname: loading $url\n" if ($verbose);
460 my $body = (LWP::Simple::get($url) || '');
462 if ($body !~ m@^\s*<(\?xml|rss)\b@si) {
463 # Not an RSS/Atom feed. Try RSS autodiscovery.
465 # (Great news, everybody: Flickr no longer provides RSS for "Sets",
466 # only for "Photostreams", and only the first 20 images of those.
469 if ($body =~ m/^\s*$/s) {
471 error ("null response: $url");
474 error ("not an RSS or Atom feed, or HTML: $url")
475 unless ($body =~ m@<(HEAD|BODY|A|IMG)\b@si);
477 # Find the first <link> with RSS or Atom in it, and use that instead.
479 $body =~ s@<LINK\s+([^<>]*)>@{
481 if ($p =~ m! \b REL \s* = \s* ['"]? alternate \b!six &&
482 $p =~ m! \b TYPE \s* = \s* ['"]? application/(atom|rss) !six &&
483 $p =~ m! \b HREF \s* = \s* ['"] ( [^<>'"]+ ) !six
485 my $u2 = html_unquote ($1);
487 my ($h) = ($url =~ m!^([a-z]+://[^/]+)!si);
490 print STDERR "$progname: found feed: $u2\n"
492 return parse_feed ($u2);
497 error ("no RSS or Atom feed for HTML page: $url");
501 $body =~ s@(<ENTRY|<ITEM)@\001$1@gsi;
502 my @items = split(/\001/, $body);
508 foreach my $item (@items) {
512 # First look for <link rel="enclosure" href="...">
515 foreach my $link ($item =~ m@<LINK[^<>]*>@gsi) {
517 my ($href) = ($link =~ m/\bHREF\s*=\s*[\"\']([^<>\'\"]+)/si);
518 my ($type) = ($link =~ m/\bTYPE\s*=\s*[\"\']?([^<>\'\"]+)/si);
519 my ($rel) = ($link =~ m/\bREL\s*=\s*[\"\']?([^<>\'\"]+)/si);
520 $href = undef unless (lc($rel || '') eq 'enclosure');
521 $href = undef if ($type && $type !~ m@^image/@si); # omit videos
522 $iurl = html_unquote($href) if $href;
523 $iurl = force_extension ($iurl, $type);
527 # Then look for <media:content url="...">
530 foreach my $link ($item =~ m@<MEDIA:CONTENT[^<>]*>@gsi) {
532 my ($href) = ($link =~ m/\bURL\s*=\s*[\"\']([^<>\'\"]+)/si);
533 my ($type) = ($link =~ m/\bTYPE\s*=\s*[\"\']?([^<>\'\"]+)/si);
534 my ($med) = ($link =~ m/\bMEDIUM\s*=\s*[\"\']?([^<>\'\"]+)/si);
535 $type = 'image/jpeg' if (!$type && lc($med || '') eq 'image');
536 $href = undef if ($type && $type !~ m@^image/@si); # omit videos
537 $iurl = html_unquote($href) if $href;
538 $iurl = force_extension ($iurl, $type);
542 # Then look for <enclosure url="..."/>
545 foreach my $link ($item =~ m@<ENCLOSURE[^<>]*>@gsi) {
547 my ($href) = ($link =~ m/\bURL\s*=\s*[\"\']([^<>\'\"]+)/si);
548 my ($type) = ($link =~ m/\bTYPE\s*=\s*[\"\']?([^<>\'\"]+)/si);
549 $href = undef if ($type && $type !~ m@^image/@si); # omit videos
550 $iurl = html_unquote($href) if ($href);
551 $iurl = force_extension ($iurl, $type);
555 # Ok, maybe there's an image in the <url> field?
558 foreach my $link ($item =~ m@<URL\b[^<>]*>([^<>]*)@gsi) {
561 $iurl = html_unquote($u2) if ($u2 =~ m/$good_file_re/io);
565 $u3 =~ s/[?&].*$//gs;
566 $iurl = html_unquote($u2) if ($u3 =~ m/$good_file_re/io);
571 # Then look for <content:encoded> or <description>... with an
572 # <img src="..."> inside. If more than one image, take the first.
574 foreach my $t ('content:encoded', 'description') {
576 foreach my $link ($item =~ m@<$t[^<>]*>(.*?)</$t>@gsi) {
579 if ($desc =~ m@<!\[CDATA\[\s*(.*?)\s*\]\]>@gs) {
582 $desc = html_unquote($desc);
584 my ($href) = ($desc =~ m@<IMG[^<>]*\bSRC=[\"\']?([^\"\'<>]+)@si);
585 $iurl = html_unquote($href) if ($href);
586 # If IMG SRC has a bogus extension, pretend it's a JPEG.
587 $iurl = force_extension ($iurl, 'image/jpeg')
588 if ($iurl && $iurl !~ m/$good_file_re/io);
592 # Find a unique ID for this image, to defeat image farms.
593 # First look for <id>...</id>
594 ($id) = ($item =~ m!<ID\b[^<>]*>\s*([^<>]+?)\s*</ID>!si) unless $id;
596 # Then look for <guid isPermaLink=...> ... </guid>
597 ($id) = ($item =~ m!<GUID\b[^<>]*>\s*([^<>]+?)\s*</GUID>!si) unless $id;
599 # Then look for <link> ... </link>
600 ($id) = ($item =~ m!<LINK\b[^<>]*>\s*([^<>]+?)\s*</LINK>!si) unless $id;
602 # If we only have a GUID or LINK, but it's an image, use that.
603 $iurl = $id if (!$iurl && $id && $id =~ m/$good_file_re/io);
606 $id = $iurl unless $id;
610 my @P = ($iurl, $id);
612 } elsif ($iurl ne $o) {
613 print STDERR "$progname: WARNING: dup ID \"$id\"" .
614 " for \"$o\" and \"$iurl\"\n";
623 # Like md5_base64 but uses filename-safe characters.
634 # expands the first URL relative to the second.
637 my ($url, $base) = @_;
639 $url =~ s/^\s+//gs; # lose whitespace at front and back
642 if (! ($url =~ m/^[a-z]+:/)) {
644 $base =~ s@(\#.*)$@@; # strip anchors
645 $base =~ s@(\?.*)$@@; # strip arguments
646 $base =~ s@/[^/]*$@/@; # take off trailing file component
649 if ($url =~ s@(\#.*)$@@) { $tail = $1; } # save anchors
650 if ($url =~ s@(\?.*)$@@) { $tail = "$1$tail"; } # save arguments
654 $base2 =~ s@^([a-z]+:/+[^/]+)/.*@$1@ # if url is an absolute path
659 $url = $base2 . $url;
660 $url =~ s@/\./@/@g; # expand "."
661 1 while ($url =~ s@/[^/]+/\.\./@/@s); # expand ".."
663 $url .= $tail; # put anchors/args back
665 print STDERR "$progname: relative URL: $ourl --> $url\n"
669 print STDERR "$progname: absolute URL: $url\n"
677 # Given the URL of an image, download it into the given directory
678 # and return the file name.
680 sub download_image($$$) {
681 my ($url, $uid, $dir) = @_;
684 $url2 =~ s/\#.*$//s; # Omit search terms after file extension
686 my ($ext) = ($url =~ m@\.([a-z\d]+)$@si);
687 ($ext) = ($url2 =~ m@\.([a-z\d]+)$@si) unless $ext;
689 # If the feed hasn't put a sane extension on their URLs, nothing's going
690 # to work. This code assumes that file names have extensions, even the
691 # ones in the cache directory.
694 print STDERR "$progname: skipping extensionless URL: $url\n"
699 # Don't bother downloading files that we will reject anyway.
701 if (! ($url =~ m/$good_file_re/io ||
702 $url2 =~ m/$good_file_re/io)) {
703 print STDERR "$progname: skipping non-image URL: $url\n"
708 my $file = md5_file ($uid);
709 $file .= '.' . lc($ext) if $ext;
711 # Don't bother doing If-Modified-Since to see if the URL has changed.
712 # If we have already downloaded it, assume it's good.
713 if (-f "$dir/$file") {
714 print STDERR "$progname: exists: $dir/$file for $uid / $url\n"
719 # Special-case kludge for Flickr:
720 # Their RSS feeds sometimes include only the small versions of the images.
721 # So if the URL ends in one of the "small-size" letters, change it to "b".
736 # Note: if we wanted to get the _k or _o version instead of the _b or _h
737 # version, we'd need to crack the DRM -- which is easy: see crack_secret
738 # in "https://www.jwz.org/hacks/galdown".
740 $url =~ s@_[sqtmnzc](\.[a-z]+)$@_b$1@si
741 if ($url =~ m@^https?://[^/?#&]*?flickr\.com/@si);
743 print STDERR "$progname: downloading: $dir/$file for $uid / $url\n"
746 $LWP::Simple::ua->agent ("$progname/$version");
748 $url =~ s/\#.*$//s; # Omit search terms
749 my $status = LWP::Simple::mirror ($url, "$dir/$file");
750 if (!LWP::Simple::is_success ($status)) {
751 print STDERR "$progname: error $status: $url\n"; # keep going
761 if ($url !~ m/^https?:/si) { # not a URL: local directory.
762 return (undef, $url);
765 my $dir = "$ENV{HOME}/Library/Caches"; # MacOS location
767 $dir = "$dir/org.jwz.xscreensaver.feeds";
768 } elsif (-d "$ENV{HOME}/.cache") { # Gnome "FreeDesktop XDG" location
769 $dir = "$ENV{HOME}/.cache/xscreensaver";
770 if (! -d $dir) { mkdir ($dir) || error ("mkdir $dir: $!"); }
772 if (! -d $dir) { mkdir ($dir) || error ("mkdir $dir: $!"); }
773 } elsif (-d "$ENV{HOME}/tmp") { # If ~/tmp/ exists, use it.
774 $dir = "$ENV{HOME}/tmp/.xscreensaver-feeds";
776 $dir = "$ENV{HOME}/.xscreensaver-feeds";
780 mkdir ($dir) || error ("mkdir $dir: $!");
781 print STDERR "$progname: mkdir $dir/\n" if ($verbose);
784 # MD5 for directory name to use for cache of a feed URL.
785 $dir .= '/' . md5_file ($url);
788 mkdir ($dir) || error ("mkdir $dir: $!");
789 print STDERR "$progname: mkdir $dir/ for $url\n" if ($verbose);
792 # At this point, we have the directory corresponding to this URL.
793 # Now check to see if the files in it are up to date, and download
796 my $stamp = '.timestamp';
797 my $lock = "$dir/$stamp";
799 print STDERR "$progname: awaiting lock: $lock\n"
802 my $mtime = ((stat($lock))[9]) || 0;
805 open ($lock_fd, '+>>', $lock) || error ("unable to write $lock: $!");
806 flock ($lock_fd, LOCK_EX) || error ("unable to lock $lock: $!");
807 seek ($lock_fd, 0, 0) || error ("unable to rewind $lock: $!");
809 my $poll_p = ($mtime + $feed_max_age < time);
811 # --no-cache cmd line arg means poll again right now.
812 $poll_p = 1 unless ($cache_p);
814 # Even if the cache is young, make sure there is at least one file,
815 # and re-check if not.
819 opendir (my $dirh, $dir) || error ("$dir: $!");
820 foreach my $f (readdir ($dirh)) {
821 next if ($f =~ m/^\./s);
828 print STDERR "$progname: no image files in cache of $url\n"
836 print STDERR "$progname: loading $url\n" if ($verbose);
839 opendir (my $dirh, $dir) || error ("$dir: $!");
840 foreach my $f (readdir ($dirh)) {
841 next if ($f eq '.' || $f eq '..');
842 $files{$f} = 0; # 0 means "file exists, should be deleted"
848 # Download each image currently in the feed.
851 my @urls = parse_feed ($url);
852 print STDERR "$progname: " . ($#urls + 1) . " images\n"
855 foreach my $p (@urls) {
856 my ($furl, $id) = @$p;
857 $furl = expand_url ($furl, $url);
859 # No need to download the same image twice, even if it was in the feed
860 # multiple times under different GUIDs.
861 next if ($seen_src_urls{$furl});
862 $seen_src_urls{$furl} = 1;
864 my $f = download_image ($furl, $id, $dir);
866 $files{$f} = 1; # Got it, don't delete
870 my $empty_p = ($count <= 0);
872 # Now delete any files that are no longer in the feed.
873 # But if there was nothing in the feed (network failure?)
874 # then don't blow away the old files.
877 foreach my $f (keys(%files)) {
880 } elsif ($files{$f}) {
883 if (unlink ("$dir/$f")) {
884 print STDERR "$progname: rm $dir/$f\n" if ($verbose > 1);
886 print STDERR "$progname: rm $dir/$f: $!\n"; # don't bail
891 # Both feed and cache are empty. No files at all. Bail.
892 error ("empty feed: $url") if ($kept <= 1);
894 # Feed is empty, but we have some files from last time. Warn.
895 print STDERR "$progname: empty feed: using cache: $url\n"
898 $mtime = time(); # update the timestamp
902 # Not yet time to re-check the URL.
903 print STDERR "$progname: using cache: $url\n" if ($verbose);
907 # Unlock and update the write date on the .timestamp file.
909 truncate ($lock_fd, 0) || error ("unable to truncate $lock: $!");
910 seek ($lock_fd, 0, 0) || error ("unable to rewind $lock: $!");
911 utime ($mtime, $mtime, $lock_fd) || error ("unable to touch $lock: $!");
912 flock ($lock_fd, LOCK_UN) || error ("unable to unlock $lock: $!");
915 print STDERR "$progname: unlocked $lock\n" if ($verbose > 1);
917 # Don't bother using the imageDirectory cache. We know that this directory
918 # is flat, and we can assume that an RSS feed doesn't contain 100,000 images
919 # like ~/Pictures/ might.
923 # Return the URL and directory name of the files of that URL's local cache.
929 sub find_random_file($) {
932 if ($use_spotlight_p == -1) {
933 $use_spotlight_p = 0;
934 if (-x '/usr/bin/mdfind') {
935 $use_spotlight_p = 1;
940 ($url, $dir) = mirror_feed ($dir);
943 $use_spotlight_p = 0;
944 print STDERR "$progname: $dir is cache for $url\n" if ($verbose > 1);
947 @all_files = read_cache ($dir);
949 if ($#all_files >= 0) {
950 # got it from the cache...
952 } elsif ($use_spotlight_p) {
953 print STDERR "$progname: spotlighting $dir...\n" if ($verbose);
954 spotlight_all_files ($dir);
955 print STDERR "$progname: found " . ($#all_files+1) .
956 " file" . ($#all_files == 0 ? "" : "s") .
960 print STDERR "$progname: recursively reading $dir...\n" if ($verbose);
961 find_all_files ($dir);
962 print STDERR "$progname: " .
963 "f=" . ($#all_files+1) . "; " .
966 "skip=${skip_count_unstat}+$skip_count_stat=" .
967 ($skip_count_unstat + $skip_count_stat) .
974 if ($#all_files < 0) {
975 print STDERR "$progname: no image files in $dir\n";
980 my $total_files = @all_files;
981 my $sparse_p = ($total_files < 20);
983 # If the directory has a lot of files in it:
984 # Make a pass through looking for hirez files (assume some are thumbs);
985 # If we found none, then, select any other file at random.
986 # Otherwise if there are a small number of files:
987 # Just select one at random (in case there's like, just one hirez).
989 for (my $check_size_p = $sparse_p ? 0 : 1;
990 $check_size_p >= 0; $check_size_p--) {
992 for (my $i = 0; $i < $max_tries; $i++) {
993 my $n = int (rand ($total_files));
994 my $file = $all_files[$n];
995 if (!$check_size_p || large_enough_p ($file)) {
997 $file =~ s@^\Q$dir/@@so || die; # remove $dir from front
1004 print STDERR "$progname: no suitable images in " . ($url || $dir) . " -- " .
1005 ($total_files <= $max_tries
1006 ? "all $total_files images"
1007 : "$max_tries of $total_files images") .
1008 " are smaller than ${min_image_width}x${min_image_height}.\n";
1010 # If we got here, blow away the cache. Maybe it's stale.
1011 unlink $cache_file_name if $cache_file_name;
1017 sub large_enough_p($) {
1020 my ($w, $h) = image_file_size ($file);
1022 if (!defined ($h)) {
1024 # Nonexistent files are obviously too small!
1025 # Already printed $verbose message about the file not existing.
1026 return 0 unless -f $file;
1028 print STDERR "$progname: $file: unable to determine image size\n"
1030 # Assume that unknown files are of good sizes: this will happen if
1031 # they matched $good_file_re, but we don't have code to parse them.
1032 # (This will also happen if the file is junk...)
1036 if ($w < $min_image_width || $h < $min_image_height) {
1037 print STDERR "$progname: $file: too small ($w x $h)\n" if ($verbose);
1041 print STDERR "$progname: $file: $w x $h\n" if ($verbose);
1047 # Given the raw body of a GIF document, returns the dimensions of the image.
1051 my $type = substr($body, 0, 6);
1053 return () unless ($type =~ /GIF8[7,9]a/);
1054 $s = substr ($body, 6, 10);
1055 my ($a,$b,$c,$d) = unpack ("C"x4, $s);
1056 return (($b<<8|$a), ($d<<8|$c));
1059 # Given the raw body of a JPEG document, returns the dimensions of the image.
1064 my $L = length($body);
1066 my $c1 = substr($body, $i, 1); $i++;
1067 my $c2 = substr($body, $i, 1); $i++;
1068 return () unless (ord($c1) == 0xFF && ord($c2) == 0xD8);
1071 while (ord($ch) != 0xDA && $i < $L) {
1072 # Find next marker, beginning with 0xFF.
1073 while (ord($ch) != 0xFF) {
1074 return () if (length($body) <= $i);
1075 $ch = substr($body, $i, 1); $i++;
1077 # markers can be padded with any number of 0xFF.
1078 while (ord($ch) == 0xFF) {
1079 return () if (length($body) <= $i);
1080 $ch = substr($body, $i, 1); $i++;
1083 # $ch contains the value of the marker.
1084 my $marker = ord($ch);
1086 if (($marker >= 0xC0) &&
1087 ($marker <= 0xCF) &&
1088 ($marker != 0xC4) &&
1089 ($marker != 0xCC)) { # it's a SOFn marker
1091 return () if (length($body) <= $i);
1092 my $s = substr($body, $i, 4); $i += 4;
1093 my ($a,$b,$c,$d) = unpack("C"x4, $s);
1094 return (($c<<8|$d), ($a<<8|$b));
1097 # We must skip variables, since FFs in variable names aren't
1098 # valid JPEG markers.
1099 return () if (length($body) <= $i);
1100 my $s = substr($body, $i, 2); $i += 2;
1101 my ($c1, $c2) = unpack ("C"x2, $s);
1102 my $length = ($c1 << 8) | $c2;
1103 return () if ($length < 2);
1110 # Given the raw body of a PNG document, returns the dimensions of the image.
1114 return () unless ($body =~ m/^\211PNG\r/s);
1115 my ($bits) = ($body =~ m/^.{12}(.{12})/s);
1116 return () unless defined ($bits);
1117 return () unless ($bits =~ /^IHDR/);
1118 my ($ign, $w, $h) = unpack("a4N2", $bits);
1123 # Given the raw body of a GIF, JPEG, or PNG document, returns the dimensions
1128 return () if (length($body) < 10);
1129 my ($w, $h) = gif_size ($body);
1130 if ($w && $h) { return ($w, $h); }
1131 ($w, $h) = jpeg_size ($body);
1132 if ($w && $h) { return ($w, $h); }
1133 # #### TODO: need image parsers for TIFF, XPM, XBM.
1134 return png_size ($body);
1137 # Returns the dimensions of the image file.
1139 sub image_file_size($) {
1142 if (! open ($in, '<:raw', $file)) {
1143 print STDERR "$progname: $file: $!\n" if ($verbose);
1147 sysread ($in, $body, 1024 * 50); # The first 50k should be enough.
1148 close $in; # (It's not for certain huge jpegs...
1149 return image_size ($body); # but we know they're huge!)
1153 # Reads the prefs we use from ~/.xscreensaver
1155 sub get_x11_prefs() {
1158 if (open (my $in, '<', $config_file)) {
1159 print STDERR "$progname: reading $config_file\n" if ($verbose > 1);
1160 local $/ = undef; # read entire file
1163 $got_any_p = get_x11_prefs_1 ($body);
1165 } elsif ($verbose > 1) {
1166 print STDERR "$progname: $config_file: $!\n";
1169 if (! $got_any_p && defined ($ENV{DISPLAY})) {
1170 # We weren't able to read settings from the .xscreensaver file.
1171 # Fall back to any settings in the X resource database
1172 # (/usr/X11R6/lib/X11/app-defaults/XScreenSaver)
1174 print STDERR "$progname: reading X resources\n" if ($verbose > 1);
1175 my $body = `appres XScreenSaver xscreensaver -1`;
1176 $got_any_p = get_x11_prefs_1 ($body);
1181 sub get_x11_prefs_1($) {
1185 $body =~ s@\\\n@@gs;
1186 $body =~ s@^[ \t]*#[^\n]*$@@gm;
1188 if ($body =~ m/^[.*]*imageDirectory:[ \t]*([^\s]+)\s*$/im) {
1189 $image_directory = $1;
1196 sub get_cocoa_prefs($) {
1198 print STDERR "$progname: reading Cocoa prefs: \"$id\"\n" if ($verbose > 1);
1199 my $v = get_cocoa_pref_1 ($id, "imageDirectory");
1200 $v = '~/Pictures' unless defined ($v); # Match default in XScreenSaverView
1201 $image_directory = $v if defined ($v);
1205 sub get_cocoa_pref_1($$) {
1206 my ($id, $key) = @_;
1207 # make sure there's nothing stupid/malicious in either string.
1208 $id =~ s/[^-a-z\d. ]/_/gsi;
1209 $key =~ s/[^-a-z\d. ]/_/gsi;
1210 my $cmd = "defaults -currentHost read \"$id\" \"$key\"";
1212 print STDERR "$progname: executing $cmd\n"
1215 my $val = `$cmd 2>/dev/null`;
1219 print STDERR "$progname: Cocoa: $id $key = \"$val\"\n"
1222 $val = undef if ($val =~ m/^$/s);
1230 print STDERR "$progname: $err\n";
1235 print STDERR "usage: $progname [--verbose] [ directory-or-feed-url ]\n\n" .
1236 " Prints the name of a randomly-selected image file. The directory\n" .
1237 " is searched recursively. Images smaller than " .
1238 "${min_image_width}x${min_image_height} are excluded.\n" .
1240 " The directory may also be the URL of an RSS/Atom feed. Enclosed\n" .
1241 " images will be downloaded and cached locally.\n" .
1247 my $cocoa_id = undef;
1250 while ($_ = $ARGV[0]) {
1252 if (m/^--?verbose$/s) { $verbose++; }
1253 elsif (m/^-v+$/s) { $verbose += length($_)-1; }
1254 elsif (m/^--?name$/s) { } # ignored, for compatibility
1255 elsif (m/^--?spotlight$/s) { $use_spotlight_p = 1; }
1256 elsif (m/^--?no-spotlight$/s) { $use_spotlight_p = 0; }
1257 elsif (m/^--?cache$/s) { $cache_p = 1; }
1258 elsif (m/^--?no-?cache$/s) { $cache_p = 0; }
1259 elsif (m/^--?cocoa$/) { $cocoa_id = shift @ARGV; }
1260 elsif (m/^--?abs(olute)?$/) { $abs_p = 1; }
1261 elsif (m/^-./) { usage; }
1262 elsif (!defined($image_directory)) { $image_directory = $_; }
1266 # Most hacks (X11 and Cocoa) pass a --directory value on the command line,
1267 # but if they don't, look it up from the resources. Currently this only
1268 # happens with "glitchpeg" which invokes xscreensaver-getimage-file
1269 # directly instead of going through the traditional path.
1271 if (! $image_directory) {
1272 if (!defined ($cocoa_id)) {
1273 # see OSX/XScreenSaverView.m
1274 $cocoa_id = $ENV{XSCREENSAVER_CLASSPATH};
1277 if (defined ($cocoa_id)) {
1278 get_cocoa_prefs($cocoa_id);
1279 error ("no imageDirectory in $cocoa_id") unless $image_directory;
1282 error ("no imageDirectory in X11 resources") unless $image_directory;
1286 usage unless (defined($image_directory));
1288 $image_directory =~ s@^feed:@http:@si;
1290 if ($image_directory =~ m/^https?:/si) {
1293 $image_directory =~ s@^~/@$ENV{HOME}/@s; # allow literal "~/"
1294 $image_directory =~ s@/+$@@s; # omit trailing /
1296 if (! -d $image_directory) {
1297 print STDERR "$progname: $image_directory not a directory or URL\n";
1302 my $file = find_random_file ($image_directory);
1304 # With --absolute return fully qualified paths instead of relative to --dir.
1307 $image_directory =~ m@^/@s) {
1308 $file = "$image_directory/$file";
1309 $file =~ s@//+@/@gs;
1312 print STDOUT "$file\n";