181dacdf66893b711e42a40cd64d7b2dab02abaa
[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                 xmldir = optxpath[utf8(dir)] = xmldir.add_element('dir', { 'path' => utf8(dir) })
595             end
596         end
597         xmldir.delete_attribute('already-generated')
598
599         #- read images/videos entries from config or from directories depending on mode
600         entries = []
601         if $mode == 'use_config' || $mode == 'use_config_changetheme'
602             msg 2, _("Handling %s from config list...") % dir
603             xmldir.elements.each { |element|
604                 if %w(image video).include?(element.name) && !element.attributes['deleted']
605                     entries << from_utf8(element.attributes['filename'])
606                 end
607             }
608         else
609             msg 2, _("Examining %s...") % dir
610             entries = Dir.entries(dir).sort
611             #- populate config in case of gen_config, add new files in case of merge_config
612             for file in entries
613                 if file =~ /['"\[\]]/
614                     msg 1, _("Ignoring %s, contains one of forbidden characters: '\"[]") % "#{dir}/#{file}"
615                 else
616                     type = entry2type(file)
617                     if type && !xmldir.elements["#{type}[@filename='#{utf8(file)}']"]
618                         xmldir.add_element type, { "filename" => utf8(file), "caption" => $empty_comments ? '' : utf8(file.sub(/\.[^\.]+$/, '')[0..17]) }
619                     end
620                 end
621             end
622             if $mode != 'gen_config'
623                 #- cleanup removed files from config and reread entries from config to get proper ordering
624                 entries = []
625                 xmldir.elements.each { |element|
626                     fullpath = "#{dir}/#{from_utf8(element.attributes['filename'])}"
627                     if %w(image video).include?(element.name)
628                         if !File.readable?(fullpath)
629                             msg 1, _("Config merge: removing %s from config; use the backup file to retrieve caption info if this was a mistake") % fullpath
630                             xmldir.delete(element)
631                         elsif !element.attributes['deleted']
632                             entries << from_utf8(element.attributes['filename'])
633                         end
634                     end
635                 }
636                 #- if there is no more elements here, there is no album here anymore
637                 if !xmldir.child_byname_notattr('image', 'deleted') && !xmldir.child_byname_notattr('video', 'deleted')
638                     xmldir.delete_attribute('thumbnails-caption')
639                     xmldir.delete_attribute('thumbnails-captionfile')
640                 end
641             end
642         end
643         images = entries.find_all { |e| entry2type(e) == 'image' }
644         msg 3, _("\t%s images") % images.length
645         videos = entries.find_all { |e| entry2type(e) == 'video' }
646         msg 3, _("\t%s videos") % videos.length
647         info("walking: #{dir}|#{$source}, #{images.length + videos.length} elements")
648
649         dest_dir = make_dest_filename(dir.sub(/^#{Regexp.quote($source)}/, $dest))
650         system("mkdir -p '#{dest_dir}'")
651
652         #- pass through if there are no images and videos
653         if images.size == 0 && videos.size == 0
654             if !$forgui
655                 #- cleanup old images/videos, especially if this directory contained images/videos previously.
656                 themestuff = Dir.entries("#{$FPATH}/themes/#{$theme}").
657                                 find_all { |e| !%w(. .. skeleton_image.html skeleton_thumbnails.html skeleton_index.html metadata CVS).include?(e) }
658                 if $mode != 'gen_config'
659                     rightful_images = []
660                     if xmldir.attributes['thumbnails-caption']
661                         rightful_images << 'thumbnails-thumbnail.jpg'
662                     end
663                     xmldir.elements.each('dir') { |child|
664                         if child.attributes['deleted']
665                             next
666                         end
667                         subdir = make_dest_filename(from_utf8(File.basename(child.attributes['path'])))
668                         rightful_images << "thumbnails-#{subdir}.jpg"
669                     }
670                     to_del = Dir.entries(dest_dir).find_all { |e| !File.directory?("#{dest_dir}/#{e}") && !rightful_images.include?(e) } - themestuff
671                     if to_del.size > 0
672                         system("rm -f " + to_del.collect { |e| "#{dest_dir}/#{e}" }.join(' '))
673                     end
674                 end
675                 
676                 #- copy any resource file that goes with the theme (css, images..)
677                 themestuff.each { |entry|
678                     if !File.exists?("#{dest_dir}/#{entry}")
679                         psys("cp '#{$FPATH}/themes/#{$theme}/#{entry}' '#{dest_dir}'")
680                     end
681                 }
682             end
683             next
684         end
685
686         msg 2, _("Outputting in %s...") % dest_dir
687
688         #- populate data structure with sizes from theme
689         for sizeobj in $images_size
690             fullscreen_images ||= {}
691             fullscreen_images[sizeobj['name']] = []
692             thumbnail_images ||= {}
693             thumbnail_images[sizeobj['name']] = []
694             thumbnail_videos ||= {}
695             thumbnail_videos[sizeobj['name']] = []
696         end
697         if $limit_sizes =~ /original/
698             fullscreen_images['original'] = []
699         end
700
701         images.size >= 1 and msg 3, _("\tcreating images thumbnails...")
702
703         #- create thumbnails for images
704         images.each { |img|
705             info("processing element")
706             base_dest_img = dest_dir + '/' + make_dest_filename(img.sub(/\.[^\.]+$/, ''))
707             if $forgui
708                 thumbnail_dest_img = base_dest_img + "-#{$default_size['thumbnails']}.jpg"
709                 gen_thumbnails_element("#{dir}/#{img}", xmldir, true, [ { 'filename' => thumbnail_dest_img, 'size' => $default_size['thumbnails'] } ])
710             else
711                 todo = []
712                 for sizeobj in $images_size
713                     size_fullscreen = sizeobj['fullscreen']
714                     size_thumbnails = sizeobj['thumbnails']
715                     fullscreen_dest_img = base_dest_img + "-#{size_fullscreen}.jpg"
716                     thumbnail_dest_img  = base_dest_img + "-#{size_thumbnails}.jpg"
717                     fullscreen_images[sizeobj['name']] << File.basename(fullscreen_dest_img)
718                     thumbnail_images[sizeobj['name']]  << File.basename(thumbnail_dest_img)
719                     todo << { 'filename' => fullscreen_dest_img, 'size' => size_fullscreen }
720                     todo << { 'filename' => thumbnail_dest_img,  'size' => size_thumbnails }
721                 end
722                 gen_thumbnails_element("#{dir}/#{img}", xmldir, true, todo)
723                 if $limit_sizes =~ /original/
724                     fullscreen_images['original'] << img
725                 end
726                 destimg = "#{dest_dir}/#{img}"
727                 if $limit_sizes =~ /original/ && !File.exists?(destimg)
728                     psys("cp '#{dir}/#{img}' '#{destimg}'")
729                 end
730             end
731         }
732
733         videos.size >= 1 and msg 3, _("\tcreating videos thumbnails...")
734
735         #- create thumbnails for videos
736         videos.each { |video|
737             info("processing element")
738             if $forgui
739                 thumbnail_dest_img = dest_dir + '/' + make_dest_filename(video.sub(/\.[^\.]+$/, '')) + "-#{$default_size['thumbnails']}.jpg"
740                 gen_thumbnails_element("#{dir}/#{video}", xmldir, true, [ { 'filename' => thumbnail_dest_img, 'size' => $default_size['thumbnails'] } ])
741             else
742                 todo = []
743                 for sizeobj in $images_size
744                     size_thumbnails = sizeobj['thumbnails']
745                     thumbnail_dest_img = dest_dir + '/' + make_dest_filename(video.sub(/\.[^\.]+$/, '')) + "-#{size_thumbnails}.jpg"
746                     thumbnail_videos[sizeobj['name']] << File.basename(thumbnail_dest_img)
747                     todo << { 'filename' => thumbnail_dest_img, 'size' => size_thumbnails }
748                 end
749                 gen_thumbnails_element("#{dir}/#{video}", xmldir, true, todo)
750             end
751             destvideo = "#{dest_dir}/#{video}"
752             if !File.exists?(destvideo)
753                 psys("cp '#{dir}/#{video}' '#{destvideo}'")
754             end
755         }
756
757         if !$forgui
758             themestuff = Dir.entries("#{$FPATH}/themes/#{$theme}").
759                              find_all { |e| !%w(. .. skeleton_image.html skeleton_thumbnails.html skeleton_index.html metadata CVS).include?(e) }
760
761             #- cleanup old images/videos (for when removing elements or sizes)
762             all_elements = fullscreen_images.collect { |e| e[1] }.flatten.
763                      concat(thumbnail_images.collect { |e| e[1] }.flatten).
764                      concat(thumbnail_videos.collect { |e| e[1] }.flatten).
765                      concat(videos)
766             to_del = Dir.entries(dest_dir).find_all { |e| !File.directory?("#{dest_dir}/#{e}") && !all_elements.include?(e) && e !~ /^thumbnails-\w+\.jpg/ } - themestuff
767             if to_del.size > 0
768                 system("rm -f " + to_del.collect { |e| "#{dest_dir}/#{e}" }.join(' '))
769             end
770
771             #- copy any resource file that goes with the theme (css, images..)
772             themestuff.each { |entry|
773                 if !File.exists?("#{dest_dir}/#{entry}")
774                     psys("cp '#{$FPATH}/themes/#{$theme}/#{entry}' '#{dest_dir}'")
775                 end
776             }
777
778             msg 3, _("\tgenerating HTML pages...")
779
780             #- generate thumbnails.html (page with thumbnails)
781             for sizeobj in $images_size
782                 info("processing size")
783                 html = $html_thumbnails.collect { |l| l.clone }
784                 iterations = {}
785                 for i in html
786                     i.sub!(/~~run_slideshow~~/, images.size <= 1 ? '' : '<a href="image-' + size2js(sizeobj['name']) + '.html#run_slideshow=1">' + utf8(_('Run slideshow!'))+'</a>')
787                     i.sub!(/~~title~~/, xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir)))
788                     substitute_html_sizes(i, sizeobj, 'thumbnails')
789                     discover_iterations(iterations, i)
790                 end
791                 html_thumbnails = ''
792                 reset_iterations(iterations)
793                 for file in entries
794                     type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
795                     if type
796                         html_thumbnails += run_iterations(iterations)
797                         if type == 'image'
798                             index = images.index(file)
799                             html_thumbnails.gsub!(/~~image_iteration~~/,
800                                                   '<a href="image-' + size2js(sizeobj['name']) + '.html#current=' + fullscreen_images[sizeobj['name']][index] +
801                                                       '" name="' + fullscreen_images[sizeobj['name']][index] + '">' +
802                                                       img_element("#{dest_dir}/#{thumbnail_images[sizeobj['name']][index]}") + '</a>')
803                             html_thumbnails.gsub!(/~~caption_iteration~~/,
804                                                   find_caption_value(xmldir, images[index]) || utf8(images[index]))
805                             html_thumbnails.gsub!(/~~ifimage\?~~(.+?)~~fi~~/) { $1 }
806                             html_thumbnails.gsub!(/~~ifvideo\?~~(.+?)~~fi~~/, '')
807                         elsif type == 'video'
808                             index = videos.index(file)
809                             if File.exists?("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}")
810                                 html_thumbnails.gsub!(/~~image_iteration~~/,
811                                                       '<a href="' + videos[index] + '">' + img_element("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}") + '</a>')
812                             else
813                                 html_thumbnails.gsub!(/~~image_iteration~~/,
814                                                       '<a href="' + videos[index] + '">' + utf8(_("(no preview)")) + '</a>')
815                             end
816                             html_thumbnails.gsub!(/~~caption_iteration~~/,
817                                                   find_caption_value(xmldir, videos[index]) || utf8(videos[index]))
818                             html_thumbnails.gsub!(/~~ifimage\?~~(.+?)~~fi~~/, '')
819                             html_thumbnails.gsub!(/~~ifvideo\?~~(.+?)~~fi~~/) { $1 }
820                         end
821                     end
822                 end
823                 html_thumbnails += close_iterations(iterations)
824                 for i in html
825                     i.sub!(/~~thumbnails~~/, html_thumbnails)
826                     i.gsub!(/~~theme~~/, $theme)
827                     i.gsub!(/~~current_size~~/, sizeobj['name'])
828                     i.gsub!(/~~current_size_js~~/, size2js(sizeobj['name']))
829                 end
830                 ios = File.open("#{dest_dir}/thumbnails-#{size2js(sizeobj['name'])}.html", "w")
831                 ios.write(html)
832                 ios.close
833             end
834
835             info("finished processing sizes")
836
837             #- generate "main" thumbnails.html page that will reload to correct size thanks to cookie
838             ios = File.open("#{dest_dir}/thumbnails.html", "w")
839             ios.write(html_reload_to_thumbnails)
840             ios.close
841
842             #- generate image.html (page with fullscreen images)
843             if images.size > 0
844                 captions4js = find_captions(xmldir, images).collect { |e| e ? '"' + e.gsub('"', '\"') + '"' : '""' }.join(', ')
845
846                 for sizeobj in $images_size
847                     html = $html_images.collect { |l| l.clone }
848                     images4js = fullscreen_images[sizeobj['name']].collect { |e| "\"#{e}\"" }.join(', ')
849                     otherimages4js = ''
850                     othersizes = []
851                     for sizeobj2 in all_images_sizes
852                         if sizeobj != sizeobj2
853                             otherimages4js += "var images_#{size2js(sizeobj2['name'])} = new Array(" + fullscreen_images[sizeobj2['name']].collect { |e| "\"#{e}\"" }.join(', ') + ")\n"
854                             othersizes << "\"#{size2js(sizeobj2['name'])}\""
855                         end
856                     end
857                     for i in html
858                         i.gsub!(/~~images~~/, images4js)
859                         i.gsub!(/~~other_images~~/, otherimages4js)
860                         i.gsub!(/~~other_sizes~~/, othersizes.join(', '))
861                         i.gsub!(/~~captions~~/, captions4js)
862                         i.gsub!(/~~title~~/, xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir)))
863                         i.gsub!(/~~thumbnails~~/, '<a href="thumbnails-' + size2js(sizeobj['name']) + '.html" id="thumbnails">' + utf8(_('return to thumbnails')) + '</a>')
864                         i.gsub!(/~~theme~~/, $theme)
865                         i.gsub!(/~~current_size~~/, size2js(sizeobj['name']))
866                         substitute_html_sizes(i, sizeobj, 'image')
867                     end
868                     ios = File.open("#{dest_dir}/image-#{size2js(sizeobj['name'])}.html", "w")
869                     ios.write(html)
870                     ios.close
871                 end
872             end
873         end
874     }
875
876     msg 3, ''
877
878     #- add attributes to <dir..> elements needing so
879     if $mode != 'use_config'
880         msg 3, _("\tfixating configuration file...")
881         $xmldoc.elements.each('//dir') { |element|
882             path = captionpath = element.attributes['path']
883             descendant_element = element.elements['descendant::image'] || element.elements['descendant::video']
884             if !descendant_element
885                 msg 3, _("\t\tremoving %s, no element in it") % path
886                 element.remove  #- means we have a directory with nothing interesting in it
887             else
888                 captionfile = "#{descendant_element.parent.attributes['path']}/#{descendant_element.attributes['filename']}"
889                 basename = File.basename(path)
890                 if element.elements['dir']
891                     if !element.attributes['subdirs-caption']
892                         element.add_attribute('subdirs-caption', basename)
893                     end
894                     if !element.attributes['subdirs-captionfile']
895                         element.add_attribute('subdirs-captionfile', captionfile)
896                     end
897                 end
898                 if element.child_byname_notattr('image', 'deleted') || element.child_byname_notattr('video', 'deleted')
899                     if !element.attributes['thumbnails-caption']
900                         element.add_attribute('thumbnails-caption', basename)
901                     end
902                     if !element.attributes['thumbnails-captionfile']
903                         element.add_attribute('thumbnails-captionfile', captionfile)
904                     end
905                 end
906             end
907         }
908     end
909
910     #- write down to disk config if necessary
911     if $config_writeto
912         ios = File.open($config_writeto, "w")
913         $xmldoc.write(ios, 0)
914         ios.close
915     end
916
917     if $forgui
918         msg 3, _(" completed necessary stuff for GUI, exiting.")
919         return
920     end
921
922     #- second pass to create index.html files and previous/next links
923     info("creating index.html")
924     msg 3, _("\trescanning directories to generate all `index.html' files...")
925
926     #- recompute the memoization because elements mights have been removed (the ones with no element in them)
927     optxpath = {}
928     $xmldoc.elements.each('//dir') { |elem|
929         optxpath[elem.attributes['path']] = elem
930     }
931
932     examined_dirs.each { |dir|
933         dir.chomp!
934         info("index.html: #{dir}|#{$source}")
935
936         xmldir = optxpath[utf8(dir)]
937         if !xmldir || (xmldir.attributes['already-generated'] && !$force) || xmldir.attributes['deleted']
938             next
939         end
940         dest_dir = make_dest_filename(dir.sub(/^#{Regexp.quote($source)}/, $dest))
941
942         previous_album = find_previous_album(xmldir)
943         next_album = find_next_album(xmldir)
944
945         if xmldir.elements['dir']
946             html = $html_index.collect { |l| l.clone }
947             iterations = {}
948             for i in html
949                 caption = xmldir.attributes['subdirs-caption']
950                 i.gsub!(/~~title~~/, caption)
951                 if xmldir.parent.name == 'dir'
952                     nav = ''
953                     path = '..'
954                     parent = xmldir.parent
955                     while parent.name == 'dir'
956                         parentcaption = parent.attributes['subdirs-caption']
957                         nav = "<a href='#{path}/index.html'>#{parentcaption}</a> #{utf8(_(" > "))} #{nav}"
958                         path += '/..'
959                         parent = parent.parent
960                     end
961                     i.gsub!(/~~ifnavigation\?~~(.+?)~~fi~~/) { $1 }
962                     i.gsub!(/~~navigation~~/, nav + caption)
963                 else
964                     i.gsub!(/~~ifnavigation\?~~(.+?)~~fi~~/, '')
965                 end
966                 discover_iterations(iterations, i)
967             end
968             
969             html_index = ''
970             reset_iterations(iterations)
971             
972             #- deal with "current" album (directs to "thumbnails" page)
973             if xmldir.attributes['thumbnails-caption']
974                 thumbnail = "#{dest_dir}/thumbnails-thumbnail.jpg"
975                 gen_thumbnails_subdir(from_utf8(xmldir.attributes['thumbnails-captionfile']), xmldir, false,
976                                       [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ], 'thumbnails')
977                 html_index += run_iterations(iterations)
978                 html_index.gsub!(/~~image_iteration~~/, "<a href='thumbnails.html'>" + img_element(thumbnail) + '</a>')
979                 html_index.gsub!(/~~caption_iteration~~/, xmldir.attributes['thumbnails-caption'])
980             end
981
982             #- deal with sub-albums (direct to subdirs/index.html pages)
983             xmldir.elements.each('dir') { |child|
984                 if child.attributes['deleted']
985                     next
986                 end
987                 subdir = make_dest_filename(from_utf8(File.basename(child.attributes['path'])))
988                 thumbnail = "#{dest_dir}/thumbnails-#{subdir}.jpg"
989                 html_index += run_iterations(iterations)
990                 captionfile, caption = find_subalbum_caption_info(child)
991                 gen_thumbnails_subdir(captionfile, child, false,
992                                       [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ], find_subalbum_info_type(child))
993                 html_index.gsub!(/~~caption_iteration~~/, caption)
994                 html_index.gsub!(/~~image_iteration~~/, "<a href='#{make_dest_filename(subdir)}/index.html'>" + img_element(thumbnail) + '</a>')
995             }
996
997             html_index += close_iterations(iterations)
998
999             for i in html
1000                 i.gsub!(/~~thumbnails~~/, html_index)
1001             end
1002             
1003         else
1004             html = html_reload_to_thumbnails
1005         end
1006
1007         ios = File.open("#{dest_dir}/index.html", "w")
1008         ios.write(html)
1009         ios.close
1010
1011         #- substitute "return to albums" and previous/next correctly
1012         if xmldir.child_byname_notattr('image', 'deleted') || xmldir.child_byname_notattr('video', 'deleted')
1013             for sizeobj in $images_size
1014                 substInFile("#{dest_dir}/thumbnails-#{size2js(sizeobj['name'])}.html") { |line|
1015                     sub_previous_next_album(previous_album, next_album, line)
1016                     if xmldir.elements['dir']
1017                         line.sub!(/~~return_to_albums~~/, '<a href="index.html">' + utf8(_('return to albums')) + '</a>')
1018                     else
1019                         if xmldir.parent.name == 'dir'
1020                             line.sub!(/~~return_to_albums~~/, '<a href="../index.html">' + utf8(_('return to albums')) + '</a>')
1021                         else
1022                             line.sub!(/~~return_to_albums~~/, '')
1023                         end
1024                     end
1025                     line
1026                 }
1027                 if xmldir.child_byname_notattr('image', 'deleted')
1028                     substInFile("#{dest_dir}/image-#{size2js(sizeobj['name'])}.html") { |line|
1029                         sub_previous_next_album(previous_album, next_album, line)
1030                     }
1031                 end
1032             end
1033         end
1034     }
1035
1036     msg 3, _(" all done.")
1037 end
1038
1039 handle_options
1040 read_config
1041 check_installation
1042
1043 build_html_skeletons
1044
1045 walk_source_dir