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