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