*** empty log message ***
[booh] / bin / booh
1 #!/usr/bin/ruby
2 #
3 #                         *  BOOH  *
4 #
5 # A.k.a `Best web-album Of the world, Or your money back, Humerus'.
6 #
7 # The acronyn sucks, however this is a tribute to Dragon Ball by
8 # Akira Toriyama, where the last enemy beaten by heroes of Dragon
9 # Ball is named "Boo". But there was already a free software project
10 # called Boo, so this one will be it "Booh". Or whatever.
11 #
12 #
13 # Copyright (c) 2004 Guillaume Cottenceau <gc3 at bluewin.ch>
14 #
15 # This software may be freely redistributed under the terms of the GNU
16 # public license version 2.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program; if not, write to the Free Software
20 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21
22 require 'getoptlong'
23 require 'gettext'
24 include GetText
25 require 'rexml/document'
26 include REXML
27 require 'timeout'
28
29 require 'booh/booh-lib'
30 require 'booh/html-merges'
31
32 #- bind text domain as soon as possible because some _() functions are called early to build data structures
33 bindtextdomain("booh")
34
35 #- options
36 $options = [
37     [ '--help',          '-h', GetoptLong::NO_ARGUMENT,       _("Get help message") ],
38
39     [ '--no-check',      '-n', GetoptLong::NO_ARGUMENT,       _("Don't check for needed external programs at startup") ],
40
41     [ '--source',        '-s', GetoptLong::REQUIRED_ARGUMENT, _("Directory which contains original images/videos as files or subdirs") ],
42     [ '--destination',   '-d', GetoptLong::REQUIRED_ARGUMENT, _("Directory which will contain the web-album") ],
43 #    [ '--clean',         '-c', GetoptLong::NO_ARGUMENT,       _("Clean destination directory") ],
44
45     [ '--theme',         '-t', GetoptLong::REQUIRED_ARGUMENT, _("Select HTML theme to use") ],
46     [ '--config',        '-C', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing images and videos within directories with captions") ],
47     [ '--config-skel',   '-k', GetoptLong::REQUIRED_ARGUMENT, _("Filename where the script will output a config skeleton") ],
48     [ '--merge-config',  '-M', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing, where to merge new images/videos from --source") ],
49
50     [ '--mproc',         '-m', GetoptLong::REQUIRED_ARGUMENT, _("Specify the number of processors for multi-processors machines") ],
51
52     [ '--verbose-level', '-v', GetoptLong::REQUIRED_ARGUMENT, _("Set max verbosity level (0: errors, 1: warnings, 2: important messages, 3: other messages)") ],
53 ]
54
55 #- default values for some globals 
56 $convert = 'convert -interlace line +profile "*"'
57 $switches = []
58 $stdout.sync = true
59
60 def usage
61     puts __("Usage: %s [OPTION]...", File.basename($0))
62     $options.each { |ary|
63         printf " %3s, %-15s %s\n", ary[1], ary[0], ary[3]
64     }
65 end
66
67 def handle_options
68     parser = GetoptLong.new
69     parser.set_options(*$options.collect { |ary| ary[0..2] })
70     begin
71         parser.each_option do |name, arg|
72             case name
73             when '--help'
74                 usage
75                 exit(0)
76
77             when '--no-check'
78                 $no_check = true
79
80             when '--source'
81                 $source = arg.sub(%r|/$|, '')
82                 if !File.directory?($source)
83                     die __("Argument to --source must be a directory")
84                 end
85             when '--destination'
86                 $dest = arg.sub(%r|/$|, '')
87                 if File.exists?($dest) && !File.directory?($dest)
88                     die __("If --destination exists, it must be a directory")
89                 end
90                 if $dest != make_dest_filename($dest)
91                     die __("Sorry, destination directory can't contain non simple alphanumeric characters.")
92                 end
93 #            when '--clean'
94 #                system("rm -rf #{$dest}")
95
96             when '--theme'
97                 select_theme(arg)
98             when '--config'
99                 if File.readable?(arg)
100                     $xmldoc = REXML::Document.new File.new(arg)
101                     $mode = 'use_config'
102                 else
103                     die __('Config file does not exist or is unreadable.')
104                 end
105             when '--config-skel'
106                 if File.exists?(arg)
107                     msg 1, __("Config skeleton file already exists, backuping to %s.backup", arg)
108                     File.rename(arg, "#{arg}.backup")
109                 end
110                 $config_writeto = arg
111                 $mode = 'gen_config'
112             when '--merge-config'
113                 if File.readable?(arg)
114                     msg 2, __("Merge config notice: backuping current config file to %s.backup", arg)
115                     $xmldoc = REXML::Document.new File.new(arg)
116                     File.rename(arg, "#{arg}.backup")
117                     $config_writeto = arg
118                     $mode = 'merge_config'
119                 else
120                     die __('Config file does not exist or is unreadable.')
121                 end
122
123             when '--mproc'
124                 $mproc = arg.to_i
125                 $pids = []
126
127             when '--verbose-level'
128                 $verbose_level = arg.to_i
129
130             end
131         end
132     rescue
133         puts $!
134         usage
135         exit(1)
136     end
137
138     if !$source && $xmldoc
139         $source = $xmldoc.root.attributes['source']
140         $dest = $xmldoc.root.attributes['destination']
141         $theme = $xmldoc.root.attributes['theme']
142     end
143
144     if !$source
145         die __("Missing --source or --config parameter.")
146     end
147     if !$dest
148         die __("Missing --destination parameter.")
149     end
150     if !$theme
151         select_theme($theme = 'simple')
152     end
153
154     if !$xmldoc
155         $xmldoc = Document.new "<booh version='#{$VERSION}' source='#{utf8($source)}' destination='#{utf8($dest)}' theme='#{$theme}'/>"
156         $xmldoc << XMLDecl.new( XMLDecl::DEFAULT_VERSION, $CURRENT_CHARSET )
157         $mode = 'gen_config'
158     end
159
160 end
161
162 def check_installation
163     if $no_check
164         return
165     end
166     %w(convert identify exif transcode mencoder).each { |prg|
167         if !system("which #{prg} >/dev/null")
168             die __("The `%s' program is typically needed. Re-run with --no-check if you're sure you're fine without it.", prg)
169         end
170     }
171 end
172
173 def replace_line(surround, keyword, line)
174     begin
175         contents = eval "$#{keyword}"
176         line.sub!(/#{surround}#{keyword}#{surround}/, contents)
177     rescue NameError
178         die __("No `%s' found for substitution", keyword)
179     end
180 end
181
182 def build_html_skeletons
183     $html_images     = File.open("#{$FPATH}/themes/#{$theme}/skeleton_image.html").readlines
184     $html_thumbnails = File.open("#{$FPATH}/themes/#{$theme}/skeleton_thumbnails.html").readlines
185     $html_index      = File.open("#{$FPATH}/themes/#{$theme}/skeleton_index.html").readlines
186     for line in $html_images + $html_thumbnails + $html_index
187         while line =~ /~~~(\w+)~~~/
188             replace_line('~~~', $1, line)
189         end
190     end
191 end
192
193 def sys(cmd)
194     msg 2, cmd
195     system(cmd)
196 end
197
198 #- parallelizable sys
199 def psys(cmd)
200     if $mproc
201         if pid = fork
202             $pids << pid
203         else
204             msg 2, cmd + ' &'
205             system(cmd)
206             exit 0
207         end
208         if $pids.length == $mproc
209             finished = Process.wait2
210             $pids.delete(finished[0])
211             $pids = $pids.find_all { |pid| Process.waitpid(pid, Process::WNOHANG) == nil }
212         end
213     else
214         sys(cmd)
215     end
216 end
217
218 def find_caption_value(xmldir, filename)
219     xmldir.elements["[@filename='#{utf8(filename)}']"].attributes['caption']
220 end
221
222 def find_captions(xmldir, images)
223     return images.collect { |img| find_caption_value(xmldir, img) }
224 end
225
226 #- grab the results of a command but don't sleep forever on a runaway process
227 def subproc_runaway_aware(command)
228     begin
229         timeout(5) {
230             return `#{command}`
231         }
232     rescue Timeout::Error    
233         msg 1, _("forgetting runaway process (transcode sucks again?)")
234         #- todo should slay transcode but dunno how to do that
235         return nil
236     end
237 end
238
239 def gen_thumbnails(orig, xmldir, dests)
240     if !dests.detect { |dest| !File.exists?(dest['filename']) } 
241         return true
242     end
243
244     felem = xmldir.elements["[@filename='#{utf8(File.basename(orig))}']"]
245
246     if entry2type(orig) == 'image'
247         convert_options = ''
248         if felem
249             rotate = felem.attributes['rotate']
250             if !rotate
251                 orientation = `exif '#{orig}'`.detect { |line| line =~ /^Orientation/ }
252                 if orientation =~ /right - top/
253                     rotate = '90'
254                 end
255                 if orientation =~ /left - bottom/
256                     rotate = '-90'
257                 end
258                 rotate ||= '0'
259                 felem.add_attribute('rotate', rotate)
260             end
261             convert_options += "-rotate #{rotate} "
262         end
263         for dest in dests
264             if !File.exists?(dest['filename'])
265                 psys("#{$convert} #{convert_options}-geometry #{dest['size']} '#{orig}' '#{dest['filename']}'")
266             end
267         end
268         return true
269
270     elsif entry2type(orig) == 'video'
271         dest_dir = make_dest_filename(File.dirname(dests[0]['filename']))
272         #- frame-offset is an attribute that allows to specify which frame to use for the thumbnail;
273         #- first try in dir to allow for: <dir .. subdirs-captionfile='/tmp/src2/people/pict0008.mov' pict0008.mov-frame-offset='100' ..>
274         frame_offset = xmldir.attributes["#{utf8(File.basename(orig))}-frame-offset"]
275         if !frame_offset
276             #- then try in elements to allow for: <video filename='bourrique.mov' frame-offset='200'/>
277             felem and frame_offset = felem.attributes['frame-offset']
278         end
279         frame_offset = (frame_offset || 5).to_i
280         for dest in dests
281             if !File.exists?("#{dest_dir}/screenshot.jpg000004.jpg")
282                 cmd = "transcode -a 0 -c #{frame_offset-5}-#{frame_offset} -i '#{orig}' -y jpg -o '#{dest_dir}/screenshot.jpg' 2>&1"
283                 msg 2, cmd
284                 if subproc_runaway_aware(cmd) =~ /V: import format.*unknown/ || !File.exists?("#{dest_dir}/screenshot.jpg000004.jpg")
285                     msg 2, __("* could not extract first image of video %s with transcode, will try first converting with mencoder", orig)
286                     cmd = "mencoder '#{orig}' -nosound -ovc lavc -lavcopts vcodec=mjpeg -o '#{dest_dir}/foo.avi' -frames #{frame_offset} -fps 25 >/dev/null 2>/dev/null"
287                     msg 2, cmd
288                     system cmd
289                     if File.exists?("#{dest_dir}/foo.avi")
290                         cmd = "transcode -a 0 -c #{frame_offset-5}-#{frame_offset} -i '#{dest_dir}/foo.avi' -y jpg -o '#{dest_dir}/screenshot.jpg' 2>&1"
291                         msg 2, cmd
292                         results = subproc_runaway_aware(cmd)
293                         system("rm -f '#{dest_dir}/foo.avi'")
294                         if results =~ /V: import format.*unknown/ || !File.exists?("#{dest_dir}/screenshot.jpg000004.jpg")
295                             msg 0, __("could not extract first image of video %s encoded by mencoder", "#{dest_dir}/foo.avi")
296                             return false
297                         end
298                     else
299                         msg 0, __("could not make mencoder to encode %s to mpeg4", "#{orig}")
300                         return false
301                     end
302                 end
303
304             end
305             sys("#{$convert} -geometry #{dest['size']} #{dest_dir}/screenshot.jpg000004.jpg '#{dest['filename']}'")
306         end
307         return true
308     end
309 end
310
311 #- stolen from CVSspam
312 def urlencode(text)
313   text.sub(/[^a-zA-Z0-9\-,.*_\/]/) do
314     "%#{sprintf('%2X', $&[0])}"
315   end
316 end
317
318 def html_refresh(target)
319     return "<html><head><META http-equiv='refresh' content='0;URL=#{target}'></head><body></body><html>"
320 end
321
322 def discover_iterations(iterations, line)
323     if line =~ /~~iterate(\d)_open(_max(\d+))?~~/
324         for iter in iterations.values
325             if iter['open']
326                 iter['open'] = false
327                 iter['close_wait'] = $1.to_i
328             end
329         end
330         iterations[$1.to_i] = { 'open' => true, 'max' => $3, 'opening' => '', 'closing' => '' }
331         if $1.to_i == 1
332             line.sub!(/.*/, '~~thumbnails~~')
333         else
334             line.sub!(/.*/, '')
335         end
336     elsif line =~ /~~iterate(\d)_close~~/
337         iterations[$1.to_i]['open']  = false;
338         iterations[$1.to_i]['close'] = true;
339         line.sub!(/.*/, '')
340     else
341         for iter in iterations.values
342             if iter['open']
343                 iter['opening'] += line
344                 line.sub!(/.*/, '')
345             end
346             if !iter['close'] && iter['close_wait'] && iterations[iter['close_wait']]['close']
347                 iter['closing'] += line
348                 line.sub!(/.*/, '')
349             end
350         end
351     end
352 end
353
354 def reset_iterations(iterations)
355     for iter in iterations.values
356         iter['value'] = 1
357     end
358 end
359
360 def run_iterations(iterations)
361     html = ''
362     for level in iterations.keys.sort
363         if iterations[level]['value'] == 1 || level == iterations.keys.max
364             html += iterations[level]['opening']
365         end
366         iterations[level]['value'] += 1
367         if iterations[level]['max'] && iterations[level]['value'] > iterations[level]['max'].to_i
368             iterations[level]['value'] = 1
369             iterations[level-1]['value'] = 1
370             html += iterations[level-1]['closing']
371         end
372     end
373     return html
374 end
375
376 def close_iterations(iterations)
377     html = ''
378     for level in iterations.keys.sort.reverse
379         html += iterations[level]['closing']
380     end
381     return html
382 end
383
384 def img_element(fullpath)
385     sizespec = `identify '#{fullpath}'` =~ / JPEG (\d+)x(\d+) / ? 'width="' + $1 + '" height="' + $2 + '"' : ''
386     return '<img src="' + File.basename(fullpath) + '" ' + sizespec + ' border="0"/>'
387 end
388
389 def walk_source_dir
390
391     `find #{$source} -type d`.sort.each { |dir|
392         dir.chomp!
393         if dir =~ /'/
394             die __("Source directory or sub-directories can't contain a single-quote character, sorry.")
395         end
396
397         #- place xml document on proper node if exists, else create
398         xmldir = $xmldoc.elements["//dir[@path='#{utf8(dir)}']"]
399         if $mode == 'use_config'
400             if !xmldir
401                 next
402             end
403         else
404             if $mode == 'gen_config' || ($mode == 'merge_config' && !xmldir)
405                 #- add the <dir..> element if necessary
406                 parent = File.dirname(dir)
407                 xmldir = $xmldoc.elements["//dir[@path='#{utf8(parent)}']"]
408                 if !xmldir
409                     xmldir = $xmldoc.root
410                 end
411                 xmldir = xmldir.add_element 'dir', { 'path' => utf8(dir), 'new' => 1 }
412             end
413         end
414
415         #- read images/videos entries from config or from directories depending on mode
416         entries = []
417         if $mode == 'use_config'
418             msg 2, __("Handling %s from config list...", dir)
419             xmldir.elements.each { |element|
420                 if %w(image video).include?(element.name)
421                     entries << from_utf8(element.attributes['filename'])
422                 end
423             }
424         else
425             msg 2, __("Examining %s...", dir)
426             entries = Dir.entries(dir).sort
427             #- populate config in case of gen_config, add new files in case of merge_config
428             for file in entries
429                 type = entry2type(file)
430                 if type && !xmldir.elements["#{type}[@filename='#{utf8(file)}']"]
431                     xmldir.add_element type, { "filename" => utf8(file), "caption" => utf8(file.sub(/\.[^\.]+$/, '')[0..17]) }
432                 end
433             end
434             if $mode == 'merge_config'
435                 #- cleanup removed files from config and reread entries from config to get proper ordering
436                 entries = []
437                 xmldir.elements.each { |element|
438                     fullpath = "#{dir}/#{from_utf8(element.attributes['filename'])}"
439                     if %w(image video).include?(element.name)
440                         if !File.readable?(fullpath)
441                             msg 1, __("Config merge: removing #{fullpath} from config; use the backup file to retrieve caption info if this was a mistake")
442                             xmldir.delete(element)
443                         else
444                             entries << from_utf8(element.attributes['filename'])
445                         end
446                     end
447                 }
448             end
449         end
450         images = entries.find_all { |e| entry2type(e) == 'image' }
451         msg 3, __("\t%s images", images.length)
452         videos = entries.find_all { |e| entry2type(e) == 'video' }
453         msg 3, __("\t%s videos", videos.length)
454
455         dest_dir = make_dest_filename(dir.sub(/^#{Regexp.quote($source)}/, $dest))
456         system("mkdir -p '#{dest_dir}'")
457
458         #- copy any resource file that goes with the theme (css, images..)
459         for entry in Dir.entries("#{$FPATH}/themes/#{$theme}")
460             if !%w(. .. skeleton_image.html skeleton_thumbnails.html skeleton_index.html parameters.rb CVS).include?(entry)
461                 if !File.exists?("#{dest_dir}/#{entry}")
462                     psys("cp '#{$FPATH}/themes/#{$theme}/#{entry}' '#{dest_dir}'")
463                 end
464             end
465         end
466
467         #- pass through if there are no images and videos
468         if images.size == 0 && videos.size == 0
469             next
470         end
471
472         msg 2, __("Outputting in %s...", dest_dir)
473
474         #- populate data structure with sizes from theme
475         for sizeobj in $images_size
476             fullscreen_images ||= {}
477             fullscreen_images[sizeobj['name']] = []
478             thumbnail_images ||= {}
479             thumbnail_images[sizeobj['name']] = []
480             thumbnail_videos ||= {}
481             thumbnail_videos[sizeobj['name']] = []
482         end
483
484         images.size >= 1 and msg 3, __("\tcreating images thumbnails...")
485
486         #- create thumbnails for images
487         images.each { |img|
488             base_dest_img = dest_dir + '/' + make_dest_filename(img.sub(/\.[^\.]+$/, ''))
489             for sizeobj in $images_size
490                 size_fullscreen = sizeobj['fullscreen']
491                 size_thumbnails = sizeobj['thumbnails']
492                 fullscreen_dest_img = base_dest_img + "-#{size_fullscreen}.jpg"
493                 thumbnail_dest_img  = base_dest_img + "-#{size_thumbnails}.jpg"
494                 fullscreen_images[sizeobj['name']] << File.basename(fullscreen_dest_img)
495                 thumbnail_images[sizeobj['name']]  << File.basename(thumbnail_dest_img)
496                 gen_thumbnails("#{dir}/#{img}", xmldir, [ { 'filename' => fullscreen_dest_img, 'size' => size_fullscreen },
497                                                           { 'filename' => thumbnail_dest_img, 'size' => size_thumbnails } ])
498             end
499         }
500
501         videos.size >= 1 and msg 3, __("\tcreating videos thumbnails...")
502
503         #- create thumbnails for videos
504         videos.each { |video|
505             thumbnail_ok = true
506             for sizeobj in $images_size
507                 size_thumbnails = sizeobj['thumbnails']
508                 thumbnail_dest_img = dest_dir + '/' + make_dest_filename(video.sub(/\.[^\.]+$/, '')) + "-#{size_thumbnails}.jpg"
509                 thumbnail_videos[sizeobj['name']] << File.basename(thumbnail_dest_img)
510                 thumbnail_ok &&= gen_thumbnails("#{dir}/#{video}", xmldir, [ { 'filename' => thumbnail_dest_img, 'size' => size_thumbnails } ])
511             end
512             destvideo = "#{dest_dir}/#{video}"
513             if !File.exists?(destvideo)
514                 psys("cp '#{dir}/#{video}' '#{destvideo}'")
515             end
516             #- cleanup temp
517             system("rm -f #{dest_dir}/screenshot.jpg00000*")
518         }
519
520         #- fake for gettext to find these; if themes need more sizes, english name for them should be added here
521         sizenames = { 'small' => utf8(_("small")), 'medium' => utf8(_("medium")), 'large' => utf8(_("large")) }
522
523         msg 3, __("\tgenerating HTML pages...")
524         
525         #- generate thumbnails.html (page with thumbnails)
526         for sizeobj in $images_size
527             html = $html_thumbnails.collect { |l| l.clone }
528             iterations = {}
529             for i in html
530                 i.sub!(/~~run_slideshow~~/, images.size <= 1 ? '' : '<a href="image-' + sizeobj['name'] + '.html?run_slideshow">' + utf8(_('Run slideshow!')) + '</a>')
531                 i.sub!(/~~title~~/, xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir)))
532                 for sizeobj2 in $images_size
533                     if sizeobj != sizeobj2
534                         i.sub!(/~~size_#{sizeobj2['name']}~~/, '<a href="thumbnails-' + sizeobj2['name'] + '.html">' + sizenames[sizeobj2['name']] + '</a>')
535                     else
536                         i.sub!(/~~size_#{sizeobj2['name']}~~/, sizenames[sizeobj2['name']])
537                     end
538                 end
539                 discover_iterations(iterations, i)
540             end
541             html_thumbnails = ''
542             reset_iterations(iterations)
543             for file in entries
544                 type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
545                 if type
546                     html_thumbnails += run_iterations(iterations)
547                     if type == 'image'
548                         index = images.index(file)
549                         html_thumbnails.gsub!(/~~image_iteration~~/,
550                                               '<a href="image-' + sizeobj['name'] + '.html?current=' + fullscreen_images[sizeobj['name']][index] + '">' +
551                                                   img_element("#{dest_dir}/#{thumbnail_images[sizeobj['name']][index]}") + '</a>')
552                         html_thumbnails.gsub!(/~~caption_iteration~~/,
553                                               find_caption_value(xmldir, images[index]) || utf8(images[index]))
554                         html_thumbnails.gsub!(/~~ifimage\?~~(.+?)~~fi~~/) { $1 }
555                         html_thumbnails.gsub!(/~~ifvideo\?~~(.+?)~~fi~~/, '')
556                     elsif type == 'video'
557                         index = videos.index(file)
558                         if File.exists?("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}")
559                             html_thumbnails.gsub!(/~~image_iteration~~/,
560                                                   '<a href="' + videos[index] + '">' + img_element("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}") + '</a>')
561                         else
562                             html_thumbnails.gsub!(/~~image_iteration~~/,
563                                                   '<a href="' + videos[index] + '">' + utf8(_("(no preview)")) + '</a>')
564                         end
565                         html_thumbnails.gsub!(/~~caption_iteration~~/,
566                                               find_caption_value(xmldir, videos[index]) || utf8(videos[index]))
567                         html_thumbnails.gsub!(/~~ifimage\?~~(.+?)~~fi~~/, '')
568                         html_thumbnails.gsub!(/~~ifvideo\?~~(.+?)~~fi~~/) { $1 }
569                     end
570                 end
571             end
572             html_thumbnails += close_iterations(iterations)
573             for i in html
574                 i.sub!(/~~thumbnails~~/, html_thumbnails)
575             end
576             ios = File.open("#{dest_dir}/thumbnails-#{sizeobj['name']}.html", "w")
577             ios.write(html)
578             ios.close
579         end
580
581         #- generate image.html (page with fullscreen images)
582         if images.size > 0
583             #- don't ask me why I need so many backslashes... the aim is to print \\\" for each " in the javascript source
584             captions4js = find_captions(xmldir, images).collect { |e| e ? '"' + e.gsub('"', '\\\\\\\\\\\\\\\\\"' ) + '"' : '""' }.join(', ')
585             for sizeobj in $images_size
586                 html = $html_images.collect { |l| l.clone }
587                 images4js = fullscreen_images[sizeobj['name']].collect { |e| "\"#{e}\"" }.join(', ')
588                 otherimages4js = ''
589                 othersizes = []
590                 for sizeobj2 in $images_size
591                     if sizeobj != sizeobj2
592                         otherimages4js += "var images_#{sizeobj2['name']} = new Array(" + fullscreen_images[sizeobj2['name']].collect { |e| "\"#{e}\"" }.join(', ') + ")\n"
593                         othersizes << "\"#{sizeobj2['name']}\""
594                     end
595                 end
596                 for i in html
597                     i.sub!(/~~images~~/, images4js)
598                     i.sub!(/~~other_images~~/, otherimages4js)
599                     i.sub!(/~~other_sizes~~/, othersizes.join(', '))
600                     i.sub!(/~~captions~~/, captions4js)
601                     i.sub!(/~~title~~/, xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir)))
602                     i.sub!(/~~thumbnails~~/, '<a href="thumbnails-' + sizeobj['name'] + '.html">' + utf8(_('Return to thumbnails')) + '</a>')
603                     for sizeobj2 in $images_size
604                         if sizeobj != sizeobj2
605                             i.sub!(/~~size_#{sizeobj2['name']}~~/,
606                                    '<a href="image-' + sizeobj2['name'] + '.html" id="link' + sizeobj2['name'] + '">' + sizenames[sizeobj2['name']] + '</a>')
607                         else
608                             i.sub!(/~~size_#{sizeobj2['name']}~~/,
609                                    sizenames[sizeobj2['name']])
610                         end
611                     end
612                 end
613                 ios = File.open("#{dest_dir}/image-#{sizeobj['name']}.html", "w")
614                 ios.write(html)
615                 ios.close
616             end
617         end
618     }
619
620     msg 3, ''
621
622     #- add attributes to <dir..> elements needing so
623     if $mode != 'use_config'
624         msg 3, __("\tfixating configuration file...")
625         $xmldoc.elements.each('//dir[@new]') { |element|
626             path = captionpath = element.attributes['path']
627             child = element
628             captionfile = nil
629             while true
630                 child = child.elements[1]
631                 if !child
632                     element.remove  #- means we have a directory with nothing interesting in it
633                     break
634                 elsif child.name == 'dir'
635                     captionpath = child.attributes['path']
636                 else
637                     captionfile = "#{captionpath}/#{child.attributes['filename']}"
638                     break
639                 end
640             end
641             basename = File.basename(path)
642             if element.elements['dir']
643                 element.add_attribute('subdirs-caption', basename)
644                 element.add_attribute('subdirs-captionfile', captionfile)
645             end
646             if element.elements['image'] || element.elements['video']
647                 element.add_attribute('thumbnails-caption', basename)
648                 element.add_attribute('thumbnails-captionfile', captionfile)
649             end
650             element.delete_attribute('new')
651         }
652     end
653
654     #- write down to disk config if necessary
655     if $config_writeto
656         ios = File.open($config_writeto, "w")
657         $xmldoc.write(ios, 0)
658         ios.close
659     end
660
661     #- second pass to create index.html files
662     default_thumbnails = $images_size.detect { |sizeobj| sizeobj['default'] }
663     if !default_thumbnails
664         die __("Theme `%s' has no default size.", $theme)
665     else
666         default_thumbnails = default_thumbnails['name']
667     end
668
669     msg 3, __("\trescanning directories to generate all `index.html' files...")
670
671     `find #{$source} -type d`.each { |dir|
672         dir.chomp!
673         xmldir = $xmldoc.elements["//dir[@path='#{utf8(dir)}']"]
674         if !xmldir
675             next
676         end
677         dest_dir = make_dest_filename(dir.sub(/^#{Regexp.quote($source)}/, $dest))
678
679         html = $html_index.collect { |l| l.clone }
680         iterations = {}
681         for i in html
682             caption = xmldir.attributes['subdirs-caption'] || xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir))
683             i.gsub!(/~~title~~/, caption)
684             if xmldir.parent.name == 'dir'
685                 nav = ''
686                 path = '..'
687                 parent = xmldir.parent
688                 while parent.name == 'dir'
689                     parentcaption = parent.attributes['subdirs-caption'] || parent.attributes['thumbnails-caption'] || File.basename(parent.attributes['path'])
690                     nav = "<a href='#{path}/index.html'>#{parentcaption}</a> #{utf8(_(" > "))} #{nav}"
691                     path += '/..'
692                     parent = parent.parent
693                 end
694                 i.gsub!(/~~ifnavigation\?~~(.+?)~~fi~~/) { $1 }
695                 i.gsub!(/~~navigation~~/, nav + caption)
696             else
697                 i.gsub!(/~~ifnavigation\?~~(.+?)~~fi~~/, '')
698             end
699             discover_iterations(iterations, i)
700         end
701
702         html_index = ''
703         reset_iterations(iterations)
704
705         if xmldir.elements['dir']
706             #- deal with "current" album (directs to "thumbnails" page)
707             if xmldir.attributes['thumbnails-caption']
708                 thumbnail = "#{dest_dir}/thumbnails-thumbnail.jpg"
709                 gen_thumbnails(from_utf8(xmldir.attributes['thumbnails-captionfile']), xmldir, [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ])
710                 html_index += run_iterations(iterations)
711                 html_index.gsub!(/~~image_iteration~~/, "<a href='thumbnails-#{default_thumbnails}.html'>" + img_element(thumbnail) + '</a>')
712                 html_index.gsub!(/~~caption_iteration~~/, xmldir.attributes['thumbnails-caption'])
713             end
714             #- cleanup temp for videos
715             system("rm -f #{dest_dir}/screenshot.jpg00000*")
716
717             #- deal with sub-albums (direct to subdirs/index.html pages)
718             xmldir.elements.each('dir') { |child|
719                 subdir = make_dest_filename(from_utf8(File.basename(child.attributes['path'])))
720                 thumbnail = "#{dest_dir}/thumbnails-#{subdir}.jpg"
721                 html_index += run_iterations(iterations)
722                 #- first look for subdirs info; if not, means there is no subdir
723                 caption = child.attributes['subdirs-caption']
724                 if caption
725                     gen_thumbnails(from_utf8(child.attributes['subdirs-captionfile']), child, [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ])
726                     html_index.gsub!(/~~caption_iteration~~/, caption)
727                 else
728                     gen_thumbnails(from_utf8(child.attributes['thumbnails-captionfile']), child, [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ])
729                     html_index.gsub!(/~~caption_iteration~~/, child.attributes['thumbnails-caption'])
730                 end
731                 html_index.gsub!(/~~image_iteration~~/, "<a href='#{make_dest_filename(subdir)}/index.html'>" + img_element(thumbnail) + '</a>')
732                 #- cleanup temp for videos
733                 system("rm -f #{dest_dir}/screenshot.jpg00000*")
734             }
735
736         else
737             html = html_refresh("thumbnails-#{default_thumbnails}.html")
738         end
739
740         html_index += close_iterations(iterations)
741         for i in html
742             i.gsub!(/~~thumbnails~~/, html_index)
743         end
744
745         ios = File.open("#{dest_dir}/index.html", "w")
746         ios.write(html)
747         ios.close
748
749         #- substitute "return to albums" correctly
750         `find '#{dest_dir}' -maxdepth 1 -name "thumbnails*.html"`.each { |thumbnails|
751             thumbnails.chomp!
752             contents = File.open(thumbnails.chomp).readlines
753             for i in contents
754                 if xmldir.elements['dir']
755                     i.sub!(/~~return_to_albums~~/, '<a href="index.html">' + utf8(_('Return to albums')) + '</a>')
756                 else
757                     if xmldir.parent.name == 'dir'
758                         i.sub!(/~~return_to_albums~~/, '<a href="../index.html">' + utf8(_('Return to albums')) + '</a>')
759                     else
760                         i.sub!(/~~return_to_albums~~/, '')
761                     end
762                 end
763             end
764             ios = File.open(thumbnails, "w")
765             ios.write(contents)
766             ios.close
767         }
768     }
769
770     msg 3, _(" all done.")
771 end
772
773 handle_options
774 check_installation
775
776 build_html_skeletons
777
778 walk_source_dir