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