don't background thumbnail creation when we'll be using "identify" to know the exact...
[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
28 require 'booh/booh-lib'
29 require 'booh/html-merges'
30
31 #- bind text domain as soon as possible because some _() functions are called early to build data structures
32 bindtextdomain("booh")
33
34 #- options
35 $options = [
36     [ '--help',          '-h', GetoptLong::NO_ARGUMENT,       _("Get help message") ],
37
38     [ '--no-check',      '-n', GetoptLong::NO_ARGUMENT,       _("Don't check for needed external programs at startup") ],
39
40     [ '--source',        '-s', GetoptLong::REQUIRED_ARGUMENT, _("Directory which contains original images/videos as files or subdirs") ],
41     [ '--destination',   '-d', GetoptLong::REQUIRED_ARGUMENT, _("Directory which will contain the web-album") ],
42 #    [ '--clean',         '-c', GetoptLong::NO_ARGUMENT,       _("Clean destination directory") ],
43
44     [ '--theme',         '-t', GetoptLong::REQUIRED_ARGUMENT, _("Select HTML theme to use") ],
45     [ '--config',        '-C', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing images and videos within directories with captions") ],
46     [ '--config-skel',   '-k', GetoptLong::REQUIRED_ARGUMENT, _("Filename where the script will output a config skeleton") ],
47     [ '--merge-config',  '-M', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing, where to merge new images/videos from --source") ],
48
49     [ '--mproc',         '-m', GetoptLong::REQUIRED_ARGUMENT, _("Specify the number of processors for multi-processors machines") ],
50
51     [ '--verbose-level', '-v', GetoptLong::REQUIRED_ARGUMENT, _("Set max verbosity level (0: errors, 1: warnings, 2: important messages, 3: other messages)") ],
52 ]
53
54 #- default values for some globals 
55 $switches = []
56 $stdout.sync = true
57
58 def usage
59     puts _("Usage: %s [OPTION]...") % File.basename($0)
60     $options.each { |ary|
61         printf " %3s, %-15s %s\n", ary[1], ary[0], ary[3]
62     }
63 end
64
65 def handle_options
66     parser = GetoptLong.new
67     parser.set_options(*$options.collect { |ary| ary[0..2] })
68     begin
69         parser.each_option do |name, arg|
70             case name
71             when '--help'
72                 usage
73                 exit(0)
74
75             when '--no-check'
76                 $no_check = true
77
78             when '--source'
79                 $source = arg.sub(%r|/$|, '')
80                 if !File.directory?($source)
81                     die _("Argument to --source must be a directory")
82                 end
83             when '--destination'
84                 $dest = arg.sub(%r|/$|, '')
85                 if File.exists?($dest) && !File.directory?($dest)
86                     die _("If --destination exists, it must be a directory")
87                 end
88                 if $dest != make_dest_filename($dest)
89                     die _("Sorry, destination directory can't contain non simple alphanumeric characters.")
90                 end
91 #            when '--clean'
92 #                system("rm -rf #{$dest}")
93
94             when '--theme'
95                 $theme = arg
96             when '--config'
97                 if File.readable?(arg)
98                     $xmldoc = REXML::Document.new File.new(arg)
99                     $mode = 'use_config'
100                 else
101                     die _('Config file does not exist or is unreadable.')
102                 end
103             when '--config-skel'
104                 if File.exists?(arg)
105                     msg 1, _("Config skeleton file already exists, backuping to %s.backup") % arg
106                     File.rename(arg, "#{arg}.backup")
107                 end
108                 $config_writeto = arg
109                 $mode = 'gen_config'
110             when '--merge-config'
111                 if File.readable?(arg)
112                     msg 2, _("Merge config notice: backuping current config file to %s.backup") % arg
113                     $xmldoc = REXML::Document.new File.new(arg)
114                     File.rename(arg, "#{arg}.backup")
115                     $config_writeto = arg
116                     $mode = 'merge_config'
117                 else
118                     die _('Config file does not exist or is unreadable.')
119                 end
120
121             when '--mproc'
122                 $mproc = arg.to_i
123                 $pids = []
124
125             when '--verbose-level'
126                 $verbose_level = arg.to_i
127
128             end
129         end
130     rescue
131         puts $!
132         usage
133         exit(1)
134     end
135
136     if !$source && $xmldoc
137         $source = $xmldoc.root.attributes['source']
138         $dest = $xmldoc.root.attributes['destination']
139         $theme = $xmldoc.root.attributes['theme']
140     end
141
142     if !$source
143         die _("Missing --source or --config parameter.")
144     end
145     if !$dest
146         die _("Missing --destination parameter.")
147     end
148     if !$theme
149         $theme = 'simple'
150     end
151     select_theme($theme)
152
153     if !$xmldoc
154         $xmldoc = Document.new "<booh version='#{$VERSION}' source='#{utf8($source)}' destination='#{utf8($dest)}' theme='#{$theme}'/>"
155         $xmldoc << XMLDecl.new( XMLDecl::DEFAULT_VERSION, $CURRENT_CHARSET )
156         $mode = 'gen_config'
157     end
158
159 end
160
161 def check_installation
162     if $no_check
163         return
164     end
165     missing = %w(convert identify exif transcode mencoder).delete_if { |prg| system("which #{prg} >/dev/null 2>/dev/null") }
166     if missing != []
167         die _("The following programs are typically needed: `%s'. Re-run with --no-check if you're sure you're fine without them.") % missing.join(', ')
168     end
169 end
170
171 def replace_line(surround, keyword, line)
172     begin
173         contents = eval "$#{keyword}"
174         line.sub!(/#{surround}#{keyword}#{surround}/, contents)
175     rescue NameError
176         die _("No `%s' found for substitution") % keyword
177     end
178 end
179
180 def build_html_skeletons
181     $html_images     = File.open("#{$FPATH}/themes/#{$theme}/skeleton_image.html").readlines
182     $html_thumbnails = File.open("#{$FPATH}/themes/#{$theme}/skeleton_thumbnails.html").readlines
183     $html_index      = File.open("#{$FPATH}/themes/#{$theme}/skeleton_index.html").readlines
184     for line in $html_images + $html_thumbnails + $html_index
185         while line =~ /~~~(\w+)~~~/
186             replace_line('~~~', $1, line)
187         end
188     end
189 end
190
191 def find_caption_value(xmldir, filename)
192     xmldir.elements["[@filename='#{utf8(filename)}']"].attributes['caption']
193 end
194
195 def find_captions(xmldir, images)
196     return images.collect { |img| find_caption_value(xmldir, img) }
197 end
198
199 #- stolen from CVSspam
200 def urlencode(text)
201   text.sub(/[^a-zA-Z0-9\-,.*_\/]/) do
202     "%#{sprintf('%2X', $&[0])}"
203   end
204 end
205
206 def html_refresh(target)
207     return "<html><head><META http-equiv='refresh' content='0;URL=#{target}'></head><body></body><html>"
208 end
209
210 def discover_iterations(iterations, line)
211     if line =~ /~~iterate(\d)_open(_max(\d+))?~~/
212         for iter in iterations.values
213             if iter['open']
214                 iter['open'] = false
215                 iter['close_wait'] = $1.to_i
216             end
217         end
218         iterations[$1.to_i] = { 'open' => true, 'max' => $3, 'opening' => '', 'closing' => '' }
219         if $1.to_i == 1
220             line.sub!(/.*/, '~~thumbnails~~')
221         else
222             line.sub!(/.*/, '')
223         end
224     elsif line =~ /~~iterate(\d)_close~~/
225         iterations[$1.to_i]['open']  = false;
226         iterations[$1.to_i]['close'] = true;
227         line.sub!(/.*/, '')
228     else
229         for iter in iterations.values
230             if iter['open']
231                 iter['opening'] += line
232                 line.sub!(/.*/, '')
233             end
234             if !iter['close'] && iter['close_wait'] && iterations[iter['close_wait']]['close']
235                 iter['closing'] += line
236                 line.sub!(/.*/, '')
237             end
238         end
239     end
240 end
241
242 def reset_iterations(iterations)
243     for iter in iterations.values
244         iter['value'] = 1
245     end
246 end
247
248 def run_iterations(iterations)
249     html = ''
250     for level in iterations.keys.sort
251         if iterations[level]['value'] == 1 || level == iterations.keys.max
252             html += iterations[level]['opening']
253         end
254         iterations[level]['value'] += 1
255         if iterations[level]['max'] && iterations[level]['value'] > iterations[level]['max'].to_i
256             iterations[level]['value'] = 1
257             iterations[level-1]['value'] = 1
258             html += iterations[level-1]['closing']
259         end
260     end
261     return html
262 end
263
264 def close_iterations(iterations)
265     html = ''
266     for level in iterations.keys.sort.reverse
267         html += iterations[level]['closing']
268     end
269     return html
270 end
271
272 def img_element(fullpath)
273     sizespec = `identify '#{fullpath}'` =~ / JPEG (\d+)x(\d+) / ? 'width="' + $1 + '" height="' + $2 + '"' : ''
274     return '<img src="' + File.basename(fullpath) + '" ' + sizespec + ' border="0"/>'
275 end
276
277 def walk_source_dir
278
279     `find #{$source} -type d`.sort.each { |dir|
280         dir.chomp!
281         if dir =~ /'/
282             die _("Source directory or sub-directories can't contain a single-quote character, sorry.")
283         end
284
285         #- place xml document on proper node if exists, else create
286         xmldir = $xmldoc.elements["//dir[@path='#{utf8(dir)}']"]
287         if $mode == 'use_config'
288             if !xmldir
289                 next
290             end
291         else
292             if $mode == 'gen_config' || ($mode == 'merge_config' && !xmldir)
293                 #- add the <dir..> element if necessary
294                 parent = File.dirname(dir)
295                 xmldir = $xmldoc.elements["//dir[@path='#{utf8(parent)}']"]
296                 if !xmldir
297                     xmldir = $xmldoc.root
298                 end
299                 xmldir = xmldir.add_element 'dir', { 'path' => utf8(dir), 'new' => 1 }
300             end
301         end
302
303         #- read images/videos entries from config or from directories depending on mode
304         entries = []
305         if $mode == 'use_config'
306             msg 2, _("Handling %s from config list...") % dir
307             xmldir.elements.each { |element|
308                 if %w(image video).include?(element.name)
309                     entries << from_utf8(element.attributes['filename'])
310                 end
311             }
312         else
313             msg 2, _("Examining %s...") % dir
314             entries = Dir.entries(dir).sort
315             #- populate config in case of gen_config, add new files in case of merge_config
316             for file in entries
317                 type = entry2type(file)
318                 if type && !xmldir.elements["#{type}[@filename='#{utf8(file)}']"]
319                     xmldir.add_element type, { "filename" => utf8(file), "caption" => utf8(file.sub(/\.[^\.]+$/, '')[0..17]) }
320                 end
321             end
322             if $mode == 'merge_config'
323                 #- cleanup removed files from config and reread entries from config to get proper ordering
324                 entries = []
325                 xmldir.elements.each { |element|
326                     fullpath = "#{dir}/#{from_utf8(element.attributes['filename'])}"
327                     if %w(image video).include?(element.name)
328                         if !File.readable?(fullpath)
329                             msg 1, _("Config merge: removing %s from config; use the backup file to retrieve caption info if this was a mistake") % fullpath
330                             xmldir.delete(element)
331                         else
332                             entries << from_utf8(element.attributes['filename'])
333                         end
334                     end
335                 }
336             end
337         end
338         images = entries.find_all { |e| entry2type(e) == 'image' }
339         msg 3, _("\t%s images") % images.length
340         videos = entries.find_all { |e| entry2type(e) == 'video' }
341         msg 3, _("\t%s videos") % videos.length
342
343         dest_dir = make_dest_filename(dir.sub(/^#{Regexp.quote($source)}/, $dest))
344         system("mkdir -p '#{dest_dir}'")
345
346         #- copy any resource file that goes with the theme (css, images..)
347         for entry in Dir.entries("#{$FPATH}/themes/#{$theme}")
348             if !%w(. .. skeleton_image.html skeleton_thumbnails.html skeleton_index.html parameters.rb CVS).include?(entry)
349                 if !File.exists?("#{dest_dir}/#{entry}")
350                     psys("cp '#{$FPATH}/themes/#{$theme}/#{entry}' '#{dest_dir}'")
351                 end
352             end
353         end
354
355         #- pass through if there are no images and videos
356         if images.size == 0 && videos.size == 0
357             next
358         end
359
360         msg 2, _("Outputting in %s...") % dest_dir
361
362         #- populate data structure with sizes from theme
363         for sizeobj in $images_size
364             fullscreen_images ||= {}
365             fullscreen_images[sizeobj['name']] = []
366             thumbnail_images ||= {}
367             thumbnail_images[sizeobj['name']] = []
368             thumbnail_videos ||= {}
369             thumbnail_videos[sizeobj['name']] = []
370         end
371
372         images.size >= 1 and msg 3, _("\tcreating images thumbnails...")
373
374         #- create thumbnails for images
375         images.each { |img|
376             base_dest_img = dest_dir + '/' + make_dest_filename(img.sub(/\.[^\.]+$/, ''))
377             for sizeobj in $images_size
378                 size_fullscreen = sizeobj['fullscreen']
379                 size_thumbnails = sizeobj['thumbnails']
380                 fullscreen_dest_img = base_dest_img + "-#{size_fullscreen}.jpg"
381                 thumbnail_dest_img  = base_dest_img + "-#{size_thumbnails}.jpg"
382                 fullscreen_images[sizeobj['name']] << File.basename(fullscreen_dest_img)
383                 thumbnail_images[sizeobj['name']]  << File.basename(thumbnail_dest_img)
384                 gen_thumbnails("#{dir}/#{img}", xmldir, true, [ { 'filename' => fullscreen_dest_img, 'size' => size_fullscreen },
385                                                                 { 'filename' => thumbnail_dest_img, 'size' => size_thumbnails } ])
386             end
387         }
388
389         videos.size >= 1 and msg 3, _("\tcreating videos thumbnails...")
390
391         #- create thumbnails for videos
392         videos.each { |video|
393             thumbnail_ok = true
394             for sizeobj in $images_size
395                 size_thumbnails = sizeobj['thumbnails']
396                 thumbnail_dest_img = dest_dir + '/' + make_dest_filename(video.sub(/\.[^\.]+$/, '')) + "-#{size_thumbnails}.jpg"
397                 thumbnail_videos[sizeobj['name']] << File.basename(thumbnail_dest_img)
398                 thumbnail_ok &&= gen_thumbnails("#{dir}/#{video}", xmldir, true, [ { 'filename' => thumbnail_dest_img, 'size' => size_thumbnails } ])
399             end
400             destvideo = "#{dest_dir}/#{video}"
401             if !File.exists?(destvideo)
402                 psys("cp '#{dir}/#{video}' '#{destvideo}'")
403             end
404             #- cleanup temp
405             system("rm -f #{dest_dir}/screenshot.jpg00000*")
406         }
407
408         #- fake for gettext to find these; if themes need more sizes, english name for them should be added here
409         sizenames = { 'small' => utf8(_("small")), 'medium' => utf8(_("medium")), 'large' => utf8(_("large")) }
410
411         msg 3, _("\tgenerating HTML pages...")
412         
413         #- generate thumbnails.html (page with thumbnails)
414         for sizeobj in $images_size
415             html = $html_thumbnails.collect { |l| l.clone }
416             iterations = {}
417             for i in html
418                 i.sub!(/~~run_slideshow~~/, images.size <= 1 ? '' : '<a href="image-' + sizeobj['name'] + '.html?run_slideshow">' + utf8(_('Run slideshow!')) + '</a>')
419                 i.sub!(/~~title~~/, xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir)))
420                 for sizeobj2 in $images_size
421                     if sizeobj != sizeobj2
422                         i.sub!(/~~size_#{sizeobj2['name']}~~/, '<a href="thumbnails-' + sizeobj2['name'] + '.html">' + sizenames[sizeobj2['name']] + '</a>')
423                     else
424                         i.sub!(/~~size_#{sizeobj2['name']}~~/, sizenames[sizeobj2['name']])
425                     end
426                 end
427                 discover_iterations(iterations, i)
428             end
429             html_thumbnails = ''
430             reset_iterations(iterations)
431             for file in entries
432                 type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
433                 if type
434                     html_thumbnails += run_iterations(iterations)
435                     if type == 'image'
436                         index = images.index(file)
437                         html_thumbnails.gsub!(/~~image_iteration~~/,
438                                               '<a href="image-' + sizeobj['name'] + '.html?current=' + fullscreen_images[sizeobj['name']][index] + '">' +
439                                                   img_element("#{dest_dir}/#{thumbnail_images[sizeobj['name']][index]}") + '</a>')
440                         html_thumbnails.gsub!(/~~caption_iteration~~/,
441                                               find_caption_value(xmldir, images[index]) || utf8(images[index]))
442                         html_thumbnails.gsub!(/~~ifimage\?~~(.+?)~~fi~~/) { $1 }
443                         html_thumbnails.gsub!(/~~ifvideo\?~~(.+?)~~fi~~/, '')
444                     elsif type == 'video'
445                         index = videos.index(file)
446                         if File.exists?("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}")
447                             html_thumbnails.gsub!(/~~image_iteration~~/,
448                                                   '<a href="' + videos[index] + '">' + img_element("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}") + '</a>')
449                         else
450                             html_thumbnails.gsub!(/~~image_iteration~~/,
451                                                   '<a href="' + videos[index] + '">' + utf8(_("(no preview)")) + '</a>')
452                         end
453                         html_thumbnails.gsub!(/~~caption_iteration~~/,
454                                               find_caption_value(xmldir, videos[index]) || utf8(videos[index]))
455                         html_thumbnails.gsub!(/~~ifimage\?~~(.+?)~~fi~~/, '')
456                         html_thumbnails.gsub!(/~~ifvideo\?~~(.+?)~~fi~~/) { $1 }
457                     end
458                 end
459             end
460             html_thumbnails += close_iterations(iterations)
461             for i in html
462                 i.sub!(/~~thumbnails~~/, html_thumbnails)
463             end
464             ios = File.open("#{dest_dir}/thumbnails-#{sizeobj['name']}.html", "w")
465             ios.write(html)
466             ios.close
467         end
468
469         #- generate image.html (page with fullscreen images)
470         if images.size > 0
471             #- don't ask me why I need so many backslashes... the aim is to print \\\" for each " in the javascript source
472             captions4js = find_captions(xmldir, images).collect { |e| e ? '"' + e.gsub('"', '\\\\\\\\\\\\\\\\\"' ) + '"' : '""' }.join(', ')
473             for sizeobj in $images_size
474                 html = $html_images.collect { |l| l.clone }
475                 images4js = fullscreen_images[sizeobj['name']].collect { |e| "\"#{e}\"" }.join(', ')
476                 otherimages4js = ''
477                 othersizes = []
478                 for sizeobj2 in $images_size
479                     if sizeobj != sizeobj2
480                         otherimages4js += "var images_#{sizeobj2['name']} = new Array(" + fullscreen_images[sizeobj2['name']].collect { |e| "\"#{e}\"" }.join(', ') + ")\n"
481                         othersizes << "\"#{sizeobj2['name']}\""
482                     end
483                 end
484                 for i in html
485                     i.sub!(/~~images~~/, images4js)
486                     i.sub!(/~~other_images~~/, otherimages4js)
487                     i.sub!(/~~other_sizes~~/, othersizes.join(', '))
488                     i.sub!(/~~captions~~/, captions4js)
489                     i.sub!(/~~title~~/, xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir)))
490                     i.sub!(/~~thumbnails~~/, '<a href="thumbnails-' + sizeobj['name'] + '.html">' + utf8(_('Return to thumbnails')) + '</a>')
491                     for sizeobj2 in $images_size
492                         if sizeobj != sizeobj2
493                             i.sub!(/~~size_#{sizeobj2['name']}~~/,
494                                    '<a href="image-' + sizeobj2['name'] + '.html" id="link' + sizeobj2['name'] + '">' + sizenames[sizeobj2['name']] + '</a>')
495                         else
496                             i.sub!(/~~size_#{sizeobj2['name']}~~/,
497                                    sizenames[sizeobj2['name']])
498                         end
499                     end
500                 end
501                 ios = File.open("#{dest_dir}/image-#{sizeobj['name']}.html", "w")
502                 ios.write(html)
503                 ios.close
504             end
505         end
506     }
507
508     msg 3, ''
509
510     #- add attributes to <dir..> elements needing so
511     if $mode != 'use_config'
512         msg 3, _("\tfixating configuration file...")
513         $xmldoc.elements.each('//dir[@new]') { |element|
514             path = captionpath = element.attributes['path']
515             child = element
516             captionfile = nil
517             while true
518                 child = child.elements[1]
519                 if !child
520                     element.remove  #- means we have a directory with nothing interesting in it
521                     break
522                 elsif child.name == 'dir'
523                     captionpath = child.attributes['path']
524                 else
525                     captionfile = "#{captionpath}/#{child.attributes['filename']}"
526                     break
527                 end
528             end
529             basename = File.basename(path)
530             if element.elements['dir']
531                 element.add_attribute('subdirs-caption', basename)
532                 element.add_attribute('subdirs-captionfile', captionfile)
533             end
534             if element.elements['image'] || element.elements['video']
535                 element.add_attribute('thumbnails-caption', basename)
536                 element.add_attribute('thumbnails-captionfile', captionfile)
537             end
538             element.delete_attribute('new')
539         }
540     end
541
542     #- write down to disk config if necessary
543     if $config_writeto
544         ios = File.open($config_writeto, "w")
545         $xmldoc.write(ios, 0)
546         ios.close
547     end
548
549     #- second pass to create index.html files
550     default_thumbnails = $images_size.detect { |sizeobj| sizeobj['default'] }
551     if !default_thumbnails
552         die _("Theme `%s' has no default size.") % $theme
553     else
554         default_thumbnails = default_thumbnails['name']
555     end
556
557     msg 3, _("\trescanning directories to generate all `index.html' files...")
558
559     `find #{$source} -type d`.each { |dir|
560         dir.chomp!
561         xmldir = $xmldoc.elements["//dir[@path='#{utf8(dir)}']"]
562         if !xmldir
563             next
564         end
565         dest_dir = make_dest_filename(dir.sub(/^#{Regexp.quote($source)}/, $dest))
566
567         html = $html_index.collect { |l| l.clone }
568         iterations = {}
569         for i in html
570             caption = xmldir.attributes['subdirs-caption'] || xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir))
571             i.gsub!(/~~title~~/, caption)
572             if xmldir.parent.name == 'dir'
573                 nav = ''
574                 path = '..'
575                 parent = xmldir.parent
576                 while parent.name == 'dir'
577                     parentcaption = parent.attributes['subdirs-caption'] || parent.attributes['thumbnails-caption'] || File.basename(parent.attributes['path'])
578                     nav = "<a href='#{path}/index.html'>#{parentcaption}</a> #{utf8(_(" > "))} #{nav}"
579                     path += '/..'
580                     parent = parent.parent
581                 end
582                 i.gsub!(/~~ifnavigation\?~~(.+?)~~fi~~/) { $1 }
583                 i.gsub!(/~~navigation~~/, nav + caption)
584             else
585                 i.gsub!(/~~ifnavigation\?~~(.+?)~~fi~~/, '')
586             end
587             discover_iterations(iterations, i)
588         end
589
590         html_index = ''
591         reset_iterations(iterations)
592
593         if xmldir.elements['dir']
594             #- deal with "current" album (directs to "thumbnails" page)
595             if xmldir.attributes['thumbnails-caption']
596                 thumbnail = "#{dest_dir}/thumbnails-thumbnail.jpg"
597                 gen_thumbnails(from_utf8(xmldir.attributes['thumbnails-captionfile']), xmldir, false, [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ])
598                 html_index += run_iterations(iterations)
599                 html_index.gsub!(/~~image_iteration~~/, "<a href='thumbnails-#{default_thumbnails}.html'>" + img_element(thumbnail) + '</a>')
600                 html_index.gsub!(/~~caption_iteration~~/, xmldir.attributes['thumbnails-caption'])
601             end
602             #- cleanup temp for videos
603             system("rm -f #{dest_dir}/screenshot.jpg00000*")
604
605             #- deal with sub-albums (direct to subdirs/index.html pages)
606             xmldir.elements.each('dir') { |child|
607                 subdir = make_dest_filename(from_utf8(File.basename(child.attributes['path'])))
608                 thumbnail = "#{dest_dir}/thumbnails-#{subdir}.jpg"
609                 html_index += run_iterations(iterations)
610                 #- first look for subdirs info; if not, means there is no subdir
611                 caption = child.attributes['subdirs-caption']
612                 if caption
613                     gen_thumbnails(from_utf8(child.attributes['subdirs-captionfile']), child, false, [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ])
614                     html_index.gsub!(/~~caption_iteration~~/, caption)
615                 else
616                     gen_thumbnails(from_utf8(child.attributes['thumbnails-captionfile']), child, false, [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ])
617                     html_index.gsub!(/~~caption_iteration~~/, child.attributes['thumbnails-caption'])
618                 end
619                 html_index.gsub!(/~~image_iteration~~/, "<a href='#{make_dest_filename(subdir)}/index.html'>" + img_element(thumbnail) + '</a>')
620                 #- cleanup temp for videos
621                 system("rm -f #{dest_dir}/screenshot.jpg00000*")
622             }
623
624         else
625             html = html_refresh("thumbnails-#{default_thumbnails}.html")
626         end
627
628         html_index += close_iterations(iterations)
629         for i in html
630             i.gsub!(/~~thumbnails~~/, html_index)
631         end
632
633         ios = File.open("#{dest_dir}/index.html", "w")
634         ios.write(html)
635         ios.close
636
637         #- substitute "return to albums" correctly
638         `find '#{dest_dir}' -maxdepth 1 -name "thumbnails*.html"`.each { |thumbnails|
639             thumbnails.chomp!
640             contents = File.open(thumbnails.chomp).readlines
641             for i in contents
642                 if xmldir.elements['dir']
643                     i.sub!(/~~return_to_albums~~/, '<a href="index.html">' + utf8(_('Return to albums')) + '</a>')
644                 else
645                     if xmldir.parent.name == 'dir'
646                         i.sub!(/~~return_to_albums~~/, '<a href="../index.html">' + utf8(_('Return to albums')) + '</a>')
647                     else
648                         i.sub!(/~~return_to_albums~~/, '')
649                     end
650                 end
651             end
652             ios = File.open(thumbnails, "w")
653             ios.write(contents)
654             ios.close
655         }
656     }
657
658     msg 3, _(" all done.")
659 end
660
661 handle_options
662 check_installation
663
664 build_html_skeletons
665
666 walk_source_dir