5 # A.k.a `Best web-album Of the world, Or your money back, Humerus'.
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.
13 # Copyright (c) 2005 Guillaume Cottenceau <gc3 at bluewin.ch>
15 # This software may be freely redistributed under the terms of the GNU
16 # public license version 2.
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.
25 require 'rexml/document'
28 require 'booh/booh-lib'
29 require 'booh/html-merges'
31 #- bind text domain as soon as possible because some _() functions are called early to build data structures
32 bindtextdomain("booh")
36 [ '--help', '-h', GetoptLong::NO_ARGUMENT, _("Get help message") ],
37 [ '--version', '-V', GetoptLong::NO_ARGUMENT, _("Print version and exit") ],
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") ],
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") ],
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") ],
58 [ '--mproc', '-m', GetoptLong::REQUIRED_ARGUMENT, _("Specify the number of processors for multi-processors machines") ],
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)") ],
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)") ],
66 #- default values for some globals
70 $ignore_videos = false
74 puts _("Usage: %s [OPTION]...") % File.basename($0)
76 printf " %3s, %-18s %s\n", ary[1], ary[0], ary[3]
81 parser = GetoptLong.new
82 parser.set_options(*$options.collect { |ary| ary[0..2] })
84 parser.each_option do |name, arg|
91 puts _("Booh version %s
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
100 $source = File.expand_path(arg.sub(%r|/$|, ''))
101 if !File.directory?($source)
102 die _("Argument to --source must be a directory")
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")
109 if $dest != make_dest_filename($dest)
110 die _("Sorry, destination directory can't contain non simple alphanumeric characters.")
113 # system("rm -rf #{$dest}")
118 arg = File.expand_path(arg)
119 if File.readable?(arg)
120 $xmldoc = REXML::Document.new File.new(arg)
123 die _('Config file does not exist or is unreadable.')
126 arg = File.expand_path(arg)
128 if File.directory?(arg)
129 die _("Config skeleton file (%s) already exists and is a directory! Please change the filename.") % arg
131 msg 1, _("Config skeleton file already exists, backuping to %s.backup") % arg
132 File.rename(arg, "#{arg}.backup")
135 $config_writeto = arg
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'
146 die _('Config file does not exist or is unreadable.')
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'
157 die _('Config file does not exist or is unreadable.')
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'
168 die _('Config file does not exist or is unreadable.')
171 arg = File.expand_path(arg)
172 if !File.readable?(arg)
173 die _('Specified directory to merge with --dir is not readable')
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'
186 die _('Config file does not exist or is unreadable.')
192 when '--thumbnails-per-row'
195 when '--optimize-for-32'
196 $optimize_for_32 = true
198 when '--empty-comments'
199 $empty_comments = true
211 when '--verbose-level'
212 $verbose_level = arg.to_i
215 $info_pipe = File.open(arg, File::WRONLY)
216 $info_pipe.sync = true
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']
236 if $mode == 'merge_config_onedir' && !$onedir
237 die _("Missing --dir for --merge-config-onedir")
239 if $mode == 'merge_config_subdirs' && !$onedir
240 die _("Missing --dir for --merge-config-subdirs")
248 die _("Missing --destination parameter.")
254 select_theme($theme, $limit_sizes, $optimize_for_32, $N_per_row)
257 additional_params = ''
259 additional_params += "limit-sizes='#{$limit_sizes}'"
262 additional_params += " optimize-for-32='true'"
265 additional_params += " thumbnails-per-row='#{$N_per_row}'"
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)
272 if $mode == 'merge_config' || $mode == 'use_config_changetheme'
273 $xmldoc.root.add_attribute('theme', $theme)
274 $xmldoc.root.add_attribute('version', $VERSION)
276 $xmldoc.root.add_attribute('limit-sizes', $limit_sizes)
278 $xmldoc.root.delete_attribute('limit-sizes')
281 $xmldoc.root.add_attribute('optimize-for-32', 'true')
283 $xmldoc.root.delete_attribute('optimize-for-32')
286 $xmldoc.root.add_attribute('thumbnails-per-row', $N_per_row)
288 $xmldoc.root.delete_attribute('thumbnails-per-row')
302 $info_pipe.puts(value)
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.")
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.")
316 missing = %w(transcode mencoder).delete_if { |prg| system("which #{prg} >/dev/null 2>/dev/null") }
318 msg 1, _("the following program(s) are needed to handle videos: '%s'. Videos will be ignored.") % missing.join(', ')
319 $ignore_videos = true
323 def replace_line(surround, keyword, line)
325 contents = eval "$#{keyword}"
326 line.sub!(/#{surround}#{keyword}#{surround}/, contents)
328 die _("No '%s' found for substitution") % keyword
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)
343 def find_caption_value(xmldir, filename)
344 if cap = xmldir.elements["*[@filename='#{utf8(filename)}']"].attributes['caption']
345 return cap.gsub("\n", '<br/>')
351 def find_captions(xmldir, images)
352 return images.collect { |img| find_caption_value(xmldir, img) }
355 #- stolen from CVSspam
357 text.sub(/[^a-zA-Z0-9\-,.*_\/]/) do
358 "%#{sprintf('%2X', $&[0])}"
363 return $limit_sizes =~ /original/ ? $images_size + [ { 'name' => 'original' } ] : $images_size
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
374 def discover_iterations(iterations, line)
375 if line =~ /~~iterate(\d)_open(_max(\d+|N))?~~/
376 for iter in iterations.values
379 iter['close_wait'] = $1.to_i
382 max = $3 == 'N' ? ($N_per_row || $default_N) : $3
383 iterations[$1.to_i] = { 'open' => true, 'max' => max, 'opening' => '', 'closing' => '' }
385 line.sub!(/.*/, '~~thumbnails~~')
389 elsif line =~ /~~iterate(\d)_close~~/
390 iterations[$1.to_i]['open'] = false;
391 iterations[$1.to_i]['close'] = true;
394 for iter in iterations.values
396 iter['opening'] += line
399 if !iter['close'] && iter['close_wait'] && iterations[iter['close_wait']]['close']
400 iter['closing'] += line
407 def reset_iterations(iterations)
408 for iter in iterations.values
413 def run_iterations(iterations)
415 for level in iterations.keys.sort
416 if iterations[level]['value'] == 1 || level == iterations.keys.max
417 html += iterations[level]['opening']
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']
429 def close_iterations(iterations)
431 for level in iterations.keys.sort.reverse
432 html += iterations[level]['closing']
437 def img_element(fullpath)
438 if size = get_image_size(fullpath)
439 sizespec = 'width="' + size[:x].to_s + '" height="' + size[:y].to_s + '"'
443 return '<img src="' + File.basename(fullpath) + '" ' + sizespec + ' class="image"/>'
447 return name.gsub(/-/, '')
450 def substitute_html_sizes(html, sizeobj, type)
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>'
458 sizestrings << '<a id="link' + size2js(sizeobj2['name']) + '">' + sizename(sizeobj2['name']) + '</a>'
461 sizestrings << sizename(sizeobj2['name'])
464 if type == 'image' && $limit_sizes =~ /original/
465 sizestrings << '<a id="linkoriginal" target="newframe">' + sizename('original') + '</a>'
468 html.sub!(/~~sizes~~(.+)~~/) { sizestrings.join($1) }
471 def xmldir2destdir(xmldir)
472 return make_dest_filename(from_utf8(File.basename(xmldir.attributes['path'])))
475 def find_previous_album(xmldir)
478 #- move to previous dir element if exists
479 if prevelem = xmldir.previous_element_byname_notattr('dir', 'deleted')
481 relative_pos += '../' + xmldir2destdir(xmldir) + '/'
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')
488 relative_pos += xmldir2destdir(child) + '/'
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 += '../'
500 end while !xmldir.child_byname_notattr('image', 'deleted') && !xmldir.child_byname_notattr('video', 'deleted')
501 return File.reduce_path(relative_pos)
504 def find_next_album(xmldir)
507 #- first child dir element (catches when initial xmldir has both thumbnails and subdirs)
508 if firstchild = xmldir.child_byname_notattr('dir', 'deleted')
510 relative_pos += xmldir2destdir(xmldir) + '/'
512 elsif nextbro = xmldir.next_element_byname_notattr('dir', 'deleted')
514 relative_pos += '../' + xmldir2destdir(xmldir) + '/'
516 #- go up until we have a next brother or we are finished
518 xmldir = xmldir.parent
519 relative_pos += '../'
520 end while xmldir && !xmldir.next_element_byname_notattr('dir', 'deleted')
522 xmldir = xmldir.next_element_byname('dir')
523 relative_pos += '../' + xmldir2destdir(xmldir) + '/'
528 end while !xmldir.child_byname_notattr('image', 'deleted') && !xmldir.child_byname_notattr('video', 'deleted')
529 return File.reduce_path(relative_pos)
532 def sub_previous_next_album(previous_album, next_album, html)
534 html.gsub!(/~~previous_album~~/, '<a href="' + previous_album + 'thumbnails.html">' + utf8(_('previous album')) + '</a>')
535 html.gsub!(/~~ifprevious_album\?~~(.+?)~~fi~~/) { $1 }
537 html.gsub!(/~~previous_album~~/, '')
538 html.gsub!(/~~ifprevious_album\?~~(.+?)~~fi~~/, '')
541 html.gsub!(/~~next_album~~/, '<a href="' + next_album + 'thumbnails.html">' + utf8(_('next album')) + '</a>')
542 html.gsub!(/~~ifnext_album\?~~(.+?)~~fi~~/) { $1 }
544 html.gsub!(/~~next_album~~/, '')
545 html.gsub!(/~~ifnext_album\?~~(.+?)~~fi~~/, '')
552 #- preprocess the path->dir, rexml is very slow with that; we seem to improve speed by 7%
554 $xmldoc.elements.each('//dir') { |elem|
555 optxpath[elem.attributes['path']] = elem
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)) }
564 examined_dirs = `find '#{$source}' -type d -follow`.sort
566 info("directories: #{examined_dirs.length}, sizes: #{$images_size.length}")
568 examined_dirs.each { |dir|
570 if File.basename(dir) =~ /^\./
571 msg 1, _("Ignoring directory %s, begins with a dot (indicating a hidden directory)") % dir
576 die _("Source directory or sub-directories can't contain a single-quote character, sorry: %s") % dir
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")
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)}']"]
592 xmldir = $xmldoc.root
594 xmldir = optxpath[utf8(dir)] = xmldir.add_element('dir', { 'path' => utf8(dir) })
597 xmldir.delete_attribute('already-generated')
599 #- read images/videos entries from config or from directories depending on mode
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'])
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
613 if file =~ /['"\[\]]/
614 msg 1, _("Ignoring %s, contains one of forbidden characters: '\"[]") % "#{dir}/#{file}"
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]) }
622 if $mode != 'gen_config'
623 #- cleanup removed files from config and reread entries from config to get proper ordering
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'])
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')
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")
649 dest_dir = make_dest_filename(dir.sub(/^#{Regexp.quote($source)}/, $dest))
650 system("mkdir -p '#{dest_dir}'")
652 #- pass through if there are no images and videos
653 if images.size == 0 && videos.size == 0
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'
660 if xmldir.attributes['thumbnails-caption']
661 rightful_images << 'thumbnails-thumbnail.jpg'
663 xmldir.elements.each('dir') { |child|
664 if child.attributes['deleted']
667 subdir = make_dest_filename(from_utf8(File.basename(child.attributes['path'])))
668 rightful_images << "thumbnails-#{subdir}.jpg"
670 to_del = Dir.entries(dest_dir).find_all { |e| !File.directory?("#{dest_dir}/#{e}") && !rightful_images.include?(e) } - themestuff
672 system("rm -f " + to_del.collect { |e| "#{dest_dir}/#{e}" }.join(' '))
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}'")
686 msg 2, _("Outputting in %s...") % dest_dir
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']] = []
697 if $limit_sizes =~ /original/
698 fullscreen_images['original'] = []
701 images.size >= 1 and msg 3, _("\tcreating images thumbnails...")
703 #- create thumbnails for images
705 info("processing element")
706 base_dest_img = dest_dir + '/' + make_dest_filename(img.sub(/\.[^\.]+$/, ''))
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'] } ])
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 }
722 gen_thumbnails_element("#{dir}/#{img}", xmldir, true, todo)
723 if $limit_sizes =~ /original/
724 fullscreen_images['original'] << img
726 destimg = "#{dest_dir}/#{img}"
727 if $limit_sizes =~ /original/ && !File.exists?(destimg)
728 psys("cp '#{dir}/#{img}' '#{destimg}'")
733 videos.size >= 1 and msg 3, _("\tcreating videos thumbnails...")
735 #- create thumbnails for videos
736 videos.each { |video|
737 info("processing element")
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'] } ])
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 }
749 gen_thumbnails_element("#{dir}/#{video}", xmldir, true, todo)
751 destvideo = "#{dest_dir}/#{video}"
752 if !File.exists?(destvideo)
753 psys("cp '#{dir}/#{video}' '#{destvideo}'")
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) }
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).
766 to_del = Dir.entries(dest_dir).find_all { |e| !File.directory?("#{dest_dir}/#{e}") && !all_elements.include?(e) && e !~ /^thumbnails-\w+\.jpg/ } - themestuff
768 system("rm -f " + to_del.collect { |e| "#{dest_dir}/#{e}" }.join(' '))
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}'")
778 msg 3, _("\tgenerating HTML pages...")
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 }
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)
792 reset_iterations(iterations)
794 type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
796 html_thumbnails += run_iterations(iterations)
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>')
813 html_thumbnails.gsub!(/~~image_iteration~~/,
814 '<a href="' + videos[index] + '">' + utf8(_("(no preview)")) + '</a>')
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 }
823 html_thumbnails += close_iterations(iterations)
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']))
830 ios = File.open("#{dest_dir}/thumbnails-#{size2js(sizeobj['name'])}.html", "w")
835 info("finished processing sizes")
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)
842 #- generate image.html (page with fullscreen images)
844 captions4js = find_captions(xmldir, images).collect { |e| e ? '"' + e.gsub('"', '\"') + '"' : '""' }.join(', ')
846 for sizeobj in $images_size
847 html = $html_images.collect { |l| l.clone }
848 images4js = fullscreen_images[sizeobj['name']].collect { |e| "\"#{e}\"" }.join(', ')
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'])}\""
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')
868 ios = File.open("#{dest_dir}/image-#{size2js(sizeobj['name'])}.html", "w")
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
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)
894 if !element.attributes['subdirs-captionfile']
895 element.add_attribute('subdirs-captionfile', captionfile)
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)
902 if !element.attributes['thumbnails-captionfile']
903 element.add_attribute('thumbnails-captionfile', captionfile)
910 #- write down to disk config if necessary
912 ios = File.open($config_writeto, "w")
913 $xmldoc.write(ios, 0)
918 msg 3, _(" completed necessary stuff for GUI, exiting.")
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...")
926 #- recompute the memoization because elements mights have been removed (the ones with no element in them)
928 $xmldoc.elements.each('//dir') { |elem|
929 optxpath[elem.attributes['path']] = elem
932 examined_dirs.each { |dir|
934 info("index.html: #{dir}|#{$source}")
936 xmldir = optxpath[utf8(dir)]
937 if !xmldir || (xmldir.attributes['already-generated'] && !$force) || xmldir.attributes['deleted']
940 dest_dir = make_dest_filename(dir.sub(/^#{Regexp.quote($source)}/, $dest))
942 previous_album = find_previous_album(xmldir)
943 next_album = find_next_album(xmldir)
945 if xmldir.elements['dir']
946 html = $html_index.collect { |l| l.clone }
949 caption = xmldir.attributes['subdirs-caption']
950 i.gsub!(/~~title~~/, caption)
951 if xmldir.parent.name == 'dir'
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}"
959 parent = parent.parent
961 i.gsub!(/~~ifnavigation\?~~(.+?)~~fi~~/) { $1 }
962 i.gsub!(/~~navigation~~/, nav + caption)
964 i.gsub!(/~~ifnavigation\?~~(.+?)~~fi~~/, '')
966 discover_iterations(iterations, i)
970 reset_iterations(iterations)
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'])
982 #- deal with sub-albums (direct to subdirs/index.html pages)
983 xmldir.elements.each('dir') { |child|
984 if child.attributes['deleted']
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>')
997 html_index += close_iterations(iterations)
1000 i.gsub!(/~~thumbnails~~/, html_index)
1004 html = html_reload_to_thumbnails
1007 ios = File.open("#{dest_dir}/index.html", "w")
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>')
1019 if xmldir.parent.name == 'dir'
1020 line.sub!(/~~return_to_albums~~/, '<a href="../index.html">' + utf8(_('return to albums')) + '</a>')
1022 line.sub!(/~~return_to_albums~~/, '')
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)
1036 msg 3, _(" all done.")
1043 build_html_skeletons