be nice with ice age browsers
[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) 2004-2006 Guillaume Cottenceau <http://zarb.org/~gc/resource/gc_mail.png>
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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     [ '--source',        '-s', GetoptLong::REQUIRED_ARGUMENT, _("Directory which contains original images/videos as files or subdirs") ],
40     [ '--destination',   '-d', GetoptLong::REQUIRED_ARGUMENT, _("Directory which will contain the web-album") ],
41 #    [ '--clean',         '-c', GetoptLong::NO_ARGUMENT,       _("Clean destination directory") ],
42
43     [ '--theme',         '-t', GetoptLong::REQUIRED_ARGUMENT, _("Select HTML theme to use") ],
44     [ '--config',        '-C', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing images and videos within directories with captions") ],
45     [ '--config-skel',   '-k', GetoptLong::REQUIRED_ARGUMENT, _("Filename where the script will output a config skeleton") ],
46     [ '--merge-config',  '-M', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing, where to merge new/removed images/videos from --source, and change theme info") ],
47     [ '--merge-config-onedir',  '-O', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing, for merging the subdir specified with --dir") ],
48     [ '--merge-config-subdirs', '-U', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing, for merging the new subdirs down the subdir specified with --dir") ],
49     [ '--dir',           '-D', GetoptLong::REQUIRED_ARGUMENT, _("Directory for merge with --merge-config-onedir or --merge-config-subdirs") ],
50     [ '--use-config',    '-u', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing, where to change theme info") ],
51     [ '--force',         '-f', GetoptLong::NO_ARGUMENT,       _("Force generation of album even if the GUI marked some directories as already generated") ],
52
53     [ '--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)") ],
54     [ '--thumbnails-per-row', '-T', GetoptLong::REQUIRED_ARGUMENT, _("Specify the amount of thumbnails per row in the thumbnails page (if applicable in theme)") ],
55     [ '--optimize-for-32', '-o', GetoptLong::NO_ARGUMENT,       _("Resize images with optimized sizes for 3/2 aspect ratio rather than 4/3 (typical aspect ratio of pictures from non digital cameras are 3/2 when pictures from digital cameras are 4/3)") ],
56     [ '--index-link',    '-l', GetoptLong::REQUIRED_ARGUMENT, _("Specify the HTML markup to use on the bottom of pages for a small link returning to wherever you see fit in your website (or somewhere else)") ],
57     [ '--made-with',     '-n', GetoptLong::REQUIRED_ARGUMENT, _("Specify the HTML markup to use on the bottom of pages for a small 'made with' message") ],
58     [ '--comments-format','-c', GetoptLong::REQUIRED_ARGUMENT, _("Specify comments format to use for images instead of only filename when creating new albums; use ImageMagick's format") ],
59
60     [ '--mproc',         '-m', GetoptLong::REQUIRED_ARGUMENT, _("Specify the number of processors for multi-processors machines") ],
61
62     [ '--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)") ],
63
64     [ '--verbose-level', '-v', GetoptLong::REQUIRED_ARGUMENT, _("Set max verbosity level (0: errors, 1: warnings, 2: important messages, 3: other messages)") ],
65     [ '--info-pipe',     '-i', GetoptLong::REQUIRED_ARGUMENT, _("Name a file where to write information about what's going on (used by the GUI)") ],
66 ]
67
68 #- default values for some globals 
69 $switches = []
70 $stdout.sync = true
71 $no_identify = false
72 $ignore_videos = false
73 $forgui = false
74 $hardlinks_ok = true
75
76 def usage
77     puts _("Usage: %s [OPTION]...") % File.basename($0)
78     $options.each { |ary|
79         printf " %3s, %-18s %s\n", ary[1], ary[0], ary[3]
80     }
81 end
82
83 def handle_options
84     parser = GetoptLong.new
85     parser.set_options(*$options.collect { |ary| ary[0..2] })
86     begin
87         parser.each_option do |name, arg|
88             case name
89             when '--help'
90                 usage
91                 exit(0)
92
93             when '--version'
94                 puts _("Booh version %s
95
96 Copyright (c) 2005 Guillaume Cottenceau.
97 This is free software; see the source for copying conditions.  There is NO
98 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.") % $VERSION
99
100                 exit(0)
101
102             when '--source'
103                 $source = File.expand_path(arg.sub(%r|/$|, ''))
104                 if !File.directory?($source)
105                     die _("Argument to --source must be a directory")
106                 end
107             when '--destination'
108                 $dest = File.expand_path(arg.sub(%r|/$|, ''))
109                 if File.exists?($dest) && !File.directory?($dest)
110                     die _("If --destination exists, it must be a directory")
111                 end
112                 if $dest != make_dest_filename($dest)
113                     die _("Sorry, destination directory can't contain non simple alphanumeric characters.")
114                 end
115 #            when '--clean'
116 #                system("rm -rf #{$dest}")
117
118             when '--theme'
119                 $theme = arg
120             when '--config'
121                 arg = File.expand_path(arg)
122                 if File.readable?(arg)
123                     $xmldoc = REXML::Document.new File.new(arg)
124                     $mode = 'use_config'
125                 else
126                     die _('Config file does not exist or is unreadable.')
127                 end
128             when '--config-skel'
129                 arg = File.expand_path(arg)
130                 if File.exists?(arg)
131                     if File.directory?(arg)
132                         die _("Config skeleton file (%s) already exists and is a directory! Please change the filename.") % arg
133                     else
134                         msg 1, _("Config skeleton file already exists, backuping to %s.backup") % arg
135                         File.rename(arg, "#{arg}.backup")
136                     end
137                 end
138                 $config_writeto = arg
139                 $mode = 'gen_config'
140             when '--merge-config'
141                 arg = File.expand_path(arg)
142                 if File.readable?(arg)
143                     msg 2, _("Merge config notice: backuping current config file to %s.backup") % arg
144                     $xmldoc = REXML::Document.new File.new(arg)
145                     File.rename(arg, "#{arg}.backup")
146                     $config_writeto = arg
147                     $mode = 'merge_config'
148                 else
149                     die _('Config file does not exist or is unreadable.')
150                 end
151             when '--merge-config-onedir'
152                 arg = File.expand_path(arg)
153                 if File.readable?(arg)
154                     msg 2, _("Merge config notice: backuping current config file to %s.backup") % arg
155                     $xmldoc = REXML::Document.new File.new(arg)
156                     File.rename(arg, "#{arg}.backup")
157                     $config_writeto = arg
158                     $mode = 'merge_config_onedir'
159                 else
160                     die _('Config file does not exist or is unreadable.')
161                 end
162             when '--merge-config-subdirs'
163                 arg = File.expand_path(arg)
164                 if File.readable?(arg)
165                     msg 2, _("Merge config notice: backuping current config file to %s.backup") % arg
166                     $xmldoc = REXML::Document.new File.new(arg)
167                     File.rename(arg, "#{arg}.backup")
168                     $config_writeto = arg
169                     $mode = 'merge_config_subdirs'
170                 else
171                     die _('Config file does not exist or is unreadable.')
172                 end
173             when '--dir'
174                 arg = File.expand_path(arg)
175                 if !File.readable?(arg)
176                     die _('Specified directory to merge with --dir is not readable')
177                 else
178                     $onedir = arg
179                 end
180             when '--use-config'
181                 arg = File.expand_path(arg)
182                 if File.readable?(arg)
183                     msg 2, _("Use config notice: backuping current config file to %s.backup") % arg
184                     $xmldoc = REXML::Document.new File.new(arg)
185                     File.rename(arg, "#{arg}.backup")
186                     $config_writeto = arg
187                     $mode = 'use_config_changetheme'
188                 else
189                     die _('Config file does not exist or is unreadable.')
190                 end
191
192             when '--sizes'
193                 $limit_sizes = arg
194
195             when '--thumbnails-per-row'
196                 $N_per_row = arg
197
198             when '--optimize-for-32'
199                 $optimize_for_32 = true
200
201             when '--made-with'
202                 $madewith = arg
203
204             when '--index-link'
205                 $indexlink = arg
206
207             when '--comments-format'
208                 $commentsformat = arg
209
210             when '--force'
211                 $force = true
212
213             when '--mproc'
214                 $mproc = arg.to_i
215                 $pids = []
216
217             when '--for-gui'
218                 $forgui = true
219
220             when '--verbose-level'
221                 $verbose_level = arg.to_i
222
223             when '--info-pipe'
224                 $info_pipe = File.open(arg, File::WRONLY)
225                 $info_pipe.sync = true
226             end
227         end
228     rescue
229         puts $!
230         usage
231         exit(1)
232     end
233
234     if !$source && $xmldoc
235         $source = from_utf8($xmldoc.root.attributes['source']).sub(%r|/$|, '')
236         $dest = from_utf8($xmldoc.root.attributes['destination']).sub(%r|/$|, '')
237         $theme ||= $xmldoc.root.attributes['theme']
238         $limit_sizes ||= $xmldoc.root.attributes['limit-sizes']
239         if $mode == 'use_config' || $mode =~ /^merge_config/
240             $optimize_for_32 = !$xmldoc.root.attributes['optimize-for-32'].nil?
241             $N_per_row = $xmldoc.root.attributes['thumbnails-per-row']
242             $madewith = $xmldoc.root.attributes['made-with']
243             $indexlink = $xmldoc.root.attributes['index-link']
244         end
245     end
246
247     if $mode == 'merge_config_onedir' && !$onedir
248         die _("Missing --dir for --merge-config-onedir")
249     end
250     if $mode == 'merge_config_subdirs' && !$onedir
251         die _("Missing --dir for --merge-config-subdirs")
252     end
253
254     if !$source
255         usage
256         exit(0)
257     end
258     if !$dest
259         die _("Missing --destination parameter.")
260     end
261     if !$theme
262         $theme = 'simple'
263     end
264
265     select_theme($theme, $limit_sizes, $optimize_for_32, $N_per_row)
266
267     if !$xmldoc
268         additional_params = ''
269         if $limit_sizes
270             additional_params += "limit-sizes='#{$limit_sizes}'"
271         end
272         if $optimize_for_32
273             additional_params += " optimize-for-32='true'"
274         end
275         if $N_per_row
276             additional_params += " thumbnails-per-row='#{$N_per_row}'"
277         end
278         if $madewith
279             additional_params += " made-with='#{$madewith}'"
280         end
281         if $indexlink
282             additional_params += " index-link='#{$indexlink}'"
283         end
284         $xmldoc = Document.new "<booh version='#{$VERSION}' source='#{utf8($source)}' destination='#{utf8($dest)}' theme='#{$theme}' #{additional_params}/>"
285         $xmldoc << XMLDecl.new(XMLDecl::DEFAULT_VERSION, $CURRENT_CHARSET)
286         $mode = 'gen_config'
287     end
288
289     if $mode == 'merge_config' || $mode == 'use_config_changetheme'
290         $xmldoc.root.add_attribute('theme', $theme)
291         $xmldoc.root.add_attribute('version', $VERSION)
292         if $limit_sizes
293             $xmldoc.root.add_attribute('limit-sizes', $limit_sizes)
294         else
295             $xmldoc.root.delete_attribute('limit-sizes')
296         end
297         if $optimize_for_32
298             $xmldoc.root.add_attribute('optimize-for-32', 'true')
299         else
300             $xmldoc.root.delete_attribute('optimize-for-32')
301         end
302         if $N_per_row
303             $xmldoc.root.add_attribute('thumbnails-per-row', $N_per_row)
304         else
305             $xmldoc.root.delete_attribute('thumbnails-per-row')
306         end
307         if $madewith
308             $xmldoc.root.add_attribute('made-with', $madewith)
309         else
310             $xmldoc.root.delete_attribute('made-with')
311         end
312         if $indexlink
313             $xmldoc.root.add_attribute('index-link', $indexlink)
314         else
315             $xmldoc.root.delete_attribute('index-link')
316         end
317     end
318
319     if $madewith
320         $madewith = $madewith.gsub('%booh', '"http://zarb.org/~gc/html/booh.html"')
321     end
322 end
323
324 def read_config
325     $config = {}
326 end
327
328 def write_config
329 end
330
331 def info(value)
332     if $info_pipe
333         $info_pipe.puts(value)
334     end
335 end
336
337 def die(value)
338     if $info_pipe
339         $info_pipe.puts("die: " + value)
340     end
341     die_ value
342 end
343
344 def check_installation
345     if !system("which convert >/dev/null 2>/dev/null")
346         die _("The program 'convert' is needed. Please install it. 
347 It is generally available with the 'ImageMagick' software package.")
348     end
349     if !system("which identify >/dev/null 2>/dev/null")
350         msg 1, _("the program 'identify' is needed to get images sizes and EXIF data. Please install it.
351 It is generally available with the 'ImageMagick' software package.")
352         $no_identify = true
353     end
354     missing = %w(transcode mencoder).delete_if { |prg| system("which #{prg} >/dev/null 2>/dev/null") }
355     if missing != []
356         msg 1, _("the following program(s) are needed to handle videos: '%s'. Videos will be ignored.") % missing.join(', ')
357         $ignore_videos = true
358     end
359 end
360
361 def replace_line(surround, keyword, line)
362     begin
363         contents = eval "$#{keyword}"
364         line.sub!(/#{surround}#{keyword}#{surround}/, contents)
365     rescue TypeError
366         die _("No '%s' found for substitution") % keyword
367     end
368 end
369
370 def build_html_skeletons
371     $html_images     = File.open("#{$FPATH}/themes/#{$theme}/skeleton_image.html").readlines
372     $html_thumbnails = File.open("#{$FPATH}/themes/#{$theme}/skeleton_thumbnails.html").readlines
373     $html_index      = File.open("#{$FPATH}/themes/#{$theme}/skeleton_index.html").readlines
374     for line in $html_images + $html_thumbnails + $html_index
375         while line =~ /~~~(\w+)~~~/
376             replace_line('~~~', $1, line)
377         end
378     end
379 end
380
381 def find_caption_value(xmldir, filename)
382     if cap = xmldir.elements["*[@filename='#{utf8(filename)}']"].attributes['caption']
383         return cap.gsub("\n", '<br/>')
384     else
385         return nil
386     end
387 end
388
389 def find_captions(xmldir, images)
390     return images.collect { |img| find_caption_value(xmldir, img) }
391 end
392
393 #- stolen from CVSspam
394 def urlencode(text)
395   text.sub(/[^a-zA-Z0-9\-,.*_\/]/) do
396     "%#{sprintf('%2X', $&[0])}"
397   end
398 end
399
400 def all_images_sizes
401     return $limit_sizes =~ /original/ ? $images_size + [ { 'name' => 'original' } ] : $images_size
402 end
403
404 def html_reload_to_thumbnails
405     html_reload_to_thumbnails = $preferred_size_reloader.clone
406     html_reload_to_thumbnails.gsub!(/~~theme~~/, $theme)
407     html_reload_to_thumbnails.gsub!(/~~default_size~~/, $default_size['name'])
408     html_reload_to_thumbnails.gsub!(/~~all_sizes~~/, all_images_sizes.collect { |s| "\"#{size2js(s['name'])}\"" }.join(', '))
409     size_auto_chooser = '';
410     all_images_sizes.sort { |a,b| b['optimizedforwidth'].to_i <=> a['optimizedforwidth'].to_i }.
411                      each { |s| size_auto_chooser += "if (w + 50 > #{s['optimizedforwidth']}) { return 'thumbnails-#{size2js(s['name'])}.html'; }\n" }
412     html_reload_to_thumbnails.gsub!(/~~size_auto_chooser~~/, size_auto_chooser)
413     return html_reload_to_thumbnails
414 end
415
416 def discover_iterations(iterations, line)
417     if line =~ /~~iterate(\d)_open(_max(\d+|N))?~~/
418         for iter in iterations.values
419             if iter['open']
420                 iter['open'] = false
421                 iter['close_wait'] = $1.to_i
422             end
423         end
424         max = $3 == 'N' ? ($N_per_row || $default_N) : $3
425         iterations[$1.to_i] = { 'open' => true, 'max' => max, 'opening' => '', 'closing' => '' }
426         if $1.to_i == 1
427             line.sub!(/.*/, '~~thumbnails~~')
428         else
429             line.sub!(/.*/, '')
430         end
431     elsif line =~ /~~iterate(\d)_close~~/
432         iterations[$1.to_i]['open']  = false;
433         iterations[$1.to_i]['close'] = true;
434         line.sub!(/.*/, '')
435     else
436         for iter in iterations.values
437             if iter['open']
438                 iter['opening'] += line
439                 line.sub!(/.*/, '')
440             end
441             if !iter['close'] && iter['close_wait'] && iterations[iter['close_wait']]['close']
442                 iter['closing'] += line
443                 line.sub!(/.*/, '')
444             end
445         end
446     end
447 end
448
449 def reset_iterations(iterations)
450     for iter in iterations.values
451         iter['value'] = 0
452     end
453 end
454
455 def run_iterations(iterations, amount)
456     html = ''
457     should_rerun = false
458     for level in iterations.keys.sort
459         if iterations[level]['value'] == 0
460             html += iterations[level]['opening']
461         elsif level == iterations.keys.max
462             if !iterations[level]['max'] || iterations[level]['max'] && iterations[level]['value'] + amount <= iterations[level]['max'].to_i
463                 html += iterations[level]['opening']
464             else
465                 should_rerun = true
466             end
467         end
468         iterations[level]['value'] += amount
469         if iterations[level]['max'] && iterations[level]['value'] > iterations[level]['max'].to_i
470             iterations[level]['value'] = 0
471             iterations[level-1]['value'] = 0
472             html += iterations[level-1]['closing']
473         end
474     end
475     if should_rerun
476         return html + run_iterations(iterations, amount)
477     else
478         return html
479     end
480 end
481
482 def close_iterations(iterations)
483     html = ''
484     for level in iterations.keys.sort.reverse
485         html += iterations[level]['closing']
486     end
487     return html
488 end
489
490 def img_element(fullpath)
491     if size = get_image_size(fullpath)
492         sizespec = 'width="' + size[:x].to_s + '" height="' + size[:y].to_s + '"'
493     else
494         sizespec = ''
495     end
496     return '<img src="' + File.basename(fullpath) + '" ' + sizespec + ' alt="image"/>'
497 end
498
499 def size2js(name)
500     return name.gsub(/-/, '')
501 end
502
503 def substitute_html_sizes(html, sizeobj, type, suffix)
504     sizestrings = []
505     if $images_size.length > 1 || (type == 'image' && $limit_sizes =~ /original/)
506         for sizeobj2 in $images_size
507             if sizeobj != sizeobj2
508                 if type == 'thumbnails'
509                     sizestrings << '<a href="thumbnails-' + size2js(sizeobj2['name']) + suffix + '.html">' + sizename(sizeobj2['name']) + '</a>'
510                 else
511                     sizestrings << '<a id="link' + size2js(sizeobj2['name']) + '">' + sizename(sizeobj2['name']) + '</a>'
512                 end
513             else
514                 sizestrings << sizename(sizeobj2['name'])
515             end
516         end
517         if type == 'image' && $limit_sizes =~ /original/
518             sizestrings << '<a id="linkoriginal" target="newframe">' + sizename('original') + '</a>'
519         end
520     end
521     html.sub!(/~~sizes~~(.+)~~/) { sizestrings.join($1) }
522 end
523
524 def xmldir2destdir(xmldir)
525     return make_dest_filename(from_utf8(File.basename(xmldir.attributes['path'])))
526 end
527
528 def find_previous_album(xmldir)
529     relative_pos = ''
530     begin
531         #- move to previous dir element if exists
532         if prevelem = xmldir.previous_element_byname_notattr('dir', 'deleted')
533             xmldir = prevelem
534             relative_pos += '../' + xmldir2destdir(xmldir) + '/'
535             child = nil
536             #- after having moved to previous dir, we need to go down last subdir until the last one
537             while child = xmldir.elements['dir']
538                 while nextchild = child.next_element_byname_notattr('dir', 'deleted')
539                     child = nextchild
540                 end
541                 relative_pos += xmldir2destdir(child) + '/'
542                 xmldir = child
543             end
544         else
545             #- previous dir doesn't exist, move to previous dir element if exists
546             xmldir = xmldir.parent
547             if xmldir.name == 'dir' && !xmldir.attributes['deleted']
548                 relative_pos += '../'
549             else
550                 return nil
551             end
552         end
553     end while !xmldir.child_byname_notattr('image', 'deleted') && !xmldir.child_byname_notattr('video', 'deleted')
554     return File.reduce_path(relative_pos)
555 end
556
557 def find_next_album(xmldir)
558     relative_pos = ''
559     begin
560         #- first child dir element (catches when initial xmldir has both thumbnails and subdirs)
561         if firstchild = xmldir.child_byname_notattr('dir', 'deleted')
562             xmldir = firstchild
563             relative_pos += xmldir2destdir(xmldir) + '/'
564         #- next brother
565         elsif nextbro = xmldir.next_element_byname_notattr('dir', 'deleted')
566             xmldir = nextbro
567             relative_pos += '../' + xmldir2destdir(xmldir) + '/'
568         else
569             #- go up until we have a next brother or we are finished
570             begin
571                 xmldir = xmldir.parent
572                 relative_pos += '../'
573             end while xmldir && !xmldir.next_element_byname_notattr('dir', 'deleted')
574             if xmldir
575                 xmldir = xmldir.next_element_byname('dir')
576                 relative_pos += '../' + xmldir2destdir(xmldir) + '/'
577             else
578                 return nil
579             end
580         end
581     end while !xmldir.child_byname_notattr('image', 'deleted') && !xmldir.child_byname_notattr('video', 'deleted')
582     return File.reduce_path(relative_pos)
583 end
584
585 def sub_previous_next_album(previous_album, next_album, html)
586     if previous_album
587         html.gsub!(/~~previous_album~~/, '<a href="' + previous_album + 'thumbnails.html">' + utf8(_('previous album')) + '</a>')
588         html.gsub!(/~~ifprevious_album\?~~(.+?)~~fi~~/) { $1 }
589     else
590         html.gsub!(/~~previous_album~~/, '')
591         html.gsub!(/~~ifprevious_album\?~~(.+?)~~fi~~/, '')
592     end
593     if next_album
594         html.gsub!(/~~next_album~~/, '<a href="' + next_album + 'thumbnails.html">' + utf8(_('next album')) + '</a>')
595         html.gsub!(/~~ifnext_album\?~~(.+?)~~fi~~/) { $1 }
596     else
597         html.gsub!(/~~next_album~~/, '')
598         html.gsub!(/~~ifnext_album\?~~(.+?)~~fi~~/, '')
599     end
600     return html
601 end
602
603 def walk_source_dir
604
605     #- preprocess the path->dir, rexml is very slow with that; we seem to improve speed by 7%
606     optxpath = {}
607     $xmldoc.elements.each('//dir') { |elem|
608         optxpath[elem.attributes['path']] = elem
609     }
610
611     examined_dirs = nil
612     if $mode == 'merge_config_onedir'
613         examined_dirs = [ $onedir ]
614     elsif $mode == 'merge_config_subdirs'
615         examined_dirs = `find '#{$onedir}' -type d -follow`.sort.collect { |v| v.chomp }.delete_if { |v| optxpath.has_key?(utf8(v)) }
616     else
617         examined_dirs = `find '#{$source}' -type d -follow`.sort.collect { |v| v.chomp }
618         if $mode == 'merge_config'
619             $xmldoc.elements.each('//dir') { |elem|
620                 if ! examined_dirs.include?(elem.attributes['path'])
621                     msg 2, _("Merging config: removing directory %s from config, isn't on filesystem anymore") % elem.attributes['path']
622                     elem.remove
623                 end
624             }
625         end
626     end
627     info("directories: #{examined_dirs.length}, sizes: #{$images_size.length}")
628
629     examined_dirs.each { |dir|
630         if dir =~ /'/
631             die _("Source directory or sub-directories can't contain a single-quote character, sorry: %s") % dir
632         end
633         if $mode !~ /^use_config/
634             Dir.entries(dir).each { |file|
635                 if file =~ /['"\[\]]/
636                     die _("Files can't contain any of the characters ', \", [ or ], sorry: %s") % "#{dir}/#{file}"
637                 end
638             }
639         end
640     }
641
642     examined_dirs.each { |dir|
643         if File.basename(dir) =~ /^\./
644             msg 1, _("Ignoring directory %s, begins with a dot (indicating a hidden directory)") % dir
645             next
646         end
647
648         dest_dir = make_dest_filename(dir.sub(/^#{Regexp.quote($source)}/, $dest))
649
650         #- place xml document on proper node if exists, else create
651         xmldir = optxpath[utf8(dir)]
652         if $mode == 'use_config' || $mode == 'use_config_changetheme'
653             if !xmldir || (xmldir.attributes['already-generated'] && !$force) || xmldir.attributes['deleted']
654                 info("walking: #{dir}|#{$source}, 0 elements")
655                 if xmldir && xmldir.attributes['deleted']
656                     system("rm -rf '#{dest_dir}'")
657                 end
658                 next
659             end
660         else
661             if $mode == 'gen_config' || (($mode == 'merge_config' || $mode == 'merge_config_subdirs') && !xmldir)
662                 #- add the <dir..> element if necessary
663                 parent = File.dirname(dir)
664                 xmldir = $xmldoc.elements["//dir[@path='#{utf8(parent)}']"]
665                 if !xmldir
666                     xmldir = $xmldoc.root
667                 end
668                 #- need to remove the already-generated mark of the parent because of the sub-albums page containing now one more element
669                 xmldir.delete_attribute('already-generated')
670                 xmldir = optxpath[utf8(dir)] = xmldir.add_element('dir', { 'path' => utf8(dir) })
671             end
672         end
673         xmldir.delete_attribute('already-generated')
674
675         #- read images/videos entries from config or from directories depending on mode
676         entries = []
677         if $mode == 'use_config' || $mode == 'use_config_changetheme'
678             msg 2, _("Handling %s from config list...") % dir
679             xmldir.elements.each { |element|
680                 if %w(image video).include?(element.name) && !element.attributes['deleted']
681                     entries << from_utf8(element.attributes['filename'])
682                 end
683             }
684         else
685             msg 2, _("Examining %s...") % dir
686             entries = Dir.entries(dir).sort
687             #- populate config in case of gen_config, add new files in case of merge_config
688             for file in entries
689                 if file =~ /['"\[\]]/
690                     msg 1, _("Ignoring %s, contains one of forbidden characters: '\"[]") % "#{dir}/#{file}"
691                 else
692                     type = entry2type(file)
693                     if type && !xmldir.elements["#{type}[@filename='#{utf8(file)}']"]
694                         if $commentsformat && type == 'image'
695                             comment = utf8(`identify -format "#{$commentsformat}" '#{dir}/#{file}'`.chomp.sub(/\.$/, ''))
696                         else
697                             comment = utf8cut(file.sub(/\.[^\.]+$/, ''), 18)
698                         end
699                         xmldir.add_element type, { "filename" => utf8(file), "caption" => comment }
700                     end
701                 end
702             end
703             if $mode != 'gen_config'
704                 #- cleanup removed files from config and reread entries from config to get proper ordering
705                 entries = []
706                 xmldir.elements.each { |element|
707                     fullpath = "#{dir}/#{from_utf8(element.attributes['filename'])}"
708                     if %w(image video).include?(element.name)
709                         if !File.readable?(fullpath)
710                             msg 1, _("Config merge: removing %s from config; use the backup file to retrieve caption info if this was a mistake") % fullpath
711                             xmldir.delete(element)
712                         elsif !element.attributes['deleted']
713                             entries << from_utf8(element.attributes['filename'])
714                         end
715                     end
716                 }
717                 #- if there is no more elements here, there is no album here anymore
718                 if !xmldir.child_byname_notattr('image', 'deleted') && !xmldir.child_byname_notattr('video', 'deleted')
719                     xmldir.delete_attribute('thumbnails-caption')
720                     xmldir.delete_attribute('thumbnails-captionfile')
721                 end
722             end
723         end
724         images = entries.find_all { |e| entry2type(e) == 'image' }
725         msg 3, _("\t%s images") % images.length
726         videos = entries.find_all { |e| entry2type(e) == 'video' }
727         msg 3, _("\t%s videos") % videos.length
728         info("walking: #{dir}|#{$source}, #{images.length + videos.length} elements")
729
730         system("mkdir -p '#{dest_dir}'")
731
732         #- generate .htaccess file
733         if !$forgui
734             ios = File.open("#{dest_dir}/.htaccess", "w")
735             ios.write("AddCharset UTF-8 .html\n")
736             if auth_user_file = xmldir.attributes['password-protect']
737                 msg 3, _("\tgenerating password protection file #{dest_dir}/.htaccess")
738                 ios.write("AuthType Basic\nAuthName \"protected area\"\nAuthUserFile #{auth_user_file}\nrequire valid-user\n")
739             end
740             ios.close
741         end
742
743         #- pass through if there are no images and videos
744         if images.size == 0 && videos.size == 0
745             if !$forgui
746                 #- cleanup old images/videos, especially if this directory contained images/videos previously.
747                 themestuff = Dir.entries("#{$FPATH}/themes/#{$theme}").
748                                 find_all { |e| !%w(. .. skeleton_image.html skeleton_thumbnails.html skeleton_index.html metadata CVS).include?(e) }
749                 if $mode != 'gen_config'
750                     rightful_images = [ '.htaccess' ]
751                     if xmldir.attributes['thumbnails-caption']
752                         rightful_images << 'thumbnails-thumbnail.jpg'
753                     end
754                     xmldir.elements.each('dir') { |child|
755                         if child.attributes['deleted']
756                             next
757                         end
758                         subdir = make_dest_filename(from_utf8(File.basename(child.attributes['path'])))
759                         rightful_images << "thumbnails-#{subdir}.jpg"
760                     }
761                     to_del = Dir.entries(dest_dir).find_all { |e| !File.directory?("#{dest_dir}/#{e}") && !rightful_images.include?(e) } - themestuff
762                     if to_del.size > 0
763                         system("rm -f " + to_del.collect { |e| "'#{dest_dir}/#{e}'" }.join(' '))
764                     end
765                 end
766                 
767                 #- copy any resource file that goes with the theme (css, images..)
768                 themestuff.each { |entry|
769                     if !File.exists?("#{dest_dir}/#{entry}")
770                         psys("cp '#{$FPATH}/themes/#{$theme}/#{entry}' '#{dest_dir}'")
771                     end
772                 }
773             end
774             next
775         end
776
777         msg 2, _("Outputting in %s...") % dest_dir
778
779         #- populate data structure with sizes from theme
780         for sizeobj in $images_size
781             fullscreen_images ||= {}
782             fullscreen_images[sizeobj['name']] = []
783             thumbnail_images ||= {}
784             thumbnail_images[sizeobj['name']] = []
785             thumbnail_videos ||= {}
786             thumbnail_videos[sizeobj['name']] = []
787         end
788         #- a special dummy size to keep 'references' to thumbnails in case of panorama, because the GUI will use the regular thumbnails
789         thumbnail_images['dont-delete-file-for-gui'] = []
790         if $limit_sizes =~ /original/
791             fullscreen_images['original'] = []
792         end
793
794         images.size >= 1 and msg 3, _("\tcreating images thumbnails...")
795
796         #- create thumbnails for images
797         images.each { |img|
798             info("processing element")
799             base_dest_img = dest_dir + '/' + make_dest_filename(img.sub(/\.[^\.]+$/, ''))
800             if $forgui
801                 thumbnail_dest_img = base_dest_img + "-#{$default_size['thumbnails']}.jpg"
802                 gen_thumbnails_element("#{dir}/#{img}", xmldir, true, [ { 'filename' => thumbnail_dest_img, 'size' => $default_size['thumbnails'] } ])
803             else
804                 todo = []
805                 elem = xmldir.elements["image[@filename='#{utf8(img)}']"]
806                 for sizeobj in $images_size
807                     size_fullscreen = sizeobj['fullscreen']
808                     size_thumbnails = sizeobj['thumbnails']
809                     fullscreen_dest_img = base_dest_img + "-#{size_fullscreen}.jpg"
810                     fullscreen_images[sizeobj['name']] << File.basename(fullscreen_dest_img)
811                     todo << { 'filename' => fullscreen_dest_img, 'size' => size_fullscreen }
812                     if pano = pano_amount(elem)
813                         thumbnail_images['dont-delete-file-for-gui'] << File.basename(base_dest_img + "-#{size_thumbnails}.jpg")
814                         size_thumbnails = size_thumbnails.sub(/(\d+)/) { ($1.to_i * pano).to_i }
815                     end
816                     thumbnail_dest_img = base_dest_img + "-#{size_thumbnails}.jpg"
817                     thumbnail_images[sizeobj['name']] << File.basename(thumbnail_dest_img)
818                     todo << { 'filename' => thumbnail_dest_img,  'size' => size_thumbnails }
819                 end
820                 gen_thumbnails_element("#{dir}/#{img}", xmldir, true, todo)
821                 if $limit_sizes =~ /original/
822                     fullscreen_images['original'] << img
823                 end
824                 destimg = "#{dest_dir}/#{img}"
825                 if $limit_sizes =~ /original/ && !File.exists?(destimg)
826                     if $hardlinks_ok
827                         if ! sys("ln '#{dir}/#{img}' '#{destimg}'")
828                             $hardlinks_ok = false
829                         end
830                     end
831                     if ! $hardlinks_ok
832                         psys("cp '#{dir}/#{img}' '#{destimg}'")
833                     end
834                 end
835             end
836         }
837
838         videos.size >= 1 and msg 3, _("\tcreating videos thumbnails...")
839
840         #- create thumbnails for videos
841         videos.each { |video|
842             info("processing element")
843             if $forgui
844                 thumbnail_dest_img = dest_dir + '/' + make_dest_filename(video.sub(/\.[^\.]+$/, '')) + "-#{$default_size['thumbnails']}.jpg"
845                 gen_thumbnails_element("#{dir}/#{video}", xmldir, true, [ { 'filename' => thumbnail_dest_img, 'size' => $default_size['thumbnails'] } ])
846             else
847                 todo = []
848                 for sizeobj in $images_size
849                     size_thumbnails = sizeobj['thumbnails']
850                     thumbnail_dest_img = dest_dir + '/' + make_dest_filename(video.sub(/\.[^\.]+$/, '')) + "-#{size_thumbnails}.jpg"
851                     thumbnail_videos[sizeobj['name']] << File.basename(thumbnail_dest_img)
852                     todo << { 'filename' => thumbnail_dest_img, 'size' => size_thumbnails }
853                 end
854                 gen_thumbnails_element("#{dir}/#{video}", xmldir, true, todo)
855             end
856             destvideo = "#{dest_dir}/#{video}"
857             if !File.exists?(destvideo)
858                 if $hardlinks_ok
859                     if ! sys("ln '#{dir}/#{video}' '#{destvideo}'")
860                         $hardlinks_ok = false
861                     end
862                 end
863                 if ! $hardlinks_ok
864                     psys("cp '#{dir}/#{video}' '#{destvideo}'")
865                 end
866             end
867         }
868
869         if !$forgui
870             themestuff = Dir.entries("#{$FPATH}/themes/#{$theme}").
871                              find_all { |e| !%w(. .. skeleton_image.html skeleton_thumbnails.html skeleton_index.html metadata CVS).include?(e) }
872
873             #- cleanup old images/videos (for when removing elements or sizes)
874             all_elements = fullscreen_images.collect { |e| e[1] }.flatten.
875                      concat(thumbnail_images.collect { |e| e[1] }.flatten).
876                      concat(thumbnail_videos.collect { |e| e[1] }.flatten).
877                      concat(videos).
878                      push('.htaccess')
879             to_del = Dir.entries(dest_dir).find_all { |e| !File.directory?("#{dest_dir}/#{e}") && !all_elements.include?(e) && e !~ /^thumbnails-\w+\.jpg/ } - themestuff
880             if to_del.size > 0
881                 msg 3, _("\tcleaning up: #{to_del.join(', ')}")
882                 system("rm -f " + to_del.collect { |e| "#{dest_dir}/#{e}" }.join(' '))
883             end
884
885             #- copy any resource file that goes with the theme (css, images..)
886             themestuff.each { |entry|
887                 if !File.exists?("#{dest_dir}/#{entry}")
888                     psys("cp '#{$FPATH}/themes/#{$theme}/#{entry}' '#{dest_dir}'")
889                 end
890             }
891
892             msg 3, _("\tgenerating HTML pages...")
893
894             #- generate thumbnails.html (page with thumbnails)
895             for sizeobj in $images_size
896                 info("processing size")
897                 html = $html_thumbnails.collect { |l| l.clone }
898                 iterations = {}
899                 for i in html
900                     i.sub!(/~~run_slideshow~~/, images.size <= 1 ? '' : '<a href="image-' + size2js(sizeobj['name']) + '.html#run_slideshow=1">' + utf8(_('Run slideshow!'))+'</a>')
901                     i.sub!(/~~title~~/, xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir)))
902                     discover_iterations(iterations, i)
903                 end
904                 html_thumbnails = ''
905                 html_thumbnails_nojs = ''
906                 reset_iterations(iterations)
907                 for file in entries
908                     type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
909                     if type
910                         if type == 'image' && elem = xmldir.elements["image[@filename='#{utf8(file)}']"]
911                             if  pano = pano_amount(elem)
912                                 html_elem = run_iterations(iterations, pano)
913                                 html_elem.gsub!(/~~colspan~~/) { 'colspan="' + pano.ceil.to_s + '"' }
914                             else
915                                 html_elem = run_iterations(iterations, 1)
916                                 html_elem.gsub!(/~~colspan~~/, '')
917                             end
918                         else 
919                             html_elem = run_iterations(iterations, 1)
920                             html_elem.gsub!(/~~colspan~~/, '')
921                         end
922                         if type == 'image'
923                             index = images.index(file)
924                             html_elem.gsub!(/~~caption_iteration~~/,
925                                             find_caption_value(xmldir, images[index]) || utf8(images[index]))
926                             html_elem.gsub!(/~~ifimage\?~~(.+?)~~fi~~/) { $1 }
927                             html_elem.gsub!(/~~ifvideo\?~~(.+?)~~fi~~/, '')
928                         elsif type == 'video'
929                             index = videos.index(file)
930                             if File.exists?("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}")
931                                 html_elem.gsub!(/~~image_iteration~~/,
932                                                 '<a href="' + videos[index] + '">' + img_element("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}") + '</a>')
933                             else
934                                 html_elem.gsub!(/~~image_iteration~~/,
935                                                 '<a href="' + videos[index] + '">' + utf8(_("(no preview)")) + '</a>')
936                             end
937                             html_elem.gsub!(/~~caption_iteration~~/, find_caption_value(xmldir, videos[index]) || utf8(videos[index]))
938                             html_elem.gsub!(/~~ifimage\?~~(.+?)~~fi~~/, '')
939                             html_elem.gsub!(/~~ifvideo\?~~(.+?)~~fi~~/) { $1 }
940                         end
941                         html_thumbnails += html_elem
942                         html_thumbnails_nojs += html_elem
943                         if type == 'image'
944                             html_thumbnails.gsub!(/~~image_iteration~~/,
945                                                   '<a href="image-' + size2js(sizeobj['name']) + '.html#current=' + fullscreen_images[sizeobj['name']][index] +
946                                                       '" name="' + fullscreen_images[sizeobj['name']][index] + '">' +
947                                                       img_element("#{dest_dir}/#{thumbnail_images[sizeobj['name']][index]}") + '</a>')
948                             html_thumbnails_nojs.gsub!(/~~image_iteration~~/, 
949                                                        '<a href="' + fullscreen_images[sizeobj['name']][index] + '" name="' + fullscreen_images[sizeobj['name']][index] + '">' +
950                                                            img_element("#{dest_dir}/#{thumbnail_images[sizeobj['name']][index]}") + '</a>')
951                         end
952                     end
953                 end
954                 html_thumbnails      += close_iterations(iterations)
955                 html_thumbnails_nojs += close_iterations(iterations)
956                 for i in html
957                     i.gsub!(/~~theme~~/, $theme)
958                     i.gsub!(/~~current_size~~/, sizeobj['name'])
959                     i.gsub!(/~~current_size_js~~/, size2js(sizeobj['name']))
960                     i.gsub!(/~~madewith~~/, $madewith || '')
961                     i.gsub!(/~~indexlink~~/, $indexlink || '')
962                 end
963                 html_nojs = html.collect { |l| l.clone }
964                 for i in html
965                     i.sub!(/~~thumbnails~~/, html_thumbnails)
966                     substitute_html_sizes(i, sizeobj, 'thumbnails', '')
967                 end
968                 ios = File.open("#{dest_dir}/thumbnails-#{size2js(sizeobj['name'])}.html", "w")
969                 ios.write(html)
970                 ios.close
971                 for i in html_nojs
972                     i.sub!(/~~thumbnails~~/, html_thumbnails_nojs)
973                     substitute_html_sizes(i, sizeobj, 'thumbnails', '-nojs')
974                 end
975                 ios = File.open("#{dest_dir}/thumbnails-#{size2js(sizeobj['name'])}-nojs.html", "w")
976                 ios.write(html_nojs)
977                 ios.close
978             end
979
980             info("finished processing sizes")
981
982             #- generate "main" thumbnails.html page that will reload to correct size thanks to cookie
983             ios = File.open("#{dest_dir}/thumbnails.html", "w")
984             ios.write(html_reload_to_thumbnails)
985             ios.close
986
987             #- generate image.html (page with fullscreen images)
988             if images.size > 0
989                 captions4js = find_captions(xmldir, images).collect { |e| e ? '"' + e.gsub('"', '\"') + '"' : '""' }.join(', ')
990
991                 for sizeobj in $images_size
992                     html = $html_images.collect { |l| l.clone }
993                     images4js = fullscreen_images[sizeobj['name']].collect { |e| "\"#{e}\"" }.join(', ')
994                     otherimages4js = ''
995                     othersizes = []
996                     for sizeobj2 in all_images_sizes
997                         if sizeobj != sizeobj2
998                             otherimages4js += "var images_#{size2js(sizeobj2['name'])} = new Array(" + fullscreen_images[sizeobj2['name']].collect { |e| "\"#{e}\"" }.join(', ') + ")\n"
999                             othersizes << "\"#{size2js(sizeobj2['name'])}\""
1000                         end
1001                     end
1002                     for i in html
1003                         i.gsub!(/~~images~~/, images4js)
1004                         i.gsub!(/~~other_images~~/, otherimages4js)
1005                         i.gsub!(/~~other_sizes~~/, othersizes.join(', '))
1006                         i.gsub!(/~~captions~~/, captions4js)
1007                         i.gsub!(/~~title~~/, xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir)))
1008                         i.gsub!(/~~thumbnails~~/, '<a href="thumbnails-' + size2js(sizeobj['name']) + '.html" id="thumbnails">' + utf8(_('return to thumbnails')) + '</a>')
1009                         i.gsub!(/~~theme~~/, $theme)
1010                         i.gsub!(/~~current_size~~/, size2js(sizeobj['name']))
1011                         i.gsub!(/~~madewith~~/, $madewith || '')
1012                         i.gsub!(/~~indexlink~~/, $indexlink || '')
1013                         substitute_html_sizes(i, sizeobj, 'image', '')
1014                     end
1015                     ios = File.open("#{dest_dir}/image-#{size2js(sizeobj['name'])}.html", "w")
1016                     ios.write(html)
1017                     ios.close
1018                 end
1019             end
1020         end
1021     }
1022
1023     msg 3, ''
1024
1025     #- add attributes to <dir..> elements needing so
1026     if $mode != 'use_config'
1027         msg 3, _("\tfixating configuration file...")
1028         $xmldoc.elements.each('//dir') { |element|
1029             path = captionpath = element.attributes['path']
1030             descendant_element = element.elements['descendant::image'] || element.elements['descendant::video']
1031             if !descendant_element
1032                 msg 3, _("\t\tremoving %s, no element in it") % path
1033                 element.remove  #- means we have a directory with nothing interesting in it
1034             else
1035                 captionfile = "#{descendant_element.parent.attributes['path']}/#{descendant_element.attributes['filename']}"
1036                 basename = File.basename(path)
1037                 if element.elements['dir']
1038                     if !element.attributes['subdirs-caption']
1039                         element.add_attribute('subdirs-caption', basename)
1040                     end
1041                     if !element.attributes['subdirs-captionfile']
1042                         element.add_attribute('subdirs-captionfile', captionfile)
1043                     end
1044                 end
1045                 if element.child_byname_notattr('image', 'deleted') || element.child_byname_notattr('video', 'deleted')
1046                     if !element.attributes['thumbnails-caption']
1047                         element.add_attribute('thumbnails-caption', basename)
1048                     end
1049                     if !element.attributes['thumbnails-captionfile']
1050                         element.add_attribute('thumbnails-captionfile', captionfile)
1051                     end
1052                 end
1053             end
1054         }
1055     end
1056
1057     #- write down to disk config if necessary
1058     if $config_writeto
1059         ios = File.open($config_writeto, "w")
1060         $xmldoc.write(ios, 0)
1061         ios.close
1062     end
1063
1064     if $forgui
1065         msg 3, _(" completed necessary stuff for GUI, exiting.")
1066         return
1067     end
1068
1069     #- second pass to create index.html files and previous/next links
1070     info("creating index.html")
1071     msg 3, _("\trescanning directories to generate all 'index.html' files...")
1072
1073     #- recompute the memoization because elements mights have been removed (the ones with no element in them)
1074     optxpath = {}
1075     $xmldoc.elements.each('//dir') { |elem|
1076         optxpath[elem.attributes['path']] = elem
1077     }
1078
1079     examined_dirs.each { |dir|
1080         info("index.html: #{dir}|#{$source}")
1081
1082         xmldir = optxpath[utf8(dir)]
1083         if !xmldir || (xmldir.attributes['already-generated'] && !$force) || xmldir.attributes['deleted']
1084             next
1085         end
1086         dest_dir = make_dest_filename(dir.sub(/^#{Regexp.quote($source)}/, $dest))
1087
1088         previous_album = find_previous_album(xmldir)
1089         next_album = find_next_album(xmldir)
1090
1091         if xmldir.elements['dir']
1092             html = $html_index.collect { |l| l.clone }
1093             iterations = {}
1094             for i in html
1095                 caption = xmldir.attributes['subdirs-caption']
1096                 i.gsub!(/~~title~~/, caption)
1097                 if xmldir.parent.name == 'dir'
1098                     nav = ''
1099                     path = '..'
1100                     parent = xmldir.parent
1101                     while parent.name == 'dir'
1102                         parentcaption = parent.attributes['subdirs-caption']
1103                         nav = "<a href='#{path}/index.html'>#{parentcaption}</a> #{utf8(_(" > "))} #{nav}"
1104                         path += '/..'
1105                         parent = parent.parent
1106                     end
1107                     i.gsub!(/~~ifnavigation\?~~(.+?)~~fi~~/) { $1 }
1108                     i.gsub!(/~~navigation~~/, nav + caption)
1109                 else
1110                     i.gsub!(/~~ifnavigation\?~~(.+?)~~fi~~/, '')
1111                 end
1112                 discover_iterations(iterations, i)
1113             end
1114             
1115             html_index = ''
1116             reset_iterations(iterations)
1117             
1118             #- deal with "current" album (directs to "thumbnails" page)
1119             if xmldir.attributes['thumbnails-caption']
1120                 thumbnail = "#{dest_dir}/thumbnails-thumbnail.jpg"
1121                 gen_thumbnails_subdir(from_utf8(xmldir.attributes['thumbnails-captionfile']), xmldir, false,
1122                                       [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ], 'thumbnails')
1123                 html_index += run_iterations(iterations, 1)
1124                 html_index.gsub!(/~~image_iteration~~/, "<a href='thumbnails.html'>" + img_element(thumbnail) + '</a>')
1125                 html_index.gsub!(/~~caption_iteration~~/, xmldir.attributes['thumbnails-caption'])
1126             end
1127
1128             #- deal with sub-albums (direct to subdirs/index.html pages)
1129             xmldir.elements.each('dir') { |child|
1130                 if child.attributes['deleted']
1131                     next
1132                 end
1133                 subdir = make_dest_filename(from_utf8(File.basename(child.attributes['path'])))
1134                 thumbnail = "#{dest_dir}/thumbnails-#{subdir}.jpg"
1135                 html_index += run_iterations(iterations, 1)
1136                 captionfile, caption = find_subalbum_caption_info(child)
1137                 gen_thumbnails_subdir(captionfile, child, false,
1138                                       [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ], find_subalbum_info_type(child))
1139                 html_index.gsub!(/~~caption_iteration~~/, caption)
1140                 html_index.gsub!(/~~image_iteration~~/, "<a href='#{make_dest_filename(subdir)}/index.html'>" + img_element(thumbnail) + '</a>')
1141             }
1142
1143             html_index += close_iterations(iterations)
1144
1145             for i in html
1146                 i.gsub!(/~~thumbnails~~/, html_index)
1147                 i.gsub!(/~~madewith~~/, $madewith || '')
1148                 i.gsub!(/~~indexlink~~/, $indexlink || '')
1149             end
1150             
1151         else
1152             html = html_reload_to_thumbnails
1153         end
1154
1155         ios = File.open("#{dest_dir}/index.html", "w")
1156         ios.write(html)
1157         ios.close
1158
1159         #- substitute "return to albums" and previous/next correctly
1160         if xmldir.child_byname_notattr('image', 'deleted') || xmldir.child_byname_notattr('video', 'deleted')
1161             for suffix in [ '', '-nojs' ]
1162                 for sizeobj in $images_size
1163                     substInFile("#{dest_dir}/thumbnails-#{size2js(sizeobj['name'])}#{suffix}.html") { |line|
1164                         sub_previous_next_album(previous_album, next_album, line)
1165                         if xmldir.elements['dir']
1166                             line.sub!(/~~return_to_albums~~/, '<a href="index.html">' + utf8(_('return to albums')) + '</a>')
1167                         else
1168                             if xmldir.parent.name == 'dir'
1169                                 line.sub!(/~~return_to_albums~~/, '<a href="../index.html">' + utf8(_('return to albums')) + '</a>')
1170                             else
1171                                 line.sub!(/~~return_to_albums~~/, '')
1172                             end
1173                         end
1174                         line
1175                     }
1176                     if suffix == '' && xmldir.child_byname_notattr('image', 'deleted')
1177                         substInFile("#{dest_dir}/image-#{size2js(sizeobj['name'])}.html") { |line|
1178                             sub_previous_next_album(previous_album, next_album, line)
1179                         }
1180                     end
1181                 end
1182             end
1183         end
1184     }
1185
1186     msg 3, _(" all done.")
1187 end
1188
1189 handle_options
1190 read_config
1191 check_installation
1192
1193 build_html_skeletons
1194
1195 walk_source_dir