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-2011 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
29 #- new style (ruby-locale separated package)
32 #- old style (locale stuff in ruby-gettext package)
33 require 'gettext/locale'
37 require 'booh/rexml/document'
40 require 'booh/booh-lib'
41 require 'booh/html-merges'
43 #- bind text domain as soon as possible because some _() functions are called early to build data structures
44 bindtextdomain("booh")
45 #- save locale for restoring for multi languages
46 $default_locale = Locale.get
50 [ '--help', '-h', GetoptLong::NO_ARGUMENT, _("Get help message") ],
51 [ '--version', '-V', GetoptLong::NO_ARGUMENT, _("Print version and exit") ],
53 [ '--source', '-s', GetoptLong::REQUIRED_ARGUMENT, _("Directory which contains original photos/videos as files or subdirs") ],
54 [ '--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!") ],
56 [ '--theme', '-t', GetoptLong::REQUIRED_ARGUMENT, _("Select HTML theme to use") ],
57 [ '--config', '-C', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing photos and videos within directories with captions") ],
58 [ '--config-skel', '-k', GetoptLong::REQUIRED_ARGUMENT, _("Filename where the script will output a config skeleton") ],
59 [ '--merge-config', '-M', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing, where to merge new/removed photos/videos from --source, and change theme info") ],
60 [ '--merge-config-onedir', '-O', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing, for merging the subdir specified with --dir") ],
61 [ '--merge-config-subdirs', '-U', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing, for merging the new subdirs down the subdir specified with --dir") ],
62 [ '--dir', '-D', GetoptLong::REQUIRED_ARGUMENT, _("Directory for merge with --merge-config-onedir or --merge-config-subdirs") ],
63 [ '--use-config', '-u', GetoptLong::REQUIRED_ARGUMENT, _("File containing config listing, where to change theme info") ],
64 [ '--force', '-f', GetoptLong::NO_ARGUMENT, _("Force generation of album even if the GUI marked some directories as already generated") ],
66 [ '--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)") ],
67 [ '--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(', ') ],
68 [ '--thumbnails-per-row', '-T', GetoptLong::REQUIRED_ARGUMENT, _("Specify the amount of thumbnails per row in the thumbnails page (if applicable in theme)") ],
69 [ '--thumbnails-per-page', '-p', GetoptLong::REQUIRED_ARGUMENT, _("Specify the amount of thumbnails per page in the thumbnails page, after which split occurs") ],
70 [ '--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)") ],
71 [ '--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") ],
72 [ '--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)") ],
73 [ '--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)") ],
74 [ '--addthis', '-a', GetoptLong::NO_ARGUMENT, _("Include the 'addthis' bookmarking and sharing button") ],
75 [ '--made-with', '-n', GetoptLong::REQUIRED_ARGUMENT, _("Specify the HTML markup to use on the bottom of pages for a small 'made with' message") ],
76 [ '--quote-html', '-q', GetoptLong::NO_ARGUMENT, _("Quote HTML markup in captions") ],
77 [ '--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") ],
79 [ '--mproc', '-m', GetoptLong::REQUIRED_ARGUMENT, _("Specify the number of processors for multi-processors machines") ],
81 [ '--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)") ],
83 [ '--verbose-level', '-v', GetoptLong::REQUIRED_ARGUMENT, _("Set max verbosity level (0: errors, 1: warnings, 2: important messages, 3: other messages)") ],
84 [ '--info-pipe', '-i', GetoptLong::REQUIRED_ARGUMENT, _("Name a file where to write information about what's going on (used by the GUI)") ],
87 #- default values for some globals
91 $ignore_videos = false
96 puts _("Usage: %s [OPTION]...") % File.basename($0)
98 printf " %3s, %-18s %s\n", ary[1], ary[0], ary[3]
103 parser = GetoptLong.new
104 parser.set_options(*$options.collect { |ary| ary[0..2] })
106 parser.each_option do |name, arg|
113 puts _("Booh version %s
115 Copyright (c) 2005-2011 Guillaume Cottenceau.
116 This is free software; see the source for copying conditions. There is NO
117 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.") % $VERSION
122 $source = File.expand_path(arg.sub(%r|/$|, ''))
123 if !File.directory?($source)
124 die _("Argument to --source must be a directory")
127 $dest = File.expand_path(arg.sub(%r|/$|, ''))
128 if File.exists?($dest) && !File.directory?($dest)
129 die _("If --destination exists, it must be a directory")
131 if $dest != make_dest_filename($dest)
132 die _("Sorry, destination directory can't contain non simple alphanumeric characters.")
135 # system("rm -rf #{$dest}")
140 arg = File.expand_path(arg)
141 if File.readable?(arg)
142 $xmldoc = REXML::Document.new File.new(arg)
145 die _('Config file does not exist or is unreadable.')
148 arg = File.expand_path(arg)
150 if File.directory?(arg)
151 die _("Config skeleton file (%s) already exists and is a directory! Please change the filename.") % arg
153 msg 1, _("Config skeleton file already exists, backuping to %s.backup") % arg
154 File.rename(arg, "#{arg}.backup")
157 $config_writeto = arg
159 when '--merge-config'
160 arg = File.expand_path(arg)
161 if File.readable?(arg)
162 msg 2, _("Merge config notice: backuping current config file to %s.backup") % arg
163 $xmldoc = REXML::Document.new File.new(arg)
164 File.rename(arg, "#{arg}.backup")
165 $config_writeto = arg
166 $mode = 'merge_config'
168 die _('Config file does not exist or is unreadable.')
170 when '--merge-config-onedir'
171 arg = File.expand_path(arg)
172 if File.readable?(arg)
173 msg 2, _("Merge config notice: backuping current config file to %s.backup") % arg
174 $xmldoc = REXML::Document.new File.new(arg)
175 File.rename(arg, "#{arg}.backup")
176 $config_writeto = arg
177 $mode = 'merge_config_onedir'
179 die _('Config file does not exist or is unreadable.')
181 when '--merge-config-subdirs'
182 arg = File.expand_path(arg)
183 if File.readable?(arg)
184 msg 2, _("Merge config notice: backuping current config file to %s.backup") % arg
185 $xmldoc = REXML::Document.new File.new(arg)
186 File.rename(arg, "#{arg}.backup")
187 $config_writeto = arg
188 $mode = 'merge_config_subdirs'
190 die _('Config file does not exist or is unreadable.')
193 arg = File.expand_path(arg)
194 if !File.readable?(arg)
195 die _('Specified directory to merge with --dir is not readable')
200 arg = File.expand_path(arg)
201 if File.readable?(arg)
202 msg 2, _("Use config notice: backuping current config file to %s.backup") % arg
203 $xmldoc = REXML::Document.new File.new(arg)
204 File.rename(arg, "#{arg}.backup")
205 $config_writeto = arg
206 $mode = 'use_config_changetheme'
208 die _('Config file does not exist or is unreadable.')
214 when '--multi-languages'
215 parts = arg.split(',')
216 if parts.size == 0 || parts.find_all { |e| ! SUPPORTED_LANGUAGES.include?(e.strip) }.size > 0
217 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(', ')
219 $multi_languages = [ parts[0..-2], parts[-1] ]
221 when '--thumbnails-per-row'
224 when '--thumbnails-per-page'
227 when '--optimize-for-32'
228 $optimize_for_32 = true
230 when '--transcode-videos'
231 parts = arg.split(':', 2)
232 if parts.size != 2 || parts[0] =~ / / || arg !~ /%f/ || arg !~ /%o/
233 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")
235 $transcode_videos = arg
237 when '--flv-generator'
238 if arg !~ /%f/ || arg !~ /%o/
239 die _("--flv-generator: argument must contain %f for the input video and %o for the output video")
255 when '--comments-format'
256 $commentsformat = arg
268 when '--verbose-level'
269 $verbose_level = arg.to_i
272 $info_pipe = File.open(arg, File::WRONLY)
273 $info_pipe.sync = true
282 if !$source && $xmldoc
283 $source = from_utf8($xmldoc.root.attributes['source']).sub(%r|/$|, '')
284 $dest = from_utf8($xmldoc.root.attributes['destination']).sub(%r|/$|, '')
285 $theme ||= $xmldoc.root.attributes['theme']
286 $limit_sizes ||= $xmldoc.root.attributes['limit-sizes']
287 if $mode == 'use_config' || $mode =~ /^merge_config/
288 $optimize_for_32 = !$xmldoc.root.attributes['optimize-for-32'].nil?
289 $N_per_row = $xmldoc.root.attributes['thumbnails-per-row']
290 languages = $xmldoc.root.attributes['multi-languages']
292 languages = languages.split(',')
293 $multi_languages = [ languages[0..-2], languages[-1] ]
295 $N_per_page = $xmldoc.root.attributes['thumbnails-per-page']
296 $madewith = $xmldoc.root.attributes['made-with']
297 $indexlink = $xmldoc.root.attributes['index-link']
298 $addthis = !$xmldoc.root.attributes['addthis'].nil?
299 $quote_html = !$xmldoc.root.attributes['quote-html'].nil?
303 if $mode == 'merge_config_onedir' && !$onedir
304 die _("Missing --dir for --merge-config-onedir")
306 if $mode == 'merge_config_subdirs' && !$onedir
307 die _("Missing --dir for --merge-config-subdirs")
315 die _("Missing --destination parameter.")
321 select_theme($theme, $limit_sizes, $optimize_for_32, $N_per_row)
324 $xmldoc = Document.new "<booh/>"
325 $xmldoc << XMLDecl.new(XMLDecl::DEFAULT_VERSION, $CURRENT_CHARSET)
326 $xmldoc.root.add_attribute('version', $VERSION)
327 $xmldoc.root.add_attribute('source', $source)
328 $xmldoc.root.add_attribute('destination', $dest)
329 $xmldoc.root.add_attribute('theme', $theme)
331 $xmldoc.root.add_attribute('limit-sizes', $limit_sizes)
334 $xmldoc.root.add_attribute('multi-languages', $multi_languages[0].join(',') + ',' + $multi_languages[1])
337 $xmldoc.root.add_attribute('optimize-for-32', 'true')
340 $xmldoc.root.add_attribute('thumbnails-per-row', $N_per_row)
343 $xmldoc.root.add_attribute('thumbnails-per-page', $N_per_page)
346 $xmldoc.root.add_attribute('made-with', $madewith)
349 $xmldoc.root.add_attribute('index-link', $indexlink)
352 $xmldoc.root.add_attribute('addthis', 'true')
355 $xmldoc.root.add_attribute('quote-html', 'true')
360 if $mode == 'merge_config' || $mode == 'use_config_changetheme'
361 $xmldoc.root.add_attribute('theme', $theme)
362 $xmldoc.root.add_attribute('version', $VERSION)
364 $xmldoc.root.add_attribute('limit-sizes', $limit_sizes)
366 $xmldoc.root.delete_attribute('limit-sizes')
369 $xmldoc.root.add_attribute('multi-languages', $multi_languages[0].join(',') + ',' + $multi_languages[1])
371 $xmldoc.root.delete_attribute('multi-languages')
375 $xmldoc.root.add_attribute('optimize-for-32', 'true')
377 $xmldoc.root.delete_attribute('optimize-for-32')
380 $xmldoc.root.add_attribute('thumbnails-per-row', $N_per_row)
382 $xmldoc.root.delete_attribute('thumbnails-per-row')
385 $xmldoc.root.add_attribute('thumbnails-per-page', $N_per_page)
387 $xmldoc.root.delete_attribute('thumbnails-per-page')
390 $xmldoc.root.add_attribute('made-with', $madewith)
392 $xmldoc.root.delete_attribute('made-with')
395 $xmldoc.root.add_attribute('index-link', $indexlink)
397 $xmldoc.root.delete_attribute('index-link')
400 $xmldoc.root.add_attribute('addthis', 'true')
402 $xmldoc.root.delete_attribute('addthis')
405 $xmldoc.root.add_attribute('quote-html', 'true')
407 $xmldoc.root.delete_attribute('quote-html')
412 $xmldoc.root.add_attribute('transcode-videos', $transcode_videos)
414 $xmldoc.root.delete_attribute('transcode-videos')
418 $xmldoc.root.add_attribute('flv-generator', $flv_generator)
420 $xmldoc.root.delete_attribute('flv-generator')
424 $madewith = $madewith.gsub('%booh', '"http://booh.org/"')
429 $htmlsuffix = '.html'
442 $info_pipe.puts(value)
448 $info_pipe.puts("die: " + value)
453 def check_installation
454 if !system("which convert >/dev/null 2>/dev/null")
455 die _("The program 'convert' is needed. Please install it.
456 It is generally available with the 'ImageMagick' software package.")
458 if !system("which identify >/dev/null 2>/dev/null")
459 msg 1, _("the program 'identify' is needed to get images sizes and EXIF data. Please install it.
460 It is generally available with the 'ImageMagick' software package.")
463 missing = %w(mplayer).delete_if { |prg| system("which #{prg} >/dev/null 2>/dev/null") }
465 msg 1, _("the following program(s) are needed to handle videos: '%s'. Videos will be ignored.") % missing.join(', ')
466 $ignore_videos = true
470 def replace_line(surround, keyword, line)
472 contents = eval "$#{keyword}"
473 line.sub!(/#{surround}#{keyword}#{surround}/, contents)
475 die _("No '%s' found for substitution") % keyword
479 def build_html_skeletons
480 $html_images = File.open("#{$themedir}/skeleton_image.html").readlines
481 $html_thumbnails = File.open("#{$themedir}/skeleton_thumbnails.html").readlines
482 $html_index = File.open("#{$themedir}/skeleton_index.html").readlines
483 for line in $html_images + $html_thumbnails + $html_index
484 while line =~ /~~~(\w+)~~~/
485 replace_line('~~~', $1, line)
490 def find_caption_value(xmldir, filename)
491 if cap = xmldir.elements["*[@filename='#{utf8(filename)}']"].attributes['caption']
498 def quote_caption(input, *for_attribute)
500 return input.gsub('<', '<').gsub('>', '>').gsub('"', '"').gsub("'", ''').gsub("\n", '<br/>')
501 elsif for_attribute[0]
502 return input.gsub('"', '"').gsub("\n", '<br/>')
504 return input.gsub("\n", '<br/>')
508 #- stolen from CVSspam
510 text.sub(/[^a-zA-Z0-9\-,.*_\/]/) do
511 "%#{sprintf('%2X', $&[0])}"
516 return $limit_sizes =~ /original/ ? $images_size + [ { 'name' => 'original' } ] : $images_size
519 def html_reload_to_thumbnails
520 html_reload_to_thumbnails = $preferred_size_reloader.clone
521 html_reload_to_thumbnails.gsub!(/~~theme~~/, $theme)
522 html_reload_to_thumbnails.gsub!(/~~default_size~~/, size2js($default_size['name']))
523 html_reload_to_thumbnails.gsub!(/~~htmlsuffix~~/, $htmlsuffix)
524 html_reload_to_thumbnails.gsub!(/~~all_sizes~~/, all_images_sizes.collect { |s| "\"#{size2js(s['name'])}\"" }.join(', '))
525 size_auto_chooser = '';
526 all_images_sizes.find_all { |s| s.has_key?('optimizedforwidth') }.
527 sort { |a,b| b['optimizedforwidth'].to_i <=> a['optimizedforwidth'].to_i }.
528 each { |s| size_auto_chooser += "if (w + 50 > #{s['optimizedforwidth']}) { return 'thumbnails-#{size2js(s['name'])}-0#{$htmlsuffix}'; }\n" }
529 html_reload_to_thumbnails.gsub!(/~~size_auto_chooser~~/, size_auto_chooser)
530 return html_reload_to_thumbnails
533 def discover_iterations(iterations, line)
534 if line =~ /~~iterate(\d)_open(_max(\d+|N))?~~/
535 for iter in iterations.values
538 iter['close_wait'] = $1.to_i
541 max = $3 == 'N' ? ($N_per_row || $default_N) : $3
542 iterations[$1.to_i] = { 'open' => true, 'max' => max, 'opening' => '', 'closing' => '' }
544 line.sub!(/.*/, '~~thumbnails~~')
548 elsif line =~ /~~iterate(\d)_close~~/
549 iterations[$1.to_i]['open'] = false;
550 iterations[$1.to_i]['close'] = true;
553 for iter in iterations.values
555 iter['opening'] += line
558 if !iter['close'] && iter['close_wait'] && iterations[iter['close_wait']]['close']
559 iter['closing'] += line
566 def reset_iterations(iterations)
567 for iter in iterations.values
572 def run_iterations(iterations, amount)
575 for level in iterations.keys.sort
576 if iterations[level]['value'] == 0
577 html += iterations[level]['opening']
578 elsif level == iterations.keys.max
579 if !iterations[level]['max'] || iterations[level]['max'] && iterations[level]['value'] + amount <= iterations[level]['max'].to_i
580 html += iterations[level]['opening']
585 iterations[level]['value'] += amount
586 if iterations[level]['max'] && iterations[level]['value'] > iterations[level]['max'].to_i
587 iterations[level]['value'] = 0
588 iterations[level-1]['value'] = 0
589 html += iterations[level-1]['closing']
593 return html + run_iterations(iterations, amount)
599 def close_iterations(iterations)
601 for level in iterations.keys.sort.reverse
602 html += iterations[level]['closing']
607 def img_element(fullpath, caption)
608 if size = get_image_size(fullpath)
609 sizespec = 'width="' + size[:x].to_s + '" height="' + size[:y].to_s + '"'
613 return '<img src="' + File.basename(fullpath) + '" ' + sizespec + ' alt="' + quote_caption(caption, true) + '"/>'
617 return name.gsub(/-/, '')
620 def substitute_html_sizes(html, sizeobj, type, suffix)
622 if $images_size.length > 1 || (type == 'image' && $limit_sizes =~ /original/)
623 for sizeobj2 in $images_size
624 sizejs = size2js(sizeobj2['name'])
625 sizen = defer_translation(sizename(sizeobj2['name'], false))
626 if sizeobj != sizeobj2
627 if type == 'thumbnails'
628 sizestrings << '<a href="thumbnails-' + sizejs + suffix + $htmlsuffix + '" onclick="set_preferred_size(\'' + sizejs + '\')">' + sizen + '</a>'
630 sizestrings << '<a id="link' + sizejs + '" onclick="set_preferred_size(\'' + sizejs + '\')">' + sizen + '</a>'
636 if type == 'image' && $limit_sizes =~ /original/
637 sizestrings << '<a id="linkoriginal" target="newframe">' + defer_translation(sizename('original', false)) + '</a>'
640 html.sub!(/~~sizes~~(.+)~~/) { sizestrings.join($1) }
643 def substitute_navigation(html, xmldir)
644 if xmldir.parent.name == 'dir'
648 parent = xmldir.parent
649 while parent.name == 'dir'
650 parentcaption = parent.attributes['subdirs-caption'] || File.basename(parent.attributes['path'])
651 nav = "<a href=\"#{path}/index#{$htmlsuffix}\">#{parentcaption}</a> #{defer_translation(N_(" > "))} #{nav}"
652 navtable = "<td><a href=\"#{path}/index#{$htmlsuffix}\">#{parentcaption}</a></td>#{navtable}"
654 parent = parent.parent
656 html.gsub!(/~~ifnavigation\?~~(.+?)~~fi~~/) { $1 }
657 html.gsub!(/~~navigation~~/, nav + (xmldir.attributes['subdirs-caption'] || File.basename(xmldir.attributes['path'])))
658 html.gsub!(/~~navigationtable~~/, '<table id="navigation"><tr>' + navtable + "<td>" +
659 (xmldir.attributes['subdirs-caption'] || File.basename(xmldir.attributes['path'])) + "</td></tr></table>")
661 html.gsub!(/~~ifnavigation\?~~(.+?)~~fi~~/, '')
665 def substitute_addthis(html)
666 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>' : '')
669 def substitute_pathtobase(html, xmldir)
672 while location.parent.name == 'dir'
674 location = location.parent
676 html.gsub!(/~~pathtobase~~/, path)
679 def xmldir2destdir(xmldir)
680 return make_dest_filename(from_utf8(File.basename(xmldir.attributes['path'])))
683 def find_previous_album(xmldir)
686 #- move to previous dir element if exists
687 if prevelem = xmldir.previous_element_byname_notattr('dir', 'deleted')
689 relative_pos += '../' + xmldir2destdir(xmldir) + '/'
691 #- after having moved to previous dir, we need to go down last subdir until the last one
692 while child = xmldir.elements['dir']
693 while nextchild = child.next_element_byname_notattr('dir', 'deleted')
696 relative_pos += xmldir2destdir(child) + '/'
700 #- previous dir doesn't exist, move to previous dir element if exists
701 xmldir = xmldir.parent
702 if xmldir.name == 'dir' && !xmldir.attributes['deleted']
703 relative_pos += '../'
708 end while !xmldir.child_byname_notattr('image', 'deleted') && !xmldir.child_byname_notattr('video', 'deleted')
709 return File.reduce_path(relative_pos)
712 def find_next_album(xmldir)
715 #- first child dir element (catches when initial xmldir has both thumbnails and subdirs)
716 if firstchild = xmldir.child_byname_notattr('dir', 'deleted')
718 relative_pos += xmldir2destdir(xmldir) + '/'
720 elsif nextbro = xmldir.next_element_byname_notattr('dir', 'deleted')
722 relative_pos += '../' + xmldir2destdir(xmldir) + '/'
724 #- go up until we have a next brother or we are finished
726 xmldir = xmldir.parent
727 relative_pos += '../'
728 end while xmldir && !xmldir.next_element_byname_notattr('dir', 'deleted')
730 xmldir = xmldir.next_element_byname('dir')
731 relative_pos += '../' + xmldir2destdir(xmldir) + '/'
736 end while !xmldir.child_byname_notattr('image', 'deleted') && !xmldir.child_byname_notattr('video', 'deleted')
737 return File.reduce_path(relative_pos)
740 def find_translation_for_file(file, msg)
742 if file =~ /\.(\w\w)\.html$/
743 bindtextdomain("booh", { :locale => "#{$1}.UTF-8" })
745 Locale.set_current($default_locale)
748 die "Internal error: cannot find multi language suffix of file '#{file}'"
755 def sub_previous_next_album(file, previous_album, next_album, html, previous_album_msg, next_album_msg)
757 html.gsub!(/~~previous_album~~/, '<a href="' + previous_album + 'thumbnails' + $htmlsuffix + '">' + previous_album_msg + '</a>')
758 html.gsub!(/~~ifprevious_album\?~~(.+?)~~fi~~/) { $1 }
760 html.gsub!(/~~previous_album~~/, '')
761 html.gsub!(/~~ifprevious_album\?~~(.+?)~~fi~~/, '')
764 html.gsub!(/~~next_album~~/, '<a href="' + next_album + 'thumbnails' + $htmlsuffix + '">' + next_album_msg + '</a>')
765 html.gsub!(/~~ifnext_album\?~~(.+?)~~fi~~/) { $1 }
767 html.gsub!(/~~next_album~~/, '')
768 html.gsub!(/~~ifnext_album\?~~(.+?)~~fi~~/, '')
773 def save_html(html, base_filename)
774 if html.class == Array
778 for language in ($multi_languages[0] + [ $multi_languages[1] ]).uniq
779 bindtextdomain("booh", { :locale => "#{language}.UTF-8" })
780 ios = File.open("#{base_filename}.#{language}.html", "w")
781 ios.write(html.gsub(/@@(.*?)@@/) { _($1) })
783 Locale.set_current($default_locale)
786 ios = File.open("#{base_filename}.html", "w")
787 ios.write(html.gsub(/@@(.*?)@@/) { utf8(_($1)) })
792 def apply_hook(name, content, *params)
800 return hook.call(content, *params)
806 #- preprocess the path->dir, rexml is very slow with that; we seem to improve speed by 7%
808 $xmldoc.elements.each('//dir') { |elem|
809 optxpath[elem.attributes['path']] = elem
813 if $mode == 'merge_config_onedir'
814 examined_dirs = [ $onedir ]
815 elsif $mode == 'merge_config_subdirs'
816 examined_dirs = `find '#{$onedir}' -type d -follow`.split("\n").sort.collect { |v| v.chomp }.delete_if { |v| optxpath.has_key?(utf8(v)) }
818 examined_dirs = `find '#{$source}' -type d -follow`.split("\n").sort.collect { |v| v.chomp }
819 if $mode == 'merge_config'
820 $xmldoc.elements.each('//dir') { |elem|
821 if ! examined_dirs.include?(elem.attributes['path'])
822 msg 2, _("Merging config: removing directory %s from config, isn't on filesystem anymore") % elem.attributes['path']
828 info("directories: #{examined_dirs.length}, sizes: #{$images_size.length}")
830 examined_dirs.each { |dir|
832 die _("Source directory or sub-directories can't contain a single-quote character, sorry: %s") % dir
834 if $mode !~ /^use_config/
835 Dir.entries(dir).each { |file|
836 if file =~ /['"\[\]]/
837 die _("Files can't contain any of the characters ', \", [ or ], sorry: %s") % "#{dir}/#{file}"
843 examined_dirs.each { |dir|
844 if File.basename(dir) =~ /^\./
845 msg 1, _("Ignoring directory %s, begins with a dot (indicating a hidden directory)") % dir
849 dest_dir = make_dest_filename(dir.sub(/^#{Regexp.quote($source)}/, $dest))
851 #- place xml document on proper node if exists, else create
852 xmldir = optxpath[utf8(dir)]
853 if $mode == 'use_config' || $mode == 'use_config_changetheme'
854 if !xmldir || (xmldir.attributes['already-generated'] && !$force) || xmldir.attributes['deleted']
855 info("walking: #{dir}|#{$source}, 0 elements")
856 if xmldir && xmldir.attributes['deleted']
857 system("rm -rf '#{dest_dir}'")
862 if $mode == 'gen_config' || (($mode == 'merge_config' || $mode == 'merge_config_subdirs') && !xmldir)
863 #- add the <dir..> element if necessary
864 parent = File.dirname(dir)
865 xmldir = $xmldoc.elements["//dir[@path='#{utf8(parent)}']"]
867 xmldir = $xmldoc.root
869 #- need to remove the already-generated mark of the parent because of the sub-albums page containing now one more element
870 xmldir.delete_attribute('already-generated')
871 xmldir = optxpath[utf8(dir)] = xmldir.add_element('dir', { 'path' => utf8(dir) })
874 xmldir.delete_attribute('already-generated')
876 #- preprocess all the existing elements, rexml is slow with that
878 xmldir.elements.each { |elem|
879 if filename = elem.attributes['filename']
880 optelements[elem.name + '|' + filename] = elem
884 #- read images/videos entries from config or from directories depending on mode
886 if $mode == 'use_config' || $mode == 'use_config_changetheme'
887 msg 2, _("Handling %s from config list...") % dir
888 xmldir.elements.each { |element|
889 if %w(image video).include?(element.name) && !element.attributes['deleted']
890 entries << from_utf8(element.attributes['filename'])
894 msg 2, _("Examining %s...") % dir
895 entries = Dir.entries(dir).sort
896 #- populate config in case of gen_config, add new files in case of merge_config
898 if file =~ /['"\[\]]/
899 msg 1, _("Ignoring %s, contains one of forbidden characters: '\"[]") % "#{dir}/#{file}"
901 type = entry2type(file)
902 if type && ! optelements[type + '|' + utf8(file)]
903 #- hack: don't run identify (which is slow) if format only contains default %t
904 if $commentsformat && type == 'image' && $commentsformat != '%t'
905 comment = utf8(`identify -format "#{$commentsformat}" '#{dir}/#{file}'`.chomp.sub(/\.$/, ''))
907 comment = utf8cut(file.sub(/\.[^\.]+$/, ''), 18)
909 optelements[type + '|' + utf8(file)] = xmldir.add_element(type, { "filename" => utf8(file), "caption" => comment })
913 if $mode != 'gen_config'
914 #- cleanup removed files from config and reread entries from config to get proper ordering
916 xmldir.elements.each { |element|
917 fullpath = "#{dir}/#{from_utf8(element.attributes['filename'])}"
918 if %w(image video).include?(element.name)
919 if !File.readable?(fullpath)
920 msg 1, _("Config merge: removing %s from config; use the backup file to retrieve caption info if this was a mistake") % fullpath
921 xmldir.delete(element)
922 elsif !element.attributes['deleted']
923 entries << from_utf8(element.attributes['filename'])
927 #- if there is no more elements here, there is no album here anymore
928 if !xmldir.child_byname_notattr('image', 'deleted') && !xmldir.child_byname_notattr('video', 'deleted')
929 xmldir.delete_attribute('thumbnails-caption')
930 xmldir.delete_attribute('thumbnails-captionfile')
934 images = entries.find_all { |e| entry2type(e) == 'image' }
935 msg 3, _("\t%s photos") % images.length
936 videos = entries.find_all { |e| entry2type(e) == 'video' }
937 msg 3, _("\t%s videos") % videos.length
938 info("walking: #{dir}|#{$source}, #{images.length + videos.length} elements")
940 system("mkdir -p '#{dest_dir}'")
942 #- generate .htaccess file
944 ios = File.open("#{dest_dir}/.htaccess", "w")
945 ios.write("AddCharset UTF-8 .html\n")
947 ios.write("<IfModule mod_expires.c>\n")
948 ios.write(" ExpiresActive On\n")
949 ios.write(" ExpiresDefault A1800\n")
950 ios.write("</IfModule>")
952 if auth_user_file = xmldir.attributes['password-protect']
953 msg 3, _("\tgenerating password protection file #{dest_dir}/.htaccess")
954 ios.write("AuthType Basic\nAuthName \"protected area\"\nAuthUserFile #{auth_user_file}\nrequire valid-user\n")
957 ios.write("Options +Multiviews\n")
958 ios.write("LanguagePriority #{$multi_languages[1]}\n")
959 ios.write("ForceLanguagePriority Prefer Fallback\n")
960 ios.write("DirectoryIndex index\n")
965 #- pass through if there are no images and videos
966 if images.size == 0 && videos.size == 0
968 #- cleanup old images/videos, especially if this directory contained images/videos previously.
969 if $mode != 'gen_config'
970 rightful_images = [ '.htaccess' ]
971 if xmldir.attributes['thumbnails-caption']
972 rightful_images << 'thumbnails-thumbnail.jpg'
974 xmldir.elements.each('dir') { |child|
975 if child.attributes['deleted']
978 subdir = make_dest_filename(from_utf8(File.basename(child.attributes['path'])))
979 rightful_images << "thumbnails-#{subdir}.jpg"
981 to_del = Dir.entries(dest_dir).find_all { |e| !File.directory?(File.join(dest_dir, e)) && !rightful_images.include?(e) }
983 File.delete(*to_del.collect { |e| File.join(dest_dir, e) })
987 #- copy any resource file that goes with the theme (css, images..)
988 themestuff = Dir.entries("#{$themedir}").
989 find_all { |e| !%w(. .. skeleton_image.html skeleton_thumbnails.html skeleton_index.html metadata root).include?(e) }
990 themestuff.each { |entry|
991 if !File.exists?(File.join(dest_dir, entry))
992 psys("cp '#{$themedir}/#{entry}' '#{dest_dir}'")
996 #- copy any root-only resource file that goes with the theme (css, images..)
997 if xmldir.parent.name != 'dir'
998 themestuff_root = Dir.entries("#{$themedir}/root").
999 find_all { |e| !%w(. ..).include?(e) }
1000 themestuff_root.each { |entry|
1001 if !File.exists?(File.join(dest_dir, entry))
1002 psys("cp '#{$themedir}/root/#{entry}' '#{dest_dir}'")
1005 #- copy flowplayer stuff if needed
1007 psys("cp #{$FPATH}/flowplayer/flowplayer* '#{dest_dir}'")
1014 msg 2, _("Outputting in %s...") % dest_dir
1016 #- populate data structure with sizes from theme
1017 for sizeobj in $images_size
1018 fullscreen_images ||= {}
1019 fullscreen_images[sizeobj['name']] = []
1020 thumbnail_images ||= {}
1021 thumbnail_images[sizeobj['name']] = []
1022 fullscreen_videos ||= {}
1023 fullscreen_videos[sizeobj['name']] = []
1024 thumbnail_videos ||= {}
1025 thumbnail_videos[sizeobj['name']] = []
1027 #- a special dummy size to keep 'references' to thumbnails in case of panorama, because the GUI will use the regular thumbnails
1028 thumbnail_images['dont-delete-file-for-gui'] = []
1029 if $limit_sizes =~ /original/
1030 fullscreen_images['original'] = []
1031 fullscreen_videos['original'] = []
1034 images.size >= 1 and msg 3, _("\tcreating photos thumbnails...")
1036 #- create thumbnails for images
1038 info("processing element")
1039 base_dest_img = dest_dir + '/' + make_dest_filename(img.sub(/\.[^\.]+$/, ''))
1040 elem = optelements['image|' + utf8(img)]
1042 thumbnail_dest_img = base_dest_img + "-#{$default_size['thumbnails']}.jpg"
1043 gen_thumbnails_element("#{dir}/#{img}", elem, true, [ { 'filename' => thumbnail_dest_img, 'size' => $default_size['thumbnails'] } ])
1046 for sizeobj in $images_size
1047 size_fullscreen = sizeobj['fullscreen']
1048 size_thumbnails = sizeobj['thumbnails']
1049 fullscreen_dest_img = base_dest_img + "-#{size_fullscreen}.jpg"
1050 fullscreen_images[sizeobj['name']] << File.basename(fullscreen_dest_img)
1051 todo << { 'filename' => fullscreen_dest_img, 'size' => size_fullscreen }
1052 if pano = pano_amount(elem)
1053 thumbnail_images['dont-delete-file-for-gui'] << File.basename(base_dest_img + "-#{size_thumbnails}.jpg")
1054 size_thumbnails = size_thumbnails.sub(/(\d+)/) { ($1.to_i * pano).to_i }
1056 thumbnail_dest_img = base_dest_img + "-#{size_thumbnails}.jpg"
1057 thumbnail_images[sizeobj['name']] << File.basename(thumbnail_dest_img)
1058 todo << { 'filename' => thumbnail_dest_img, 'size' => size_thumbnails }
1060 gen_thumbnails_element("#{dir}/#{img}", elem, true, todo)
1061 if $limit_sizes =~ /original/
1062 fullscreen_images['original'] << img
1064 destimg = "#{dest_dir}/#{img}"
1065 if $limit_sizes =~ /original/ && !File.exists?(destimg)
1067 if ! sys("ln '#{dir}/#{img}' '#{destimg}'")
1068 $hardlinks_ok = false
1072 psys("cp '#{dir}/#{img}' '#{destimg}'")
1078 videos.size >= 1 and msg 3, _("\tcreating videos thumbnails...")
1079 transcoded_videos = {}
1082 #- create thumbnails for videos
1083 videos.each { |video|
1084 info("processing element")
1085 base_dest_img = dest_dir + '/' + make_dest_filename(video.sub(/\.[^\.]+$/, ''))
1086 elem = optelements['video|' + utf8(video)]
1088 thumbnail_dest_img = base_dest_img + "-#{$default_size['thumbnails']}.jpg"
1089 gen_thumbnails_element("#{dir}/#{video}", elem, true, [ { 'filename' => thumbnail_dest_img, 'size' => $default_size['thumbnails'] } ])
1092 for sizeobj in $images_size
1093 size_fullscreen = sizeobj['fullscreen']
1094 size_thumbnails = sizeobj['thumbnails']
1095 fullscreen_dest_img = base_dest_img + "-#{size_fullscreen}.jpg"
1096 fullscreen_videos[sizeobj['name']] << File.basename(fullscreen_dest_img)
1097 todo << { 'filename' => fullscreen_dest_img, 'size' => size_fullscreen }
1098 thumbnail_dest_img = base_dest_img + "-#{size_thumbnails}.jpg"
1099 thumbnail_videos[sizeobj['name']] << File.basename(thumbnail_dest_img)
1100 todo << { 'filename' => thumbnail_dest_img, 'size' => size_thumbnails }
1102 gen_thumbnails_element("#{dir}/#{video}", elem, true, todo)
1104 if $transcode_videos
1105 parts = $transcode_videos.split(':', 2)
1106 basedestvideo = video.sub(/\.\w+/, '') + '.' + parts[0]
1107 transcoded_videos[video] = basedestvideo
1108 destvideo = "#{dest_dir}/#{basedestvideo}"
1109 if ! File.exists?(destvideo)
1110 psys(parts[1].gsub(/%f/, "'#{dir}/#{video}'").gsub(/%o/, "'#{destvideo}'"))
1113 elsif $flv_generator
1114 basedestvideo = video.sub(/\.\w+/, '') + '.flv'
1115 flv_videos[video] = basedestvideo
1116 destvideo = "#{dest_dir}/#{basedestvideo}"
1117 if File.exists?(destvideo) && File.size(destvideo) == 0
1118 File.delete(destvideo)
1120 if ! File.exists?(destvideo)
1121 psys($flv_generator.gsub(/%f/, "'#{dir}/#{video}'").gsub(/%o/, "'#{destvideo}'"))
1125 destvideo = "#{dest_dir}/#{video}"
1126 if ! File.exists?(destvideo)
1128 if ! sys("ln '#{dir}/#{video}' '#{destvideo}'")
1129 $hardlinks_ok = false
1133 psys("cp '#{dir}/#{video}' '#{destvideo}'")
1141 #- cleanup old images/videos (for when removing elements or sizes)
1142 all_elements = fullscreen_images.collect { |e| e[1] }.flatten.
1143 concat(thumbnail_images.collect { |e| e[1] }.flatten).
1144 concat(fullscreen_videos.collect { |e| e[1] }.flatten).
1145 concat(thumbnail_videos.collect { |e| e[1] }.flatten).
1146 concat($transcode_videos ? transcoded_videos.values : $flv_generator ? flv_videos.values : videos).
1148 to_del = Dir.entries(dest_dir).find_all { |e| !File.directory?(File.join(dest_dir, e)) && !all_elements.include?(e) && e !~ /^thumbnails-\w+\.jpg/ }
1150 msg 3, _("\tcleaning up: #{to_del.join(', ')}")
1151 File.delete(*to_del.collect { |e| File.join(dest_dir, e) })
1154 #- copy any resource file that goes with the theme (css, images..)
1155 themestuff = Dir.entries("#{$themedir}").
1156 find_all { |e| !%w(. .. skeleton_image.html skeleton_thumbnails.html skeleton_index.html metadata root).include?(e) }
1157 themestuff.each { |entry|
1158 if !File.exists?(File.join(dest_dir, entry))
1159 psys("cp '#{$themedir}/#{entry}' '#{dest_dir}'")
1163 #- copy any root-only resource file that goes with the theme (css, images..)
1164 if xmldir.parent.name != 'dir'
1165 themestuff_root = Dir.entries("#{$themedir}/root").
1166 find_all { |e| !%w(. ..).include?(e) }
1167 themestuff_root.each { |entry|
1168 if !File.exists?(File.join(dest_dir, entry))
1169 psys("cp '#{$themedir}/root/#{entry}' '#{dest_dir}'")
1172 #- copy flowplayer stuff if needed
1174 psys("cp #{$FPATH}/flowplayer/flowplayer* '#{dest_dir}'")
1178 msg 3, _("\tgenerating HTML pages...")
1179 #- fixup max per page
1181 $N_per_page = $N_per_page.to_i / ($N_per_row || $default_N).to_i * ($N_per_row || $default_N).to_i
1184 #- generate thumbnails*.html (page with thumbnails)
1185 element2thumbnailpage4js = []
1186 for sizeobj in $images_size
1187 info("processing size")
1188 html = $html_thumbnails.collect { |l| l.clone }
1191 i.sub!(/~~title~~/, quote_caption(xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir))))
1192 i.sub!(/~~flowplayer_head_code~~/, ($flv_generator && videos.size > 0) ? '<script type="text/javascript" src="~~pathtobase~~flowplayer-3.2.6.min.js"></script>' : '')
1193 discover_iterations(iterations, i)
1196 html_thumbnails = ''
1197 html_thumbnails_nojs = ''
1200 reset_iterations(iterations)
1201 #- preprocess the @filename->elem, rexml is very slow with that; we dramatically improve this part of the processing
1203 xmldir.elements.each('image') { |elem|
1204 optfilename[elem.attributes['filename']] = elem
1207 type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
1209 homogeinize_width = 100 / ($N_per_row || $default_N).to_i
1210 if type == 'image' && elem = optfilename[utf8(file)]
1211 if pano = pano_amount(elem)
1212 html_elem = run_iterations(iterations, pano)
1213 counter += count = pano.ceil
1214 html_elem.gsub!(/~~colspan~~/) { "colspan=\"#{count}\"" }
1215 homogeinize_width *= count
1217 html_elem = run_iterations(iterations, 1)
1219 html_elem.gsub!(/~~colspan~~/, '')
1222 html_elem = run_iterations(iterations, 1)
1224 html_elem.gsub!(/~~colspan~~/, '')
1226 html_elem.gsub!(/~~homogeinize_width~~/) { "width=\"#{homogeinize_width}%\"" }
1228 index = images.index(file)
1229 caption = find_caption_value(xmldir, images[index]) || utf8(images[index])
1230 html_elem.gsub!(/~~caption_iteration~~/, quote_caption(caption))
1231 html_elem.gsub!(/~~ifimage\?~~(.+?)~~fi~~/) { $1 }
1232 html_elem.gsub!(/~~ifvideo\?~~(.+?)~~fi~~/, '')
1233 elsif type == 'video'
1234 index = videos.index(file)
1235 caption = find_caption_value(xmldir, videos[index]) || utf8(videos[index])
1236 if File.exists?("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}")
1237 video_preview = '<div class="thumbnail_video">' + img_element("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}", caption) + '</div>'
1239 video_preview = defer_translation(N_("(no preview)"))
1242 size = get_image_size("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}")
1244 sizeobj['thumbnails'] =~ /(\d+)x(\d+)/
1245 size = { :x => $1, :y => $2 }
1247 sizespec = 'width:' + size[:x].to_s + 'px;height:' + (size[:y] + 24).to_s + 'px'
1248 image_iteration = '<a href="' + flv_videos[videos[index]] + '" style="display:block;' + sizespec + '"' +
1249 ' id="player' + index.to_s + '">' + video_preview +
1250 '<img src="~~pathtobase~~play_video.png" style="position:relative;top:-' + ((size[:y]+48)/2).to_s + 'px;border:0;background-color:transparent"/></a>' +
1251 '<script>flowplayer("player' + index.to_s + '", "~~pathtobase~~flowplayer-3.2.7.swf")</script>'
1252 html_elem.gsub!(/~~image_iteration~~/, apply_hook(:image_iteration, image_iteration, 'video'))
1254 html_elem.gsub!(/~~image_iteration~~/,
1255 '<a href="' + ( $transcode_videos ? transcoded_videos[videos[index]] : videos[index] ) + '">' +
1256 video_preview + '</a>')
1258 html_elem.gsub!(/~~caption_iteration~~/, quote_caption(caption))
1259 html_elem.gsub!(/~~ifimage\?~~(.+?)~~fi~~/, '')
1260 html_elem.gsub!(/~~ifvideo\?~~(.+?)~~fi~~/) { $1 }
1262 html_thumbnails += html_elem
1263 html_thumbnails_nojs += html_elem
1265 img_preview = '<div class="thumbnail_image">' + img_element("#{dest_dir}/#{thumbnail_images[sizeobj['name']][index]}", caption) + '</div>'
1266 html_thumbnails.gsub!(/~~image_iteration~~/,
1267 '<a href="image-' + size2js(sizeobj['name']) + $htmlsuffix + '#current=' + fullscreen_images[sizeobj['name']][index] +
1268 '" name="' + fullscreen_images[sizeobj['name']][index] + '">' + img_preview + '</a>')
1269 html_thumbnails_nojs.gsub!(/~~image_iteration~~/,
1270 '<a href="' + fullscreen_images[sizeobj['name']][index] + '" name="' + fullscreen_images[sizeobj['name']][index] + '">' +
1271 img_preview + '</a>')
1273 #- remember in which thumbnails page is this element, for element->thumbnail link
1274 if sizeobj == $images_size[0]
1275 element2thumbnailpage4js << pagecount
1278 if counter == $N_per_page
1279 html_thumbnails += close_iterations(iterations)
1280 html_thumbnails_nojs += close_iterations(iterations)
1281 all_pages << [ html_thumbnails, html_thumbnails_nojs ]
1282 html_thumbnails = ''
1283 html_thumbnails_nojs = ''
1285 reset_iterations(iterations)
1291 html_thumbnails += close_iterations(iterations)
1292 html_thumbnails_nojs += close_iterations(iterations)
1293 all_pages << [ html_thumbnails, html_thumbnails_nojs ]
1296 i.gsub!(/~~theme~~/, $theme)
1297 i.gsub!(/~~current_size~~/, sizeobj['name'])
1298 i.gsub!(/~~htmlsuffix~~/, $htmlsuffix)
1299 i.gsub!(/~~current_size_js~~/, size2js(sizeobj['name']))
1300 i.gsub!(/~~madewith~~/, $madewith || '')
1301 i.gsub!(/~~indexlink~~/, $indexlink || '')
1302 if !$indexlink || $indexlink.empty?
1303 i.gsub!(/~~ifindexlink\?~~(.+?)~~fi~~/) { }
1305 i.gsub!(/~~ifindexlink\?~~(.+?)~~fi~~/) { $1 }
1307 substitute_addthis(i)
1308 substitute_navigation(i, xmldir)
1310 html_nojs = html.collect { |l| l.clone }
1312 for page in all_pages
1313 html_thumbnails, html_thumbnails_nojs = page
1314 final_html = html.collect { |l| l.clone }
1315 mstuff = defer_translation(N_("Pages: ")) +
1316 (pagecount > 0 ? "<a href=\"thumbnails-#{size2js(sizeobj['name'])}%nojs-#{pagecount - 1}#{$htmlsuffix}\">" + defer_translation(N_("<- Previous")) + "</a> " : '') +
1317 all_pages.collect_with_index { |p,idx| page == p ? idx + 1 : "<a href=\"thumbnails-#{size2js(sizeobj['name'])}%nojs-#{idx}#{$htmlsuffix}\">#{idx + 1}</a>" }.join(', ') +
1318 (pagecount < all_pages.size - 1 ? " <a href=\"thumbnails-#{size2js(sizeobj['name'])}%nojs-#{pagecount + 1}#{$htmlsuffix}\">" + defer_translation(N_("Next ->")) + "</a> " : '')
1320 i.sub!(/~~run_slideshow_link~~/, entries.size <= 1 ? '' : 'image-' + size2js(sizeobj['name']) + $htmlsuffix + '#run_slideshow=1')
1321 i.sub!(/~~run_slideshow_text~~/, defer_translation(N_("Run slideshow!")))
1322 i.sub!(/~~run_slideshow~~/,
1323 entries.size <= 1 ? '' : '<a href="image-' + size2js(sizeobj['name']) + $htmlsuffix + '#run_slideshow=1">' + defer_translation(N_("Run slideshow!"))+'</a>')
1324 i.sub!(/~~thumbnails~~/, html_thumbnails)
1325 if all_pages.size == 1
1326 i.gsub!(/~~ifmultiplepages\?~~.*~~fi~~/, '')
1328 i.gsub!(/~~ifmultiplepages\?~~(.+?)~~fi~~/) { $1 }
1329 i.gsub!(/~~multiplepagesstuff~~/, mstuff.gsub('%nojs', ''))
1331 substitute_html_sizes(i, sizeobj, 'thumbnails', "-#{pagecount}")
1332 substitute_pathtobase(i, xmldir)
1334 save_html(final_html, "#{dest_dir}/thumbnails-#{size2js(sizeobj['name'])}-#{pagecount}")
1335 final_html_nojs = html_nojs.collect { |l| l.clone }
1336 for i in final_html_nojs
1337 i.sub!(/~~run_slideshow~~/, defer_translation(N_("<i>Click on an image to view it larger</i>")))
1338 i.sub!(/~~thumbnails~~/, html_thumbnails_nojs)
1339 if all_pages.size == 1
1340 i.gsub!(/~~ifmultiplepages\?~~.*~~fi~~/, '')
1342 i.gsub!(/~~ifmultiplepages\?~~(.+?)~~fi~~/) { $1 }
1343 i.gsub!(/~~multiplepagesstuff~~/, mstuff.gsub('%nojs', '-nojs'))
1345 substitute_html_sizes(i, sizeobj, 'thumbnails', "-nojs-#{pagecount}")
1346 substitute_pathtobase(i, xmldir)
1348 save_html(final_html_nojs, "#{dest_dir}/thumbnails-#{size2js(sizeobj['name'])}-nojs-#{pagecount}")
1353 info("finished processing sizes")
1355 #- generate "main" thumbnails.html page that will reload to correct size thanks to cookie
1356 save_html(html_reload_to_thumbnails, "#{dest_dir}/thumbnails")
1358 #- generate image.html (page with fullscreen images)
1363 type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
1365 caption = find_caption_value(xmldir, file)
1367 captions4js << '"' + quote_caption(caption, true) + '"'
1371 types4js << '"' + type + '"'
1373 index = videos.index(file)
1375 videos4js << '"' + flv_videos[videos[index]] + '"'
1377 videos4js << '"' + videos[index] + '"'
1385 for sizeobj in $images_size
1388 elemsheights4js = []
1390 type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
1393 index = images.index(file)
1394 elements4js << '"' + fullscreen_images[sizeobj['name']][index] + '"'
1395 size = get_image_size("#{dest_dir}/#{fullscreen_images[sizeobj['name']][index]}")
1397 elemswidths4js << size[:x].to_s
1398 elemsheights4js << size[:y].to_s
1400 elemswidths4js << "''"
1401 elemsheights4js << "''"
1404 index = videos.index(file)
1405 elements4js << '"' + fullscreen_videos[sizeobj['name']][index] + '"'
1406 size = get_image_size("#{dest_dir}/#{fullscreen_videos[sizeobj['name']][index]}")
1408 elemswidths4js << size[:x].to_s
1409 elemsheights4js << size[:y].to_s
1411 elemswidths4js << "''"
1412 elemsheights4js << "''"
1418 html = $html_images.collect { |l| l.clone }
1419 hiddenimages4remotes = '<span style="display:none">' + thumbnail_images[sizeobj['name']][0..4].collect { |e| "<img src=\"#{e}\"/>" }.join('') + '</span>'
1420 otherelements4js = ''
1422 for sizeobj2 in all_images_sizes
1423 if sizeobj != sizeobj2
1426 type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
1429 index = images.index(file)
1430 oe4js << '"' + fullscreen_images[sizeobj2['name']][index] + '"'
1431 elsif sizeobj2['name'] != 'original'
1432 index = videos.index(file)
1433 oe4js << '"' + fullscreen_videos[sizeobj2['name']][index] + '"'
1437 otherelements4js += "var elements_#{size2js(sizeobj2['name'])} = new Array(" + oe4js.join(', ') + ");\n"
1438 othersizes << "\"#{size2js(sizeobj2['name'])}\""
1442 i.gsub!(/~~images~~/, elements4js.join(', '))
1443 i.gsub!(/~~types~~/, types4js.join(', '))
1444 i.gsub!(/~~videos~~/, videos4js.join(', '))
1445 i.gsub!(/~~widths~~/, elemswidths4js.join(', '))
1446 i.gsub!(/~~heights~~/, elemsheights4js.join(', '))
1447 i.gsub!(/~~hidden_images_for_remotes~~/, hiddenimages4remotes)
1448 i.gsub!(/~~other_images~~/, otherelements4js)
1449 i.gsub!(/~~thumbnailspages~~/, element2thumbnailpage4js.collect { |e| "\"#{e}\"" }.join(', '))
1450 i.gsub!(/~~other_sizes~~/, othersizes.join(', '))
1451 i.gsub!(/~~captions~~/, captions4js.join(', '))
1452 i.gsub!(/~~title~~/, quote_caption(xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir))))
1453 if $flv_generator && videos.size > 0
1454 i.sub!(/~~flowplayer_head_code~~/, '<script type="text/javascript" src="~~pathtobase~~flowplayer-3.2.6.min.js"></script>')
1455 i.sub!(/~~flowplayer_active~~/, 'true')
1457 i.sub!(/~~flowplayer_head_code~~/, '')
1458 i.sub!(/~~flowplayer_active~~/, 'false')
1461 i.gsub!(/~~thumbnails~~/, '<a id="thumbnails">' + defer_translation(N_('return to thumbnails')) + '</a>')
1462 i.gsub!(/~~theme~~/, $theme)
1463 i.gsub!(/~~current_size~~/, size2js(sizeobj['name']))
1464 i.gsub!(/~~htmlsuffix~~/, $htmlsuffix)
1465 i.gsub!(/~~madewith~~/, $madewith || '')
1466 i.gsub!(/~~indexlink~~/, $indexlink || '')
1467 if !$indexlink || $indexlink.empty?
1468 i.gsub!(/~~ifindexlink\?~~(.+?)~~fi~~/) { }
1470 i.gsub!(/~~ifindexlink\?~~(.+?)~~fi~~/) { $1 }
1472 substitute_addthis(i)
1473 substitute_html_sizes(i, sizeobj, 'image', '')
1474 substitute_navigation(i, xmldir)
1475 substitute_pathtobase(i, xmldir)
1477 save_html(html, "#{dest_dir}/image-#{size2js(sizeobj['name'])}")
1484 #- add attributes to <dir..> elements needing so
1485 if $mode != 'use_config'
1486 msg 3, _("\tfixating configuration file...")
1487 $xmldoc.elements.each('//dir') { |element|
1488 path = captionpath = element.attributes['path']
1489 descendant_element = nil
1490 #- search if there is at least one image or video down that dir; use workarounds to rexml slowness
1491 #- first, look down only one level, very fast
1493 element.elements.each { |elem|
1497 if elem.name == 'image' || elem.name == 'video'
1498 descendant_element = elem
1502 if descendant_element.nil?
1503 #- if there was nothing or only directory down one level, look down the first subdir
1504 if ! first_desc.nil?
1505 first_desc.elements.each { |elem|
1506 if elem.name == 'image' || elem.name == 'video'
1507 descendant_element = elem
1512 if descendant_element.nil?
1513 #- if there was still nothing found, use complete albeit slow method
1514 descendant_element = element.elements['descendant::image'] || element.elements['descendant::video']
1517 if !descendant_element
1518 msg 3, _("\t\tremoving %s, no element in it") % path
1519 element.remove #- means we have a directory with nothing interesting in it
1521 captionfile = "#{descendant_element.parent.attributes['path']}/#{descendant_element.attributes['filename']}"
1522 basename = File.basename(path)
1523 if element.elements['dir']
1524 if !element.attributes['subdirs-caption']
1525 element.add_attribute('subdirs-caption', basename)
1527 if !element.attributes['subdirs-captionfile']
1528 element.add_attribute('subdirs-captionfile', captionfile)
1531 if element.child_byname_notattr('image', 'deleted') || element.child_byname_notattr('video', 'deleted')
1532 if !element.attributes['thumbnails-caption']
1533 element.add_attribute('thumbnails-caption', basename)
1535 if !element.attributes['thumbnails-captionfile']
1536 element.add_attribute('thumbnails-captionfile', captionfile)
1543 #- write down to disk config if necessary
1545 ios = File.open($config_writeto, "w")
1551 msg 3, _("completed necessary stuff for GUI, exiting.")
1555 #- second pass to create index.html files and previous/next links
1556 info("creating index.html")
1557 msg 3, _("\trescanning directories to generate all 'index.html' files...")
1559 #- recompute the memoization because elements mights have been removed (the ones with no element in them)
1561 $xmldoc.elements.each('//dir') { |elem|
1562 optxpath[elem.attributes['path']] = elem
1565 examined_dirs.each { |dir|
1566 info("index.html: #{dir}|#{$source}")
1568 xmldir = optxpath[utf8(dir)]
1569 if !xmldir || (xmldir.attributes['already-generated'] && !$force) || xmldir.attributes['deleted']
1572 dest_dir = make_dest_filename(dir.sub(/^#{Regexp.quote($source)}/, $dest))
1574 previous_album = find_previous_album(xmldir)
1575 next_album = find_next_album(xmldir)
1577 if xmldir.elements['dir']
1578 html = $html_index.collect { |l| l.clone }
1581 caption = xmldir.attributes['subdirs-caption']
1582 i.gsub!(/~~title~~/, quote_caption(caption))
1583 substitute_navigation(i, xmldir)
1584 substitute_pathtobase(i, xmldir)
1585 discover_iterations(iterations, i)
1589 reset_iterations(iterations)
1591 #- deal with "current" album (directs to "thumbnails" page)
1592 if xmldir.attributes['thumbnails-caption']
1593 thumbnail = "#{dest_dir}/thumbnails-thumbnail.jpg"
1594 gen_thumbnails_subdir(from_utf8(xmldir.attributes['thumbnails-captionfile']), xmldir, false,
1595 [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ], 'thumbnails')
1596 html_index += run_iterations(iterations, 1)
1597 caption = xmldir.attributes['thumbnails-caption']
1598 html_index.gsub!(/~~image_iteration~~/, "<a href=\"thumbnails#{$htmlsuffix}\">" + img_element(thumbnail, caption) + '</a>')
1599 html_index.gsub!(/~~caption_iteration~~/, quote_caption(caption))
1602 #- deal with sub-albums (direct to subdirs/index.html pages)
1603 xmldir.elements.each('dir') { |child|
1604 if child.attributes['deleted']
1607 subdir = make_dest_filename(from_utf8(File.basename(child.attributes['path'])))
1608 thumbnail = "#{dest_dir}/thumbnails-#{subdir}.jpg"
1609 html_index += run_iterations(iterations, 1)
1610 captionfile, caption = find_subalbum_caption_info(child)
1611 gen_thumbnails_subdir(captionfile, child, false,
1612 [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ], find_subalbum_info_type(child))
1613 html_index.gsub!(/~~caption_iteration~~/, quote_caption(caption))
1614 html_index.gsub!(/~~image_iteration~~/, "<a href=\"#{subdir}/index#{$htmlsuffix}\">" + img_element(thumbnail, caption) + '</a>')
1617 html_index += close_iterations(iterations)
1620 i.gsub!(/~~thumbnails~~/, html_index)
1621 i.gsub!(/~~madewith~~/, $madewith || '')
1622 i.gsub!(/~~indexlink~~/, $indexlink || '')
1623 if !$indexlink || $indexlink.empty?
1624 i.gsub!(/~~ifindexlink\?~~(.+?)~~fi~~/) { }
1626 i.gsub!(/~~ifindexlink\?~~(.+?)~~fi~~/) { $1 }
1628 substitute_addthis(i)
1632 html = html_reload_to_thumbnails
1635 save_html(html, "#{dest_dir}/index")
1637 #- in case MultiViews will not work, generate some compat
1638 ios = File.open("#{dest_dir}/index.html", "w")
1639 ios.write("<html><head><meta http-equiv=\"refresh\" content=\"0.1;url=index.#{$multi_languages[1]}.html\"></head></html>")
1643 #- substitute multiple "return to albums", previous/next correctly
1644 #- the following two statements are dramatical optimizations to executing for each substInFile callback
1645 dirpresent = xmldir.elements['dir']
1646 parentname = xmldir.parent.name
1647 if xmldir.child_byname_notattr('image', 'deleted') || xmldir.child_byname_notattr('video', 'deleted')
1648 for suffix in [ '', '-nojs' ]
1649 for sizeobj in $images_size
1650 Dir.glob("#{dest_dir}/thumbnails-#{size2js(sizeobj['name'])}#{suffix}-*.html") do |file|
1651 #- unroll translations, they are costly if rerun for each line of files
1652 rta = find_translation_for_file(file, N_('return to albums'))
1653 pa = find_translation_for_file(file, N_('previous album'))
1654 na = find_translation_for_file(file, N_('next album'))
1655 substInFile(file) { |line|
1656 sub_previous_next_album(file, previous_album, next_album, line, pa, na)
1658 line.sub!(/~~return_to_albums~~/, '<a href="index' + $htmlsuffix + '">' + rta + '</a>')
1660 if parentname == 'dir'
1661 line.sub!(/~~return_to_albums~~/, '<a href="../index' + $htmlsuffix + '">' + rta + '</a>')
1663 line.sub!(/~~return_to_albums~~/, '')
1669 if suffix == '' && xmldir.child_byname_notattr('image', 'deleted')
1670 Dir.glob("#{dest_dir}/image-#{size2js(sizeobj['name'])}*.html") do |file|
1671 pa = find_translation_for_file(file, N_('previous album'))
1672 na = find_translation_for_file(file, N_('next album'))
1673 substInFile(file) { |line|
1674 sub_previous_next_album(file, previous_album, next_album, line, pa, na)
1683 msg 3, _(" all done.")
1690 build_html_skeletons