parse App12
[mkgallery.git] / mkgallery.pl
1 #!/usr/bin/perl
2
3 # $Id$
4
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/
8
9 # Copyright (c) 2006 Eugene G. Crosser
10
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.
14 #
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:
18 #
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.
26
27 package FsObj;
28
29 use strict;
30 use Carp;
31 use POSIX qw/getcwd strftime/;
32 use CGI qw/:html *table *Tr *center *div/;
33 use Image::Info qw/image_info dim/;
34 use Term::ReadLine;
35 use Getopt::Long;
36
37 use Image::Magick;
38
39 my @sizes = (160, 640);
40
41 ######################################################################
42
43 my $debug = 0;
44 my $asktitle = 0;
45 my $noasktitle = 0;
46
47 GetOptions('asktitle'=>\$asktitle,
48                 'noasktitle'=>\$noasktitle,
49                 'debug'=>\$debug);
50
51 my $term = new Term::ReadLine "Edit Title";
52
53 FsObj->new(getcwd)->iterate;
54
55 sub new {
56         my $this = shift;
57         my $class;
58         my $self;
59         if (ref($this)) {
60                 $class = ref($this);
61                 my $parent = $this;
62                 my $name = shift;
63                 my $fullpath = $parent->{-fullpath}.'/'.$name;
64                 $self = {
65                                 -parent=>$parent,
66                                 -root=>$parent->{-root},
67                                 -base=>$name,
68                                 -fullpath=>$fullpath,
69                                 -inc=>'../'.$parent->{-inc},
70                         };
71         } else {
72                 $class = $this;
73                 my $root=shift;
74                 $self = {
75                                 -root=>$root,
76                                 -fullpath=>$root,
77                                 -inc=>getinc($root),
78                         };
79         }
80         bless $self, $class;
81         if ($debug) {
82                 print "new $class:\n";
83                 foreach my $k(keys %$self) {
84                         print "\t$k\t=\t$self->{$k}\n";
85                 }
86         }
87         return $self;
88 }
89
90 sub getinc {
91         my $fullpath=shift;     # this is not a method
92         my $depth=20;           # arbitrary max depth
93
94         my $inc=".include";
95         while ( ! -d $fullpath."/".$inc ) {
96                 $inc = "../".$inc;
97                 last unless ($depth-- > 0);
98         }
99         if ($depth > 0) {
100                 return $inc.'/';                # prefix with trailing slash
101         } else {
102                 return 'NO-.INCLUDE-IN-PATH/';  # won't work anyway
103         }
104 }
105
106 sub iterate {
107         my $self = shift;
108         my $fullpath .= $self->{-fullpath};
109         print "iterate in dir $fullpath\n" if ($debug);
110
111         my @rdirlist;
112         my @rimglist;
113         my $D;
114         unless (opendir($D,$fullpath)) {
115                 warn "cannot opendir $fullpath: $!";
116                 return;
117         }
118         while (my $de = readdir($D)) {
119                 next if ($de =~ /^\./);
120                 my $child = $self->new($de);
121                 if ($child->isdir) {
122                         push(@rdirlist,$child);
123                 } elsif ($child->isimg) {
124                         push(@rimglist,$child);
125                 }
126         }
127         closedir($D);
128         my @dirlist = sort {$a->{-base} cmp $b->{-base}} @rdirlist;
129         undef @rdirlist; # inplace sorting would be handy here
130         my @imglist = sort {$a->{-base} cmp $b->{-base}} @rimglist;
131         undef @rimglist; # optimize away unsorted versions
132         $self->{-firstimg} = $imglist[0];
133
134         print "Dir: $self->{-fullpath}\n" if ($debug);
135
136 # 1. first of all, fill title for this directory and create hidden subdirs
137
138         $self->initdir;
139
140 # 2. recurse into subdirectories to get their titles filled
141 #    before we start writing out subalbum list
142
143         foreach my $dir(@dirlist) {
144                 $dir->iterate;
145         }
146
147 # 3. iterate through images to build cross-links,
148
149         my $previmg = undef;
150         foreach my $img(@imglist) {
151                 # list-linking must be done before generating
152                 # aux html because aux pages rely on prev/next refs
153                 if ($previmg) {
154                         $previmg->{-nextimg} = $img;
155                         $img->{-previmg} = $previmg;
156                 }
157                 $previmg=$img;
158         }
159
160 # 4. create scaled versions and aux html pages
161
162         foreach my $img(@imglist) {
163                 # scaled versions must be generated before aux html
164                 # and main image index because they both rely on
165                 # refs to scaled images and they may be just original
166                 # images, this is not known before we try scaling.
167                 $img->makescaled;
168                 # finally, make aux html pages
169                 $img->makeaux;
170         }
171
172 # 5. start building index.html for the directory
173
174         $self->startindex;
175
176 # 6. iterate through subdirectories to build subalbums list
177
178         if (@dirlist) {
179                 $self->startsublist;
180                 foreach my $dir(@dirlist) {
181                         $dir->sub_entry;
182                 }
183                 $self->endsublist;
184         }
185
186 # 7. iterate through images to build thumb list
187
188         if (@imglist) {
189                 $self->startimglist;
190                 foreach my $img(@imglist) {
191                         print "Img: $img->{-fullpath}\n" if ($debug);
192                         $img->img_entry;
193                 }
194                 $self->endimglist;
195         }
196
197 # 8. comlplete building index.html for the directory
198
199         $self->endindex;
200 }
201
202 sub isdir {
203         my $self = shift;
204         return ( -d $self->{-fullpath} );
205 }
206
207 sub isimg {
208         my $self = shift;
209         my $fullpath = $self->{-fullpath};
210         return 0 unless ( -f $fullpath );
211         my $info = image_info($fullpath);
212         if (my $error = $info->{error}) {
213                 if (($error !~ "Unrecognized file format") &&
214                     ($error !~ "Can't read head")) {
215                         warn "File \"$fullpath\": $error\n";
216                 }
217                 return 0;
218         }
219
220         tryapp12($info) unless ($info->{'ExifVersion'});
221
222         $self->{-isimg} = 1;
223         $self->{-info} = $info;
224         return 1;
225 }
226
227 sub tryapp12 {
228         my $info = shift;       # this is not a method
229         my $app12;
230         # dirty hack to take care of Image::Info parser strangeness
231         foreach my $k(keys %$info) {
232                 $app12=substr($k,6).$info->{$k} if ($k =~ /^App12-/);
233         }
234         return unless ($app12); # bad luck
235         my $seenfirstline=0;
236         foreach my $ln(split /[\r\n]+/,$app12) {
237                 $ln =~ s/[[:^print:]\000]/ /g;
238                 unless ($seenfirstline) {
239                         $seenfirstline=1;
240                         $info->{'Make'}=$ln;
241                         next;
242                 }
243                 my ($k,$v)=split /=/,$ln,2;
244                 if ($k eq 'TimeDate') {
245                         $info->{'DateTime'} =
246                                 strftime("%Y:%m:%d %H:%M:%S", localtime($v))
247                                                         unless ($v < 0);
248                 } elsif ($k eq 'Shutter') {
249                         $info->{'ExposureTime'} = '1/'.int(1000000/$v+.5);
250                 } elsif ($k eq 'Flash') {
251                         $info->{'Flash'} = $v?'Flash fired':'Flash did not fire';
252                 } elsif ($k eq 'Type') {
253                         $info->{'Model'} = $v;
254                 } elsif ($k eq 'Version') {
255                         $info->{'Software'} = $v;
256                 } elsif ($k eq 'Fnumber') {
257                         $info->{'FNumber'} = $v;
258                 }
259         }
260 }
261
262 sub initdir {
263         my $self = shift;
264         my $fullpath = $self->{-fullpath};
265         for my $subdir(@sizes, 'html') {
266                 my $tdir=sprintf "%s/.%s",$self->{-fullpath},$subdir;
267                 mkdir($tdir,0755) unless ( -d $tdir );
268         }
269         $self->edittitle;
270 }
271
272 sub edittitle {
273         my $self = shift;
274         my $fullpath = $self->{-fullpath};
275         my $title;
276         my $T;
277         if (open($T,'<'.$fullpath.'/.title')) {
278                 $title = <$T>;
279                 $title =~ s/[\r\n]*$//;
280                 close($T);
281         }
282         if ($asktitle || (!$title && !$noasktitle)) {
283                 my $prompt = $self->{-base};
284                 $prompt = '/' unless ($prompt);
285                 my $OUT = $term->OUT || \*STDOUT;
286                 print $OUT "Enter title for $fullpath\n";
287                 $title = $term->readline($prompt.' >',$title);
288                 $term->addhistory($title) if ($title);
289                 if (open($T,'>'.$fullpath.'/.title')) {
290                         print $T $title,"\n";
291                         close($T);
292                 }
293         }
294         unless ($title) {
295                 $title=substr($fullpath,length($self->{-root}));
296         }
297         $self->{-title}=$title;
298         print "title in $fullpath is $title\n" if ($debug);
299 }
300
301 sub makescaled {
302         my $self = shift;
303         my $fn = $self->{-fullpath};
304         my $name = $self->{-base};
305         my $dn = $self->{-parent}->{-fullpath};
306         my ($w, $h) = dim($self->{-info});
307         my $max = ($w > $h)?$w:$h;
308
309         foreach my $size(@sizes) {
310                 my $nref = '.'.$size.'/'.$name;
311                 my $nfn = $dn.'/'.$nref;
312                 my $factor=$size/$max;
313                 if ($factor >= 1) {
314                         $self->{$size} = $name; # unscaled version will do
315                 } else {
316                         $self->{$size} = $nref;
317                         if (isnewer($fn,$nfn)) {
318                                 doscaling($fn,$nfn,$factor,$w,$h);
319                         }
320                 }
321         }
322 }
323
324 sub isnewer {
325         my ($fn1,$fn2) = @_;                    # this is not a method
326         my @stat1=stat($fn1);
327         my @stat2=stat($fn2);
328         return (!@stat2 || ($stat1[9] > $stat2[9]));
329         # true if $fn2 is absent or is older than $fn1
330 }
331
332 sub doscaling {
333         my ($src,$dest,$factor,$w,$h) = @_;     # this is not a method
334         my $im = new Image::Magick;
335         my $err;
336         print "doscaling $src -> $dest by $factor\n" if ($debug);
337         $err = $im->Read($src);
338         unless ($err) {
339                 $im->Scale(width=>$w*$factor,height=>$h*$factor);
340                 $err=$im->Write($dest);
341                 warn "ImageMagick: write \"$dest\": $err" if ($err);
342         } else {        # fallback to command-line tools
343                 warn "ImageMagick: read \"$src\": $err";
344                 system("djpeg \"$src\" | pnmscale \"$factor\" | cjpeg >\"$dest\"");
345         }
346         undef $im;
347 }
348
349 sub makeaux {
350         my $self = shift;
351         my $name = $self->{-base};
352         my $dn = $self->{-parent}->{-fullpath};
353         my $pref = $self->{-previmg}->{-base};
354         my $nref = $self->{-nextimg}->{-base};
355         my $inc = $self->{-inc};
356         my $title = $self->{-info}->{'Comment'};
357         $title = $name unless ($title);
358
359         print "slide: \"$pref\"->\"$name\"->\"$nref\"\n" if ($debug);
360
361         # slideshow
362         for my $refresh('static', 'slide') {
363                 my $fn = sprintf("%s/.html/%s-%s.html",$dn,$name,$refresh);
364                 my $imgsrc = '../'.$self->{$sizes[1]};
365                 my $fwdref;
366                 my $bakref;
367                 if ($nref) {
368                         $fwdref = sprintf("%s-%s.html",$nref,$refresh);
369                 } else {
370                         $fwdref = '../index.html';
371                 }
372                 if ($pref) {
373                         $bakref = sprintf("%s-%s.html",$pref,$refresh);
374                 } else {
375                         $bakref = '../index.html';
376                 }
377                 my $toggleref;
378                 my $toggletext;
379                 if ($refresh eq 'slide') {
380                         $toggleref=sprintf("%s-static.html",$name);
381                         $toggletext = 'Stop!';
382                 } else {
383                         $toggleref=sprintf("%s-slide.html",$name);
384                         $toggletext = 'Play-&gt;';
385                 }
386                 my $F;
387                 unless (open($F,'>'.$fn)) {
388                         warn "cannot open \"$fn\": $!";
389                         next;
390                 }
391                 if ($refresh eq 'slide') {
392                         print $F start_html(-title=>$title,
393                                         -bgcolor=>"#808080",
394                                         -head=>meta({-http_equiv=>'Refresh',
395                                                 -content=>"3; url=$fwdref"}),
396                                         -style=>{-src=>$inc."gallery.css"},
397                                 ),"\n";
398                                         
399                 } else {
400                         print $F start_html(-title=>$title,
401                                         -bgcolor=>"#808080",
402                                         -style=>{-src=>$inc."gallery.css"},
403                                 ),"\n";
404                 }
405                 print $F start_center,"\n",
406                         h1($title),"\n",
407                         start_table({-class=>'navi'}),start_Tr,"\n",
408                         td(a({-href=>"../index.html"},"Index")),"\n",
409                         td(a({-href=>$bakref},"&lt;&lt;Prev")),"\n",
410                         td(a({-href=>$toggleref},$toggletext)),"\n",
411                         td(a({-href=>$fwdref},"Next&gt;&gt;")),"\n",
412                         end_Tr,
413                         end_table,"\n",
414                         table({-class=>'picframe'},
415                                 Tr(td(img({-src=>$imgsrc})))),"\n",
416                         end_center,"\n",
417                         end_html,"\n";
418                 close($F);
419         }
420         my $fn = sprintf("%s/.html/%s-info.html",$dn,$name);
421         my $F;
422         unless (open($F,'>'.$fn)) {
423                 warn "cannot open \"$fn\": $!";
424                 return;
425         }
426
427         # info html
428         my $imgsrc = sprintf("../.%s/%s",$sizes[0],$name);
429         print $F start_html(-title=>$title,
430                                 -style=>{-src=>$inc."gallery.css"},),"\n",
431                 start_center,"\n",
432                 h1($title),"\n",
433                 table({-class=>'ipage'},Tr(td(img({-src=>$imgsrc})),td($self->infotable))),
434                 a({-href=>'../index.html'},'Index'),"\n",
435                 end_center,"\n",
436                 end_html,"\n";
437         close($F);
438 }
439
440 sub startindex {
441         my $self = shift;
442         my $fn = $self->{-fullpath}.'/index.html';
443         my $IND;
444         unless (open($IND,'>'.$fn)) {
445                 warn "cannot open $fn: $!";
446                 return;
447         }
448         $self->{-IND} = $IND;
449
450         my $inc = $self->{-inc};
451         my $title = $self->{-title};
452         print $IND start_html(-title => $title,
453                         -style=>{-src=>[$inc."gallery.css",
454                                         $inc."lightbox.css"]},
455                         -script=>[{-code=>"var incPrefix='$inc';"},
456                                 {-src=>$inc."gallery.js"},
457                                 {-src=>$inc."lightbox.js"}]),
458                 a({-href=>"../index.html"},"UP"),"\n",
459                 start_center,"\n",
460                 h1($title),"\n",
461                 "\n";
462 }
463
464 sub endindex {
465         my $self = shift;
466         my $IND = $self->{-IND};
467
468         print $IND end_center,end_html,"\n";
469
470         close($IND) if ($IND);
471         undef $self->{-IND};
472 }
473
474 sub startsublist {
475         my $self = shift;
476         my $IND = $self->{-IND};
477
478         print $IND h2("Albums"),"\n",start_table,"\n";
479 }
480
481 sub sub_entry {
482         my $self = shift;
483         my $IND = $self->{-parent}->{-IND};
484         my $name = $self->{-base};
485         my $title = $self->{-title};
486
487         print $IND Tr(td(a({-href=>$name.'/index.html'},$name)),
488                         td(a({-href=>$name.'/index.html'},$title))),"\n";
489 }
490
491 sub endsublist {
492         my $self = shift;
493         my $IND = $self->{-IND};
494
495         print $IND end_table,"\n",br({-clear=>'all'}),hr,"\n\n";
496 }
497
498 sub startimglist {
499         my $self = shift;
500         my $IND = $self->{-IND};
501         my $first = $self->{-firstimg}->{-base};
502         my $slideref = sprintf(".html/%s-slide.html",$first);
503
504         print $IND h2("Images"),"\n",
505                 a({-href=>$slideref},'Slideshow'),
506                 "\n";
507 }
508
509 sub img_entry {
510         my $self = shift;
511         my $IND = $self->{-parent}->{-IND};
512         my $name = $self->{-base};
513         my $title = $self->{-info}->{'Comment'};
514         $title = $name unless ($title);
515         my $thumb = $self->{$sizes[0]};
516         my $medium = $self->{$sizes[1]};
517         my $info = $self->{-info};
518         my ($w, $h) = dim($info);
519
520         print $IND start_div({-class=>'ibox',-id=>$name,
521                                 -OnClick=>"HideIbox('$name');"}),"\n",
522                 start_div({-class=>'iboxtitle'}),
523                 span({-style=>'float: left;'},b("Info for $name")),
524                 span({-style=>'float: right;'},
525                         a({-href=>"#",-OnClick=>"HideIbox('$name');"},"Close")),
526                 br({-clear=>'all'}),"\n",
527                 end_div,"\n",
528                 $self->infotable,
529                 end_div,"\n";
530
531         print $IND table({-class=>'slide'},Tr(td(
532                 a({-href=>".html/$name-info.html",
533                         -onClick=>"return showIbox('$name');"},$title),
534                 br,
535                 a({-href=>$medium,-rel=>"lightbox",-title=>$title},
536                         img({-src=>$thumb})),
537                 br,
538                 a({-href=>$name},"($w x $h)"),
539                 br))),"\n";
540 }
541
542 sub endimglist {
543         my $self = shift;
544         my $IND = $self->{-IND};
545
546         print $IND br({-clear=>'all'}),hr,"\n\n";
547 }
548
549 sub infotable {
550         my $self = shift;
551         my $info = $self->{-info};
552         my $msg='';
553
554         my @infokeys=(
555                 'DateTime',
556                 'ExposureTime',
557                 'FNumber',
558                 'Flash',
559                 'ISOSpeedRatings',
560                 'MeteringMode',
561                 'ExposureProgram',
562                 'FocalLength',
563                 'FileSource',
564                 'Make',
565                 'Model',
566                 'Software',
567         );
568         $msg.=start_table({-class=>'infotable'})."\n";
569         foreach my $k(@infokeys) {
570                 $msg.=Tr(td($k.":"),td($info->{$k}))."\n" if ($info->{$k});
571         }
572         $msg.=end_table."\n";
573 }
574