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