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-2009 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
24 #- new style (ruby-locale separated package)
27 #- old style (locale stuff in ruby-gettext package)
28 require 'gettext/locale'
32 require 'booh/rexml/document'
35 require 'booh/booh-lib'
36 require 'booh/html-merges'
38 #- bind text domain as soon as possible because some _() functions are called early to build data structures
39 bindtextdomain("booh")
40 #- save locale for restoring for multi languages
41 $default_locale = Locale.get
45 [ '--help', '-h', GetoptLong::NO_ARGUMENT, _("Get help message") ],
46 [ '--version', '-V', GetoptLong::NO_ARGUMENT, _("Print version and exit") ],
48 [ '--source', '-s', GetoptLong::REQUIRED_ARGUMENT, _("Directory which contains original photos/videos as files or subdirs") ],
49 [ '--destination', '-d', GetoptLong::REQUIRED_ARGUMENT, _("Directory which will contain the web-album; if it already exits, then all existing files and directories inside it will be removed!") ],
51 [ '--theme', '-t', GetoptLong::REQUIRED_ARGUMENT, _("Select HTML theme to use") ],
52 [ '--config', '-C', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing photos and videos within directories with captions") ],
53 [ '--config-skel', '-k', GetoptLong::REQUIRED_ARGUMENT, _("Filename where the script will output a config skeleton") ],
54 [ '--merge-config', '-M', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing, where to merge new/removed photos/videos from --source, and change theme info") ],
55 [ '--merge-config-onedir', '-O', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing, for merging the subdir specified with --dir") ],
56 [ '--merge-config-subdirs', '-U', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing, for merging the new subdirs down the subdir specified with --dir") ],
57 [ '--dir', '-D', GetoptLong::REQUIRED_ARGUMENT, _("Directory for merge with --merge-config-onedir or --merge-config-subdirs") ],
58 [ '--use-config', '-u', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing, where to change theme info") ],
59 [ '--force', '-f', GetoptLong::NO_ARGUMENT, _("Force generation of album even if the GUI marked some directories as already generated") ],
61 [ '--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)") ],
62 [ '--multi-languages', '-L', GetoptLong::REQUIRED_ARGUMENT, _("Specify the list of languages to support (uses Apache MultiViews); this is a comma-separated list of supported languages, with last element used as the fallback language; for example: 'fr,eo,en,en'; supported languages: %s") % SUPPORTED_LANGUAGES.join(', ') ],
63 [ '--thumbnails-per-row', '-T', GetoptLong::REQUIRED_ARGUMENT, _("Specify the amount of thumbnails per row in the thumbnails page (if applicable in theme)") ],
64 [ '--thumbnails-per-page', '-p', GetoptLong::REQUIRED_ARGUMENT, _("Specify the amount of thumbnails per page in the thumbnails page, after which split occurs") ],
65 [ '--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 photos from point-and-shoot cameras - also called compact cameras - is 4/3, whereas photos from SLR cameras - also called reflex cameras - is 3/2)") ],
66 [ '--transcode-videos', '-r', GetoptLong::REQUIRED_ARGUMENT, _("Transcode videos with given external program; %f is the placeholder for the input video, %o for the output video; before the external program, the output video extension should be given followed by a colon") ],
67 [ '--flv-generator', '-F', GetoptLong::REQUIRED_ARGUMENT, _("Use embedded flash player for videos (flowplayer) and use this .flv generator (%f is the placeholder for the input video, %o for the output video)") ],
68 [ '--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)") ],
69 [ '--addthis', '-a', GetoptLong::NO_ARGUMENT, _("Include the 'addthis' bookmarking and sharing button") ],
70 [ '--made-with', '-n', GetoptLong::REQUIRED_ARGUMENT, _("Specify the HTML markup to use on the bottom of pages for a small 'made with' message") ],
71 [ '--quote-html', '-q', GetoptLong::NO_ARGUMENT, _("Quote HTML markup in captions") ],
72 [ '--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") ],
74 [ '--mproc', '-m', GetoptLong::REQUIRED_ARGUMENT, _("Specify the number of processors for multi-processors machines") ],
76 [ '--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)") ],
78 [ '--verbose-level', '-v', GetoptLong::REQUIRED_ARGUMENT, _("Set max verbosity level (0: errors, 1: warnings, 2: important messages, 3: other messages)") ],
79 [ '--info-pipe', '-i', GetoptLong::REQUIRED_ARGUMENT, _("Name a file where to write information about what's going on (used by the GUI)") ],
82 #- default values for some globals
86 $ignore_videos = false
91 puts _("Usage: %s [OPTION]...") % File.basename($0)
93 printf " %3s, %-18s %s\n", ary[1], ary[0], ary[3]
98 parser = GetoptLong.new
99 parser.set_options(*$options.collect { |ary| ary[0..2] })
101 parser.each_option do |name, arg|
108 puts _("Booh version %s
110 Copyright (c) 2005-2009 Guillaume Cottenceau.
111 This is free software; see the source for copying conditions. There is NO
112 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.") % $VERSION
117 $source = File.expand_path(arg.sub(%r|/$|, ''))
118 if !File.directory?($source)
119 die _("Argument to --source must be a directory")
122 $dest = File.expand_path(arg.sub(%r|/$|, ''))
123 if File.exists?($dest) && !File.directory?($dest)
124 die _("If --destination exists, it must be a directory")
126 if $dest != make_dest_filename($dest)
127 die _("Sorry, destination directory can't contain non simple alphanumeric characters.")
130 # system("rm -rf #{$dest}")
135 arg = File.expand_path(arg)
136 if File.readable?(arg)
137 $xmldoc = REXML::Document.new File.new(arg)
140 die _('Config file does not exist or is unreadable.')
143 arg = File.expand_path(arg)
145 if File.directory?(arg)
146 die _("Config skeleton file (%s) already exists and is a directory! Please change the filename.") % arg
148 msg 1, _("Config skeleton file already exists, backuping to %s.backup") % arg
149 File.rename(arg, "#{arg}.backup")
152 $config_writeto = arg
154 when '--merge-config'
155 arg = File.expand_path(arg)
156 if File.readable?(arg)
157 msg 2, _("Merge config notice: backuping current config file to %s.backup") % arg
158 $xmldoc = REXML::Document.new File.new(arg)
159 File.rename(arg, "#{arg}.backup")
160 $config_writeto = arg
161 $mode = 'merge_config'
163 die _('Config file does not exist or is unreadable.')
165 when '--merge-config-onedir'
166 arg = File.expand_path(arg)
167 if File.readable?(arg)
168 msg 2, _("Merge config notice: backuping current config file to %s.backup") % arg
169 $xmldoc = REXML::Document.new File.new(arg)
170 File.rename(arg, "#{arg}.backup")
171 $config_writeto = arg
172 $mode = 'merge_config_onedir'
174 die _('Config file does not exist or is unreadable.')
176 when '--merge-config-subdirs'
177 arg = File.expand_path(arg)
178 if File.readable?(arg)
179 msg 2, _("Merge config notice: backuping current config file to %s.backup") % arg
180 $xmldoc = REXML::Document.new File.new(arg)
181 File.rename(arg, "#{arg}.backup")
182 $config_writeto = arg
183 $mode = 'merge_config_subdirs'
185 die _('Config file does not exist or is unreadable.')
188 arg = File.expand_path(arg)
189 if !File.readable?(arg)
190 die _('Specified directory to merge with --dir is not readable')
195 arg = File.expand_path(arg)
196 if File.readable?(arg)
197 msg 2, _("Use config notice: backuping current config file to %s.backup") % arg
198 $xmldoc = REXML::Document.new File.new(arg)
199 File.rename(arg, "#{arg}.backup")
200 $config_writeto = arg
201 $mode = 'use_config_changetheme'
203 die _('Config file does not exist or is unreadable.')
209 when '--multi-languages'
210 parts = arg.split(',')
211 if parts.size == 0 || parts.find_all { |e| ! SUPPORTED_LANGUAGES.include?(e.strip) }.size > 0
212 die _("--multi-languages: argument must be a comma-separated list of supported languages, with last element used as the fallback language; for example: 'fr,eo,en,en'; supported languages: %s") % SUPPORTED_LANGUAGES.join(', ')
214 $multi_languages = [ parts[0..-2], parts[-1] ]
216 when '--thumbnails-per-row'
219 when '--thumbnails-per-page'
222 when '--optimize-for-32'
223 $optimize_for_32 = true
225 when '--transcode-videos'
226 parts = arg.split(':', 2)
227 if parts.size != 2 || parts[0] =~ / / || arg !~ /%f/ || arg !~ /%o/
228 die _("--transcode-videos: argument must be the external program for transcoding, and contain %f for the input video, %o for the output video, and before the external program, the output video extension should be given followed by a colon")
230 $transcode_videos = arg
232 when '--flv-generator'
233 if arg !~ /%f/ || arg !~ /%o/
234 die _("--flv-generator: argument must contain %f for the input video and %o for the output video")
250 when '--comments-format'
251 $commentsformat = arg
263 when '--verbose-level'
264 $verbose_level = arg.to_i
267 $info_pipe = File.open(arg, File::WRONLY)
268 $info_pipe.sync = true
277 if !$source && $xmldoc
278 $source = from_utf8($xmldoc.root.attributes['source']).sub(%r|/$|, '')
279 $dest = from_utf8($xmldoc.root.attributes['destination']).sub(%r|/$|, '')
280 $theme ||= $xmldoc.root.attributes['theme']
281 $limit_sizes ||= $xmldoc.root.attributes['limit-sizes']
282 if $mode == 'use_config' || $mode =~ /^merge_config/
283 $optimize_for_32 = !$xmldoc.root.attributes['optimize-for-32'].nil?
284 $N_per_row = $xmldoc.root.attributes['thumbnails-per-row']
285 languages = $xmldoc.root.attributes['multi-languages']
287 languages = languages.split(',')
288 $multi_languages = [ languages[0..-2], languages[-1] ]
290 $N_per_page = $xmldoc.root.attributes['thumbnails-per-page']
291 $madewith = $xmldoc.root.attributes['made-with']
292 $indexlink = $xmldoc.root.attributes['index-link']
293 $addthis = !$xmldoc.root.attributes['addthis'].nil?
294 $quote_html = !$xmldoc.root.attributes['quote-html'].nil?
298 if $mode == 'merge_config_onedir' && !$onedir
299 die _("Missing --dir for --merge-config-onedir")
301 if $mode == 'merge_config_subdirs' && !$onedir
302 die _("Missing --dir for --merge-config-subdirs")
310 die _("Missing --destination parameter.")
316 select_theme($theme, $limit_sizes, $optimize_for_32, $N_per_row)
319 $xmldoc = Document.new "<booh/>"
320 $xmldoc << XMLDecl.new(XMLDecl::DEFAULT_VERSION, $CURRENT_CHARSET)
321 $xmldoc.root.add_attribute('version', $VERSION)
322 $xmldoc.root.add_attribute('source', $source)
323 $xmldoc.root.add_attribute('destination', $dest)
324 $xmldoc.root.add_attribute('theme', $theme)
326 $xmldoc.root.add_attribute('limit-sizes', $limit_sizes)
329 $xmldoc.root.add_attribute('multi-languages', $multi_languages[0].join(',') + ',' + $multi_languages[1])
332 $xmldoc.root.add_attribute('optimize-for-32', 'true')
335 $xmldoc.root.add_attribute('thumbnails-per-row', $N_per_row)
338 $xmldoc.root.add_attribute('thumbnails-per-page', $N_per_page)
341 $xmldoc.root.add_attribute('made-with', $madewith)
344 $xmldoc.root.add_attribute('index-link', $indexlink)
347 $xmldoc.root.add_attribute('addthis', 'true')
350 $xmldoc.root.add_attribute('quote-html', 'true')
355 if $mode == 'merge_config' || $mode == 'use_config_changetheme'
356 $xmldoc.root.add_attribute('theme', $theme)
357 $xmldoc.root.add_attribute('version', $VERSION)
359 $xmldoc.root.add_attribute('limit-sizes', $limit_sizes)
361 $xmldoc.root.delete_attribute('limit-sizes')
364 $xmldoc.root.add_attribute('multi-languages', $multi_languages[0].join(',') + ',' + $multi_languages[1])
366 $xmldoc.root.delete_attribute('multi-languages')
370 $xmldoc.root.add_attribute('optimize-for-32', 'true')
372 $xmldoc.root.delete_attribute('optimize-for-32')
375 $xmldoc.root.add_attribute('thumbnails-per-row', $N_per_row)
377 $xmldoc.root.delete_attribute('thumbnails-per-row')
380 $xmldoc.root.add_attribute('thumbnails-per-page', $N_per_page)
382 $xmldoc.root.delete_attribute('thumbnails-per-page')
385 $xmldoc.root.add_attribute('made-with', $madewith)
387 $xmldoc.root.delete_attribute('made-with')
390 $xmldoc.root.add_attribute('index-link', $indexlink)
392 $xmldoc.root.delete_attribute('index-link')
395 $xmldoc.root.add_attribute('addthis', 'true')
397 $xmldoc.root.delete_attribute('addthis')
400 $xmldoc.root.add_attribute('quote-html', 'true')
402 $xmldoc.root.delete_attribute('quote-html')
407 $xmldoc.root.add_attribute('transcode-videos', $transcode_videos)
409 $xmldoc.root.delete_attribute('transcode-videos')
413 $xmldoc.root.add_attribute('flv-generator', $flv_generator)
415 $xmldoc.root.delete_attribute('flv-generator')
419 $madewith = $madewith.gsub('%booh', '"http://booh.org/"')
424 $htmlsuffix = '.html'
437 $info_pipe.puts(value)
443 $info_pipe.puts("die: " + value)
448 def check_installation
449 if !system("which convert >/dev/null 2>/dev/null")
450 die _("The program 'convert' is needed. Please install it.
451 It is generally available with the 'ImageMagick' software package.")
453 if !system("which identify >/dev/null 2>/dev/null")
454 msg 1, _("the program 'identify' is needed to get images sizes and EXIF data. Please install it.
455 It is generally available with the 'ImageMagick' software package.")
458 missing = %w(mplayer).delete_if { |prg| system("which #{prg} >/dev/null 2>/dev/null") }
460 msg 1, _("the following program(s) are needed to handle videos: '%s'. Videos will be ignored.") % missing.join(', ')
461 $ignore_videos = true
465 def replace_line(surround, keyword, line)
467 contents = eval "$#{keyword}"
468 line.sub!(/#{surround}#{keyword}#{surround}/, contents)
470 die _("No '%s' found for substitution") % keyword
474 def build_html_skeletons
475 $html_images = File.open("#{$themedir}/skeleton_image.html").readlines
476 $html_thumbnails = File.open("#{$themedir}/skeleton_thumbnails.html").readlines
477 $html_index = File.open("#{$themedir}/skeleton_index.html").readlines
478 for line in $html_images + $html_thumbnails + $html_index
479 while line =~ /~~~(\w+)~~~/
480 replace_line('~~~', $1, line)
485 def find_caption_value(xmldir, filename)
486 if cap = xmldir.elements["*[@filename='#{utf8(filename)}']"].attributes['caption']
493 def quote_caption(input, *for_attribute)
495 return input.gsub('<', '<').gsub('>', '>').gsub('"', '"').gsub("'", ''').gsub("\n", '<br/>')
496 elsif for_attribute[0]
497 return input.gsub('"', '"').gsub("\n", '<br/>')
499 return input.gsub("\n", '<br/>')
503 #- stolen from CVSspam
505 text.sub(/[^a-zA-Z0-9\-,.*_\/]/) do
506 "%#{sprintf('%2X', $&[0])}"
511 return $limit_sizes =~ /original/ ? $images_size + [ { 'name' => 'original' } ] : $images_size
514 def html_reload_to_thumbnails
515 html_reload_to_thumbnails = $preferred_size_reloader.clone
516 html_reload_to_thumbnails.gsub!(/~~theme~~/, $theme)
517 html_reload_to_thumbnails.gsub!(/~~default_size~~/, size2js($default_size['name']))
518 html_reload_to_thumbnails.gsub!(/~~htmlsuffix~~/, $htmlsuffix)
519 html_reload_to_thumbnails.gsub!(/~~all_sizes~~/, all_images_sizes.collect { |s| "\"#{size2js(s['name'])}\"" }.join(', '))
520 size_auto_chooser = '';
521 all_images_sizes.find_all { |s| s.has_key?('optimizedforwidth') }.
522 sort { |a,b| b['optimizedforwidth'].to_i <=> a['optimizedforwidth'].to_i }.
523 each { |s| size_auto_chooser += "if (w + 50 > #{s['optimizedforwidth']}) { return 'thumbnails-#{size2js(s['name'])}-0#{$htmlsuffix}'; }\n" }
524 html_reload_to_thumbnails.gsub!(/~~size_auto_chooser~~/, size_auto_chooser)
525 return html_reload_to_thumbnails
528 def discover_iterations(iterations, line)
529 if line =~ /~~iterate(\d)_open(_max(\d+|N))?~~/
530 for iter in iterations.values
533 iter['close_wait'] = $1.to_i
536 max = $3 == 'N' ? ($N_per_row || $default_N) : $3
537 iterations[$1.to_i] = { 'open' => true, 'max' => max, 'opening' => '', 'closing' => '' }
539 line.sub!(/.*/, '~~thumbnails~~')
543 elsif line =~ /~~iterate(\d)_close~~/
544 iterations[$1.to_i]['open'] = false;
545 iterations[$1.to_i]['close'] = true;
548 for iter in iterations.values
550 iter['opening'] += line
553 if !iter['close'] && iter['close_wait'] && iterations[iter['close_wait']]['close']
554 iter['closing'] += line
561 def reset_iterations(iterations)
562 for iter in iterations.values
567 def run_iterations(iterations, amount)
570 for level in iterations.keys.sort
571 if iterations[level]['value'] == 0
572 html += iterations[level]['opening']
573 elsif level == iterations.keys.max
574 if !iterations[level]['max'] || iterations[level]['max'] && iterations[level]['value'] + amount <= iterations[level]['max'].to_i
575 html += iterations[level]['opening']
580 iterations[level]['value'] += amount
581 if iterations[level]['max'] && iterations[level]['value'] > iterations[level]['max'].to_i
582 iterations[level]['value'] = 0
583 iterations[level-1]['value'] = 0
584 html += iterations[level-1]['closing']
588 return html + run_iterations(iterations, amount)
594 def close_iterations(iterations)
596 for level in iterations.keys.sort.reverse
597 html += iterations[level]['closing']
602 def img_element(fullpath, caption)
603 if size = get_image_size(fullpath)
604 sizespec = 'width="' + size[:x].to_s + '" height="' + size[:y].to_s + '"'
608 return '<img src="' + File.basename(fullpath) + '" ' + sizespec + ' alt="' + quote_caption(caption, true) + '"/>'
612 return name.gsub(/-/, '')
615 def substitute_html_sizes(html, sizeobj, type, suffix)
617 if $images_size.length > 1 || (type == 'image' && $limit_sizes =~ /original/)
618 for sizeobj2 in $images_size
619 sizejs = size2js(sizeobj2['name'])
620 sizen = defer_translation(sizename(sizeobj2['name'], false))
621 if sizeobj != sizeobj2
622 if type == 'thumbnails'
623 sizestrings << '<a href="thumbnails-' + sizejs + suffix + $htmlsuffix + '" onclick="set_preferred_size(\'' + sizejs + '\')">' + sizen + '</a>'
625 sizestrings << '<a id="link' + sizejs + '" onclick="set_preferred_size(\'' + sizejs + '\')">' + sizen + '</a>'
631 if type == 'image' && $limit_sizes =~ /original/
632 sizestrings << '<a id="linkoriginal" target="newframe">' + defer_translation(sizename('original', false)) + '</a>'
635 html.sub!(/~~sizes~~(.+)~~/) { sizestrings.join($1) }
638 def substitute_navigation(html, xmldir)
639 if xmldir.parent.name == 'dir'
642 parent = xmldir.parent
643 while parent.name == 'dir'
644 parentcaption = parent.attributes['subdirs-caption'] || File.basename(parent.attributes['path'])
645 nav = "<a href=\"#{path}/index#{$htmlsuffix}\">#{parentcaption}</a> #{defer_translation(N_(" > "))} #{nav}"
647 parent = parent.parent
649 html.gsub!(/~~ifnavigation\?~~(.+?)~~fi~~/) { $1 }
650 html.gsub!(/~~navigation~~/, nav + (xmldir.attributes['subdirs-caption'] || File.basename(xmldir.attributes['path'])))
652 html.gsub!(/~~ifnavigation\?~~(.+?)~~fi~~/, '')
656 def substitute_addthis(html)
657 html.gsub!(/~~addthis~~/, $addthis ? '<a class="addthis_button" href="http://www.addthis.com/bookmark.php?v=250"><img src="http://s7.addthis.com/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="' + defer_translation(N_("Bookmark and Share")) + '" style="border:0"/></a><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js"></script>' : '')
660 def substitute_pathtobase(html, xmldir)
663 while location.parent.name == 'dir'
665 location = location.parent
667 html.gsub!(/~~pathtobase~~/, path)
670 def xmldir2destdir(xmldir)
671 return make_dest_filename(from_utf8(File.basename(xmldir.attributes['path'])))
674 def find_previous_album(xmldir)
677 #- move to previous dir element if exists
678 if prevelem = xmldir.previous_element_byname_notattr('dir', 'deleted')
680 relative_pos += '../' + xmldir2destdir(xmldir) + '/'
682 #- after having moved to previous dir, we need to go down last subdir until the last one
683 while child = xmldir.elements['dir']
684 while nextchild = child.next_element_byname_notattr('dir', 'deleted')
687 relative_pos += xmldir2destdir(child) + '/'
691 #- previous dir doesn't exist, move to previous dir element if exists
692 xmldir = xmldir.parent
693 if xmldir.name == 'dir' && !xmldir.attributes['deleted']
694 relative_pos += '../'
699 end while !xmldir.child_byname_notattr('image', 'deleted') && !xmldir.child_byname_notattr('video', 'deleted')
700 return File.reduce_path(relative_pos)
703 def find_next_album(xmldir)
706 #- first child dir element (catches when initial xmldir has both thumbnails and subdirs)
707 if firstchild = xmldir.child_byname_notattr('dir', 'deleted')
709 relative_pos += xmldir2destdir(xmldir) + '/'
711 elsif nextbro = xmldir.next_element_byname_notattr('dir', 'deleted')
713 relative_pos += '../' + xmldir2destdir(xmldir) + '/'
715 #- go up until we have a next brother or we are finished
717 xmldir = xmldir.parent
718 relative_pos += '../'
719 end while xmldir && !xmldir.next_element_byname_notattr('dir', 'deleted')
721 xmldir = xmldir.next_element_byname('dir')
722 relative_pos += '../' + xmldir2destdir(xmldir) + '/'
727 end while !xmldir.child_byname_notattr('image', 'deleted') && !xmldir.child_byname_notattr('video', 'deleted')
728 return File.reduce_path(relative_pos)
731 def find_translation_for_file(file, msg)
733 if file =~ /\.(\w\w)\.html$/
734 bindtextdomain("booh", { :locale => "#{$1}.UTF-8" })
736 Locale.set_current($default_locale)
739 die "Internal error: cannot find multi language suffix of file '#{file}'"
746 def sub_previous_next_album(file, previous_album, next_album, html, previous_album_msg, next_album_msg)
748 html.gsub!(/~~previous_album~~/, '<a href="' + previous_album + 'thumbnails' + $htmlsuffix + '">' + previous_album_msg + '</a>')
749 html.gsub!(/~~ifprevious_album\?~~(.+?)~~fi~~/) { $1 }
751 html.gsub!(/~~previous_album~~/, '')
752 html.gsub!(/~~ifprevious_album\?~~(.+?)~~fi~~/, '')
755 html.gsub!(/~~next_album~~/, '<a href="' + next_album + 'thumbnails' + $htmlsuffix + '">' + next_album_msg + '</a>')
756 html.gsub!(/~~ifnext_album\?~~(.+?)~~fi~~/) { $1 }
758 html.gsub!(/~~next_album~~/, '')
759 html.gsub!(/~~ifnext_album\?~~(.+?)~~fi~~/, '')
764 def save_html(html, base_filename)
765 if html.class == Array
769 for language in ($multi_languages[0] + [ $multi_languages[1] ]).uniq
770 bindtextdomain("booh", { :locale => "#{language}.UTF-8" })
771 ios = File.open("#{base_filename}.#{language}.html", "w")
772 ios.write(html.gsub(/@@(.*?)@@/) { _($1) })
774 Locale.set_current($default_locale)
777 ios = File.open("#{base_filename}.html", "w")
778 ios.write(html.gsub(/@@(.*?)@@/) { utf8(_($1)) })
783 def apply_hook(name, content, *params)
791 return hook.call(content, *params)
797 #- preprocess the path->dir, rexml is very slow with that; we seem to improve speed by 7%
799 $xmldoc.elements.each('//dir') { |elem|
800 optxpath[elem.attributes['path']] = elem
804 if $mode == 'merge_config_onedir'
805 examined_dirs = [ $onedir ]
806 elsif $mode == 'merge_config_subdirs'
807 examined_dirs = `find '#{$onedir}' -type d -follow`.sort.collect { |v| v.chomp }.delete_if { |v| optxpath.has_key?(utf8(v)) }
809 examined_dirs = `find '#{$source}' -type d -follow`.sort.collect { |v| v.chomp }
810 if $mode == 'merge_config'
811 $xmldoc.elements.each('//dir') { |elem|
812 if ! examined_dirs.include?(elem.attributes['path'])
813 msg 2, _("Merging config: removing directory %s from config, isn't on filesystem anymore") % elem.attributes['path']
819 info("directories: #{examined_dirs.length}, sizes: #{$images_size.length}")
821 examined_dirs.each { |dir|
823 die _("Source directory or sub-directories can't contain a single-quote character, sorry: %s") % dir
825 if $mode !~ /^use_config/
826 Dir.entries(dir).each { |file|
827 if file =~ /['"\[\]]/
828 die _("Files can't contain any of the characters ', \", [ or ], sorry: %s") % "#{dir}/#{file}"
834 examined_dirs.each { |dir|
835 if File.basename(dir) =~ /^\./
836 msg 1, _("Ignoring directory %s, begins with a dot (indicating a hidden directory)") % dir
840 dest_dir = make_dest_filename(dir.sub(/^#{Regexp.quote($source)}/, $dest))
842 #- place xml document on proper node if exists, else create
843 xmldir = optxpath[utf8(dir)]
844 if $mode == 'use_config' || $mode == 'use_config_changetheme'
845 if !xmldir || (xmldir.attributes['already-generated'] && !$force) || xmldir.attributes['deleted']
846 info("walking: #{dir}|#{$source}, 0 elements")
847 if xmldir && xmldir.attributes['deleted']
848 system("rm -rf '#{dest_dir}'")
853 if $mode == 'gen_config' || (($mode == 'merge_config' || $mode == 'merge_config_subdirs') && !xmldir)
854 #- add the <dir..> element if necessary
855 parent = File.dirname(dir)
856 xmldir = $xmldoc.elements["//dir[@path='#{utf8(parent)}']"]
858 xmldir = $xmldoc.root
860 #- need to remove the already-generated mark of the parent because of the sub-albums page containing now one more element
861 xmldir.delete_attribute('already-generated')
862 xmldir = optxpath[utf8(dir)] = xmldir.add_element('dir', { 'path' => utf8(dir) })
865 xmldir.delete_attribute('already-generated')
867 #- preprocess all the existing elements, rexml is slow with that
869 xmldir.elements.each { |elem|
870 if filename = elem.attributes['filename']
871 optelements[elem.name + '|' + filename] = elem
875 #- read images/videos entries from config or from directories depending on mode
877 if $mode == 'use_config' || $mode == 'use_config_changetheme'
878 msg 2, _("Handling %s from config list...") % dir
879 xmldir.elements.each { |element|
880 if %w(image video).include?(element.name) && !element.attributes['deleted']
881 entries << from_utf8(element.attributes['filename'])
885 msg 2, _("Examining %s...") % dir
886 entries = Dir.entries(dir).sort
887 #- populate config in case of gen_config, add new files in case of merge_config
889 if file =~ /['"\[\]]/
890 msg 1, _("Ignoring %s, contains one of forbidden characters: '\"[]") % "#{dir}/#{file}"
892 type = entry2type(file)
893 if type && ! optelements[type + '|' + utf8(file)]
894 #- hack: don't run identify (which is slow) if format only contains default %t
895 if $commentsformat && type == 'image' && $commentsformat != '%t'
896 comment = utf8(`identify -format "#{$commentsformat}" '#{dir}/#{file}'`.chomp.sub(/\.$/, ''))
898 comment = utf8cut(file.sub(/\.[^\.]+$/, ''), 18)
900 optelements[type + '|' + utf8(file)] = xmldir.add_element(type, { "filename" => utf8(file), "caption" => comment })
904 if $mode != 'gen_config'
905 #- cleanup removed files from config and reread entries from config to get proper ordering
907 xmldir.elements.each { |element|
908 fullpath = "#{dir}/#{from_utf8(element.attributes['filename'])}"
909 if %w(image video).include?(element.name)
910 if !File.readable?(fullpath)
911 msg 1, _("Config merge: removing %s from config; use the backup file to retrieve caption info if this was a mistake") % fullpath
912 xmldir.delete(element)
913 elsif !element.attributes['deleted']
914 entries << from_utf8(element.attributes['filename'])
918 #- if there is no more elements here, there is no album here anymore
919 if !xmldir.child_byname_notattr('image', 'deleted') && !xmldir.child_byname_notattr('video', 'deleted')
920 xmldir.delete_attribute('thumbnails-caption')
921 xmldir.delete_attribute('thumbnails-captionfile')
925 images = entries.find_all { |e| entry2type(e) == 'image' }
926 msg 3, _("\t%s photos") % images.length
927 videos = entries.find_all { |e| entry2type(e) == 'video' }
928 msg 3, _("\t%s videos") % videos.length
929 info("walking: #{dir}|#{$source}, #{images.length + videos.length} elements")
931 system("mkdir -p '#{dest_dir}'")
933 #- generate .htaccess file
935 ios = File.open("#{dest_dir}/.htaccess", "w")
936 ios.write("AddCharset UTF-8 .html\n")
937 if auth_user_file = xmldir.attributes['password-protect']
938 msg 3, _("\tgenerating password protection file #{dest_dir}/.htaccess")
939 ios.write("AuthType Basic\nAuthName \"protected area\"\nAuthUserFile #{auth_user_file}\nrequire valid-user\n")
942 ios.write("Options +Multiviews\n")
943 ios.write("LanguagePriority #{$multi_languages[1]}\n")
944 ios.write("ForceLanguagePriority Prefer Fallback\n")
945 ios.write("DirectoryIndex index\n")
950 #- pass through if there are no images and videos
951 if images.size == 0 && videos.size == 0
953 #- cleanup old images/videos, especially if this directory contained images/videos previously.
954 if $mode != 'gen_config'
955 rightful_images = [ '.htaccess' ]
956 if xmldir.attributes['thumbnails-caption']
957 rightful_images << 'thumbnails-thumbnail.jpg'
959 xmldir.elements.each('dir') { |child|
960 if child.attributes['deleted']
963 subdir = make_dest_filename(from_utf8(File.basename(child.attributes['path'])))
964 rightful_images << "thumbnails-#{subdir}.jpg"
966 to_del = Dir.entries(dest_dir).find_all { |e| !File.directory?(File.join(dest_dir, e)) && !rightful_images.include?(e) }
968 File.delete(*to_del.collect { |e| File.join(dest_dir, e) })
972 #- copy any resource file that goes with the theme (css, images..)
973 themestuff = Dir.entries("#{$themedir}").
974 find_all { |e| !%w(. .. skeleton_image.html skeleton_thumbnails.html skeleton_index.html metadata root).include?(e) }
975 themestuff.each { |entry|
976 if !File.exists?(File.join(dest_dir, entry))
977 psys("cp '#{$themedir}/#{entry}' '#{dest_dir}'")
981 #- copy any root-only resource file that goes with the theme (css, images..)
982 if xmldir.parent.name != 'dir'
983 themestuff_root = Dir.entries("#{$themedir}/root").
984 find_all { |e| !%w(. ..).include?(e) }
985 themestuff_root.each { |entry|
986 if !File.exists?(File.join(dest_dir, entry))
987 psys("cp '#{$themedir}/root/#{entry}' '#{dest_dir}'")
990 #- copy flowplayer stuff if needed
992 psys("cp #{$FPATH}/flowplayer/flowplayer* '#{dest_dir}'")
999 msg 2, _("Outputting in %s...") % dest_dir
1001 #- populate data structure with sizes from theme
1002 for sizeobj in $images_size
1003 fullscreen_images ||= {}
1004 fullscreen_images[sizeobj['name']] = []
1005 thumbnail_images ||= {}
1006 thumbnail_images[sizeobj['name']] = []
1007 fullscreen_videos ||= {}
1008 fullscreen_videos[sizeobj['name']] = []
1009 thumbnail_videos ||= {}
1010 thumbnail_videos[sizeobj['name']] = []
1012 #- a special dummy size to keep 'references' to thumbnails in case of panorama, because the GUI will use the regular thumbnails
1013 thumbnail_images['dont-delete-file-for-gui'] = []
1014 if $limit_sizes =~ /original/
1015 fullscreen_images['original'] = []
1016 fullscreen_videos['original'] = []
1019 images.size >= 1 and msg 3, _("\tcreating photos thumbnails...")
1021 #- create thumbnails for images
1023 info("processing element")
1024 base_dest_img = dest_dir + '/' + make_dest_filename(img.sub(/\.[^\.]+$/, ''))
1025 elem = optelements['image|' + utf8(img)]
1027 thumbnail_dest_img = base_dest_img + "-#{$default_size['thumbnails']}.jpg"
1028 gen_thumbnails_element("#{dir}/#{img}", elem, true, [ { 'filename' => thumbnail_dest_img, 'size' => $default_size['thumbnails'] } ])
1031 for sizeobj in $images_size
1032 size_fullscreen = sizeobj['fullscreen']
1033 size_thumbnails = sizeobj['thumbnails']
1034 fullscreen_dest_img = base_dest_img + "-#{size_fullscreen}.jpg"
1035 fullscreen_images[sizeobj['name']] << File.basename(fullscreen_dest_img)
1036 todo << { 'filename' => fullscreen_dest_img, 'size' => size_fullscreen }
1037 if pano = pano_amount(elem)
1038 thumbnail_images['dont-delete-file-for-gui'] << File.basename(base_dest_img + "-#{size_thumbnails}.jpg")
1039 size_thumbnails = size_thumbnails.sub(/(\d+)/) { ($1.to_i * pano).to_i }
1041 thumbnail_dest_img = base_dest_img + "-#{size_thumbnails}.jpg"
1042 thumbnail_images[sizeobj['name']] << File.basename(thumbnail_dest_img)
1043 todo << { 'filename' => thumbnail_dest_img, 'size' => size_thumbnails }
1045 gen_thumbnails_element("#{dir}/#{img}", elem, true, todo)
1046 if $limit_sizes =~ /original/
1047 fullscreen_images['original'] << img
1049 destimg = "#{dest_dir}/#{img}"
1050 if $limit_sizes =~ /original/ && !File.exists?(destimg)
1052 if ! sys("ln '#{dir}/#{img}' '#{destimg}'")
1053 $hardlinks_ok = false
1057 psys("cp '#{dir}/#{img}' '#{destimg}'")
1063 videos.size >= 1 and msg 3, _("\tcreating videos thumbnails...")
1064 transcoded_videos = {}
1067 #- create thumbnails for videos
1068 videos.each { |video|
1069 info("processing element")
1070 base_dest_img = dest_dir + '/' + make_dest_filename(video.sub(/\.[^\.]+$/, ''))
1071 elem = optelements['video|' + utf8(video)]
1073 thumbnail_dest_img = base_dest_img + "-#{$default_size['thumbnails']}.jpg"
1074 gen_thumbnails_element("#{dir}/#{video}", elem, true, [ { 'filename' => thumbnail_dest_img, 'size' => $default_size['thumbnails'] } ])
1077 for sizeobj in $images_size
1078 size_fullscreen = sizeobj['fullscreen']
1079 size_thumbnails = sizeobj['thumbnails']
1080 fullscreen_dest_img = base_dest_img + "-#{size_fullscreen}.jpg"
1081 fullscreen_videos[sizeobj['name']] << File.basename(fullscreen_dest_img)
1082 todo << { 'filename' => fullscreen_dest_img, 'size' => size_fullscreen }
1083 thumbnail_dest_img = base_dest_img + "-#{size_thumbnails}.jpg"
1084 thumbnail_videos[sizeobj['name']] << File.basename(thumbnail_dest_img)
1085 todo << { 'filename' => thumbnail_dest_img, 'size' => size_thumbnails }
1087 gen_thumbnails_element("#{dir}/#{video}", elem, true, todo)
1089 if $transcode_videos
1090 parts = $transcode_videos.split(':', 2)
1091 basedestvideo = video.sub(/\.\w+/, '') + '.' + parts[0]
1092 transcoded_videos[video] = basedestvideo
1093 destvideo = "#{dest_dir}/#{basedestvideo}"
1094 if ! File.exists?(destvideo)
1095 psys(parts[1].gsub(/%f/, "'#{dir}/#{video}'").gsub(/%o/, "'#{destvideo}'"))
1098 elsif $flv_generator
1099 basedestvideo = video.sub(/\.\w+/, '') + '.flv'
1100 flv_videos[video] = basedestvideo
1101 destvideo = "#{dest_dir}/#{basedestvideo}"
1102 if File.exists?(destvideo) && File.size(destvideo) == 0
1103 File.delete(destvideo)
1105 if ! File.exists?(destvideo)
1106 psys($flv_generator.gsub(/%f/, "'#{dir}/#{video}'").gsub(/%o/, "'#{destvideo}'"))
1110 destvideo = "#{dest_dir}/#{video}"
1111 if ! File.exists?(destvideo)
1113 if ! sys("ln '#{dir}/#{video}' '#{destvideo}'")
1114 $hardlinks_ok = false
1118 psys("cp '#{dir}/#{video}' '#{destvideo}'")
1126 #- cleanup old images/videos (for when removing elements or sizes)
1127 all_elements = fullscreen_images.collect { |e| e[1] }.flatten.
1128 concat(thumbnail_images.collect { |e| e[1] }.flatten).
1129 concat(fullscreen_videos.collect { |e| e[1] }.flatten).
1130 concat(thumbnail_videos.collect { |e| e[1] }.flatten).
1131 concat($transcode_videos ? transcoded_videos.values : $flv_generator ? flv_videos.values : videos).
1133 to_del = Dir.entries(dest_dir).find_all { |e| !File.directory?(File.join(dest_dir, e)) && !all_elements.include?(e) && e !~ /^thumbnails-\w+\.jpg/ }
1135 msg 3, _("\tcleaning up: #{to_del.join(', ')}")
1136 File.delete(*to_del.collect { |e| File.join(dest_dir, e) })
1139 #- copy any resource file that goes with the theme (css, images..)
1140 themestuff = Dir.entries("#{$themedir}").
1141 find_all { |e| !%w(. .. skeleton_image.html skeleton_thumbnails.html skeleton_index.html metadata root).include?(e) }
1142 themestuff.each { |entry|
1143 if !File.exists?(File.join(dest_dir, entry))
1144 psys("cp '#{$themedir}/#{entry}' '#{dest_dir}'")
1148 #- copy any root-only resource file that goes with the theme (css, images..)
1149 if xmldir.parent.name != 'dir'
1150 themestuff_root = Dir.entries("#{$themedir}/root").
1151 find_all { |e| !%w(. ..).include?(e) }
1152 themestuff_root.each { |entry|
1153 if !File.exists?(File.join(dest_dir, entry))
1154 psys("cp '#{$themedir}/root/#{entry}' '#{dest_dir}'")
1157 #- copy flowplayer stuff if needed
1159 psys("cp #{$FPATH}/flowplayer/flowplayer* '#{dest_dir}'")
1163 msg 3, _("\tgenerating HTML pages...")
1164 #- fixup max per page
1166 $N_per_page = $N_per_page.to_i / ($N_per_row || $default_N).to_i * ($N_per_row || $default_N).to_i
1169 #- generate thumbnails*.html (page with thumbnails)
1170 element2thumbnailpage4js = []
1171 for sizeobj in $images_size
1172 info("processing size")
1173 html = $html_thumbnails.collect { |l| l.clone }
1176 i.sub!(/~~title~~/, quote_caption(xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir))))
1177 i.sub!(/~~flowplayer_head_code~~/, ($flv_generator && videos.size > 0) ? '<script type="text/javascript" src="~~pathtobase~~flowplayer-3.1.4.min.js"></script>' : '')
1178 discover_iterations(iterations, i)
1181 html_thumbnails = ''
1182 html_thumbnails_nojs = ''
1185 reset_iterations(iterations)
1186 #- preprocess the @filename->elem, rexml is very slow with that; we dramatically improve this part of the processing
1188 xmldir.elements.each('image') { |elem|
1189 optfilename[elem.attributes['filename']] = elem
1192 type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
1194 homogeinize_width = 100 / ($N_per_row || $default_N).to_i
1195 if type == 'image' && elem = optfilename[utf8(file)]
1196 if pano = pano_amount(elem)
1197 html_elem = run_iterations(iterations, pano)
1198 counter += count = pano.ceil
1199 html_elem.gsub!(/~~colspan~~/) { "colspan=\"#{count}\"" }
1200 homogeinize_width *= count
1202 html_elem = run_iterations(iterations, 1)
1204 html_elem.gsub!(/~~colspan~~/, '')
1207 html_elem = run_iterations(iterations, 1)
1209 html_elem.gsub!(/~~colspan~~/, '')
1211 html_elem.gsub!(/~~homogeinize_width~~/) { "width=\"#{homogeinize_width}%\"" }
1213 index = images.index(file)
1214 caption = find_caption_value(xmldir, images[index]) || utf8(images[index])
1215 html_elem.gsub!(/~~caption_iteration~~/, quote_caption(caption))
1216 html_elem.gsub!(/~~ifimage\?~~(.+?)~~fi~~/) { $1 }
1217 html_elem.gsub!(/~~ifvideo\?~~(.+?)~~fi~~/, '')
1218 elsif type == 'video'
1219 index = videos.index(file)
1220 caption = find_caption_value(xmldir, videos[index]) || utf8(videos[index])
1221 if File.exists?("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}")
1222 video_preview = '<div class="thumbnail_video">' + img_element("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}", caption) + '</div>'
1224 video_preview = defer_translation(N_("(no preview)"))
1227 size = get_image_size("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}")
1229 sizeobj['thumbnails'] =~ /(\d+)x(\d+)/
1230 size = { :x => $1, :y => $2 }
1232 sizespec = 'width:' + size[:x].to_s + 'px;height:' + (size[:y] + 24).to_s + 'px'
1233 image_iteration = '<a href="' + flv_videos[videos[index]] + '" style="display:block;' + sizespec + '"' +
1234 ' id="player' + index.to_s + '">' + video_preview +
1235 '<img src="~~pathtobase~~play_video.png" style="position:relative;top:-' + ((size[:y]+48)/2).to_s + 'px;border:0;background-color:transparent"/></a>' +
1236 '<script>flowplayer("player' + index.to_s + '", "~~pathtobase~~flowplayer-3.1.5.swf")</script>'
1237 html_elem.gsub!(/~~image_iteration~~/, apply_hook(:image_iteration, image_iteration, 'video'))
1239 html_elem.gsub!(/~~image_iteration~~/,
1240 '<a href="' + ( $transcode_videos ? transcoded_videos[videos[index]] : videos[index] ) + '">' +
1241 video_preview + '</a>')
1243 html_elem.gsub!(/~~caption_iteration~~/, quote_caption(caption))
1244 html_elem.gsub!(/~~ifimage\?~~(.+?)~~fi~~/, '')
1245 html_elem.gsub!(/~~ifvideo\?~~(.+?)~~fi~~/) { $1 }
1247 html_thumbnails += html_elem
1248 html_thumbnails_nojs += html_elem
1250 img_preview = '<div class="thumbnail_image">' + img_element("#{dest_dir}/#{thumbnail_images[sizeobj['name']][index]}", caption) + '</div>'
1251 html_thumbnails.gsub!(/~~image_iteration~~/,
1252 '<a href="image-' + size2js(sizeobj['name']) + $htmlsuffix + '#current=' + fullscreen_images[sizeobj['name']][index] +
1253 '" name="' + fullscreen_images[sizeobj['name']][index] + '">' + img_preview + '</a>')
1254 html_thumbnails_nojs.gsub!(/~~image_iteration~~/,
1255 '<a href="' + fullscreen_images[sizeobj['name']][index] + '" name="' + fullscreen_images[sizeobj['name']][index] + '">' +
1256 img_preview + '</a>')
1258 #- remember in which thumbnails page is this element, for element->thumbnail link
1259 if sizeobj == $images_size[0]
1260 element2thumbnailpage4js << pagecount
1263 if counter == $N_per_page
1264 html_thumbnails += close_iterations(iterations)
1265 html_thumbnails_nojs += close_iterations(iterations)
1266 all_pages << [ html_thumbnails, html_thumbnails_nojs ]
1267 html_thumbnails = ''
1268 html_thumbnails_nojs = ''
1270 reset_iterations(iterations)
1276 html_thumbnails += close_iterations(iterations)
1277 html_thumbnails_nojs += close_iterations(iterations)
1278 all_pages << [ html_thumbnails, html_thumbnails_nojs ]
1281 i.gsub!(/~~theme~~/, $theme)
1282 i.gsub!(/~~current_size~~/, sizeobj['name'])
1283 i.gsub!(/~~htmlsuffix~~/, $htmlsuffix)
1284 i.gsub!(/~~current_size_js~~/, size2js(sizeobj['name']))
1285 i.gsub!(/~~madewith~~/, $madewith || '')
1286 i.gsub!(/~~indexlink~~/, $indexlink || '')
1287 substitute_addthis(i)
1288 substitute_navigation(i, xmldir)
1290 html_nojs = html.collect { |l| l.clone }
1292 for page in all_pages
1293 html_thumbnails, html_thumbnails_nojs = page
1294 final_html = html.collect { |l| l.clone }
1295 mstuff = defer_translation(N_("Pages: ")) +
1296 (pagecount > 0 ? "<a href=\"thumbnails-#{size2js(sizeobj['name'])}%nojs-#{pagecount - 1}#{$htmlsuffix}\">" + defer_translation(N_("<- Previous")) + "</a> " : '') +
1297 all_pages.collect_with_index { |p,idx| page == p ? idx + 1 : "<a href=\"thumbnails-#{size2js(sizeobj['name'])}%nojs-#{idx}#{$htmlsuffix}\">#{idx + 1}</a>" }.join(', ') +
1298 (pagecount < all_pages.size - 1 ? " <a href=\"thumbnails-#{size2js(sizeobj['name'])}%nojs-#{pagecount + 1}#{$htmlsuffix}\">" + defer_translation(N_("Next ->")) + "</a> " : '')
1300 i.sub!(/~~run_slideshow~~/,
1301 entries.size <= 1 ? '' : '<a href="image-' + size2js(sizeobj['name']) + $htmlsuffix + '#run_slideshow=1">' + defer_translation(N_("Run slideshow!"))+'</a>')
1302 i.sub!(/~~thumbnails~~/, html_thumbnails)
1303 if all_pages.size == 1
1304 i.gsub!(/~~ifmultiplepages\?~~.*~~fi~~/, '')
1306 i.gsub!(/~~ifmultiplepages\?~~(.+?)~~fi~~/) { $1 }
1307 i.gsub!(/~~multiplepagesstuff~~/, mstuff.gsub('%nojs', ''))
1309 substitute_html_sizes(i, sizeobj, 'thumbnails', "-#{pagecount}")
1310 substitute_pathtobase(i, xmldir)
1312 save_html(final_html, "#{dest_dir}/thumbnails-#{size2js(sizeobj['name'])}-#{pagecount}")
1313 final_html_nojs = html_nojs.collect { |l| l.clone }
1314 for i in final_html_nojs
1315 i.sub!(/~~run_slideshow~~/, defer_translation(N_("<i>Click on an image to view it larger</i>")))
1316 i.sub!(/~~thumbnails~~/, html_thumbnails_nojs)
1317 if all_pages.size == 1
1318 i.gsub!(/~~ifmultiplepages\?~~.*~~fi~~/, '')
1320 i.gsub!(/~~ifmultiplepages\?~~(.+?)~~fi~~/) { $1 }
1321 i.gsub!(/~~multiplepagesstuff~~/, mstuff.gsub('%nojs', '-nojs'))
1323 substitute_html_sizes(i, sizeobj, 'thumbnails', "-nojs-#{pagecount}")
1324 substitute_pathtobase(i, xmldir)
1326 save_html(final_html_nojs, "#{dest_dir}/thumbnails-#{size2js(sizeobj['name'])}-nojs-#{pagecount}")
1331 info("finished processing sizes")
1333 #- generate "main" thumbnails.html page that will reload to correct size thanks to cookie
1334 save_html(html_reload_to_thumbnails, "#{dest_dir}/thumbnails")
1336 #- generate image.html (page with fullscreen images)
1341 type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
1343 caption = find_caption_value(xmldir, file)
1345 captions4js << '"' + quote_caption(caption, true) + '"'
1349 types4js << '"' + type + '"'
1351 index = videos.index(file)
1353 videos4js << '"' + flv_videos[videos[index]] + '"'
1355 videos4js << '"' + videos[index] + '"'
1363 for sizeobj in $images_size
1365 videoswidths4js = []
1366 videosheights4js = []
1368 type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
1371 index = images.index(file)
1372 elements4js << '"' + fullscreen_images[sizeobj['name']][index] + '"'
1373 videoswidths4js << "''"
1374 videosheights4js << "''"
1376 index = videos.index(file)
1377 elements4js << '"' + fullscreen_videos[sizeobj['name']][index] + '"'
1378 size = get_image_size("#{dest_dir}/#{fullscreen_videos[sizeobj['name']][index]}")
1379 videoswidths4js << size[:x].to_s
1380 videosheights4js << size[:y].to_s
1385 html = $html_images.collect { |l| l.clone }
1386 hiddenimages4remotes = '<span style="display:none">' + thumbnail_images[sizeobj['name']][0..4].collect { |e| "<img src=\"#{e}\"/>" }.join('') + '</span>'
1387 otherelements4js = ''
1389 for sizeobj2 in all_images_sizes
1390 if sizeobj != sizeobj2
1393 type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
1396 index = images.index(file)
1397 oe4js << '"' + fullscreen_images[sizeobj2['name']][index] + '"'
1399 index = videos.index(file)
1400 oe4js << '"' + fullscreen_videos[sizeobj2['name']][index] + '"'
1404 otherelements4js += "var elements_#{size2js(sizeobj2['name'])} = new Array(" + oe4js.join(', ') + ");\n"
1405 othersizes << "\"#{size2js(sizeobj2['name'])}\""
1409 i.gsub!(/~~images~~/, elements4js.join(', '))
1410 i.gsub!(/~~types~~/, types4js.join(', '))
1411 i.gsub!(/~~videos~~/, videos4js.join(', '))
1412 i.gsub!(/~~videos_widths~~/, videoswidths4js.join(', '))
1413 i.gsub!(/~~videos_heights~~/, videosheights4js.join(', '))
1414 i.gsub!(/~~hidden_images_for_remotes~~/, hiddenimages4remotes)
1415 i.gsub!(/~~other_images~~/, otherelements4js)
1416 i.gsub!(/~~thumbnailspages~~/, element2thumbnailpage4js.collect { |e| "\"#{e}\"" }.join(', '))
1417 i.gsub!(/~~other_sizes~~/, othersizes.join(', '))
1418 i.gsub!(/~~captions~~/, captions4js.join(', '))
1419 i.gsub!(/~~title~~/, quote_caption(xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir))))
1420 if $flv_generator && videos.size > 0
1421 i.sub!(/~~flowplayer_head_code~~/, '<script type="text/javascript" src="~~pathtobase~~flowplayer-3.1.4.min.js"></script>')
1422 i.sub!(/~~flowplayer_active~~/, 'true')
1424 i.sub!(/~~flowplayer_head_code~~/, '')
1425 i.sub!(/~~flowplayer_active~~/, 'false')
1428 i.gsub!(/~~thumbnails~~/, '<a href="thumbnails-' + size2js(sizeobj['name']) + $htmlsuffix + '" id="thumbnails">' + defer_translation(N_('return to thumbnails')) + '</a>')
1429 i.gsub!(/~~theme~~/, $theme)
1430 i.gsub!(/~~current_size~~/, size2js(sizeobj['name']))
1431 i.gsub!(/~~htmlsuffix~~/, $htmlsuffix)
1432 i.gsub!(/~~madewith~~/, $madewith || '')
1433 i.gsub!(/~~indexlink~~/, $indexlink || '')
1434 substitute_addthis(i)
1435 substitute_html_sizes(i, sizeobj, 'image', '')
1436 substitute_navigation(i, xmldir)
1437 substitute_pathtobase(i, xmldir)
1439 save_html(html, "#{dest_dir}/image-#{size2js(sizeobj['name'])}")
1446 #- add attributes to <dir..> elements needing so
1447 if $mode != 'use_config'
1448 msg 3, _("\tfixating configuration file...")
1449 $xmldoc.elements.each('//dir') { |element|
1450 path = captionpath = element.attributes['path']
1451 descendant_element = nil
1452 #- search if there is at least one image or video down that dir; use workarounds to rexml slowness
1453 #- first, look down only one level, very fast
1455 element.elements.each { |elem|
1459 if elem.name == 'image' || elem.name == 'video'
1460 descendant_element = elem
1464 if descendant_element.nil?
1465 #- if there was nothing or only directory down one level, look down the first subdir
1466 if ! first_desc.nil?
1467 first_desc.elements.each { |elem|
1468 if elem.name == 'image' || elem.name == 'video'
1469 descendant_element = elem
1474 if descendant_element.nil?
1475 #- if there was still nothing found, use complete albeit slow method
1476 descendant_element = element.elements['descendant::image'] || element.elements['descendant::video']
1479 if !descendant_element
1480 msg 3, _("\t\tremoving %s, no element in it") % path
1481 element.remove #- means we have a directory with nothing interesting in it
1483 captionfile = "#{descendant_element.parent.attributes['path']}/#{descendant_element.attributes['filename']}"
1484 basename = File.basename(path)
1485 if element.elements['dir']
1486 if !element.attributes['subdirs-caption']
1487 element.add_attribute('subdirs-caption', basename)
1489 if !element.attributes['subdirs-captionfile']
1490 element.add_attribute('subdirs-captionfile', captionfile)
1493 if element.child_byname_notattr('image', 'deleted') || element.child_byname_notattr('video', 'deleted')
1494 if !element.attributes['thumbnails-caption']
1495 element.add_attribute('thumbnails-caption', basename)
1497 if !element.attributes['thumbnails-captionfile']
1498 element.add_attribute('thumbnails-captionfile', captionfile)
1505 #- write down to disk config if necessary
1507 ios = File.open($config_writeto, "w")
1513 msg 3, _("completed necessary stuff for GUI, exiting.")
1517 #- second pass to create index.html files and previous/next links
1518 info("creating index.html")
1519 msg 3, _("\trescanning directories to generate all 'index.html' files...")
1521 #- recompute the memoization because elements mights have been removed (the ones with no element in them)
1523 $xmldoc.elements.each('//dir') { |elem|
1524 optxpath[elem.attributes['path']] = elem
1527 examined_dirs.each { |dir|
1528 info("index.html: #{dir}|#{$source}")
1530 xmldir = optxpath[utf8(dir)]
1531 if !xmldir || (xmldir.attributes['already-generated'] && !$force) || xmldir.attributes['deleted']
1534 dest_dir = make_dest_filename(dir.sub(/^#{Regexp.quote($source)}/, $dest))
1536 previous_album = find_previous_album(xmldir)
1537 next_album = find_next_album(xmldir)
1539 if xmldir.elements['dir']
1540 html = $html_index.collect { |l| l.clone }
1543 caption = xmldir.attributes['subdirs-caption']
1544 i.gsub!(/~~title~~/, quote_caption(caption))
1545 substitute_navigation(i, xmldir)
1546 substitute_pathtobase(i, xmldir)
1547 discover_iterations(iterations, i)
1551 reset_iterations(iterations)
1553 #- deal with "current" album (directs to "thumbnails" page)
1554 if xmldir.attributes['thumbnails-caption']
1555 thumbnail = "#{dest_dir}/thumbnails-thumbnail.jpg"
1556 gen_thumbnails_subdir(from_utf8(xmldir.attributes['thumbnails-captionfile']), xmldir, false,
1557 [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ], 'thumbnails')
1558 html_index += run_iterations(iterations, 1)
1559 caption = xmldir.attributes['thumbnails-caption']
1560 html_index.gsub!(/~~image_iteration~~/, "<a href=\"thumbnails#{$htmlsuffix}\">" + img_element(thumbnail, caption) + '</a>')
1561 html_index.gsub!(/~~caption_iteration~~/, quote_caption(caption))
1564 #- deal with sub-albums (direct to subdirs/index.html pages)
1565 xmldir.elements.each('dir') { |child|
1566 if child.attributes['deleted']
1569 subdir = make_dest_filename(from_utf8(File.basename(child.attributes['path'])))
1570 thumbnail = "#{dest_dir}/thumbnails-#{subdir}.jpg"
1571 html_index += run_iterations(iterations, 1)
1572 captionfile, caption = find_subalbum_caption_info(child)
1573 gen_thumbnails_subdir(captionfile, child, false,
1574 [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ], find_subalbum_info_type(child))
1575 html_index.gsub!(/~~caption_iteration~~/, quote_caption(caption))
1576 html_index.gsub!(/~~image_iteration~~/, "<a href=\"#{subdir}/index#{$htmlsuffix}\">" + img_element(thumbnail, caption) + '</a>')
1579 html_index += close_iterations(iterations)
1582 i.gsub!(/~~thumbnails~~/, html_index)
1583 i.gsub!(/~~madewith~~/, $madewith || '')
1584 i.gsub!(/~~indexlink~~/, $indexlink || '')
1585 substitute_addthis(i)
1589 html = html_reload_to_thumbnails
1592 save_html(html, "#{dest_dir}/index")
1594 #- in case MultiViews will not work, generate some compat
1595 ios = File.open("#{dest_dir}/index.html", "w")
1596 ios.write("<html><head><meta http-equiv=\"refresh\" content=\"0.1;url=index.#{$multi_languages[1]}.html\"></head></html>")
1600 #- substitute multiple "return to albums", previous/next correctly
1601 #- the following two statements are dramatical optimizations to executing for each substInFile callback
1602 dirpresent = xmldir.elements['dir']
1603 parentname = xmldir.parent.name
1604 if xmldir.child_byname_notattr('image', 'deleted') || xmldir.child_byname_notattr('video', 'deleted')
1605 for suffix in [ '', '-nojs' ]
1606 for sizeobj in $images_size
1607 Dir.glob("#{dest_dir}/thumbnails-#{size2js(sizeobj['name'])}#{suffix}-*.html") do |file|
1608 #- unroll translations, they are costly if rerun for each line of files
1609 rta = find_translation_for_file(file, N_('return to albums'))
1610 pa = find_translation_for_file(file, N_('previous album'))
1611 na = find_translation_for_file(file, N_('next album'))
1612 substInFile(file) { |line|
1613 sub_previous_next_album(file, previous_album, next_album, line, pa, na)
1615 line.sub!(/~~return_to_albums~~/, '<a href="index' + $htmlsuffix + '">' + rta + '</a>')
1617 if parentname == 'dir'
1618 line.sub!(/~~return_to_albums~~/, '<a href="../index' + $htmlsuffix + '">' + rta + '</a>')
1620 line.sub!(/~~return_to_albums~~/, '')
1626 if suffix == '' && xmldir.child_byname_notattr('image', 'deleted')
1627 Dir.glob("#{dest_dir}/image-#{size2js(sizeobj['name'])}*.html") do |file|
1628 pa = find_translation_for_file(file, N_('previous album'))
1629 na = find_translation_for_file(file, N_('next album'))
1630 substInFile(file) { |line|
1631 sub_previous_next_album(file, previous_album, next_album, line, pa, na)
1640 msg 3, _(" all done.")
1647 build_html_skeletons