fix merging of config file (when adding image/videos in a
[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     if size = get_image_size(fullpath)
274         sizespec = 'width="${size[:x]}" height="${size[:y]}"'
275     else
276         sizespec = ''
277     end
278     return '<img src="' + File.basename(fullpath) + '" ' + sizespec + ' border="0"/>'
279 end
280
281 def walk_source_dir
282
283     `find #{$source} -type d`.sort.each { |dir|
284         dir.chomp!
285         if dir =~ /'/
286             die _("Source directory or sub-directories can't contain a single-quote character, sorry.")
287         end
288
289         #- place xml document on proper node if exists, else create
290         xmldir = $xmldoc.elements["//dir[@path='#{utf8(dir)}']"]
291         if $mode == 'use_config'
292             if !xmldir
293                 next
294             end
295         else
296             if $mode == 'gen_config' || ($mode == 'merge_config' && !xmldir)
297                 #- add the <dir..> element if necessary
298                 parent = File.dirname(dir)
299                 xmldir = $xmldoc.elements["//dir[@path='#{utf8(parent)}']"]
300                 if !xmldir
301                     xmldir = $xmldoc.root
302                 end
303                 xmldir = xmldir.add_element 'dir', { 'path' => utf8(dir) }
304             end
305         end
306
307         #- read images/videos entries from config or from directories depending on mode
308         entries = []
309         if $mode == 'use_config'
310             msg 2, _("Handling %s from config list...") % dir
311             xmldir.elements.each { |element|
312                 if %w(image video).include?(element.name)
313                     entries << from_utf8(element.attributes['filename'])
314                 end
315             }
316         else
317             msg 2, _("Examining %s...") % dir
318             entries = Dir.entries(dir).sort
319             #- populate config in case of gen_config, add new files in case of merge_config
320             for file in entries
321                 type = entry2type(file)
322                 if type && !xmldir.elements["#{type}[@filename='#{utf8(file)}']"]
323                     xmldir.add_element type, { "filename" => utf8(file), "caption" => utf8(file.sub(/\.[^\.]+$/, '')[0..17]) }
324                 end
325             end
326             if $mode == 'merge_config'
327                 #- cleanup removed files from config and reread entries from config to get proper ordering
328                 entries = []
329                 xmldir.elements.each { |element|
330                     fullpath = "#{dir}/#{from_utf8(element.attributes['filename'])}"
331                     if %w(image video).include?(element.name)
332                         if !File.readable?(fullpath)
333                             msg 1, _("Config merge: removing %s from config; use the backup file to retrieve caption info if this was a mistake") % fullpath
334                             xmldir.delete(element)
335                         else
336                             entries << from_utf8(element.attributes['filename'])
337                         end
338                     end
339                 }
340             end
341         end
342         images = entries.find_all { |e| entry2type(e) == 'image' }
343         msg 3, _("\t%s images") % images.length
344         videos = entries.find_all { |e| entry2type(e) == 'video' }
345         msg 3, _("\t%s videos") % videos.length
346
347         dest_dir = make_dest_filename(dir.sub(/^#{Regexp.quote($source)}/, $dest))
348         system("mkdir -p '#{dest_dir}'")
349
350         #- copy any resource file that goes with the theme (css, images..)
351         for entry in Dir.entries("#{$FPATH}/themes/#{$theme}")
352             if !%w(. .. skeleton_image.html skeleton_thumbnails.html skeleton_index.html parameters.rb CVS).include?(entry)
353                 if !File.exists?("#{dest_dir}/#{entry}")
354                     psys("cp '#{$FPATH}/themes/#{$theme}/#{entry}' '#{dest_dir}'")
355                 end
356             end
357         end
358
359         #- pass through if there are no images and videos
360         if images.size == 0 && videos.size == 0
361             next
362         end
363
364         msg 2, _("Outputting in %s...") % dest_dir
365
366         #- populate data structure with sizes from theme
367         for sizeobj in $images_size
368             fullscreen_images ||= {}
369             fullscreen_images[sizeobj['name']] = []
370             thumbnail_images ||= {}
371             thumbnail_images[sizeobj['name']] = []
372             thumbnail_videos ||= {}
373             thumbnail_videos[sizeobj['name']] = []
374         end
375
376         images.size >= 1 and msg 3, _("\tcreating images thumbnails...")
377
378         #- create thumbnails for images
379         images.each { |img|
380             base_dest_img = dest_dir + '/' + make_dest_filename(img.sub(/\.[^\.]+$/, ''))
381             for sizeobj in $images_size
382                 size_fullscreen = sizeobj['fullscreen']
383                 size_thumbnails = sizeobj['thumbnails']
384                 fullscreen_dest_img = base_dest_img + "-#{size_fullscreen}.jpg"
385                 thumbnail_dest_img  = base_dest_img + "-#{size_thumbnails}.jpg"
386                 fullscreen_images[sizeobj['name']] << File.basename(fullscreen_dest_img)
387                 thumbnail_images[sizeobj['name']]  << File.basename(thumbnail_dest_img)
388                 gen_thumbnails("#{dir}/#{img}", xmldir, true, [ { 'filename' => fullscreen_dest_img, 'size' => size_fullscreen },
389                                                                 { 'filename' => thumbnail_dest_img, 'size' => size_thumbnails } ])
390             end
391         }
392
393         videos.size >= 1 and msg 3, _("\tcreating videos thumbnails...")
394
395         #- create thumbnails for videos
396         videos.each { |video|
397             thumbnail_ok = true
398             for sizeobj in $images_size
399                 size_thumbnails = sizeobj['thumbnails']
400                 thumbnail_dest_img = dest_dir + '/' + make_dest_filename(video.sub(/\.[^\.]+$/, '')) + "-#{size_thumbnails}.jpg"
401                 thumbnail_videos[sizeobj['name']] << File.basename(thumbnail_dest_img)
402                 thumbnail_ok &&= gen_thumbnails("#{dir}/#{video}", xmldir, true, [ { 'filename' => thumbnail_dest_img, 'size' => size_thumbnails } ])
403             end
404             destvideo = "#{dest_dir}/#{video}"
405             if !File.exists?(destvideo)
406                 psys("cp '#{dir}/#{video}' '#{destvideo}'")
407             end
408             #- cleanup temp
409             system("rm -f #{dest_dir}/screenshot.jpg00000*")
410         }
411
412         #- fake for gettext to find these; if themes need more sizes, english name for them should be added here
413         sizenames = { 'small' => utf8(_("small")), 'medium' => utf8(_("medium")), 'large' => utf8(_("large")) }
414
415         msg 3, _("\tgenerating HTML pages...")
416         
417         #- generate thumbnails.html (page with thumbnails)
418         for sizeobj in $images_size
419             html = $html_thumbnails.collect { |l| l.clone }
420             iterations = {}
421             for i in html
422                 i.sub!(/~~run_slideshow~~/, images.size <= 1 ? '' : '<a href="image-' + sizeobj['name'] + '.html?run_slideshow">' + utf8(_('Run slideshow!')) + '</a>')
423                 i.sub!(/~~title~~/, xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir)))
424                 for sizeobj2 in $images_size
425                     if sizeobj != sizeobj2
426                         i.sub!(/~~size_#{sizeobj2['name']}~~/, '<a href="thumbnails-' + sizeobj2['name'] + '.html">' + sizenames[sizeobj2['name']] + '</a>')
427                     else
428                         i.sub!(/~~size_#{sizeobj2['name']}~~/, sizenames[sizeobj2['name']])
429                     end
430                 end
431                 discover_iterations(iterations, i)
432             end
433             html_thumbnails = ''
434             reset_iterations(iterations)
435             for file in entries
436                 type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
437                 if type
438                     html_thumbnails += run_iterations(iterations)
439                     if type == 'image'
440                         index = images.index(file)
441                         html_thumbnails.gsub!(/~~image_iteration~~/,
442                                               '<a href="image-' + sizeobj['name'] + '.html?current=' + fullscreen_images[sizeobj['name']][index] + '">' +
443                                                   img_element("#{dest_dir}/#{thumbnail_images[sizeobj['name']][index]}") + '</a>')
444                         html_thumbnails.gsub!(/~~caption_iteration~~/,
445                                               find_caption_value(xmldir, images[index]) || utf8(images[index]))
446                         html_thumbnails.gsub!(/~~ifimage\?~~(.+?)~~fi~~/) { $1 }
447                         html_thumbnails.gsub!(/~~ifvideo\?~~(.+?)~~fi~~/, '')
448                     elsif type == 'video'
449                         index = videos.index(file)
450                         if File.exists?("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}")
451                             html_thumbnails.gsub!(/~~image_iteration~~/,
452                                                   '<a href="' + videos[index] + '">' + img_element("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}") + '</a>')
453                         else
454                             html_thumbnails.gsub!(/~~image_iteration~~/,
455                                                   '<a href="' + videos[index] + '">' + utf8(_("(no preview)")) + '</a>')
456                         end
457                         html_thumbnails.gsub!(/~~caption_iteration~~/,
458                                               find_caption_value(xmldir, videos[index]) || utf8(videos[index]))
459                         html_thumbnails.gsub!(/~~ifimage\?~~(.+?)~~fi~~/, '')
460                         html_thumbnails.gsub!(/~~ifvideo\?~~(.+?)~~fi~~/) { $1 }
461                     end
462                 end
463             end
464             html_thumbnails += close_iterations(iterations)
465             for i in html
466                 i.sub!(/~~thumbnails~~/, html_thumbnails)
467             end
468             ios = File.open("#{dest_dir}/thumbnails-#{sizeobj['name']}.html", "w")
469             ios.write(html)
470             ios.close
471         end
472
473         #- generate image.html (page with fullscreen images)
474         if images.size > 0
475             #- don't ask me why I need so many backslashes... the aim is to print \\\" for each " in the javascript source
476             captions4js = find_captions(xmldir, images).collect { |e| e ? '"' + e.gsub('"', '\\\\\\\\\\\\\\\\\"' ) + '"' : '""' }.join(', ')
477             for sizeobj in $images_size
478                 html = $html_images.collect { |l| l.clone }
479                 images4js = fullscreen_images[sizeobj['name']].collect { |e| "\"#{e}\"" }.join(', ')
480                 otherimages4js = ''
481                 othersizes = []
482                 for sizeobj2 in $images_size
483                     if sizeobj != sizeobj2
484                         otherimages4js += "var images_#{sizeobj2['name']} = new Array(" + fullscreen_images[sizeobj2['name']].collect { |e| "\"#{e}\"" }.join(', ') + ")\n"
485                         othersizes << "\"#{sizeobj2['name']}\""
486                     end
487                 end
488                 for i in html
489                     i.sub!(/~~images~~/, images4js)
490                     i.sub!(/~~other_images~~/, otherimages4js)
491                     i.sub!(/~~other_sizes~~/, othersizes.join(', '))
492                     i.sub!(/~~captions~~/, captions4js)
493                     i.sub!(/~~title~~/, xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir)))
494                     i.sub!(/~~thumbnails~~/, '<a href="thumbnails-' + sizeobj['name'] + '.html">' + utf8(_('Return to thumbnails')) + '</a>')
495                     for sizeobj2 in $images_size
496                         if sizeobj != sizeobj2
497                             i.sub!(/~~size_#{sizeobj2['name']}~~/,
498                                    '<a href="image-' + sizeobj2['name'] + '.html" id="link' + sizeobj2['name'] + '">' + sizenames[sizeobj2['name']] + '</a>')
499                         else
500                             i.sub!(/~~size_#{sizeobj2['name']}~~/,
501                                    sizenames[sizeobj2['name']])
502                         end
503                     end
504                 end
505                 ios = File.open("#{dest_dir}/image-#{sizeobj['name']}.html", "w")
506                 ios.write(html)
507                 ios.close
508             end
509         end
510     }
511
512     msg 3, ''
513
514     #- add attributes to <dir..> elements needing so
515     if $mode != 'use_config'
516         msg 3, _("\tfixating configuration file...")
517         $xmldoc.elements.each('//dir') { |element|
518             path = captionpath = element.attributes['path']
519             child = element
520             captionfile = nil
521             while true
522                 child = child.elements[1]
523                 if !child
524                     element.remove  #- means we have a directory with nothing interesting in it
525                     break
526                 elsif child.name == 'dir'
527                     captionpath = child.attributes['path']
528                 else
529                     captionfile = "#{captionpath}/#{child.attributes['filename']}"
530                     break
531                 end
532             end
533             basename = File.basename(path)
534             if element.elements['dir']
535                 if !element.attributes['subdirs-caption']
536                     element.add_attribute('subdirs-caption', basename)
537                 end
538                 if !element.attributes['subdirs-captionfile']
539                     element.add_attribute('subdirs-captionfile', captionfile)
540                 end
541             end
542             if element.elements['image'] || element.elements['video']
543                 if !element.attributes['thumbnails-caption']
544                     element.add_attribute('thumbnails-caption', basename)
545                 end
546                 if !element.attributes['thumbnails-captionfile']
547                     element.add_attribute('thumbnails-captionfile', captionfile)
548                 end
549             end
550         }
551     end
552
553     #- write down to disk config if necessary
554     if $config_writeto
555         ios = File.open($config_writeto, "w")
556         $xmldoc.write(ios, 0)
557         ios.close
558     end
559
560     #- second pass to create index.html files
561     default_thumbnails = $images_size.detect { |sizeobj| sizeobj['default'] }
562     if !default_thumbnails
563         die _("Theme `%s' has no default size.") % $theme
564     else
565         default_thumbnails = default_thumbnails['name']
566     end
567
568     msg 3, _("\trescanning directories to generate all `index.html' files...")
569
570     `find #{$source} -type d`.each { |dir|
571         dir.chomp!
572         xmldir = $xmldoc.elements["//dir[@path='#{utf8(dir)}']"]
573         if !xmldir
574             next
575         end
576         dest_dir = make_dest_filename(dir.sub(/^#{Regexp.quote($source)}/, $dest))
577
578         html = $html_index.collect { |l| l.clone }
579         iterations = {}
580         for i in html
581             caption = xmldir.attributes['subdirs-caption'] || xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir))
582             i.gsub!(/~~title~~/, caption)
583             if xmldir.parent.name == 'dir'
584                 nav = ''
585                 path = '..'
586                 parent = xmldir.parent
587                 while parent.name == 'dir'
588                     parentcaption = parent.attributes['subdirs-caption'] || parent.attributes['thumbnails-caption'] || File.basename(parent.attributes['path'])
589                     nav = "<a href='#{path}/index.html'>#{parentcaption}</a> #{utf8(_(" > "))} #{nav}"
590                     path += '/..'
591                     parent = parent.parent
592                 end
593                 i.gsub!(/~~ifnavigation\?~~(.+?)~~fi~~/) { $1 }
594                 i.gsub!(/~~navigation~~/, nav + caption)
595             else
596                 i.gsub!(/~~ifnavigation\?~~(.+?)~~fi~~/, '')
597             end
598             discover_iterations(iterations, i)
599         end
600
601         html_index = ''
602         reset_iterations(iterations)
603
604         if xmldir.elements['dir']
605             #- deal with "current" album (directs to "thumbnails" page)
606             if xmldir.attributes['thumbnails-caption']
607                 thumbnail = "#{dest_dir}/thumbnails-thumbnail.jpg"
608                 gen_thumbnails(from_utf8(xmldir.attributes['thumbnails-captionfile']), xmldir, false, [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ])
609                 html_index += run_iterations(iterations)
610                 html_index.gsub!(/~~image_iteration~~/, "<a href='thumbnails-#{default_thumbnails}.html'>" + img_element(thumbnail) + '</a>')
611                 html_index.gsub!(/~~caption_iteration~~/, xmldir.attributes['thumbnails-caption'])
612             end
613             #- cleanup temp for videos
614             system("rm -f #{dest_dir}/screenshot.jpg00000*")
615
616             #- deal with sub-albums (direct to subdirs/index.html pages)
617             xmldir.elements.each('dir') { |child|
618                 subdir = make_dest_filename(from_utf8(File.basename(child.attributes['path'])))
619                 thumbnail = "#{dest_dir}/thumbnails-#{subdir}.jpg"
620                 html_index += run_iterations(iterations)
621                 #- first look for subdirs info; if not, means there is no subdir
622                 caption = child.attributes['subdirs-caption']
623                 if caption
624                     gen_thumbnails(from_utf8(child.attributes['subdirs-captionfile']), child, false, [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ])
625                     html_index.gsub!(/~~caption_iteration~~/, caption)
626                 else
627                     gen_thumbnails(from_utf8(child.attributes['thumbnails-captionfile']), child, false, [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ])
628                     html_index.gsub!(/~~caption_iteration~~/, child.attributes['thumbnails-caption'])
629                 end
630                 html_index.gsub!(/~~image_iteration~~/, "<a href='#{make_dest_filename(subdir)}/index.html'>" + img_element(thumbnail) + '</a>')
631                 #- cleanup temp for videos
632                 system("rm -f #{dest_dir}/screenshot.jpg00000*")
633             }
634
635         else
636             html = html_refresh("thumbnails-#{default_thumbnails}.html")
637         end
638
639         html_index += close_iterations(iterations)
640         for i in html
641             i.gsub!(/~~thumbnails~~/, html_index)
642         end
643
644         ios = File.open("#{dest_dir}/index.html", "w")
645         ios.write(html)
646         ios.close
647
648         #- substitute "return to albums" correctly
649         `find '#{dest_dir}' -maxdepth 1 -name "thumbnails*.html"`.each { |thumbnails|
650             thumbnails.chomp!
651             contents = File.open(thumbnails.chomp).readlines
652             for i in contents
653                 if xmldir.elements['dir']
654                     i.sub!(/~~return_to_albums~~/, '<a href="index.html">' + utf8(_('Return to albums')) + '</a>')
655                 else
656                     if xmldir.parent.name == 'dir'
657                         i.sub!(/~~return_to_albums~~/, '<a href="../index.html">' + utf8(_('Return to albums')) + '</a>')
658                     else
659                         i.sub!(/~~return_to_albums~~/, '')
660                     end
661                 end
662             end
663             ios = File.open(thumbnails, "w")
664             ios.write(contents)
665             ios.close
666         }
667     }
668
669     msg 3, _(" all done.")
670 end
671
672 handle_options
673 check_installation
674
675 build_html_skeletons
676
677 walk_source_dir