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