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-2010 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-2010 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'
641 navtable = '<table id="navigation"><tr>'
643 parent = xmldir.parent
644 while parent.name == 'dir'
645 parentcaption = parent.attributes['subdirs-caption'] || File.basename(parent.attributes['path'])
646 nav = "<a href=\"#{path}/index#{$htmlsuffix}\">#{parentcaption}</a> #{defer_translation(N_(" > "))} #{nav}"
647 navtable += "<td><a href=\"#{path}/index#{$htmlsuffix}\">#{parentcaption}</a></td>"
649 parent = parent.parent
651 html.gsub!(/~~ifnavigation\?~~(.+?)~~fi~~/) { $1 }
652 html.gsub!(/~~navigation~~/, nav + (xmldir.attributes['subdirs-caption'] || File.basename(xmldir.attributes['path'])))
653 html.gsub!(/~~navigationtable~~/, navtable + "<td>" + (xmldir.attributes['subdirs-caption'] || File.basename(xmldir.attributes['path']) + "</td></tr></table>"))
655 html.gsub!(/~~ifnavigation\?~~(.+?)~~fi~~/, '')
659 def substitute_addthis(html)
660 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>' : '')
663 def substitute_pathtobase(html, xmldir)
666 while location.parent.name == 'dir'
668 location = location.parent
670 html.gsub!(/~~pathtobase~~/, path)
673 def xmldir2destdir(xmldir)
674 return make_dest_filename(from_utf8(File.basename(xmldir.attributes['path'])))
677 def find_previous_album(xmldir)
680 #- move to previous dir element if exists
681 if prevelem = xmldir.previous_element_byname_notattr('dir', 'deleted')
683 relative_pos += '../' + xmldir2destdir(xmldir) + '/'
685 #- after having moved to previous dir, we need to go down last subdir until the last one
686 while child = xmldir.elements['dir']
687 while nextchild = child.next_element_byname_notattr('dir', 'deleted')
690 relative_pos += xmldir2destdir(child) + '/'
694 #- previous dir doesn't exist, move to previous dir element if exists
695 xmldir = xmldir.parent
696 if xmldir.name == 'dir' && !xmldir.attributes['deleted']
697 relative_pos += '../'
702 end while !xmldir.child_byname_notattr('image', 'deleted') && !xmldir.child_byname_notattr('video', 'deleted')
703 return File.reduce_path(relative_pos)
706 def find_next_album(xmldir)
709 #- first child dir element (catches when initial xmldir has both thumbnails and subdirs)
710 if firstchild = xmldir.child_byname_notattr('dir', 'deleted')
712 relative_pos += xmldir2destdir(xmldir) + '/'
714 elsif nextbro = xmldir.next_element_byname_notattr('dir', 'deleted')
716 relative_pos += '../' + xmldir2destdir(xmldir) + '/'
718 #- go up until we have a next brother or we are finished
720 xmldir = xmldir.parent
721 relative_pos += '../'
722 end while xmldir && !xmldir.next_element_byname_notattr('dir', 'deleted')
724 xmldir = xmldir.next_element_byname('dir')
725 relative_pos += '../' + xmldir2destdir(xmldir) + '/'
730 end while !xmldir.child_byname_notattr('image', 'deleted') && !xmldir.child_byname_notattr('video', 'deleted')
731 return File.reduce_path(relative_pos)
734 def find_translation_for_file(file, msg)
736 if file =~ /\.(\w\w)\.html$/
737 bindtextdomain("booh", { :locale => "#{$1}.UTF-8" })
739 Locale.set_current($default_locale)
742 die "Internal error: cannot find multi language suffix of file '#{file}'"
749 def sub_previous_next_album(file, previous_album, next_album, html, previous_album_msg, next_album_msg)
751 html.gsub!(/~~previous_album~~/, '<a href="' + previous_album + 'thumbnails' + $htmlsuffix + '">' + previous_album_msg + '</a>')
752 html.gsub!(/~~ifprevious_album\?~~(.+?)~~fi~~/) { $1 }
754 html.gsub!(/~~previous_album~~/, '')
755 html.gsub!(/~~ifprevious_album\?~~(.+?)~~fi~~/, '')
758 html.gsub!(/~~next_album~~/, '<a href="' + next_album + 'thumbnails' + $htmlsuffix + '">' + next_album_msg + '</a>')
759 html.gsub!(/~~ifnext_album\?~~(.+?)~~fi~~/) { $1 }
761 html.gsub!(/~~next_album~~/, '')
762 html.gsub!(/~~ifnext_album\?~~(.+?)~~fi~~/, '')
767 def save_html(html, base_filename)
768 if html.class == Array
772 for language in ($multi_languages[0] + [ $multi_languages[1] ]).uniq
773 bindtextdomain("booh", { :locale => "#{language}.UTF-8" })
774 ios = File.open("#{base_filename}.#{language}.html", "w")
775 ios.write(html.gsub(/@@(.*?)@@/) { _($1) })
777 Locale.set_current($default_locale)
780 ios = File.open("#{base_filename}.html", "w")
781 ios.write(html.gsub(/@@(.*?)@@/) { utf8(_($1)) })
786 def apply_hook(name, content, *params)
794 return hook.call(content, *params)
800 #- preprocess the path->dir, rexml is very slow with that; we seem to improve speed by 7%
802 $xmldoc.elements.each('//dir') { |elem|
803 optxpath[elem.attributes['path']] = elem
807 if $mode == 'merge_config_onedir'
808 examined_dirs = [ $onedir ]
809 elsif $mode == 'merge_config_subdirs'
810 examined_dirs = `find '#{$onedir}' -type d -follow`.split.sort.collect { |v| v.chomp }.delete_if { |v| optxpath.has_key?(utf8(v)) }
812 examined_dirs = `find '#{$source}' -type d -follow`.split.sort.collect { |v| v.chomp }
813 if $mode == 'merge_config'
814 $xmldoc.elements.each('//dir') { |elem|
815 if ! examined_dirs.include?(elem.attributes['path'])
816 msg 2, _("Merging config: removing directory %s from config, isn't on filesystem anymore") % elem.attributes['path']
822 info("directories: #{examined_dirs.length}, sizes: #{$images_size.length}")
824 examined_dirs.each { |dir|
826 die _("Source directory or sub-directories can't contain a single-quote character, sorry: %s") % dir
828 if $mode !~ /^use_config/
829 Dir.entries(dir).each { |file|
830 if file =~ /['"\[\]]/
831 die _("Files can't contain any of the characters ', \", [ or ], sorry: %s") % "#{dir}/#{file}"
837 examined_dirs.each { |dir|
838 if File.basename(dir) =~ /^\./
839 msg 1, _("Ignoring directory %s, begins with a dot (indicating a hidden directory)") % dir
843 dest_dir = make_dest_filename(dir.sub(/^#{Regexp.quote($source)}/, $dest))
845 #- place xml document on proper node if exists, else create
846 xmldir = optxpath[utf8(dir)]
847 if $mode == 'use_config' || $mode == 'use_config_changetheme'
848 if !xmldir || (xmldir.attributes['already-generated'] && !$force) || xmldir.attributes['deleted']
849 info("walking: #{dir}|#{$source}, 0 elements")
850 if xmldir && xmldir.attributes['deleted']
851 system("rm -rf '#{dest_dir}'")
856 if $mode == 'gen_config' || (($mode == 'merge_config' || $mode == 'merge_config_subdirs') && !xmldir)
857 #- add the <dir..> element if necessary
858 parent = File.dirname(dir)
859 xmldir = $xmldoc.elements["//dir[@path='#{utf8(parent)}']"]
861 xmldir = $xmldoc.root
863 #- need to remove the already-generated mark of the parent because of the sub-albums page containing now one more element
864 xmldir.delete_attribute('already-generated')
865 xmldir = optxpath[utf8(dir)] = xmldir.add_element('dir', { 'path' => utf8(dir) })
868 xmldir.delete_attribute('already-generated')
870 #- preprocess all the existing elements, rexml is slow with that
872 xmldir.elements.each { |elem|
873 if filename = elem.attributes['filename']
874 optelements[elem.name + '|' + filename] = elem
878 #- read images/videos entries from config or from directories depending on mode
880 if $mode == 'use_config' || $mode == 'use_config_changetheme'
881 msg 2, _("Handling %s from config list...") % dir
882 xmldir.elements.each { |element|
883 if %w(image video).include?(element.name) && !element.attributes['deleted']
884 entries << from_utf8(element.attributes['filename'])
888 msg 2, _("Examining %s...") % dir
889 entries = Dir.entries(dir).sort
890 #- populate config in case of gen_config, add new files in case of merge_config
892 if file =~ /['"\[\]]/
893 msg 1, _("Ignoring %s, contains one of forbidden characters: '\"[]") % "#{dir}/#{file}"
895 type = entry2type(file)
896 if type && ! optelements[type + '|' + utf8(file)]
897 #- hack: don't run identify (which is slow) if format only contains default %t
898 if $commentsformat && type == 'image' && $commentsformat != '%t'
899 comment = utf8(`identify -format "#{$commentsformat}" '#{dir}/#{file}'`.chomp.sub(/\.$/, ''))
901 comment = utf8cut(file.sub(/\.[^\.]+$/, ''), 18)
903 optelements[type + '|' + utf8(file)] = xmldir.add_element(type, { "filename" => utf8(file), "caption" => comment })
907 if $mode != 'gen_config'
908 #- cleanup removed files from config and reread entries from config to get proper ordering
910 xmldir.elements.each { |element|
911 fullpath = "#{dir}/#{from_utf8(element.attributes['filename'])}"
912 if %w(image video).include?(element.name)
913 if !File.readable?(fullpath)
914 msg 1, _("Config merge: removing %s from config; use the backup file to retrieve caption info if this was a mistake") % fullpath
915 xmldir.delete(element)
916 elsif !element.attributes['deleted']
917 entries << from_utf8(element.attributes['filename'])
921 #- if there is no more elements here, there is no album here anymore
922 if !xmldir.child_byname_notattr('image', 'deleted') && !xmldir.child_byname_notattr('video', 'deleted')
923 xmldir.delete_attribute('thumbnails-caption')
924 xmldir.delete_attribute('thumbnails-captionfile')
928 images = entries.find_all { |e| entry2type(e) == 'image' }
929 msg 3, _("\t%s photos") % images.length
930 videos = entries.find_all { |e| entry2type(e) == 'video' }
931 msg 3, _("\t%s videos") % videos.length
932 info("walking: #{dir}|#{$source}, #{images.length + videos.length} elements")
934 system("mkdir -p '#{dest_dir}'")
936 #- generate .htaccess file
938 ios = File.open("#{dest_dir}/.htaccess", "w")
939 ios.write("AddCharset UTF-8 .html\n")
940 if auth_user_file = xmldir.attributes['password-protect']
941 msg 3, _("\tgenerating password protection file #{dest_dir}/.htaccess")
942 ios.write("AuthType Basic\nAuthName \"protected area\"\nAuthUserFile #{auth_user_file}\nrequire valid-user\n")
945 ios.write("Options +Multiviews\n")
946 ios.write("LanguagePriority #{$multi_languages[1]}\n")
947 ios.write("ForceLanguagePriority Prefer Fallback\n")
948 ios.write("DirectoryIndex index\n")
953 #- pass through if there are no images and videos
954 if images.size == 0 && videos.size == 0
956 #- cleanup old images/videos, especially if this directory contained images/videos previously.
957 if $mode != 'gen_config'
958 rightful_images = [ '.htaccess' ]
959 if xmldir.attributes['thumbnails-caption']
960 rightful_images << 'thumbnails-thumbnail.jpg'
962 xmldir.elements.each('dir') { |child|
963 if child.attributes['deleted']
966 subdir = make_dest_filename(from_utf8(File.basename(child.attributes['path'])))
967 rightful_images << "thumbnails-#{subdir}.jpg"
969 to_del = Dir.entries(dest_dir).find_all { |e| !File.directory?(File.join(dest_dir, e)) && !rightful_images.include?(e) }
971 File.delete(*to_del.collect { |e| File.join(dest_dir, e) })
975 #- copy any resource file that goes with the theme (css, images..)
976 themestuff = Dir.entries("#{$themedir}").
977 find_all { |e| !%w(. .. skeleton_image.html skeleton_thumbnails.html skeleton_index.html metadata root).include?(e) }
978 themestuff.each { |entry|
979 if !File.exists?(File.join(dest_dir, entry))
980 psys("cp '#{$themedir}/#{entry}' '#{dest_dir}'")
984 #- copy any root-only resource file that goes with the theme (css, images..)
985 if xmldir.parent.name != 'dir'
986 themestuff_root = Dir.entries("#{$themedir}/root").
987 find_all { |e| !%w(. ..).include?(e) }
988 themestuff_root.each { |entry|
989 if !File.exists?(File.join(dest_dir, entry))
990 psys("cp '#{$themedir}/root/#{entry}' '#{dest_dir}'")
993 #- copy flowplayer stuff if needed
995 psys("cp #{$FPATH}/flowplayer/flowplayer* '#{dest_dir}'")
1002 msg 2, _("Outputting in %s...") % dest_dir
1004 #- populate data structure with sizes from theme
1005 for sizeobj in $images_size
1006 fullscreen_images ||= {}
1007 fullscreen_images[sizeobj['name']] = []
1008 thumbnail_images ||= {}
1009 thumbnail_images[sizeobj['name']] = []
1010 fullscreen_videos ||= {}
1011 fullscreen_videos[sizeobj['name']] = []
1012 thumbnail_videos ||= {}
1013 thumbnail_videos[sizeobj['name']] = []
1015 #- a special dummy size to keep 'references' to thumbnails in case of panorama, because the GUI will use the regular thumbnails
1016 thumbnail_images['dont-delete-file-for-gui'] = []
1017 if $limit_sizes =~ /original/
1018 fullscreen_images['original'] = []
1019 fullscreen_videos['original'] = []
1022 images.size >= 1 and msg 3, _("\tcreating photos thumbnails...")
1024 #- create thumbnails for images
1026 info("processing element")
1027 base_dest_img = dest_dir + '/' + make_dest_filename(img.sub(/\.[^\.]+$/, ''))
1028 elem = optelements['image|' + utf8(img)]
1030 thumbnail_dest_img = base_dest_img + "-#{$default_size['thumbnails']}.jpg"
1031 gen_thumbnails_element("#{dir}/#{img}", elem, true, [ { 'filename' => thumbnail_dest_img, 'size' => $default_size['thumbnails'] } ])
1034 for sizeobj in $images_size
1035 size_fullscreen = sizeobj['fullscreen']
1036 size_thumbnails = sizeobj['thumbnails']
1037 fullscreen_dest_img = base_dest_img + "-#{size_fullscreen}.jpg"
1038 fullscreen_images[sizeobj['name']] << File.basename(fullscreen_dest_img)
1039 todo << { 'filename' => fullscreen_dest_img, 'size' => size_fullscreen }
1040 if pano = pano_amount(elem)
1041 thumbnail_images['dont-delete-file-for-gui'] << File.basename(base_dest_img + "-#{size_thumbnails}.jpg")
1042 size_thumbnails = size_thumbnails.sub(/(\d+)/) { ($1.to_i * pano).to_i }
1044 thumbnail_dest_img = base_dest_img + "-#{size_thumbnails}.jpg"
1045 thumbnail_images[sizeobj['name']] << File.basename(thumbnail_dest_img)
1046 todo << { 'filename' => thumbnail_dest_img, 'size' => size_thumbnails }
1048 gen_thumbnails_element("#{dir}/#{img}", elem, true, todo)
1049 if $limit_sizes =~ /original/
1050 fullscreen_images['original'] << img
1052 destimg = "#{dest_dir}/#{img}"
1053 if $limit_sizes =~ /original/ && !File.exists?(destimg)
1055 if ! sys("ln '#{dir}/#{img}' '#{destimg}'")
1056 $hardlinks_ok = false
1060 psys("cp '#{dir}/#{img}' '#{destimg}'")
1066 videos.size >= 1 and msg 3, _("\tcreating videos thumbnails...")
1067 transcoded_videos = {}
1070 #- create thumbnails for videos
1071 videos.each { |video|
1072 info("processing element")
1073 base_dest_img = dest_dir + '/' + make_dest_filename(video.sub(/\.[^\.]+$/, ''))
1074 elem = optelements['video|' + utf8(video)]
1076 thumbnail_dest_img = base_dest_img + "-#{$default_size['thumbnails']}.jpg"
1077 gen_thumbnails_element("#{dir}/#{video}", elem, true, [ { 'filename' => thumbnail_dest_img, 'size' => $default_size['thumbnails'] } ])
1080 for sizeobj in $images_size
1081 size_fullscreen = sizeobj['fullscreen']
1082 size_thumbnails = sizeobj['thumbnails']
1083 fullscreen_dest_img = base_dest_img + "-#{size_fullscreen}.jpg"
1084 fullscreen_videos[sizeobj['name']] << File.basename(fullscreen_dest_img)
1085 todo << { 'filename' => fullscreen_dest_img, 'size' => size_fullscreen }
1086 thumbnail_dest_img = base_dest_img + "-#{size_thumbnails}.jpg"
1087 thumbnail_videos[sizeobj['name']] << File.basename(thumbnail_dest_img)
1088 todo << { 'filename' => thumbnail_dest_img, 'size' => size_thumbnails }
1090 gen_thumbnails_element("#{dir}/#{video}", elem, true, todo)
1092 if $transcode_videos
1093 parts = $transcode_videos.split(':', 2)
1094 basedestvideo = video.sub(/\.\w+/, '') + '.' + parts[0]
1095 transcoded_videos[video] = basedestvideo
1096 destvideo = "#{dest_dir}/#{basedestvideo}"
1097 if ! File.exists?(destvideo)
1098 psys(parts[1].gsub(/%f/, "'#{dir}/#{video}'").gsub(/%o/, "'#{destvideo}'"))
1101 elsif $flv_generator
1102 basedestvideo = video.sub(/\.\w+/, '') + '.flv'
1103 flv_videos[video] = basedestvideo
1104 destvideo = "#{dest_dir}/#{basedestvideo}"
1105 if File.exists?(destvideo) && File.size(destvideo) == 0
1106 File.delete(destvideo)
1108 if ! File.exists?(destvideo)
1109 psys($flv_generator.gsub(/%f/, "'#{dir}/#{video}'").gsub(/%o/, "'#{destvideo}'"))
1113 destvideo = "#{dest_dir}/#{video}"
1114 if ! File.exists?(destvideo)
1116 if ! sys("ln '#{dir}/#{video}' '#{destvideo}'")
1117 $hardlinks_ok = false
1121 psys("cp '#{dir}/#{video}' '#{destvideo}'")
1129 #- cleanup old images/videos (for when removing elements or sizes)
1130 all_elements = fullscreen_images.collect { |e| e[1] }.flatten.
1131 concat(thumbnail_images.collect { |e| e[1] }.flatten).
1132 concat(fullscreen_videos.collect { |e| e[1] }.flatten).
1133 concat(thumbnail_videos.collect { |e| e[1] }.flatten).
1134 concat($transcode_videos ? transcoded_videos.values : $flv_generator ? flv_videos.values : videos).
1136 to_del = Dir.entries(dest_dir).find_all { |e| !File.directory?(File.join(dest_dir, e)) && !all_elements.include?(e) && e !~ /^thumbnails-\w+\.jpg/ }
1138 msg 3, _("\tcleaning up: #{to_del.join(', ')}")
1139 File.delete(*to_del.collect { |e| File.join(dest_dir, e) })
1142 #- copy any resource file that goes with the theme (css, images..)
1143 themestuff = Dir.entries("#{$themedir}").
1144 find_all { |e| !%w(. .. skeleton_image.html skeleton_thumbnails.html skeleton_index.html metadata root).include?(e) }
1145 themestuff.each { |entry|
1146 if !File.exists?(File.join(dest_dir, entry))
1147 psys("cp '#{$themedir}/#{entry}' '#{dest_dir}'")
1151 #- copy any root-only resource file that goes with the theme (css, images..)
1152 if xmldir.parent.name != 'dir'
1153 themestuff_root = Dir.entries("#{$themedir}/root").
1154 find_all { |e| !%w(. ..).include?(e) }
1155 themestuff_root.each { |entry|
1156 if !File.exists?(File.join(dest_dir, entry))
1157 psys("cp '#{$themedir}/root/#{entry}' '#{dest_dir}'")
1160 #- copy flowplayer stuff if needed
1162 psys("cp #{$FPATH}/flowplayer/flowplayer* '#{dest_dir}'")
1166 msg 3, _("\tgenerating HTML pages...")
1167 #- fixup max per page
1169 $N_per_page = $N_per_page.to_i / ($N_per_row || $default_N).to_i * ($N_per_row || $default_N).to_i
1172 #- generate thumbnails*.html (page with thumbnails)
1173 element2thumbnailpage4js = []
1174 for sizeobj in $images_size
1175 info("processing size")
1176 html = $html_thumbnails.collect { |l| l.clone }
1179 i.sub!(/~~title~~/, quote_caption(xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir))))
1180 i.sub!(/~~flowplayer_head_code~~/, ($flv_generator && videos.size > 0) ? '<script type="text/javascript" src="~~pathtobase~~flowplayer-3.2.2.min.js"></script>' : '')
1181 discover_iterations(iterations, i)
1184 html_thumbnails = ''
1185 html_thumbnails_nojs = ''
1188 reset_iterations(iterations)
1189 #- preprocess the @filename->elem, rexml is very slow with that; we dramatically improve this part of the processing
1191 xmldir.elements.each('image') { |elem|
1192 optfilename[elem.attributes['filename']] = elem
1195 type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
1197 homogeinize_width = 100 / ($N_per_row || $default_N).to_i
1198 if type == 'image' && elem = optfilename[utf8(file)]
1199 if pano = pano_amount(elem)
1200 html_elem = run_iterations(iterations, pano)
1201 counter += count = pano.ceil
1202 html_elem.gsub!(/~~colspan~~/) { "colspan=\"#{count}\"" }
1203 homogeinize_width *= count
1205 html_elem = run_iterations(iterations, 1)
1207 html_elem.gsub!(/~~colspan~~/, '')
1210 html_elem = run_iterations(iterations, 1)
1212 html_elem.gsub!(/~~colspan~~/, '')
1214 html_elem.gsub!(/~~homogeinize_width~~/) { "width=\"#{homogeinize_width}%\"" }
1216 index = images.index(file)
1217 caption = find_caption_value(xmldir, images[index]) || utf8(images[index])
1218 html_elem.gsub!(/~~caption_iteration~~/, quote_caption(caption))
1219 html_elem.gsub!(/~~ifimage\?~~(.+?)~~fi~~/) { $1 }
1220 html_elem.gsub!(/~~ifvideo\?~~(.+?)~~fi~~/, '')
1221 elsif type == 'video'
1222 index = videos.index(file)
1223 caption = find_caption_value(xmldir, videos[index]) || utf8(videos[index])
1224 if File.exists?("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}")
1225 video_preview = '<div class="thumbnail_video">' + img_element("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}", caption) + '</div>'
1227 video_preview = defer_translation(N_("(no preview)"))
1230 size = get_image_size("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}")
1232 sizeobj['thumbnails'] =~ /(\d+)x(\d+)/
1233 size = { :x => $1, :y => $2 }
1235 sizespec = 'width:' + size[:x].to_s + 'px;height:' + (size[:y] + 24).to_s + 'px'
1236 image_iteration = '<a href="' + flv_videos[videos[index]] + '" style="display:block;' + sizespec + '"' +
1237 ' id="player' + index.to_s + '">' + video_preview +
1238 '<img src="~~pathtobase~~play_video.png" style="position:relative;top:-' + ((size[:y]+48)/2).to_s + 'px;border:0;background-color:transparent"/></a>' +
1239 '<script>flowplayer("player' + index.to_s + '", "~~pathtobase~~flowplayer-3.2.2.swf")</script>'
1240 html_elem.gsub!(/~~image_iteration~~/, apply_hook(:image_iteration, image_iteration, 'video'))
1242 html_elem.gsub!(/~~image_iteration~~/,
1243 '<a href="' + ( $transcode_videos ? transcoded_videos[videos[index]] : videos[index] ) + '">' +
1244 video_preview + '</a>')
1246 html_elem.gsub!(/~~caption_iteration~~/, quote_caption(caption))
1247 html_elem.gsub!(/~~ifimage\?~~(.+?)~~fi~~/, '')
1248 html_elem.gsub!(/~~ifvideo\?~~(.+?)~~fi~~/) { $1 }
1250 html_thumbnails += html_elem
1251 html_thumbnails_nojs += html_elem
1253 img_preview = '<div class="thumbnail_image">' + img_element("#{dest_dir}/#{thumbnail_images[sizeobj['name']][index]}", caption) + '</div>'
1254 html_thumbnails.gsub!(/~~image_iteration~~/,
1255 '<a href="image-' + size2js(sizeobj['name']) + $htmlsuffix + '#current=' + fullscreen_images[sizeobj['name']][index] +
1256 '" name="' + fullscreen_images[sizeobj['name']][index] + '">' + img_preview + '</a>')
1257 html_thumbnails_nojs.gsub!(/~~image_iteration~~/,
1258 '<a href="' + fullscreen_images[sizeobj['name']][index] + '" name="' + fullscreen_images[sizeobj['name']][index] + '">' +
1259 img_preview + '</a>')
1261 #- remember in which thumbnails page is this element, for element->thumbnail link
1262 if sizeobj == $images_size[0]
1263 element2thumbnailpage4js << pagecount
1266 if counter == $N_per_page
1267 html_thumbnails += close_iterations(iterations)
1268 html_thumbnails_nojs += close_iterations(iterations)
1269 all_pages << [ html_thumbnails, html_thumbnails_nojs ]
1270 html_thumbnails = ''
1271 html_thumbnails_nojs = ''
1273 reset_iterations(iterations)
1279 html_thumbnails += close_iterations(iterations)
1280 html_thumbnails_nojs += close_iterations(iterations)
1281 all_pages << [ html_thumbnails, html_thumbnails_nojs ]
1284 i.gsub!(/~~theme~~/, $theme)
1285 i.gsub!(/~~current_size~~/, sizeobj['name'])
1286 i.gsub!(/~~htmlsuffix~~/, $htmlsuffix)
1287 i.gsub!(/~~current_size_js~~/, size2js(sizeobj['name']))
1288 i.gsub!(/~~madewith~~/, $madewith || '')
1289 i.gsub!(/~~indexlink~~/, $indexlink || '')
1290 if $indexlink.empty?
1291 i.gsub!(/~~ifindexlink\?~~(.+?)~~fi~~/) { }
1293 i.gsub!(/~~ifindexlink\?~~(.+?)~~fi~~/) { $1 }
1295 substitute_addthis(i)
1296 substitute_navigation(i, xmldir)
1298 html_nojs = html.collect { |l| l.clone }
1300 for page in all_pages
1301 html_thumbnails, html_thumbnails_nojs = page
1302 final_html = html.collect { |l| l.clone }
1303 mstuff = defer_translation(N_("Pages: ")) +
1304 (pagecount > 0 ? "<a href=\"thumbnails-#{size2js(sizeobj['name'])}%nojs-#{pagecount - 1}#{$htmlsuffix}\">" + defer_translation(N_("<- Previous")) + "</a> " : '') +
1305 all_pages.collect_with_index { |p,idx| page == p ? idx + 1 : "<a href=\"thumbnails-#{size2js(sizeobj['name'])}%nojs-#{idx}#{$htmlsuffix}\">#{idx + 1}</a>" }.join(', ') +
1306 (pagecount < all_pages.size - 1 ? " <a href=\"thumbnails-#{size2js(sizeobj['name'])}%nojs-#{pagecount + 1}#{$htmlsuffix}\">" + defer_translation(N_("Next ->")) + "</a> " : '')
1308 i.sub!(/~~run_slideshow_link~~/, entries.size <= 1 ? '' : 'image-' + size2js(sizeobj['name']) + $htmlsuffix + '#run_slideshow=1')
1309 i.sub!(/~~run_slideshow_text~~/, defer_translation(N_("Run slideshow!")))
1310 i.sub!(/~~run_slideshow~~/,
1311 entries.size <= 1 ? '' : '<a href="image-' + size2js(sizeobj['name']) + $htmlsuffix + '#run_slideshow=1">' + defer_translation(N_("Run slideshow!"))+'</a>')
1312 i.sub!(/~~thumbnails~~/, html_thumbnails)
1313 if all_pages.size == 1
1314 i.gsub!(/~~ifmultiplepages\?~~.*~~fi~~/, '')
1316 i.gsub!(/~~ifmultiplepages\?~~(.+?)~~fi~~/) { $1 }
1317 i.gsub!(/~~multiplepagesstuff~~/, mstuff.gsub('%nojs', ''))
1319 substitute_html_sizes(i, sizeobj, 'thumbnails', "-#{pagecount}")
1320 substitute_pathtobase(i, xmldir)
1322 save_html(final_html, "#{dest_dir}/thumbnails-#{size2js(sizeobj['name'])}-#{pagecount}")
1323 final_html_nojs = html_nojs.collect { |l| l.clone }
1324 for i in final_html_nojs
1325 i.sub!(/~~run_slideshow~~/, defer_translation(N_("<i>Click on an image to view it larger</i>")))
1326 i.sub!(/~~thumbnails~~/, html_thumbnails_nojs)
1327 if all_pages.size == 1
1328 i.gsub!(/~~ifmultiplepages\?~~.*~~fi~~/, '')
1330 i.gsub!(/~~ifmultiplepages\?~~(.+?)~~fi~~/) { $1 }
1331 i.gsub!(/~~multiplepagesstuff~~/, mstuff.gsub('%nojs', '-nojs'))
1333 substitute_html_sizes(i, sizeobj, 'thumbnails', "-nojs-#{pagecount}")
1334 substitute_pathtobase(i, xmldir)
1336 save_html(final_html_nojs, "#{dest_dir}/thumbnails-#{size2js(sizeobj['name'])}-nojs-#{pagecount}")
1341 info("finished processing sizes")
1343 #- generate "main" thumbnails.html page that will reload to correct size thanks to cookie
1344 save_html(html_reload_to_thumbnails, "#{dest_dir}/thumbnails")
1346 #- generate image.html (page with fullscreen images)
1351 type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
1353 caption = find_caption_value(xmldir, file)
1355 captions4js << '"' + quote_caption(caption, true) + '"'
1359 types4js << '"' + type + '"'
1361 index = videos.index(file)
1363 videos4js << '"' + flv_videos[videos[index]] + '"'
1365 videos4js << '"' + videos[index] + '"'
1373 for sizeobj in $images_size
1375 videoswidths4js = []
1376 videosheights4js = []
1378 type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
1381 index = images.index(file)
1382 elements4js << '"' + fullscreen_images[sizeobj['name']][index] + '"'
1383 videoswidths4js << "''"
1384 videosheights4js << "''"
1386 index = videos.index(file)
1387 elements4js << '"' + fullscreen_videos[sizeobj['name']][index] + '"'
1388 size = get_image_size("#{dest_dir}/#{fullscreen_videos[sizeobj['name']][index]}")
1389 videoswidths4js << size[:x].to_s
1390 videosheights4js << size[:y].to_s
1395 html = $html_images.collect { |l| l.clone }
1396 hiddenimages4remotes = '<span style="display:none">' + thumbnail_images[sizeobj['name']][0..4].collect { |e| "<img src=\"#{e}\"/>" }.join('') + '</span>'
1397 otherelements4js = ''
1399 for sizeobj2 in all_images_sizes
1400 if sizeobj != sizeobj2
1403 type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
1406 index = images.index(file)
1407 oe4js << '"' + fullscreen_images[sizeobj2['name']][index] + '"'
1408 elsif sizeobj2['name'] != 'original'
1409 index = videos.index(file)
1410 oe4js << '"' + fullscreen_videos[sizeobj2['name']][index] + '"'
1414 otherelements4js += "var elements_#{size2js(sizeobj2['name'])} = new Array(" + oe4js.join(', ') + ");\n"
1415 othersizes << "\"#{size2js(sizeobj2['name'])}\""
1419 i.gsub!(/~~images~~/, elements4js.join(', '))
1420 i.gsub!(/~~types~~/, types4js.join(', '))
1421 i.gsub!(/~~videos~~/, videos4js.join(', '))
1422 i.gsub!(/~~videos_widths~~/, videoswidths4js.join(', '))
1423 i.gsub!(/~~videos_heights~~/, videosheights4js.join(', '))
1424 i.gsub!(/~~hidden_images_for_remotes~~/, hiddenimages4remotes)
1425 i.gsub!(/~~other_images~~/, otherelements4js)
1426 i.gsub!(/~~thumbnailspages~~/, element2thumbnailpage4js.collect { |e| "\"#{e}\"" }.join(', '))
1427 i.gsub!(/~~other_sizes~~/, othersizes.join(', '))
1428 i.gsub!(/~~captions~~/, captions4js.join(', '))
1429 i.gsub!(/~~title~~/, quote_caption(xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir))))
1430 if $flv_generator && videos.size > 0
1431 i.sub!(/~~flowplayer_head_code~~/, '<script type="text/javascript" src="~~pathtobase~~flowplayer-3.2.2.min.js"></script>')
1432 i.sub!(/~~flowplayer_active~~/, 'true')
1434 i.sub!(/~~flowplayer_head_code~~/, '')
1435 i.sub!(/~~flowplayer_active~~/, 'false')
1438 i.gsub!(/~~thumbnails~~/, '<a id="thumbnails">' + defer_translation(N_('return to thumbnails')) + '</a>')
1439 i.gsub!(/~~theme~~/, $theme)
1440 i.gsub!(/~~current_size~~/, size2js(sizeobj['name']))
1441 i.gsub!(/~~htmlsuffix~~/, $htmlsuffix)
1442 i.gsub!(/~~madewith~~/, $madewith || '')
1443 i.gsub!(/~~indexlink~~/, $indexlink || '')
1444 if $indexlink.empty?
1445 i.gsub!(/~~ifindexlink\?~~(.+?)~~fi~~/) { }
1447 i.gsub!(/~~ifindexlink\?~~(.+?)~~fi~~/) { $1 }
1449 substitute_addthis(i)
1450 substitute_html_sizes(i, sizeobj, 'image', '')
1451 substitute_navigation(i, xmldir)
1452 substitute_pathtobase(i, xmldir)
1454 save_html(html, "#{dest_dir}/image-#{size2js(sizeobj['name'])}")
1461 #- add attributes to <dir..> elements needing so
1462 if $mode != 'use_config'
1463 msg 3, _("\tfixating configuration file...")
1464 $xmldoc.elements.each('//dir') { |element|
1465 path = captionpath = element.attributes['path']
1466 descendant_element = nil
1467 #- search if there is at least one image or video down that dir; use workarounds to rexml slowness
1468 #- first, look down only one level, very fast
1470 element.elements.each { |elem|
1474 if elem.name == 'image' || elem.name == 'video'
1475 descendant_element = elem
1479 if descendant_element.nil?
1480 #- if there was nothing or only directory down one level, look down the first subdir
1481 if ! first_desc.nil?
1482 first_desc.elements.each { |elem|
1483 if elem.name == 'image' || elem.name == 'video'
1484 descendant_element = elem
1489 if descendant_element.nil?
1490 #- if there was still nothing found, use complete albeit slow method
1491 descendant_element = element.elements['descendant::image'] || element.elements['descendant::video']
1494 if !descendant_element
1495 msg 3, _("\t\tremoving %s, no element in it") % path
1496 element.remove #- means we have a directory with nothing interesting in it
1498 captionfile = "#{descendant_element.parent.attributes['path']}/#{descendant_element.attributes['filename']}"
1499 basename = File.basename(path)
1500 if element.elements['dir']
1501 if !element.attributes['subdirs-caption']
1502 element.add_attribute('subdirs-caption', basename)
1504 if !element.attributes['subdirs-captionfile']
1505 element.add_attribute('subdirs-captionfile', captionfile)
1508 if element.child_byname_notattr('image', 'deleted') || element.child_byname_notattr('video', 'deleted')
1509 if !element.attributes['thumbnails-caption']
1510 element.add_attribute('thumbnails-caption', basename)
1512 if !element.attributes['thumbnails-captionfile']
1513 element.add_attribute('thumbnails-captionfile', captionfile)
1520 #- write down to disk config if necessary
1522 ios = File.open($config_writeto, "w")
1528 msg 3, _("completed necessary stuff for GUI, exiting.")
1532 #- second pass to create index.html files and previous/next links
1533 info("creating index.html")
1534 msg 3, _("\trescanning directories to generate all 'index.html' files...")
1536 #- recompute the memoization because elements mights have been removed (the ones with no element in them)
1538 $xmldoc.elements.each('//dir') { |elem|
1539 optxpath[elem.attributes['path']] = elem
1542 examined_dirs.each { |dir|
1543 info("index.html: #{dir}|#{$source}")
1545 xmldir = optxpath[utf8(dir)]
1546 if !xmldir || (xmldir.attributes['already-generated'] && !$force) || xmldir.attributes['deleted']
1549 dest_dir = make_dest_filename(dir.sub(/^#{Regexp.quote($source)}/, $dest))
1551 previous_album = find_previous_album(xmldir)
1552 next_album = find_next_album(xmldir)
1554 if xmldir.elements['dir']
1555 html = $html_index.collect { |l| l.clone }
1558 caption = xmldir.attributes['subdirs-caption']
1559 i.gsub!(/~~title~~/, quote_caption(caption))
1560 substitute_navigation(i, xmldir)
1561 substitute_pathtobase(i, xmldir)
1562 discover_iterations(iterations, i)
1566 reset_iterations(iterations)
1568 #- deal with "current" album (directs to "thumbnails" page)
1569 if xmldir.attributes['thumbnails-caption']
1570 thumbnail = "#{dest_dir}/thumbnails-thumbnail.jpg"
1571 gen_thumbnails_subdir(from_utf8(xmldir.attributes['thumbnails-captionfile']), xmldir, false,
1572 [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ], 'thumbnails')
1573 html_index += run_iterations(iterations, 1)
1574 caption = xmldir.attributes['thumbnails-caption']
1575 html_index.gsub!(/~~image_iteration~~/, "<a href=\"thumbnails#{$htmlsuffix}\">" + img_element(thumbnail, caption) + '</a>')
1576 html_index.gsub!(/~~caption_iteration~~/, quote_caption(caption))
1579 #- deal with sub-albums (direct to subdirs/index.html pages)
1580 xmldir.elements.each('dir') { |child|
1581 if child.attributes['deleted']
1584 subdir = make_dest_filename(from_utf8(File.basename(child.attributes['path'])))
1585 thumbnail = "#{dest_dir}/thumbnails-#{subdir}.jpg"
1586 html_index += run_iterations(iterations, 1)
1587 captionfile, caption = find_subalbum_caption_info(child)
1588 gen_thumbnails_subdir(captionfile, child, false,
1589 [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ], find_subalbum_info_type(child))
1590 html_index.gsub!(/~~caption_iteration~~/, quote_caption(caption))
1591 html_index.gsub!(/~~image_iteration~~/, "<a href=\"#{subdir}/index#{$htmlsuffix}\">" + img_element(thumbnail, caption) + '</a>')
1594 html_index += close_iterations(iterations)
1597 i.gsub!(/~~thumbnails~~/, html_index)
1598 i.gsub!(/~~madewith~~/, $madewith || '')
1599 i.gsub!(/~~indexlink~~/, $indexlink || '')
1600 if $indexlink.empty?
1601 i.gsub!(/~~ifindexlink\?~~(.+?)~~fi~~/) { }
1603 i.gsub!(/~~ifindexlink\?~~(.+?)~~fi~~/) { $1 }
1605 substitute_addthis(i)
1609 html = html_reload_to_thumbnails
1612 save_html(html, "#{dest_dir}/index")
1614 #- in case MultiViews will not work, generate some compat
1615 ios = File.open("#{dest_dir}/index.html", "w")
1616 ios.write("<html><head><meta http-equiv=\"refresh\" content=\"0.1;url=index.#{$multi_languages[1]}.html\"></head></html>")
1620 #- substitute multiple "return to albums", previous/next correctly
1621 #- the following two statements are dramatical optimizations to executing for each substInFile callback
1622 dirpresent = xmldir.elements['dir']
1623 parentname = xmldir.parent.name
1624 if xmldir.child_byname_notattr('image', 'deleted') || xmldir.child_byname_notattr('video', 'deleted')
1625 for suffix in [ '', '-nojs' ]
1626 for sizeobj in $images_size
1627 Dir.glob("#{dest_dir}/thumbnails-#{size2js(sizeobj['name'])}#{suffix}-*.html") do |file|
1628 #- unroll translations, they are costly if rerun for each line of files
1629 rta = find_translation_for_file(file, N_('return to albums'))
1630 pa = find_translation_for_file(file, N_('previous album'))
1631 na = find_translation_for_file(file, N_('next album'))
1632 substInFile(file) { |line|
1633 sub_previous_next_album(file, previous_album, next_album, line, pa, na)
1635 line.sub!(/~~return_to_albums~~/, '<a href="index' + $htmlsuffix + '">' + rta + '</a>')
1637 if parentname == 'dir'
1638 line.sub!(/~~return_to_albums~~/, '<a href="../index' + $htmlsuffix + '">' + rta + '</a>')
1640 line.sub!(/~~return_to_albums~~/, '')
1646 if suffix == '' && xmldir.child_byname_notattr('image', 'deleted')
1647 Dir.glob("#{dest_dir}/image-#{size2js(sizeobj['name'])}*.html") do |file|
1648 pa = find_translation_for_file(file, N_('previous album'))
1649 na = find_translation_for_file(file, N_('next album'))
1650 substInFile(file) { |line|
1651 sub_previous_next_album(file, previous_album, next_album, line, pa, na)
1660 msg 3, _(" all done.")
1667 build_html_skeletons