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) 2004-2006 Guillaume Cottenceau <http://zarb.org/~gc/resource/gc_mail.png>
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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/removed images/videos from --source, and change theme info") ],
47 [ '--merge-config-onedir', '-O', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing, for merging the subdir specified with --dir") ],
48 [ '--merge-config-subdirs', '-U', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing, for merging the new subdirs down the subdir specified with --dir") ],
49 [ '--dir', '-D', GetoptLong::REQUIRED_ARGUMENT, _("Directory for merge with --merge-config-onedir or --merge-config-subdirs") ],
50 [ '--use-config', '-u', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing, where to change theme info") ],
51 [ '--force', '-f', GetoptLong::NO_ARGUMENT, _("Force generation of album even if the GUI marked some directories as already generated") ],
53 [ '--sizes', '-S', GetoptLong::REQUIRED_ARGUMENT, _("Specify the list of images sizes to use instead of all specified in the theme (this is a comma-separated list)") ],
54 [ '--thumbnails-per-row', '-T', GetoptLong::REQUIRED_ARGUMENT, _("Specify the amount of thumbnails per row in the thumbnails page (if applicable in theme)") ],
55 [ '--thumbnails-per-page', '-p', GetoptLong::REQUIRED_ARGUMENT, _("Specify the amount of thumbnails per page in the thumbnails page, after which split occurs") ],
56 [ '--optimize-for-32', '-o', GetoptLong::NO_ARGUMENT, _("Resize images with optimized sizes for 3/2 aspect ratio rather than 4/3 (typical aspect ratio of pictures from non digital cameras are 3/2 when pictures from digital cameras are 4/3)") ],
57 [ '--index-link', '-l', GetoptLong::REQUIRED_ARGUMENT, _("Specify the HTML markup to use on the bottom of pages for a small link returning to wherever you see fit in your website (or somewhere else)") ],
58 [ '--made-with', '-n', GetoptLong::REQUIRED_ARGUMENT, _("Specify the HTML markup to use on the bottom of pages for a small 'made with' message") ],
59 [ '--comments-format','-c', GetoptLong::REQUIRED_ARGUMENT, _("Specify comments format to use for images instead of only filename when creating new albums; use ImageMagick's format") ],
61 [ '--mproc', '-m', GetoptLong::REQUIRED_ARGUMENT, _("Specify the number of processors for multi-processors machines") ],
63 [ '--for-gui', '-g', GetoptLong::NO_ARGUMENT, _("Do the minimum work to be able to see the album under the GUI (don't generate all thumbnails)") ],
65 [ '--verbose-level', '-v', GetoptLong::REQUIRED_ARGUMENT, _("Set max verbosity level (0: errors, 1: warnings, 2: important messages, 3: other messages)") ],
66 [ '--info-pipe', '-i', GetoptLong::REQUIRED_ARGUMENT, _("Name a file where to write information about what's going on (used by the GUI)") ],
69 #- default values for some globals
73 $ignore_videos = false
78 puts _("Usage: %s [OPTION]...") % File.basename($0)
80 printf " %3s, %-18s %s\n", ary[1], ary[0], ary[3]
85 parser = GetoptLong.new
86 parser.set_options(*$options.collect { |ary| ary[0..2] })
88 parser.each_option do |name, arg|
95 puts _("Booh version %s
97 Copyright (c) 2005 Guillaume Cottenceau.
98 This is free software; see the source for copying conditions. There is NO
99 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.") % $VERSION
104 $source = File.expand_path(arg.sub(%r|/$|, ''))
105 if !File.directory?($source)
106 die _("Argument to --source must be a directory")
109 $dest = File.expand_path(arg.sub(%r|/$|, ''))
110 if File.exists?($dest) && !File.directory?($dest)
111 die _("If --destination exists, it must be a directory")
113 if $dest != make_dest_filename($dest)
114 die _("Sorry, destination directory can't contain non simple alphanumeric characters.")
117 # system("rm -rf #{$dest}")
122 arg = File.expand_path(arg)
123 if File.readable?(arg)
124 $xmldoc = REXML::Document.new File.new(arg)
127 die _('Config file does not exist or is unreadable.')
130 arg = File.expand_path(arg)
132 if File.directory?(arg)
133 die _("Config skeleton file (%s) already exists and is a directory! Please change the filename.") % arg
135 msg 1, _("Config skeleton file already exists, backuping to %s.backup") % arg
136 File.rename(arg, "#{arg}.backup")
139 $config_writeto = arg
141 when '--merge-config'
142 arg = File.expand_path(arg)
143 if File.readable?(arg)
144 msg 2, _("Merge config notice: backuping current config file to %s.backup") % arg
145 $xmldoc = REXML::Document.new File.new(arg)
146 File.rename(arg, "#{arg}.backup")
147 $config_writeto = arg
148 $mode = 'merge_config'
150 die _('Config file does not exist or is unreadable.')
152 when '--merge-config-onedir'
153 arg = File.expand_path(arg)
154 if File.readable?(arg)
155 msg 2, _("Merge config notice: backuping current config file to %s.backup") % arg
156 $xmldoc = REXML::Document.new File.new(arg)
157 File.rename(arg, "#{arg}.backup")
158 $config_writeto = arg
159 $mode = 'merge_config_onedir'
161 die _('Config file does not exist or is unreadable.')
163 when '--merge-config-subdirs'
164 arg = File.expand_path(arg)
165 if File.readable?(arg)
166 msg 2, _("Merge config notice: backuping current config file to %s.backup") % arg
167 $xmldoc = REXML::Document.new File.new(arg)
168 File.rename(arg, "#{arg}.backup")
169 $config_writeto = arg
170 $mode = 'merge_config_subdirs'
172 die _('Config file does not exist or is unreadable.')
175 arg = File.expand_path(arg)
176 if !File.readable?(arg)
177 die _('Specified directory to merge with --dir is not readable')
182 arg = File.expand_path(arg)
183 if File.readable?(arg)
184 msg 2, _("Use config notice: backuping current config file to %s.backup") % arg
185 $xmldoc = REXML::Document.new File.new(arg)
186 File.rename(arg, "#{arg}.backup")
187 $config_writeto = arg
188 $mode = 'use_config_changetheme'
190 die _('Config file does not exist or is unreadable.')
196 when '--thumbnails-per-row'
199 when '--thumbnails-per-page'
202 when '--optimize-for-32'
203 $optimize_for_32 = true
211 when '--comments-format'
212 $commentsformat = arg
224 when '--verbose-level'
225 $verbose_level = arg.to_i
228 $info_pipe = File.open(arg, File::WRONLY)
229 $info_pipe.sync = true
238 if !$source && $xmldoc
239 $source = from_utf8($xmldoc.root.attributes['source']).sub(%r|/$|, '')
240 $dest = from_utf8($xmldoc.root.attributes['destination']).sub(%r|/$|, '')
241 $theme ||= $xmldoc.root.attributes['theme']
242 $limit_sizes ||= $xmldoc.root.attributes['limit-sizes']
243 if $mode == 'use_config' || $mode =~ /^merge_config/
244 $optimize_for_32 = !$xmldoc.root.attributes['optimize-for-32'].nil?
245 $N_per_row = $xmldoc.root.attributes['thumbnails-per-row']
246 $N_per_page = $xmldoc.root.attributes['thumbnails-per-page']
247 $madewith = $xmldoc.root.attributes['made-with']
248 $indexlink = $xmldoc.root.attributes['index-link']
252 if $mode == 'merge_config_onedir' && !$onedir
253 die _("Missing --dir for --merge-config-onedir")
255 if $mode == 'merge_config_subdirs' && !$onedir
256 die _("Missing --dir for --merge-config-subdirs")
264 die _("Missing --destination parameter.")
270 select_theme($theme, $limit_sizes, $optimize_for_32, $N_per_row)
273 additional_params = ''
275 additional_params += "limit-sizes='#{$limit_sizes}'"
278 additional_params += " optimize-for-32='true'"
281 additional_params += " thumbnails-per-row='#{$N_per_row}'"
284 additional_params += " thumbnails-per-page='#{$N_per_page}'"
287 additional_params += " made-with='#{$madewith}'"
290 additional_params += " index-link='#{$indexlink}'"
292 $xmldoc = Document.new "<booh version='#{$VERSION}' source='#{utf8($source)}' destination='#{utf8($dest)}' theme='#{$theme}' #{additional_params}/>"
293 $xmldoc << XMLDecl.new(XMLDecl::DEFAULT_VERSION, $CURRENT_CHARSET)
297 if $mode == 'merge_config' || $mode == 'use_config_changetheme'
298 $xmldoc.root.add_attribute('theme', $theme)
299 $xmldoc.root.add_attribute('version', $VERSION)
301 $xmldoc.root.add_attribute('limit-sizes', $limit_sizes)
303 $xmldoc.root.delete_attribute('limit-sizes')
306 $xmldoc.root.add_attribute('optimize-for-32', 'true')
308 $xmldoc.root.delete_attribute('optimize-for-32')
311 $xmldoc.root.add_attribute('thumbnails-per-row', $N_per_row)
313 $xmldoc.root.delete_attribute('thumbnails-per-row')
316 $xmldoc.root.add_attribute('thumbnails-per-page', $N_per_page)
318 $xmldoc.root.delete_attribute('thumbnails-per-page')
321 $xmldoc.root.add_attribute('made-with', $madewith)
323 $xmldoc.root.delete_attribute('made-with')
326 $xmldoc.root.add_attribute('index-link', $indexlink)
328 $xmldoc.root.delete_attribute('index-link')
333 $madewith = $madewith.gsub('%booh', '"http://booh.org/"')
346 $info_pipe.puts(value)
352 $info_pipe.puts("die: " + value)
357 def check_installation
358 if !system("which convert >/dev/null 2>/dev/null")
359 die _("The program 'convert' is needed. Please install it.
360 It is generally available with the 'ImageMagick' software package.")
362 if !system("which identify >/dev/null 2>/dev/null")
363 msg 1, _("the program 'identify' is needed to get images sizes and EXIF data. Please install it.
364 It is generally available with the 'ImageMagick' software package.")
367 missing = %w(transcode mencoder).delete_if { |prg| system("which #{prg} >/dev/null 2>/dev/null") }
369 msg 1, _("the following program(s) are needed to handle videos: '%s'. Videos will be ignored.") % missing.join(', ')
370 $ignore_videos = true
374 def replace_line(surround, keyword, line)
376 contents = eval "$#{keyword}"
377 line.sub!(/#{surround}#{keyword}#{surround}/, contents)
379 die _("No '%s' found for substitution") % keyword
383 def build_html_skeletons
384 $html_images = File.open("#{$FPATH}/themes/#{$theme}/skeleton_image.html").readlines
385 $html_thumbnails = File.open("#{$FPATH}/themes/#{$theme}/skeleton_thumbnails.html").readlines
386 $html_index = File.open("#{$FPATH}/themes/#{$theme}/skeleton_index.html").readlines
387 for line in $html_images + $html_thumbnails + $html_index
388 while line =~ /~~~(\w+)~~~/
389 replace_line('~~~', $1, line)
394 def find_caption_value(xmldir, filename)
395 if cap = xmldir.elements["*[@filename='#{utf8(filename)}']"].attributes['caption']
396 return cap.gsub("\n", '<br/>')
402 def find_captions(xmldir, images)
403 return images.collect { |img| find_caption_value(xmldir, img) }
406 #- stolen from CVSspam
408 text.sub(/[^a-zA-Z0-9\-,.*_\/]/) do
409 "%#{sprintf('%2X', $&[0])}"
414 return $limit_sizes =~ /original/ ? $images_size + [ { 'name' => 'original' } ] : $images_size
417 def html_reload_to_thumbnails
418 html_reload_to_thumbnails = $preferred_size_reloader.clone
419 html_reload_to_thumbnails.gsub!(/~~theme~~/, $theme)
420 html_reload_to_thumbnails.gsub!(/~~default_size~~/, $default_size['name'])
421 html_reload_to_thumbnails.gsub!(/~~all_sizes~~/, all_images_sizes.collect { |s| "\"#{size2js(s['name'])}\"" }.join(', '))
422 size_auto_chooser = '';
423 all_images_sizes.find_all { |s| s.has_key?('optimizedforwidth') }.
424 sort { |a,b| b['optimizedforwidth'].to_i <=> a['optimizedforwidth'].to_i }.
425 each { |s| size_auto_chooser += "if (w + 50 > #{s['optimizedforwidth']}) { return 'thumbnails-#{size2js(s['name'])}-0.html'; }\n" }
426 html_reload_to_thumbnails.gsub!(/~~size_auto_chooser~~/, size_auto_chooser)
427 return html_reload_to_thumbnails
430 def discover_iterations(iterations, line)
431 if line =~ /~~iterate(\d)_open(_max(\d+|N))?~~/
432 for iter in iterations.values
435 iter['close_wait'] = $1.to_i
438 max = $3 == 'N' ? ($N_per_row || $default_N) : $3
439 iterations[$1.to_i] = { 'open' => true, 'max' => max, 'opening' => '', 'closing' => '' }
441 line.sub!(/.*/, '~~thumbnails~~')
445 elsif line =~ /~~iterate(\d)_close~~/
446 iterations[$1.to_i]['open'] = false;
447 iterations[$1.to_i]['close'] = true;
450 for iter in iterations.values
452 iter['opening'] += line
455 if !iter['close'] && iter['close_wait'] && iterations[iter['close_wait']]['close']
456 iter['closing'] += line
463 def reset_iterations(iterations)
464 for iter in iterations.values
469 def run_iterations(iterations, amount)
472 for level in iterations.keys.sort
473 if iterations[level]['value'] == 0
474 html += iterations[level]['opening']
475 elsif level == iterations.keys.max
476 if !iterations[level]['max'] || iterations[level]['max'] && iterations[level]['value'] + amount <= iterations[level]['max'].to_i
477 html += iterations[level]['opening']
482 iterations[level]['value'] += amount
483 if iterations[level]['max'] && iterations[level]['value'] > iterations[level]['max'].to_i
484 iterations[level]['value'] = 0
485 iterations[level-1]['value'] = 0
486 html += iterations[level-1]['closing']
490 return html + run_iterations(iterations, amount)
496 def close_iterations(iterations)
498 for level in iterations.keys.sort.reverse
499 html += iterations[level]['closing']
504 def img_element(fullpath)
505 if size = get_image_size(fullpath)
506 sizespec = 'width="' + size[:x].to_s + '" height="' + size[:y].to_s + '"'
510 return '<img src="' + File.basename(fullpath) + '" ' + sizespec + ' alt="image"/>'
514 return name.gsub(/-/, '')
517 def substitute_html_sizes(html, sizeobj, type, suffix)
519 if $images_size.length > 1 || (type == 'image' && $limit_sizes =~ /original/)
520 for sizeobj2 in $images_size
521 sizejs = size2js(sizeobj2['name'])
522 sizen = sizename(sizeobj2['name'])
523 if sizeobj != sizeobj2
524 if type == 'thumbnails'
525 sizestrings << '<a href="thumbnails-' + sizejs + suffix + '.html" onclick="set_preferred_size(\'' + sizejs + '\')">' + sizen + '</a>'
527 sizestrings << '<a id="link' + sizejs + '" onclick="set_preferred_size(\'' + sizejs + '\')">' + sizen + '</a>'
533 if type == 'image' && $limit_sizes =~ /original/
534 sizestrings << '<a id="linkoriginal" target="newframe">' + sizename('original') + '</a>'
537 html.sub!(/~~sizes~~(.+)~~/) { sizestrings.join($1) }
540 def substitute_navigation(html, xmldir)
541 if xmldir.parent.name == 'dir'
544 parent = xmldir.parent
545 while parent.name == 'dir'
546 parentcaption = parent.attributes['subdirs-caption'] || File.basename(parent.attributes['path'])
547 nav = "<a href=\"#{path}/index.html\">#{parentcaption}</a> #{utf8(_(" > "))} #{nav}"
549 parent = parent.parent
551 html.gsub!(/~~ifnavigation\?~~(.+?)~~fi~~/) { $1 }
552 html.gsub!(/~~navigation~~/, nav + (xmldir.attributes['subdirs-caption'] || File.basename(xmldir.attributes['path'])))
554 html.gsub!(/~~ifnavigation\?~~(.+?)~~fi~~/, '')
558 def xmldir2destdir(xmldir)
559 return make_dest_filename(from_utf8(File.basename(xmldir.attributes['path'])))
562 def find_previous_album(xmldir)
565 #- move to previous dir element if exists
566 if prevelem = xmldir.previous_element_byname_notattr('dir', 'deleted')
568 relative_pos += '../' + xmldir2destdir(xmldir) + '/'
570 #- after having moved to previous dir, we need to go down last subdir until the last one
571 while child = xmldir.elements['dir']
572 while nextchild = child.next_element_byname_notattr('dir', 'deleted')
575 relative_pos += xmldir2destdir(child) + '/'
579 #- previous dir doesn't exist, move to previous dir element if exists
580 xmldir = xmldir.parent
581 if xmldir.name == 'dir' && !xmldir.attributes['deleted']
582 relative_pos += '../'
587 end while !xmldir.child_byname_notattr('image', 'deleted') && !xmldir.child_byname_notattr('video', 'deleted')
588 return File.reduce_path(relative_pos)
591 def find_next_album(xmldir)
594 #- first child dir element (catches when initial xmldir has both thumbnails and subdirs)
595 if firstchild = xmldir.child_byname_notattr('dir', 'deleted')
597 relative_pos += xmldir2destdir(xmldir) + '/'
599 elsif nextbro = xmldir.next_element_byname_notattr('dir', 'deleted')
601 relative_pos += '../' + xmldir2destdir(xmldir) + '/'
603 #- go up until we have a next brother or we are finished
605 xmldir = xmldir.parent
606 relative_pos += '../'
607 end while xmldir && !xmldir.next_element_byname_notattr('dir', 'deleted')
609 xmldir = xmldir.next_element_byname('dir')
610 relative_pos += '../' + xmldir2destdir(xmldir) + '/'
615 end while !xmldir.child_byname_notattr('image', 'deleted') && !xmldir.child_byname_notattr('video', 'deleted')
616 return File.reduce_path(relative_pos)
619 def sub_previous_next_album(previous_album, next_album, html)
621 html.gsub!(/~~previous_album~~/, '<a href="' + previous_album + 'thumbnails.html">' + utf8(_('previous album')) + '</a>')
622 html.gsub!(/~~ifprevious_album\?~~(.+?)~~fi~~/) { $1 }
624 html.gsub!(/~~previous_album~~/, '')
625 html.gsub!(/~~ifprevious_album\?~~(.+?)~~fi~~/, '')
628 html.gsub!(/~~next_album~~/, '<a href="' + next_album + 'thumbnails.html">' + utf8(_('next album')) + '</a>')
629 html.gsub!(/~~ifnext_album\?~~(.+?)~~fi~~/) { $1 }
631 html.gsub!(/~~next_album~~/, '')
632 html.gsub!(/~~ifnext_album\?~~(.+?)~~fi~~/, '')
639 #- preprocess the path->dir, rexml is very slow with that; we seem to improve speed by 7%
641 $xmldoc.elements.each('//dir') { |elem|
642 optxpath[elem.attributes['path']] = elem
646 if $mode == 'merge_config_onedir'
647 examined_dirs = [ $onedir ]
648 elsif $mode == 'merge_config_subdirs'
649 examined_dirs = `find '#{$onedir}' -type d -follow`.sort.collect { |v| v.chomp }.delete_if { |v| optxpath.has_key?(utf8(v)) }
651 examined_dirs = `find '#{$source}' -type d -follow`.sort.collect { |v| v.chomp }
652 if $mode == 'merge_config'
653 $xmldoc.elements.each('//dir') { |elem|
654 if ! examined_dirs.include?(elem.attributes['path'])
655 msg 2, _("Merging config: removing directory %s from config, isn't on filesystem anymore") % elem.attributes['path']
661 info("directories: #{examined_dirs.length}, sizes: #{$images_size.length}")
663 examined_dirs.each { |dir|
665 die _("Source directory or sub-directories can't contain a single-quote character, sorry: %s") % dir
667 if $mode !~ /^use_config/
668 Dir.entries(dir).each { |file|
669 if file =~ /['"\[\]]/
670 die _("Files can't contain any of the characters ', \", [ or ], sorry: %s") % "#{dir}/#{file}"
676 examined_dirs.each { |dir|
677 if File.basename(dir) =~ /^\./
678 msg 1, _("Ignoring directory %s, begins with a dot (indicating a hidden directory)") % dir
682 dest_dir = make_dest_filename(dir.sub(/^#{Regexp.quote($source)}/, $dest))
684 #- place xml document on proper node if exists, else create
685 xmldir = optxpath[utf8(dir)]
686 if $mode == 'use_config' || $mode == 'use_config_changetheme'
687 if !xmldir || (xmldir.attributes['already-generated'] && !$force) || xmldir.attributes['deleted']
688 info("walking: #{dir}|#{$source}, 0 elements")
689 if xmldir && xmldir.attributes['deleted']
690 system("rm -rf '#{dest_dir}'")
695 if $mode == 'gen_config' || (($mode == 'merge_config' || $mode == 'merge_config_subdirs') && !xmldir)
696 #- add the <dir..> element if necessary
697 parent = File.dirname(dir)
698 xmldir = $xmldoc.elements["//dir[@path='#{utf8(parent)}']"]
700 xmldir = $xmldoc.root
702 #- need to remove the already-generated mark of the parent because of the sub-albums page containing now one more element
703 xmldir.delete_attribute('already-generated')
704 xmldir = optxpath[utf8(dir)] = xmldir.add_element('dir', { 'path' => utf8(dir) })
707 xmldir.delete_attribute('already-generated')
709 #- read images/videos entries from config or from directories depending on mode
711 if $mode == 'use_config' || $mode == 'use_config_changetheme'
712 msg 2, _("Handling %s from config list...") % dir
713 xmldir.elements.each { |element|
714 if %w(image video).include?(element.name) && !element.attributes['deleted']
715 entries << from_utf8(element.attributes['filename'])
719 msg 2, _("Examining %s...") % dir
720 entries = Dir.entries(dir).sort
721 #- populate config in case of gen_config, add new files in case of merge_config
723 if file =~ /['"\[\]]/
724 msg 1, _("Ignoring %s, contains one of forbidden characters: '\"[]") % "#{dir}/#{file}"
726 type = entry2type(file)
727 if type && !xmldir.elements["#{type}[@filename='#{utf8(file)}']"]
728 #- hack: don't run identify (which is slow) if format only contains default %t
729 if $commentsformat && type == 'image' && $commentsformat != '%t'
730 comment = utf8(`identify -format "#{$commentsformat}" '#{dir}/#{file}'`.chomp.sub(/\.$/, ''))
732 comment = utf8cut(file.sub(/\.[^\.]+$/, ''), 18)
734 xmldir.add_element type, { "filename" => utf8(file), "caption" => comment }
738 if $mode != 'gen_config'
739 #- cleanup removed files from config and reread entries from config to get proper ordering
741 xmldir.elements.each { |element|
742 fullpath = "#{dir}/#{from_utf8(element.attributes['filename'])}"
743 if %w(image video).include?(element.name)
744 if !File.readable?(fullpath)
745 msg 1, _("Config merge: removing %s from config; use the backup file to retrieve caption info if this was a mistake") % fullpath
746 xmldir.delete(element)
747 elsif !element.attributes['deleted']
748 entries << from_utf8(element.attributes['filename'])
752 #- if there is no more elements here, there is no album here anymore
753 if !xmldir.child_byname_notattr('image', 'deleted') && !xmldir.child_byname_notattr('video', 'deleted')
754 xmldir.delete_attribute('thumbnails-caption')
755 xmldir.delete_attribute('thumbnails-captionfile')
759 images = entries.find_all { |e| entry2type(e) == 'image' }
760 msg 3, _("\t%s images") % images.length
761 videos = entries.find_all { |e| entry2type(e) == 'video' }
762 msg 3, _("\t%s videos") % videos.length
763 info("walking: #{dir}|#{$source}, #{images.length + videos.length} elements")
765 system("mkdir -p '#{dest_dir}'")
767 #- generate .htaccess file
769 ios = File.open("#{dest_dir}/.htaccess", "w")
770 ios.write("AddCharset UTF-8 .html\n")
771 if auth_user_file = xmldir.attributes['password-protect']
772 msg 3, _("\tgenerating password protection file #{dest_dir}/.htaccess")
773 ios.write("AuthType Basic\nAuthName \"protected area\"\nAuthUserFile #{auth_user_file}\nrequire valid-user\n")
778 #- pass through if there are no images and videos
779 if images.size == 0 && videos.size == 0
781 #- cleanup old images/videos, especially if this directory contained images/videos previously.
782 themestuff = Dir.entries("#{$FPATH}/themes/#{$theme}").
783 find_all { |e| !%w(. .. skeleton_image.html skeleton_thumbnails.html skeleton_index.html metadata CVS).include?(e) }
784 if $mode != 'gen_config'
785 rightful_images = [ '.htaccess' ]
786 if xmldir.attributes['thumbnails-caption']
787 rightful_images << 'thumbnails-thumbnail.jpg'
789 xmldir.elements.each('dir') { |child|
790 if child.attributes['deleted']
793 subdir = make_dest_filename(from_utf8(File.basename(child.attributes['path'])))
794 rightful_images << "thumbnails-#{subdir}.jpg"
796 to_del = Dir.entries(dest_dir).find_all { |e| !File.directory?("#{dest_dir}/#{e}") && !rightful_images.include?(e) } - themestuff
798 system("rm -f " + to_del.collect { |e| "'#{dest_dir}/#{e}'" }.join(' '))
802 #- copy any resource file that goes with the theme (css, images..)
803 themestuff.each { |entry|
804 if !File.exists?("#{dest_dir}/#{entry}")
805 psys("cp '#{$FPATH}/themes/#{$theme}/#{entry}' '#{dest_dir}'")
812 msg 2, _("Outputting in %s...") % dest_dir
814 #- populate data structure with sizes from theme
815 for sizeobj in $images_size
816 fullscreen_images ||= {}
817 fullscreen_images[sizeobj['name']] = []
818 thumbnail_images ||= {}
819 thumbnail_images[sizeobj['name']] = []
820 thumbnail_videos ||= {}
821 thumbnail_videos[sizeobj['name']] = []
823 #- a special dummy size to keep 'references' to thumbnails in case of panorama, because the GUI will use the regular thumbnails
824 thumbnail_images['dont-delete-file-for-gui'] = []
825 if $limit_sizes =~ /original/
826 fullscreen_images['original'] = []
829 images.size >= 1 and msg 3, _("\tcreating images thumbnails...")
831 #- create thumbnails for images
833 info("processing element")
834 base_dest_img = dest_dir + '/' + make_dest_filename(img.sub(/\.[^\.]+$/, ''))
836 thumbnail_dest_img = base_dest_img + "-#{$default_size['thumbnails']}.jpg"
837 gen_thumbnails_element("#{dir}/#{img}", xmldir, true, [ { 'filename' => thumbnail_dest_img, 'size' => $default_size['thumbnails'] } ])
840 elem = xmldir.elements["image[@filename='#{utf8(img)}']"]
841 for sizeobj in $images_size
842 size_fullscreen = sizeobj['fullscreen']
843 size_thumbnails = sizeobj['thumbnails']
844 fullscreen_dest_img = base_dest_img + "-#{size_fullscreen}.jpg"
845 fullscreen_images[sizeobj['name']] << File.basename(fullscreen_dest_img)
846 todo << { 'filename' => fullscreen_dest_img, 'size' => size_fullscreen }
847 if pano = pano_amount(elem)
848 thumbnail_images['dont-delete-file-for-gui'] << File.basename(base_dest_img + "-#{size_thumbnails}.jpg")
849 size_thumbnails = size_thumbnails.sub(/(\d+)/) { ($1.to_i * pano).to_i }
851 thumbnail_dest_img = base_dest_img + "-#{size_thumbnails}.jpg"
852 thumbnail_images[sizeobj['name']] << File.basename(thumbnail_dest_img)
853 todo << { 'filename' => thumbnail_dest_img, 'size' => size_thumbnails }
855 gen_thumbnails_element("#{dir}/#{img}", xmldir, true, todo)
856 if $limit_sizes =~ /original/
857 fullscreen_images['original'] << img
859 destimg = "#{dest_dir}/#{img}"
860 if $limit_sizes =~ /original/ && !File.exists?(destimg)
862 if ! sys("ln '#{dir}/#{img}' '#{destimg}'")
863 $hardlinks_ok = false
867 psys("cp '#{dir}/#{img}' '#{destimg}'")
873 videos.size >= 1 and msg 3, _("\tcreating videos thumbnails...")
875 #- create thumbnails for videos
876 videos.each { |video|
877 info("processing element")
879 thumbnail_dest_img = dest_dir + '/' + make_dest_filename(video.sub(/\.[^\.]+$/, '')) + "-#{$default_size['thumbnails']}.jpg"
880 gen_thumbnails_element("#{dir}/#{video}", xmldir, true, [ { 'filename' => thumbnail_dest_img, 'size' => $default_size['thumbnails'] } ])
883 for sizeobj in $images_size
884 size_thumbnails = sizeobj['thumbnails']
885 thumbnail_dest_img = dest_dir + '/' + make_dest_filename(video.sub(/\.[^\.]+$/, '')) + "-#{size_thumbnails}.jpg"
886 thumbnail_videos[sizeobj['name']] << File.basename(thumbnail_dest_img)
887 todo << { 'filename' => thumbnail_dest_img, 'size' => size_thumbnails }
889 gen_thumbnails_element("#{dir}/#{video}", xmldir, true, todo)
891 destvideo = "#{dest_dir}/#{video}"
892 if !File.exists?(destvideo)
894 if ! sys("ln '#{dir}/#{video}' '#{destvideo}'")
895 $hardlinks_ok = false
899 psys("cp '#{dir}/#{video}' '#{destvideo}'")
905 themestuff = Dir.entries("#{$FPATH}/themes/#{$theme}").
906 find_all { |e| !%w(. .. skeleton_image.html skeleton_thumbnails.html skeleton_index.html metadata CVS).include?(e) }
908 #- cleanup old images/videos (for when removing elements or sizes)
909 all_elements = fullscreen_images.collect { |e| e[1] }.flatten.
910 concat(thumbnail_images.collect { |e| e[1] }.flatten).
911 concat(thumbnail_videos.collect { |e| e[1] }.flatten).
914 to_del = Dir.entries(dest_dir).find_all { |e| !File.directory?("#{dest_dir}/#{e}") && !all_elements.include?(e) && e !~ /^thumbnails-\w+\.jpg/ } - themestuff
916 msg 3, _("\tcleaning up: #{to_del.join(', ')}")
917 system("rm -f " + to_del.collect { |e| "#{dest_dir}/#{e}" }.join(' '))
920 #- copy any resource file that goes with the theme (css, images..)
921 themestuff.each { |entry|
922 if !File.exists?("#{dest_dir}/#{entry}")
923 psys("cp '#{$FPATH}/themes/#{$theme}/#{entry}' '#{dest_dir}'")
927 msg 3, _("\tgenerating HTML pages...")
928 #- fixup max per page
929 if $N_per_page && $N_per_row
930 $N_per_page = $N_per_page.to_i / $N_per_row.to_i * $N_per_row.to_i
933 #- generate thumbnails*.html (page with thumbnails)
934 image2thumbnailpage4js = []
935 for sizeobj in $images_size
936 info("processing size")
937 html = $html_thumbnails.collect { |l| l.clone }
941 xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir)))
942 discover_iterations(iterations, i)
946 html_thumbnails_nojs = ''
949 reset_iterations(iterations)
950 #- preprocess the @filename->elem, rexml is very slow with that; we dramatically improve this part of the processing
952 xmldir.elements.each('image') { |elem|
953 optfilename[elem.attributes['filename']] = elem
956 type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
958 if type == 'image' && elem = optfilename[utf8(file)]
959 if pano = pano_amount(elem)
960 html_elem = run_iterations(iterations, pano)
961 counter += count = pano.ceil
962 html_elem.gsub!(/~~colspan~~/) { "colspan=\"#{count}\"" }
964 html_elem = run_iterations(iterations, 1)
966 html_elem.gsub!(/~~colspan~~/, '')
969 html_elem = run_iterations(iterations, 1)
971 html_elem.gsub!(/~~colspan~~/, '')
974 index = images.index(file)
975 html_elem.gsub!(/~~caption_iteration~~/,
976 find_caption_value(xmldir, images[index]) || utf8(images[index]))
977 html_elem.gsub!(/~~ifimage\?~~(.+?)~~fi~~/) { $1 }
978 html_elem.gsub!(/~~ifvideo\?~~(.+?)~~fi~~/, '')
979 elsif type == 'video'
980 index = videos.index(file)
981 if File.exists?("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}")
982 html_elem.gsub!(/~~image_iteration~~/,
983 '<a href="' + videos[index] + '">' + img_element("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}") + '</a>')
985 html_elem.gsub!(/~~image_iteration~~/,
986 '<a href="' + videos[index] + '">' + utf8(_("(no preview)")) + '</a>')
988 html_elem.gsub!(/~~caption_iteration~~/, find_caption_value(xmldir, videos[index]) || utf8(videos[index]))
989 html_elem.gsub!(/~~ifimage\?~~(.+?)~~fi~~/, '')
990 html_elem.gsub!(/~~ifvideo\?~~(.+?)~~fi~~/) { $1 }
992 html_thumbnails += html_elem
993 html_thumbnails_nojs += html_elem
995 html_thumbnails.gsub!(/~~image_iteration~~/,
996 '<a href="image-' + size2js(sizeobj['name']) + '.html#current=' + fullscreen_images[sizeobj['name']][index] +
997 '" name="' + fullscreen_images[sizeobj['name']][index] + '">' +
998 img_element("#{dest_dir}/#{thumbnail_images[sizeobj['name']][index]}") + '</a>')
999 html_thumbnails_nojs.gsub!(/~~image_iteration~~/,
1000 '<a href="' + fullscreen_images[sizeobj['name']][index] + '" name="' + fullscreen_images[sizeobj['name']][index] + '">' +
1001 img_element("#{dest_dir}/#{thumbnail_images[sizeobj['name']][index]}") + '</a>')
1002 #- remember in which thumbnails page is this element, for image->thumbnail link
1003 if sizeobj == $images_size[0]
1004 image2thumbnailpage4js << pagecount
1008 if counter == $N_per_page
1009 html_thumbnails += close_iterations(iterations)
1010 html_thumbnails_nojs += close_iterations(iterations)
1011 all_pages << [ html_thumbnails, html_thumbnails_nojs ]
1012 html_thumbnails = ''
1013 html_thumbnails_nojs = ''
1015 reset_iterations(iterations)
1021 html_thumbnails += close_iterations(iterations)
1022 html_thumbnails_nojs += close_iterations(iterations)
1023 all_pages << [ html_thumbnails, html_thumbnails_nojs ]
1026 i.gsub!(/~~theme~~/, $theme)
1027 i.gsub!(/~~current_size~~/, sizeobj['name'])
1028 i.gsub!(/~~current_size_js~~/, size2js(sizeobj['name']))
1029 i.gsub!(/~~madewith~~/, $madewith || '')
1030 i.gsub!(/~~indexlink~~/, $indexlink || '')
1031 substitute_navigation(i, xmldir)
1033 html_nojs = html.collect { |l| l.clone }
1035 for page in all_pages
1036 html_thumbnails, html_thumbnails_nojs = page
1037 final_html = html.collect { |l| l.clone }
1038 mstuff = utf8(_("Pages: %s") % (pagecount > 0 ? "<a href=\"thumbnails-#{size2js(sizeobj['name'])}%nojs-#{pagecount - 1}.html\">" + _("<- Previous") + "</a> " : '') +
1039 all_pages.collect_with_index { |p,idx| page == p ? idx + 1 : "<a href=\"thumbnails-#{size2js(sizeobj['name'])}%nojs-#{idx}.html\">#{idx + 1}</a>" }.join(', ') +
1040 (pagecount < all_pages.size - 1 ? " <a href=\"thumbnails-#{size2js(sizeobj['name'])}%nojs-#{pagecount + 1}.html\">" + _("Next ->") + "</a> " : ''))
1042 i.sub!(/~~run_slideshow~~/,
1043 images.size <= 1 ? '' : '<a href="image-' + size2js(sizeobj['name']) + '.html#run_slideshow=1">' + utf8(_("Run slideshow!"))+'</a>')
1044 i.sub!(/~~thumbnails~~/, html_thumbnails)
1045 if all_pages.size == 1
1046 i.gsub!(/~~ifmultiplepages\?~~.*~~fi~~/, '')
1048 i.gsub!(/~~ifmultiplepages\?~~(.+?)~~fi~~/) { $1 }
1049 i.gsub!(/~~multiplepagesstuff~~/, mstuff.gsub('%nojs', ''))
1051 substitute_html_sizes(i, sizeobj, 'thumbnails', "-#{pagecount}")
1053 ios = File.open("#{dest_dir}/thumbnails-#{size2js(sizeobj['name'])}-#{pagecount}.html", "w")
1054 ios.write(final_html)
1056 final_html_nojs = html_nojs.collect { |l| l.clone }
1057 for i in final_html_nojs
1058 i.sub!(/~~run_slideshow~~/, utf8(_("<i>Click on an image to view it larger</i>")))
1059 i.sub!(/~~thumbnails~~/, html_thumbnails_nojs)
1060 if all_pages.size == 1
1061 i.gsub!(/~~ifmultiplepages\?~~.*~~fi~~/, '')
1063 i.gsub!(/~~ifmultiplepages\?~~(.+?)~~fi~~/) { $1 }
1064 i.gsub!(/~~multiplepagesstuff~~/, mstuff.gsub('%nojs', '-nojs'))
1066 substitute_html_sizes(i, sizeobj, 'thumbnails', "-nojs-#{pagecount}")
1068 ios = File.open("#{dest_dir}/thumbnails-#{size2js(sizeobj['name'])}-nojs-#{pagecount}.html", "w")
1069 ios.write(final_html_nojs)
1075 info("finished processing sizes")
1077 #- generate "main" thumbnails.html page that will reload to correct size thanks to cookie
1078 ios = File.open("#{dest_dir}/thumbnails.html", "w")
1079 ios.write(html_reload_to_thumbnails)
1082 #- generate image.html (page with fullscreen images)
1084 captions4js = find_captions(xmldir, images).collect { |e| e ? '"' + e.gsub('"', '\"') + '"' : '""' }.join(', ')
1085 thumbnailspage4js = image2thumbnailpage4js.collect { |e| "\"#{e}\"" }.join(', ')
1086 for sizeobj in $images_size
1087 html = $html_images.collect { |l| l.clone }
1088 images4js = fullscreen_images[sizeobj['name']].collect { |e| "\"#{e}\"" }.join(', ')
1091 for sizeobj2 in all_images_sizes
1092 if sizeobj != sizeobj2
1093 otherimages4js += "var images_#{size2js(sizeobj2['name'])} = new Array(" + fullscreen_images[sizeobj2['name']].collect { |e| "\"#{e}\"" }.join(', ') + ")\n"
1094 othersizes << "\"#{size2js(sizeobj2['name'])}\""
1098 i.gsub!(/~~images~~/, images4js)
1099 i.gsub!(/~~other_images~~/, otherimages4js)
1100 i.gsub!(/~~thumbnailspages~~/, thumbnailspage4js)
1101 i.gsub!(/~~other_sizes~~/, othersizes.join(', '))
1102 i.gsub!(/~~captions~~/, captions4js)
1103 i.gsub!(/~~title~~/, xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir)))
1104 i.gsub!(/~~thumbnails~~/, '<a href="thumbnails-' + size2js(sizeobj['name']) + '.html" id="thumbnails">' + utf8(_('return to thumbnails')) + '</a>')
1105 i.gsub!(/~~theme~~/, $theme)
1106 i.gsub!(/~~current_size~~/, size2js(sizeobj['name']))
1107 i.gsub!(/~~madewith~~/, $madewith || '')
1108 i.gsub!(/~~indexlink~~/, $indexlink || '')
1109 substitute_html_sizes(i, sizeobj, 'image', '')
1110 substitute_navigation(i, xmldir)
1112 ios = File.open("#{dest_dir}/image-#{size2js(sizeobj['name'])}.html", "w")
1122 #- add attributes to <dir..> elements needing so
1123 if $mode != 'use_config'
1124 msg 3, _("\tfixating configuration file...")
1125 $xmldoc.elements.each('//dir') { |element|
1126 path = captionpath = element.attributes['path']
1127 descendant_element = element.elements['descendant::image'] || element.elements['descendant::video']
1128 if !descendant_element
1129 msg 3, _("\t\tremoving %s, no element in it") % path
1130 element.remove #- means we have a directory with nothing interesting in it
1132 captionfile = "#{descendant_element.parent.attributes['path']}/#{descendant_element.attributes['filename']}"
1133 basename = File.basename(path)
1134 if element.elements['dir']
1135 if !element.attributes['subdirs-caption']
1136 element.add_attribute('subdirs-caption', basename)
1138 if !element.attributes['subdirs-captionfile']
1139 element.add_attribute('subdirs-captionfile', captionfile)
1142 if element.child_byname_notattr('image', 'deleted') || element.child_byname_notattr('video', 'deleted')
1143 if !element.attributes['thumbnails-caption']
1144 element.add_attribute('thumbnails-caption', basename)
1146 if !element.attributes['thumbnails-captionfile']
1147 element.add_attribute('thumbnails-captionfile', captionfile)
1154 #- write down to disk config if necessary
1156 ios = File.open($config_writeto, "w")
1157 $xmldoc.write(ios, 0)
1162 msg 3, _(" completed necessary stuff for GUI, exiting.")
1166 #- second pass to create index.html files and previous/next links
1167 info("creating index.html")
1168 msg 3, _("\trescanning directories to generate all 'index.html' files...")
1170 #- recompute the memoization because elements mights have been removed (the ones with no element in them)
1172 $xmldoc.elements.each('//dir') { |elem|
1173 optxpath[elem.attributes['path']] = elem
1176 examined_dirs.each { |dir|
1177 info("index.html: #{dir}|#{$source}")
1179 xmldir = optxpath[utf8(dir)]
1180 if !xmldir || (xmldir.attributes['already-generated'] && !$force) || xmldir.attributes['deleted']
1183 dest_dir = make_dest_filename(dir.sub(/^#{Regexp.quote($source)}/, $dest))
1185 previous_album = find_previous_album(xmldir)
1186 next_album = find_next_album(xmldir)
1188 if xmldir.elements['dir']
1189 html = $html_index.collect { |l| l.clone }
1192 caption = xmldir.attributes['subdirs-caption']
1193 i.gsub!(/~~title~~/, caption)
1194 substitute_navigation(i, xmldir)
1195 discover_iterations(iterations, i)
1199 reset_iterations(iterations)
1201 #- deal with "current" album (directs to "thumbnails" page)
1202 if xmldir.attributes['thumbnails-caption']
1203 thumbnail = "#{dest_dir}/thumbnails-thumbnail.jpg"
1204 gen_thumbnails_subdir(from_utf8(xmldir.attributes['thumbnails-captionfile']), xmldir, false,
1205 [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ], 'thumbnails')
1206 html_index += run_iterations(iterations, 1)
1207 html_index.gsub!(/~~image_iteration~~/, "<a href=\"thumbnails.html\">" + img_element(thumbnail) + '</a>')
1208 html_index.gsub!(/~~caption_iteration~~/, xmldir.attributes['thumbnails-caption'])
1211 #- deal with sub-albums (direct to subdirs/index.html pages)
1212 xmldir.elements.each('dir') { |child|
1213 if child.attributes['deleted']
1216 subdir = make_dest_filename(from_utf8(File.basename(child.attributes['path'])))
1217 thumbnail = "#{dest_dir}/thumbnails-#{subdir}.jpg"
1218 html_index += run_iterations(iterations, 1)
1219 captionfile, caption = find_subalbum_caption_info(child)
1220 gen_thumbnails_subdir(captionfile, child, false,
1221 [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ], find_subalbum_info_type(child))
1222 html_index.gsub!(/~~caption_iteration~~/, caption)
1223 html_index.gsub!(/~~image_iteration~~/, "<a href=\"#{subdir}/index.html\">" + img_element(thumbnail) + '</a>')
1226 html_index += close_iterations(iterations)
1229 i.gsub!(/~~thumbnails~~/, html_index)
1230 i.gsub!(/~~madewith~~/, $madewith || '')
1231 i.gsub!(/~~indexlink~~/, $indexlink || '')
1235 html = html_reload_to_thumbnails
1238 ios = File.open("#{dest_dir}/index.html", "w")
1242 #- substitute multiple "return to albums", previous/next correctly
1243 #- the following two statements are dramatical optimizations to executing for each substInFile callback
1244 dirpresent = xmldir.elements['dir']
1245 parentname = xmldir.parent.name
1246 if xmldir.child_byname_notattr('image', 'deleted') || xmldir.child_byname_notattr('video', 'deleted')
1247 for suffix in [ '', '-nojs' ]
1248 for sizeobj in $images_size
1249 Dir.glob("#{dest_dir}/thumbnails-#{size2js(sizeobj['name'])}#{suffix}-*.html") do |file|
1250 substInFile(file) { |line|
1251 sub_previous_next_album(previous_album, next_album, line)
1253 line.sub!(/~~return_to_albums~~/, '<a href="index.html">' + utf8(_('return to albums')) + '</a>')
1255 if parentname == 'dir'
1256 line.sub!(/~~return_to_albums~~/, '<a href="../index.html">' + utf8(_('return to albums')) + '</a>')
1258 line.sub!(/~~return_to_albums~~/, '')
1263 if suffix == '' && xmldir.child_byname_notattr('image', 'deleted')
1264 substInFile("#{dest_dir}/image-#{size2js(sizeobj['name'])}.html") { |line|
1265 sub_previous_next_album(previous_album, next_album, line)
1274 msg 3, _(" all done.")
1281 build_html_skeletons