5 # Recursively create image gallery index and slideshow wrappings.
6 # Makes use of (slightly modified) "lightbox" Javascript/CSS as published
7 # at http://www.huddletogether.com/projects/lightbox/
9 # Copyright (c) 2006 Eugene G. Crosser
11 # This software is provided 'as-is', without any express or implied
12 # warranty. In no event will the authors be held liable for any damages
13 # arising from the use of this software.
15 # Permission is granted to anyone to use this software for any purpose,
16 # including commercial applications, and to alter it and redistribute it
17 # freely, subject to the following restrictions:
19 # 1. The origin of this software must not be misrepresented; you must not
20 # claim that you wrote the original software. If you use this software
21 # in a product, an acknowledgment in the product documentation would be
22 # appreciated but is not required.
23 # 2. Altered source versions must be plainly marked as such, and must not be
24 # misrepresented as being the original software.
25 # 3. This notice may not be removed or altered from any source distribution.
31 use POSIX qw/getcwd strftime/;
32 use CGI qw/:html *table *Tr *center *div *Link/;
33 use Image::Info qw/image_info dim/;
38 binmode(STDOUT, ":utf8");
40 my $haveimagick = eval { require Image::Magick; };
41 { package Image::Magick; } # to make perl compiler happy
43 my $haverssxml = eval { require XML::RSS; };
44 { package XML::RSS; } # to make perl compiler happy
46 my @sizes = (160, 640);
48 ######################################################################
62 'asktitle'=>\$asktitle,
63 'noasktitle'=>\$noasktitle,
64 'rssfile=s'=>\$rssfile,
69 if ($rssfile && ! $haverssxml) {
70 print STDERR "You need to get XML::RSS from CPAN to use --rssfile\n";
74 my $term = new Term::ReadLine "Edit Title";
76 FsObj->new(getcwd)->iterate;
79 my $itemstodel = @{$rssobj->{'rss'}->{'items'}} - 15;
80 while ($itemstodel-- > 0) {
81 pop(@{$rssobj->{'rss'}->{'items'}})
83 $rssobj->{'rss'}->save($rssobj->{'file'});
88 print STDERR <<__END__;
90 --help: print help message and exit
91 --incpath: do not try to find .include diretory upstream, use
92 specified path (absolute or relavive). Use with causion.
93 --debug: print a lot of debugging info to stdout as you run
94 --asktitle: ask to edit album titles even if there are ".title" files
95 --noasktitle: don't ask to enter album titles even where ".title"
96 files are absent. Use partial directory names as titles.
97 --rssfile=...: build RSS feed for newly added "albums", give name of rss file
111 my $fullpath = $parent->{-fullpath}.'/'.$name;
114 -root=>$parent->{-root},
116 -fullpath=>$fullpath,
117 -inc=>'../'.$parent->{-inc},
118 -rss=>'../'.$parent->{-rss},
132 print "new $class:\n";
133 foreach my $k(keys %$self) {
134 print "\t$k\t=\t$self->{$k}\n";
141 my $fullpath=shift; # this is not a method
142 my $depth=20; # arbitrary max depth
145 return $incpath."/.include";
149 while ( ! -d $fullpath."/".$inc ) {
151 last unless ($depth-- > 0);
154 return $inc.'/'; # prefix with trailing slash
156 return 'NO-.INCLUDE-IN-PATH/'; # won't work anyway
161 my $fullpath=shift; # this is not a method
162 my $depth=20; # arbitrary max depth
164 return "" unless $rssfile;
167 while ( ! -f $fullpath."/".$rss ) {
169 last unless ($depth-- > 0);
172 $rssobj->{'file'} = $rss;
173 $rssobj->{'rss'} = new XML::RSS (version=>2);
174 $rssobj->{'rss'}->parsefile($rss);
177 print STDERR "There is no $rssfile in this or parent ".
178 "directories, you must create one with mkgalrss.pl\n";
185 my $fullpath .= $self->{-fullpath};
186 print "iterate in dir $fullpath\n" if ($debug);
192 unless (opendir($D,$fullpath)) {
193 warn "cannot opendir $fullpath: $!";
196 while (my $de = readdir($D)) {
197 next if ($de =~ /^\./);
198 my $child = $self->new($de);
199 my @stat = stat($child->{-fullpath});
200 $youngest = $stat[9] if ($youngest < $stat[9]);
202 push(@rdirlist,$child);
203 } elsif ($child->isimg) {
204 push(@rimglist,$child);
208 my @dirlist = sort {$a->{-base} cmp $b->{-base}} @rdirlist;
209 undef @rdirlist; # inplace sorting would be handy here
210 my @imglist = sort {$a->{-base} cmp $b->{-base}} @rimglist;
211 undef @rimglist; # optimize away unsorted versions
212 $self->{-firstimg} = $imglist[0];
214 print "Dir: $self->{-fullpath}\n" if ($debug);
216 # 1. first of all, fill title for this directory and create hidden subdirs
220 # 2. recurse into subdirectories to get their titles filled
221 # before we start writing out subalbum list
223 foreach my $dir(@dirlist) {
227 # 3. iterate through images to build cross-links,
230 foreach my $img(@imglist) {
231 # list-linking must be done before generating
232 # aux html because aux pages rely on prev/next refs
234 $previmg->{-nextimg} = $img;
235 $img->{-previmg} = $previmg;
240 # 4. create scaled versions and aux html pages
242 foreach my $img(@imglist) {
243 # scaled versions must be generated before aux html
244 # and main image index because they both rely on
245 # refs to scaled images and they may be just original
246 # images, this is not known before we try scaling.
248 # finally, make aux html pages
252 # no need to go beyond this point if the directory timestamp did not
253 # change since we built index.html file last time.
255 my @istat = stat($self->{-fullpath}.'/index.html');
256 return unless ($youngest > $istat[9]);
258 # 5. start building index.html for the directory
262 # 6. iterate through subdirectories to build subalbums list
266 foreach my $dir(@dirlist) {
272 # 7. iterate through images to build thumb list
276 foreach my $img(@imglist) {
277 print "Img: $img->{-fullpath}\n" if ($debug);
283 # 8. comlplete building index.html for the directory
290 return ( -d $self->{-fullpath} );
295 my $fullpath = $self->{-fullpath};
296 return 0 unless ( -f $fullpath );
297 my $info = image_info($fullpath);
298 if (my $error = $info->{error}) {
299 if (($error !~ "Unrecognized file format") &&
300 ($error !~ "Can't read head")) {
301 warn "File \"$fullpath\": $error\n";
306 tryapp12($info) unless ($info->{'ExifVersion'});
309 $self->{-info} = $info;
314 my $info = shift; # this is not a method
316 # dirty hack to take care of Image::Info parser strangeness
317 foreach my $k(keys %$info) {
318 $app12=substr($k,6).$info->{$k} if ($k =~ /^App12-/);
320 return unless ($app12); # bad luck
322 foreach my $ln(split /[\r\n]+/,$app12) {
323 $ln =~ s/[[:^print:]\000]/ /g;
324 unless ($seenfirstline) {
329 my ($k,$v)=split /=/,$ln,2;
330 if ($k eq 'TimeDate') {
331 $info->{'DateTime'} =
332 strftime("%Y:%m:%d %H:%M:%S", localtime($v))
334 } elsif ($k eq 'Shutter') {
335 $info->{'ExposureTime'} = '1/'.int(1000000/$v+.5);
336 } elsif ($k eq 'Flash') {
337 $info->{'Flash'} = $v?'Flash fired':'Flash did not fire';
338 } elsif ($k eq 'Type') {
339 $info->{'Model'} = $v;
340 } elsif ($k eq 'Version') {
341 $info->{'Software'} = $v;
342 } elsif ($k eq 'Fnumber') {
343 $info->{'FNumber'} = $v;
350 my $fullpath = $self->{-fullpath};
351 for my $subdir(@sizes, 'html') {
352 my $tdir=sprintf "%s/.%s",$self->{-fullpath},$subdir;
353 mkdir($tdir,0755) unless ( -d $tdir );
360 my $fullpath = $self->{-fullpath};
363 if (open($T,'<'.$fullpath.'/.title')) {
365 $title =~ s/[\r\n]*$//;
368 if ($asktitle || (!$title && !$noasktitle)) {
369 my $prompt = $self->{-base};
370 $prompt = '/' unless ($prompt);
371 my $OUT = $term->OUT || \*STDOUT;
372 print $OUT "Enter title for $fullpath\n";
373 $title = $term->readline($prompt.' >',$title);
374 $term->addhistory($title) if ($title);
375 if (open($T,'>'.$fullpath.'/.title')) {
376 print $T $title,"\n";
381 $title=substr($fullpath,length($self->{-root}));
383 $self->{-title}=$title;
384 print "title in $fullpath is $title\n" if ($debug);
389 my $fn = $self->{-fullpath};
390 my $name = $self->{-base};
391 my $dn = $self->{-parent}->{-fullpath};
392 my ($w, $h) = dim($self->{-info});
393 my $max = ($w > $h)?$w:$h;
395 foreach my $size(@sizes) {
396 my $nref = '.'.$size.'/'.$name;
397 my $nfn = $dn.'/'.$nref;
398 my $factor=$size/$max;
400 $self->{$size} = $name; # unscaled version will do
402 $self->{$size} = $nref;
403 if (isnewer($fn,$nfn)) {
404 doscaling($fn,$nfn,$factor,$w,$h);
411 my ($fn1,$fn2) = @_; # this is not a method
412 my @stat1=stat($fn1);
413 my @stat2=stat($fn2);
414 return (!@stat2 || ($stat1[9] > $stat2[9]));
415 # true if $fn2 is absent or is older than $fn1
419 my ($src,$dest,$factor,$w,$h) = @_; # this is not a method
423 my $im = new Image::Magick;
424 print "doscaling $src -> $dest by $factor\n" if ($debug);
425 if ($err = $im->Read($src)) {
426 warn "ImageMagick: read \"$src\": $err";
428 $im->Scale(width=>$w*$factor,height=>$h*$factor);
429 $err=$im->Write($dest);
430 warn "ImageMagick: write \"$dest\": $err" if ($err);
434 if ($err) { # fallback to command-line tools
435 system("djpeg \"$src\" | pnmscale \"$factor\" | cjpeg >\"$dest\"");
441 my $name = $self->{-base};
442 my $dn = $self->{-parent}->{-fullpath};
443 my $pref = $self->{-previmg}->{-base};
444 my $nref = $self->{-nextimg}->{-base};
445 my $inc = $self->{-inc};
446 my $title = $self->{-info}->{'Comment'};
447 $title = $name unless ($title);
449 print "slide: \"$title\": \"$pref\"->\"$name\"->\"$nref\"\n" if ($debug);
452 for my $refresh('static', 'slide') {
453 my $fn = sprintf("%s/.html/%s-%s.html",$dn,$name,$refresh);
454 if (isnewer($self->{-fullpath},$fn)) {
455 my $imgsrc = '../'.$self->{$sizes[1]};
459 $fwdref = sprintf("%s-%s.html",$nref,$refresh);
461 $fwdref = '../index.html';
464 $bakref = sprintf("%s-%s.html",$pref,$refresh);
466 $bakref = '../index.html';
470 if ($refresh eq 'slide') {
471 $toggleref=sprintf("%s-static.html",$name);
472 $toggletext = 'Stop!';
474 $toggleref=sprintf("%s-slide.html",$name);
475 $toggletext = 'Play->';
478 unless (open($F,'>'.$fn)) {
479 warn "cannot open \"$fn\": $!";
482 binmode($F, ":utf8");
483 if ($refresh eq 'slide') {
488 -head=>meta({-http_equiv=>'Refresh',
489 -content=>"3; url=$fwdref"}),
490 -style=>{-src=>$inc."gallery.css"},
494 print $F start_html(-title=>$title,
497 -style=>{-src=>$inc."gallery.css"},
500 print $F start_center,"\n",
502 start_table({-class=>'navi'}),start_Tr,"\n",
503 td(a({-href=>"../index.html"},"Index")),"\n",
504 td(a({-href=>$bakref},"<<Prev")),"\n",
505 td(a({-href=>$toggleref},$toggletext)),"\n",
506 td(a({-href=>$fwdref},"Next>>")),"\n",
509 table({-class=>'picframe'},
510 Tr(td(img({-src=>$imgsrc})))),"\n",
518 my $fn = sprintf("%s/.html/%s-info.html",$dn,$name);
519 if (isnewer($self->{-fullpath},$fn)) {
521 unless (open($F,'>'.$fn)) {
522 warn "cannot open \"$fn\": $!";
525 my $imgsrc = sprintf("../.%s/%s",$sizes[0],$name);
526 print $F start_html(-title=>$title,
528 -style=>{-src=>$inc."gallery.css"},),"\n",
531 table({-class=>'ipage'},
532 Tr(td(img({-src=>$imgsrc})),
533 td($self->infotable))),
534 a({-href=>'../index.html'},'Index'),"\n",
543 my $fn = $self->{-fullpath}.'/index.html';
544 my $block = $self->{-fullpath}.'/.noindex';
545 $fn = '/dev/null' if ( -f $block );
547 unless (open($IND,'>'.$fn)) {
548 warn "cannot open $fn: $!";
551 binmode($IND, ":utf8");
552 $self->{-IND} = $IND;
554 my $inc = $self->{-inc};
555 my $title = $self->{-title};
558 $rsslink=Link({-rel=>'alternate',
559 -type=>'application/rss+xml',
561 -href=>$self->{-rss}});
563 print $IND start_html(-title => $title,
566 -style=>{-src=>[$inc."gallery.css",
567 $inc."lightbox.css"],
569 .lbLoading {background: #fff url(".$inc."loading.gif) no-repeat center;}
570 #lbPrevLink {background: transparent url(".$inc.
571 "prevlabel.gif) no-repeat 0% 15%;}
572 #lbPrevLink:hover {background: transparent url(".$inc.
573 "prevlabel.gif) no-repeat 0% 15%;}
574 #lbNextLink {background: transparent url(".$inc.
575 "nextlabel.gif) no-repeat 0% 15%;}
576 #lbNextLink:hover {background: transparent url(".$inc.
577 "nextlabel.gif) no-repeat 0% 15%;}
578 #lbCloseLink {background: transparent url(".$inc.
579 "closelabel.gif) no-repeat center;}
580 .lightboxDesc {display: block;}"},
582 {-src=>$inc."mootools.js"},
583 {-src=>$inc."gallery.js"},
584 {-src=>$inc."lightbox.js"},
586 var incPrefix='$inc';
587 window.addEvent('domready',function(){
588 Lightbox.init({descriptions: '.lightboxDesc', showControls: true});
591 a({-href=>"../index.html"},"UP"),"\n",
599 my $IND = $self->{-IND};
601 print $IND end_center,end_html,"\n";
603 close($IND) if ($IND);
606 my $rsstitle=sprintf "%s [%d images, %d subalbums]",
610 my $rsslink=$rssobj->{'rss'}->channel('link')."index.html";
611 $rssobj->{'rss'}->add_item(
612 title => $self->{-title},
614 description => $rsstitle,
621 my $IND = $self->{-IND};
623 print $IND h2("Albums"),"\n",start_table,"\n";
628 my $IND = $self->{-parent}->{-IND};
629 my $name = $self->{-base};
630 my $title = $self->{-title};
632 $self->{-parent}->{-numofsubs}++;
633 print $IND Tr(td(a({-href=>$name.'/index.html'},$name)),
634 td(a({-href=>$name.'/index.html'},$title))),"\n";
639 my $IND = $self->{-IND};
641 print $IND end_table,"\n",br({-clear=>'all'}),hr,"\n\n";
646 my $IND = $self->{-IND};
647 my $first = $self->{-firstimg}->{-base};
648 my $slideref = sprintf(".html/%s-slide.html",$first);
650 print $IND h2("Images"),"\n",
651 a({-href=>$slideref},'Slideshow'),
657 my $IND = $self->{-parent}->{-IND};
658 my $name = $self->{-base};
659 my $title = $self->{-info}->{'Comment'};
660 $title = $name unless ($title);
661 my $thumb = $self->{$sizes[0]};
662 my $medium = $self->{$sizes[1]};
663 my $info = $self->{-info};
664 my ($w, $h) = dim($info);
666 $self->{-parent}->{-numofimgs}++;
667 print $IND start_div({-class=>'ibox',-id=>$name,
668 -OnClick=>"HideIbox('$name');"}),"\n",
669 start_div({-class=>'iboxtitle'}),
670 span({-style=>'float: left;'},b("Info for $name")),
671 span({-style=>'float: right;'},
672 a({-href=>"#",-OnClick=>"HideIbox('$name');"},"Close")),
673 br({-clear=>'all'}),"\n",
678 print $IND a({-name=>$name}),
679 table({-class=>'slide'},Tr(td(
680 div({-class=>"lightboxDesc $name"},
681 a({-href=>".html/$name-info.html",-title=>'Image Info',
682 -onClick=>"return showIbox('$name');"},
684 a({-href=>".html/$name-static.html",-title=>$title,
686 -OnClick=>"Lightbox.show('$medium','$title');return false;"},
687 img({-src=>$thumb})),
689 div({-style=>"display: none;"},
690 a({-href=>$thumb,-rel=>"lightbox[thm]",
691 -title=>'Thumb'},"Thm"),
692 a({-href=>$medium,-rel=>"lightbox[sml]",
693 -title=>'Small'},"Sml")),
694 a({-href=>$name,-title=>'Original'},"($w x $h)"),
700 my $IND = $self->{-IND};
702 print $IND br({-clear=>'all'}),hr,"\n\n";
707 my $info = $self->{-info};
724 $msg.=start_table({-class=>'infotable'})."\n";
725 foreach my $k(@infokeys) {
726 $msg.=Tr(td($k.":"),td($info->{$k}))."\n" if ($info->{$k});
728 $msg.=end_table."\n";