no longer use internalized rexml
[booh] / bin / booh-backend
old mode 100755 (executable)
new mode 100644 (file)
index 5a512c2..12de9d8
@@ -10,7 +10,7 @@
 # called Boo, so this one will be it "Booh". Or whatever.
 #
 #
-# Copyright (c) 2004-2008 Guillaume Cottenceau <http://zarb.org/~gc/resource/gc_mail.png>
+# Copyright (c) 2004-2013 Guillaume Cottenceau <http://zarb.org/~gc/resource/gc_mail.png>
 #
 # This software may be freely redistributed under the terms of the GNU
 # public license version 2.
 # along with this program; if not, write to the Free Software
 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
+begin
+    require 'rubygems'
+rescue LoadError
+end
+
 require 'getoptlong'
+begin
+    #- new style (ruby-locale separated package)
+    require 'locale'
+rescue LoadError
+    #- old style (locale stuff in ruby-gettext package)
+    require 'gettext/locale'
+end
 require 'gettext'
-require 'gettext/locale'
 include GetText
-require 'booh/rexml/document'
+require 'rexml/document'
 include REXML
 
 require 'booh/booh-lib'
@@ -58,8 +69,11 @@ $options = [
     [ '--thumbnails-per-page', '-p', GetoptLong::REQUIRED_ARGUMENT, _("Specify the amount of thumbnails per page in the thumbnails page, after which split occurs") ],
     [ '--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)") ],
     [ '--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") ],
+    [ '--mp4-generator', '-F', GetoptLong::REQUIRED_ARGUMENT, _("Use this .mp4 generator (%f is the placeholder for the input video, %o for the output video)") ],
     [ '--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)") ],
+    [ '--addthis', '-a', GetoptLong::NO_ARGUMENT, _("Include the 'addthis' bookmarking and sharing button") ],
     [ '--made-with',     '-n', GetoptLong::REQUIRED_ARGUMENT, _("Specify the HTML markup to use on the bottom of pages for a small 'made with' message") ],
+    [ '--quote-html',    '-q', GetoptLong::NO_ARGUMENT, _("Quote HTML markup in captions") ],
     [ '--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") ],
 
     [ '--mproc',         '-m', GetoptLong::REQUIRED_ARGUMENT, _("Specify the number of processors for multi-processors machines") ],
@@ -98,7 +112,7 @@ def handle_options
             when '--version'
                 puts _("Booh version %s
 
-Copyright (c) 2005-2008 Guillaume Cottenceau.
+Copyright (c) 2005-2013 Guillaume Cottenceau.
 This is free software; see the source for copying conditions.  There is NO
 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.") % $VERSION
 
@@ -220,12 +234,24 @@ warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.") %
                 end
                 $transcode_videos = arg
 
+            when '--mp4-generator'
+                if arg !~ /%f/ || arg !~ /%o/
+                    die _("--mp4-generator: argument must contain %f for the input video and %o for the output video")
+                end
+                $mp4_generator = arg
+
             when '--made-with'
                 $madewith = arg
 
             when '--index-link'
                 $indexlink = arg
 
+            when '--addthis'
+                $addthis = true
+
+            when '--quote-html'
+                $quote_html = true
+
             when '--comments-format'
                 $commentsformat = arg
 
@@ -269,6 +295,8 @@ warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.") %
             $N_per_page = $xmldoc.root.attributes['thumbnails-per-page']
             $madewith = $xmldoc.root.attributes['made-with']
             $indexlink = $xmldoc.root.attributes['index-link']
+            $addthis = !$xmldoc.root.attributes['addthis'].nil?
+            $quote_html = !$xmldoc.root.attributes['quote-html'].nil?
         end
     end
 
@@ -287,7 +315,7 @@ warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.") %
         die _("Missing --destination parameter.")
     end
     if !$theme
-        $theme = 'simple'
+        $theme = 'gradient'
     end
 
     select_theme($theme, $limit_sizes, $optimize_for_32, $N_per_row)
@@ -320,6 +348,12 @@ warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.") %
         if $indexlink
             $xmldoc.root.add_attribute('index-link', $indexlink)
         end
+        if $addthis
+            $xmldoc.root.add_attribute('addthis', 'true')
+        end
+        if $quote_html
+            $xmldoc.root.add_attribute('quote-html', 'true')
+        end
         $mode = 'gen_config'
     end
 
@@ -362,6 +396,16 @@ warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.") %
         else
             $xmldoc.root.delete_attribute('index-link')
         end
+        if $addthis
+            $xmldoc.root.add_attribute('addthis', 'true')
+        else
+            $xmldoc.root.delete_attribute('addthis')
+        end
+        if $quote_html
+            $xmldoc.root.add_attribute('quote-html', 'true')
+        else
+            $xmldoc.root.delete_attribute('quote-html')
+        end
     end
 
     if $transcode_videos
@@ -370,6 +414,12 @@ warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.") %
         $xmldoc.root.delete_attribute('transcode-videos')
     end
 
+    if $mp4_generator
+        $xmldoc.root.add_attribute('mp4-generator', $mp4_generator)
+    else
+        $xmldoc.root.delete_attribute('mp4-generator')
+    end
+
     if $madewith
         $madewith = $madewith.gsub('%booh', '"http://booh.org/"')
     end
@@ -427,9 +477,9 @@ def replace_line(surround, keyword, line)
 end
 
 def build_html_skeletons
-    $html_images     = File.open("#{$FPATH}/themes/#{$theme}/skeleton_image.html").readlines
-    $html_thumbnails = File.open("#{$FPATH}/themes/#{$theme}/skeleton_thumbnails.html").readlines
-    $html_index      = File.open("#{$FPATH}/themes/#{$theme}/skeleton_index.html").readlines
+    $html_images     = File.open("#{$themedir}/skeleton_image.html").readlines
+    $html_thumbnails = File.open("#{$themedir}/skeleton_thumbnails.html").readlines
+    $html_index      = File.open("#{$themedir}/skeleton_index.html").readlines
     for line in $html_images + $html_thumbnails + $html_index
         while line =~ /~~~(\w+)~~~/
             replace_line('~~~', $1, line)
@@ -439,14 +489,20 @@ end
 
 def find_caption_value(xmldir, filename)
     if cap = xmldir.elements["*[@filename='#{utf8(filename)}']"].attributes['caption']
-        return cap.gsub("\n", '<br/>')
+        return cap
     else
         return nil
     end
 end
 
-def find_captions(xmldir, images)
-    return images.collect { |img| find_caption_value(xmldir, img) }
+def quote_caption(input, *for_attribute)
+    if $quote_html
+        return input.gsub('<', '&lt;').gsub('>', '&gt;').gsub('"', '&quot;').gsub("'", '&#39;').gsub("\n", '<br/>')
+    elsif for_attribute[0]
+        return input.gsub('"', '&quot;').gsub("\n", '<br/>')
+    else
+        return input.gsub("\n", '<br/>')
+    end
 end
 
 #- stolen from CVSspam
@@ -463,7 +519,7 @@ end
 def html_reload_to_thumbnails
     html_reload_to_thumbnails = $preferred_size_reloader.clone
     html_reload_to_thumbnails.gsub!(/~~theme~~/, $theme)
-    html_reload_to_thumbnails.gsub!(/~~default_size~~/, $default_size['name'])
+    html_reload_to_thumbnails.gsub!(/~~default_size~~/, size2js($default_size['name']))
     html_reload_to_thumbnails.gsub!(/~~htmlsuffix~~/, $htmlsuffix)
     html_reload_to_thumbnails.gsub!(/~~all_sizes~~/, all_images_sizes.collect { |s| "\"#{size2js(s['name'])}\"" }.join(', '))
     size_auto_chooser = '';
@@ -548,13 +604,13 @@ def close_iterations(iterations)
     return html
 end
 
-def img_element(fullpath)
+def img_element(fullpath, caption)
     if size = get_image_size(fullpath)
         sizespec = 'width="' + size[:x].to_s + '" height="' + size[:y].to_s + '"'
     else
         sizespec = ''
     end
-    return '<img src="' + File.basename(fullpath) + '" ' + sizespec + ' alt="image"/>'
+    return '<img src="' + File.basename(fullpath) + '" ' + sizespec + ' alt="' + quote_caption(caption, true) + '"/>'
 end
 
 def size2js(name)
@@ -578,7 +634,7 @@ def substitute_html_sizes(html, sizeobj, type, suffix)
             end
         end
         if type == 'image' && $limit_sizes =~ /original/
-            sizestrings << '<a id="linkoriginal" target="newframe">' + defer_translation(sizename('original'), false) + '</a>'
+            sizestrings << '<a id="linkoriginal" target="newframe">' + defer_translation(sizename('original', false)) + '</a>'
         end
     end
     html.sub!(/~~sizes~~(.+)~~/) { sizestrings.join($1) }
@@ -587,21 +643,29 @@ end
 def substitute_navigation(html, xmldir)
     if xmldir.parent.name == 'dir'
         nav = ''
+        navtable = ''
         path = '..'
         parent = xmldir.parent
         while parent.name == 'dir'
             parentcaption = parent.attributes['subdirs-caption'] || File.basename(parent.attributes['path'])
             nav = "<a href=\"#{path}/index#{$htmlsuffix}\">#{parentcaption}</a> #{defer_translation(N_(" > "))} #{nav}"
+            navtable = "<td><a href=\"#{path}/index#{$htmlsuffix}\">#{parentcaption}</a></td>#{navtable}"
             path += '/..'
             parent = parent.parent
         end
         html.gsub!(/~~ifnavigation\?~~(.+?)~~fi~~/) { $1 }
         html.gsub!(/~~navigation~~/, nav + (xmldir.attributes['subdirs-caption'] || File.basename(xmldir.attributes['path'])))
+        html.gsub!(/~~navigationtable~~/, '<table id="navigation"><tr>' + navtable + "<td>" +
+                                          (xmldir.attributes['subdirs-caption'] || File.basename(xmldir.attributes['path'])) + "</td></tr></table>")
     else
         html.gsub!(/~~ifnavigation\?~~(.+?)~~fi~~/, '')
     end
 end
 
+def substitute_addthis(html)
+    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>' : '')
+end
+
 def substitute_pathtobase(html, xmldir)
     path = ''
     location = xmldir
@@ -725,6 +789,18 @@ def save_html(html, base_filename)
     end
 end
 
+def apply_hook(name, content, *params)
+    if $hooks.nil?
+        return content
+    end
+    hook = $hooks[name]
+    if hook.nil?
+        return content
+    else
+        return hook.call(content, *params)
+    end
+end
+
 def walk_source_dir
 
     #- preprocess the path->dir, rexml is very slow with that; we seem to improve speed by 7%
@@ -737,9 +813,9 @@ def walk_source_dir
     if $mode == 'merge_config_onedir'
         examined_dirs = [ $onedir ]
     elsif $mode == 'merge_config_subdirs'
-        examined_dirs = `find '#{$onedir}' -type d -follow`.sort.collect { |v| v.chomp }.delete_if { |v| optxpath.has_key?(utf8(v)) }
+        examined_dirs = `find '#{$onedir}' -type d -follow`.split("\n").sort.collect { |v| v.chomp }.delete_if { |v| optxpath.has_key?(utf8(v)) }
     else
-        examined_dirs = `find '#{$source}' -type d -follow`.sort.collect { |v| v.chomp }
+        examined_dirs = `find '#{$source}' -type d -follow`.split("\n").sort.collect { |v| v.chomp }
         if $mode == 'merge_config'
             $xmldoc.elements.each('//dir') { |elem|
                 if ! examined_dirs.include?(elem.attributes['path'])
@@ -797,6 +873,14 @@ def walk_source_dir
         end
         xmldir.delete_attribute('already-generated')
 
+        #- preprocess all the existing elements, rexml is slow with that
+        optelements = {}
+        xmldir.elements.each { |elem|
+            if filename = elem.attributes['filename']
+                optelements[elem.name + '|' + filename] = elem
+            end
+        }
+
         #- read images/videos entries from config or from directories depending on mode
         entries = []
         if $mode == 'use_config' || $mode == 'use_config_changetheme'
@@ -815,14 +899,14 @@ def walk_source_dir
                     msg 1, _("Ignoring %s, contains one of forbidden characters: '\"[]") % "#{dir}/#{file}"
                 else
                     type = entry2type(file)
-                    if type && !xmldir.elements["#{type}[@filename='#{utf8(file)}']"]
+                    if type && ! optelements[type + '|' + utf8(file)]
                         #- hack: don't run identify (which is slow) if format only contains default %t
                         if $commentsformat && type == 'image' && $commentsformat != '%t'
                             comment = utf8(`identify -format "#{$commentsformat}" '#{dir}/#{file}'`.chomp.sub(/\.$/, ''))
                         else
                             comment = utf8cut(file.sub(/\.[^\.]+$/, ''), 18)
                         end
-                        xmldir.add_element type, { "filename" => utf8(file), "caption" => comment }
+                        optelements[type + '|' + utf8(file)] = xmldir.add_element(type, { "filename" => utf8(file), "caption" => comment })
                     end
                 end
             end
@@ -859,12 +943,18 @@ def walk_source_dir
         if !$forgui
             ios = File.open("#{dest_dir}/.htaccess", "w")
             ios.write("AddCharset UTF-8 .html\n")
+            ios.write("\n")
+            ios.write("<IfModule mod_expires.c>\n")
+            ios.write(" ExpiresActive On\n")
+            ios.write(" ExpiresDefault A1800\n")
+            ios.write("</IfModule>")
+            ios.write("\n")
             if auth_user_file = xmldir.attributes['password-protect']
                 msg 3, _("\tgenerating password protection file #{dest_dir}/.htaccess")
                 ios.write("AuthType Basic\nAuthName \"protected area\"\nAuthUserFile #{auth_user_file}\nrequire valid-user\n")
             end
             if $multi_languages
-                ios.write("Options Multiviews\n")
+                ios.write("Options +Multiviews\n")
                 ios.write("LanguagePriority #{$multi_languages[1]}\n")
                 ios.write("ForceLanguagePriority Prefer Fallback\n")
                 ios.write("DirectoryIndex index\n")
@@ -895,21 +985,21 @@ def walk_source_dir
                 end
                 
                 #- copy any resource file that goes with the theme (css, images..)
-                themestuff = Dir.entries("#{$FPATH}/themes/#{$theme}").
-                                 find_all { |e| !%w(. .. skeleton_image.html skeleton_thumbnails.html skeleton_index.html metadata root CVS).include?(e) }
+                themestuff = Dir.entries("#{$themedir}").
+                                 find_all { |e| !%w(. .. skeleton_image.html skeleton_thumbnails.html skeleton_index.html metadata root).include?(e) }
                 themestuff.each { |entry|
                     if !File.exists?(File.join(dest_dir, entry))
-                        psys("cp '#{$FPATH}/themes/#{$theme}/#{entry}' '#{dest_dir}'")
+                        psys("cp '#{$themedir}/#{entry}' '#{dest_dir}'")
                     end
                 }
 
                 #- copy any root-only resource file that goes with the theme (css, images..)
                 if xmldir.parent.name != 'dir'
-                    themestuff_root = Dir.entries("#{$FPATH}/themes/#{$theme}/root").
-                                          find_all { |e| !%w(. .. CVS).include?(e) }
+                    themestuff_root = Dir.entries("#{$themedir}/root").
+                                          find_all { |e| !%w(. ..).include?(e) }
                     themestuff_root.each { |entry|
                         if !File.exists?(File.join(dest_dir, entry))
-                            psys("cp '#{$FPATH}/themes/#{$theme}/root/#{entry}' '#{dest_dir}'")
+                            psys("cp '#{$themedir}/root/#{entry}' '#{dest_dir}'")
                         end
                     }
                 end
@@ -925,6 +1015,8 @@ def walk_source_dir
             fullscreen_images[sizeobj['name']] = []
             thumbnail_images ||= {}
             thumbnail_images[sizeobj['name']] = []
+            fullscreen_videos ||= {}
+            fullscreen_videos[sizeobj['name']] = []
             thumbnail_videos ||= {}
             thumbnail_videos[sizeobj['name']] = []
         end
@@ -932,6 +1024,7 @@ def walk_source_dir
         thumbnail_images['dont-delete-file-for-gui'] = []
         if $limit_sizes =~ /original/
             fullscreen_images['original'] = []
+            fullscreen_videos['original'] = []
         end
 
         images.size >= 1 and msg 3, _("\tcreating photos thumbnails...")
@@ -940,12 +1033,12 @@ def walk_source_dir
         images.each { |img|
             info("processing element")
             base_dest_img = dest_dir + '/' + make_dest_filename(img.sub(/\.[^\.]+$/, ''))
+            elem = optelements['image|' + utf8(img)]
             if $forgui
                 thumbnail_dest_img = base_dest_img + "-#{$default_size['thumbnails']}.jpg"
-                gen_thumbnails_element("#{dir}/#{img}", xmldir, true, [ { 'filename' => thumbnail_dest_img, 'size' => $default_size['thumbnails'] } ])
+                gen_thumbnails_element("#{dir}/#{img}", elem, true, [ { 'filename' => thumbnail_dest_img, 'size' => $default_size['thumbnails'] } ])
             else
                 todo = []
-                elem = xmldir.elements["image[@filename='#{utf8(img)}']"]
                 for sizeobj in $images_size
                     size_fullscreen = sizeobj['fullscreen']
                     size_thumbnails = sizeobj['thumbnails']
@@ -958,9 +1051,9 @@ def walk_source_dir
                     end
                     thumbnail_dest_img = base_dest_img + "-#{size_thumbnails}.jpg"
                     thumbnail_images[sizeobj['name']] << File.basename(thumbnail_dest_img)
-                    todo << { 'filename' => thumbnail_dest_img,  'size' => size_thumbnails }
+                    todo << { 'filename' => thumbnail_dest_img, 'size' => size_thumbnails }
                 end
-                gen_thumbnails_element("#{dir}/#{img}", xmldir, true, todo)
+                gen_thumbnails_element("#{dir}/#{img}", elem, true, todo)
                 if $limit_sizes =~ /original/
                     fullscreen_images['original'] << img
                 end
@@ -980,22 +1073,29 @@ def walk_source_dir
 
         videos.size >= 1 and msg 3, _("\tcreating videos thumbnails...")
         transcoded_videos = {}
+        mp4_videos = {}
 
         #- create thumbnails for videos
         videos.each { |video|
             info("processing element")
+            base_dest_img = dest_dir + '/' + make_dest_filename(video.sub(/\.[^\.]+$/, ''))
+            elem = optelements['video|' + utf8(video)]
             if $forgui
-                thumbnail_dest_img = dest_dir + '/' + make_dest_filename(video.sub(/\.[^\.]+$/, '')) + "-#{$default_size['thumbnails']}.jpg"
-                gen_thumbnails_element("#{dir}/#{video}", xmldir, true, [ { 'filename' => thumbnail_dest_img, 'size' => $default_size['thumbnails'] } ])
+                thumbnail_dest_img = base_dest_img + "-#{$default_size['thumbnails']}.jpg"
+                gen_thumbnails_element("#{dir}/#{video}", elem, true, [ { 'filename' => thumbnail_dest_img, 'size' => $default_size['thumbnails'] } ])
             else
                 todo = []
                 for sizeobj in $images_size
+                    size_fullscreen = sizeobj['fullscreen']
                     size_thumbnails = sizeobj['thumbnails']
-                    thumbnail_dest_img = dest_dir + '/' + make_dest_filename(video.sub(/\.[^\.]+$/, '')) + "-#{size_thumbnails}.jpg"
+                    fullscreen_dest_img = base_dest_img + "-#{size_fullscreen}.jpg"
+                    fullscreen_videos[sizeobj['name']] << File.basename(fullscreen_dest_img)
+                    todo << { 'filename' => fullscreen_dest_img, 'size' => size_fullscreen }
+                    thumbnail_dest_img = base_dest_img + "-#{size_thumbnails}.jpg"
                     thumbnail_videos[sizeobj['name']] << File.basename(thumbnail_dest_img)
                     todo << { 'filename' => thumbnail_dest_img, 'size' => size_thumbnails }
                 end
-                gen_thumbnails_element("#{dir}/#{video}", xmldir, true, todo)
+                gen_thumbnails_element("#{dir}/#{video}", elem, true, todo)
 
                 if $transcode_videos
                     parts = $transcode_videos.split(':', 2)
@@ -1005,6 +1105,20 @@ def walk_source_dir
                     if ! File.exists?(destvideo)
                         psys(parts[1].gsub(/%f/, "'#{dir}/#{video}'").gsub(/%o/, "'#{destvideo}'"))
                     end
+
+                elsif $mp4_generator
+                    msg 3, "video1"
+                    basedestvideo = video.sub(/\.\w+/, '') + '.mp4'
+                    mp4_videos[video] = basedestvideo
+                    destvideo = "#{dest_dir}/#{basedestvideo}"
+                    if File.exists?(destvideo) && File.size(destvideo) == 0
+                        File.delete(destvideo)
+                    end
+                    if ! File.exists?(destvideo)
+                        psys($mp4_generator.gsub(/%f/, "'#{dir}/#{video}'").gsub(/%o/, "'#{destvideo}'"))
+                    end
+                    msg 3, "video2"
+
                 else
                     destvideo = "#{dest_dir}/#{video}"
                     if ! File.exists?(destvideo)
@@ -1025,50 +1139,50 @@ def walk_source_dir
             #- cleanup old images/videos (for when removing elements or sizes)
             all_elements = fullscreen_images.collect { |e| e[1] }.flatten.
                      concat(thumbnail_images.collect { |e| e[1] }.flatten).
+                     concat(fullscreen_videos.collect { |e| e[1] }.flatten).
                      concat(thumbnail_videos.collect { |e| e[1] }.flatten).
-                     concat($transcode_videos ? transcoded_videos.values : videos).
+                     concat($transcode_videos ? transcoded_videos.values : $mp4_generator ? mp4_videos.values : videos).
                      push('.htaccess')
             to_del = Dir.entries(dest_dir).find_all { |e| !File.directory?(File.join(dest_dir, e)) && !all_elements.include?(e) && e !~ /^thumbnails-\w+\.jpg/ }
             if to_del.size > 0
-                msg 3, _("\tcleaning up: #{to_del.join(', ')}")
+                msg 3, _("\tcleaning up: ") + to_del.join(', ')
                 File.delete(*to_del.collect { |e| File.join(dest_dir, e) })
             end
 
             #- copy any resource file that goes with the theme (css, images..)
-            themestuff = Dir.entries("#{$FPATH}/themes/#{$theme}").
-                             find_all { |e| !%w(. .. skeleton_image.html skeleton_thumbnails.html skeleton_index.html metadata root CVS).include?(e) }
+            themestuff = Dir.entries("#{$themedir}").
+                             find_all { |e| !%w(. .. skeleton_image.html skeleton_thumbnails.html skeleton_index.html metadata root).include?(e) }
             themestuff.each { |entry|
                 if !File.exists?(File.join(dest_dir, entry))
-                    psys("cp '#{$FPATH}/themes/#{$theme}/#{entry}' '#{dest_dir}'")
+                    psys("cp '#{$themedir}/#{entry}' '#{dest_dir}'")
                 end
             }
             
             #- copy any root-only resource file that goes with the theme (css, images..)
             if xmldir.parent.name != 'dir'
-                themestuff_root = Dir.entries("#{$FPATH}/themes/#{$theme}/root").
-                                      find_all { |e| !%w(. .. CVS).include?(e) }
+                themestuff_root = Dir.entries("#{$themedir}/root").
+                                      find_all { |e| !%w(. ..).include?(e) }
                 themestuff_root.each { |entry|
                     if !File.exists?(File.join(dest_dir, entry))
-                        psys("cp '#{$FPATH}/themes/#{$theme}/root/#{entry}' '#{dest_dir}'")
+                        psys("cp '#{$themedir}/root/#{entry}' '#{dest_dir}'")
                     end
                 }
             end
             
             msg 3, _("\tgenerating HTML pages...")
             #- fixup max per page
-            if $N_per_page && $N_per_row
-                $N_per_page = $N_per_page.to_i / $N_per_row.to_i * $N_per_row.to_i
+            if $N_per_page
+                $N_per_page = $N_per_page.to_i / ($N_per_row || $default_N).to_i * ($N_per_row || $default_N).to_i
             end
 
             #- generate thumbnails*.html (page with thumbnails)
-            image2thumbnailpage4js = []
+            element2thumbnailpage4js = []
             for sizeobj in $images_size
                 info("processing size")
                 html = $html_thumbnails.collect { |l| l.clone }
                 iterations = {}
                 for i in html
-                    i.sub!(/~~title~~/,
-                           xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir)))
+                    i.sub!(/~~title~~/, quote_caption(xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir))))
                     discover_iterations(iterations, i)
                 end
                 all_pages = []
@@ -1085,7 +1199,7 @@ def walk_source_dir
                 for file in entries
                     type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
                     if type
-                        homogeinize_width = 100 / $N_per_row.to_i
+                        homogeinize_width = 100 / ($N_per_row || $default_N).to_i
                         if type == 'image' && elem = optfilename[utf8(file)]
                             if pano = pano_amount(elem)
                                 html_elem = run_iterations(iterations, pano)
@@ -1105,39 +1219,52 @@ def walk_source_dir
                         html_elem.gsub!(/~~homogeinize_width~~/) { "width=\"#{homogeinize_width}%\"" }
                         if type == 'image'
                             index = images.index(file)
-                            html_elem.gsub!(/~~caption_iteration~~/,
-                                            find_caption_value(xmldir, images[index]) || utf8(images[index]))
+                            caption = find_caption_value(xmldir, images[index]) || utf8(images[index])
+                            html_elem.gsub!(/~~caption_iteration~~/, quote_caption(caption))
                             html_elem.gsub!(/~~ifimage\?~~(.+?)~~fi~~/) { $1 }
                             html_elem.gsub!(/~~ifvideo\?~~(.+?)~~fi~~/, '')
                         elsif type == 'video'
                             index = videos.index(file)
+                            caption = find_caption_value(xmldir, videos[index]) || utf8(videos[index])
                             if File.exists?("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}")
-                                html_elem.gsub!(/~~image_iteration~~/,
-                                                '<a href="' + ( $transcode_videos ? transcoded_videos[videos[index]] : videos[index] ) + '">' +
-                                                    img_element("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}") + '</a>')
+                                video_preview = '<div class="thumbnail_video">' + img_element("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}", caption) + '</div>'
+                            else
+                                video_preview = defer_translation(N_("(no preview)"))
+                            end
+                            if $mp4_generator
+                                size = get_image_size("#{dest_dir}/#{thumbnail_videos[sizeobj['name']][index]}")
+                                if ! size
+                                    sizeobj['thumbnails'] =~ /(\d+)x(\d+)/
+                                    size = { :x => $1, :y => $2 }
+                                end
+                                sizespec = 'width:' + size[:x].to_s + 'px;height:' + (size[:y] + 24).to_s + 'px'
+                                image_iteration = '<a href="' + mp4_videos[videos[index]] + '" style="display:block;' + sizespec + '"' +
+                                                  '   id="player' + index.to_s + '">' + video_preview +
+                                                  '<img src="~~pathtobase~~play_video.png" style="position:relative;top:-' + ((size[:y]+48)/2).to_s + 'px;border:0;background-color:transparent"/></a>'
+                                html_elem.gsub!(/~~image_iteration~~/, apply_hook(:image_iteration, image_iteration, 'video'))
                             else
                                 html_elem.gsub!(/~~image_iteration~~/,
                                                 '<a href="' + ( $transcode_videos ? transcoded_videos[videos[index]] : videos[index] ) + '">' +
-                                                    defer_translation(N_("(no preview)")) + '</a>')
+                                                    video_preview + '</a>')
                             end
-                            html_elem.gsub!(/~~caption_iteration~~/, find_caption_value(xmldir, videos[index]) || utf8(videos[index]))
+                            html_elem.gsub!(/~~caption_iteration~~/, quote_caption(caption))
                             html_elem.gsub!(/~~ifimage\?~~(.+?)~~fi~~/, '')
                             html_elem.gsub!(/~~ifvideo\?~~(.+?)~~fi~~/) { $1 }
                         end
                         html_thumbnails += html_elem
                         html_thumbnails_nojs += html_elem
                         if type == 'image'
+                            img_preview = '<div class="thumbnail_image">' + img_element("#{dest_dir}/#{thumbnail_images[sizeobj['name']][index]}", caption) + '</div>'
                             html_thumbnails.gsub!(/~~image_iteration~~/,
                                                   '<a href="image-' + size2js(sizeobj['name']) + $htmlsuffix + '#current=' + fullscreen_images[sizeobj['name']][index] +
-                                                      '" name="' + fullscreen_images[sizeobj['name']][index] + '">' +
-                                                      img_element("#{dest_dir}/#{thumbnail_images[sizeobj['name']][index]}") + '</a>')
+                                                      '" name="' + fullscreen_images[sizeobj['name']][index] + '">' + img_preview + '</a>')
                             html_thumbnails_nojs.gsub!(/~~image_iteration~~/, 
                                                        '<a href="' + fullscreen_images[sizeobj['name']][index] + '" name="' + fullscreen_images[sizeobj['name']][index] + '">' +
-                                                       img_element("#{dest_dir}/#{thumbnail_images[sizeobj['name']][index]}") + '</a>')
-                            #- remember in which thumbnails page is this element, for image->thumbnail link
-                            if sizeobj == $images_size[0]
-                                image2thumbnailpage4js << pagecount
-                            end
+                                                       img_preview + '</a>')
+                        end
+                        #- remember in which thumbnails page is this element, for element->thumbnail link
+                        if sizeobj == $images_size[0]
+                            element2thumbnailpage4js << pagecount
                         end
 
                         if counter == $N_per_page
@@ -1164,6 +1291,12 @@ def walk_source_dir
                     i.gsub!(/~~current_size_js~~/, size2js(sizeobj['name']))
                     i.gsub!(/~~madewith~~/, $madewith || '')
                     i.gsub!(/~~indexlink~~/, $indexlink || '')
+                    if !$indexlink || $indexlink.empty?
+                       i.gsub!(/~~ifindexlink\?~~(.+?)~~fi~~/) { }
+                    else
+                       i.gsub!(/~~ifindexlink\?~~(.+?)~~fi~~/) { $1 }
+                    end
+                    substitute_addthis(i)
                     substitute_navigation(i, xmldir)
                 end
                 html_nojs = html.collect { |l| l.clone }
@@ -1176,8 +1309,10 @@ def walk_source_dir
                              all_pages.collect_with_index { |p,idx| page == p ? idx + 1 : "<a href=\"thumbnails-#{size2js(sizeobj['name'])}%nojs-#{idx}#{$htmlsuffix}\">#{idx + 1}</a>" }.join(', ') +
                              (pagecount < all_pages.size - 1 ? " <a href=\"thumbnails-#{size2js(sizeobj['name'])}%nojs-#{pagecount + 1}#{$htmlsuffix}\">" + defer_translation(N_("Next ->")) + "</a> " : '')
                     for i in final_html
+                        i.sub!(/~~run_slideshow_link~~/, entries.size <= 1 ? '' : 'image-' + size2js(sizeobj['name']) + $htmlsuffix + '#run_slideshow=1')
+                        i.sub!(/~~run_slideshow_text~~/, defer_translation(N_("Run slideshow!")))
                         i.sub!(/~~run_slideshow~~/,
-                               images.size <= 1 ? '' : '<a href="image-' + size2js(sizeobj['name']) + $htmlsuffix + '#run_slideshow=1">' + defer_translation(N_("Run slideshow!"))+'</a>')
+                               entries.size <= 1 ? '' : '<a href="image-' + size2js(sizeobj['name']) + $htmlsuffix + '#run_slideshow=1">' + defer_translation(N_("Run slideshow!"))+'</a>')
                         i.sub!(/~~thumbnails~~/, html_thumbnails)
                         if all_pages.size == 1
                             i.gsub!(/~~ifmultiplepages\?~~.*~~fi~~/, '')
@@ -1213,39 +1348,118 @@ def walk_source_dir
             save_html(html_reload_to_thumbnails, "#{dest_dir}/thumbnails")
 
             #- generate image.html (page with fullscreen images)
-            if images.size > 0
-                captions4js = find_captions(xmldir, images).collect { |e| e ? '"' + e.gsub('"', '\"') + '"' : '""' }.join(', ')
-                thumbnailspage4js = image2thumbnailpage4js.collect { |e| "\"#{e}\"" }.join(', ')
-                for sizeobj in $images_size
-                    html = $html_images.collect { |l| l.clone }
-                    images4js = fullscreen_images[sizeobj['name']].collect { |e| "\"#{e}\"" }.join(', ')
-                    otherimages4js = ''
-                    othersizes = []
-                    for sizeobj2 in all_images_sizes
-                        if sizeobj != sizeobj2
-                            otherimages4js += "var images_#{size2js(sizeobj2['name'])} = new Array(" + fullscreen_images[sizeobj2['name']].collect { |e| "\"#{e}\"" }.join(', ') + ")\n"
-                            othersizes << "\"#{size2js(sizeobj2['name'])}\""
+            captions4js = []
+            types4js = []
+            videos4js = []
+            for file in entries
+                type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
+                if type
+                    caption = find_caption_value(xmldir, file)
+                    if caption
+                        captions4js << '"' + quote_caption(caption, true) + '"'
+                    else
+                        captions4js << '""'
+                    end
+                    types4js << '"' + type + '"'
+                    if type == 'video'
+                        index = videos.index(file)
+                        if $mp4_generator
+                            videos4js << '"' + mp4_videos[videos[index]] + '"'
+                        else
+                            videos4js << '"' + videos[index] + '"'
                         end
+                    else
+                        videos4js << '""'
                     end
-                    for i in html
-                        i.gsub!(/~~images~~/, images4js)
-                        i.gsub!(/~~other_images~~/, otherimages4js)
-                        i.gsub!(/~~thumbnailspages~~/, thumbnailspage4js)
-                        i.gsub!(/~~other_sizes~~/, othersizes.join(', '))
-                        i.gsub!(/~~captions~~/, captions4js)
-                        i.gsub!(/~~title~~/, xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir)))
-                        i.gsub!(/~~thumbnails~~/, '<a href="thumbnails-' + size2js(sizeobj['name']) + $htmlsuffix + '" id="thumbnails">' + defer_translation(N_('return to thumbnails')) + '</a>')
-                        i.gsub!(/~~theme~~/, $theme)
-                        i.gsub!(/~~current_size~~/, size2js(sizeobj['name']))
-                        i.gsub!(/~~htmlsuffix~~/, $htmlsuffix)
-                        i.gsub!(/~~madewith~~/, $madewith || '')
-                        i.gsub!(/~~indexlink~~/, $indexlink || '')
-                        substitute_html_sizes(i, sizeobj, 'image', '')
-                        substitute_navigation(i, xmldir)
-                        substitute_pathtobase(i, xmldir)
+                end
+            end
+
+            for sizeobj in $images_size
+                elements4js = []
+                elemswidths4js = []
+                elemsheights4js = []
+                for file in entries
+                    type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
+                    if type
+                        if type == 'image'
+                            index = images.index(file)
+                            elements4js << '"' + fullscreen_images[sizeobj['name']][index] + '"'
+                            size = get_image_size("#{dest_dir}/#{fullscreen_images[sizeobj['name']][index]}")
+                            if size
+                                elemswidths4js << size[:x].to_s
+                                elemsheights4js << size[:y].to_s
+                            else
+                                elemswidths4js << "''"
+                                elemsheights4js << "''"
+                            end
+                        else
+                            index = videos.index(file)
+                            elements4js << '"' + fullscreen_videos[sizeobj['name']][index] + '"'
+                            size = get_image_size("#{dest_dir}/#{fullscreen_videos[sizeobj['name']][index]}")
+                            if size
+                                elemswidths4js << size[:x].to_s
+                                elemsheights4js << size[:y].to_s
+                            else
+                                elemswidths4js << "''"
+                                elemsheights4js << "''"
+                            end
+                        end
+                    end
+                end
+
+                html = $html_images.collect { |l| l.clone }
+                hiddenimages4remotes = '<span style="display:none">' + thumbnail_images[sizeobj['name']][0..4].collect { |e| "<img src=\"#{e}\"/>" }.join('') + '</span>'
+                otherelements4js = ''
+                othersizes = []
+                for sizeobj2 in all_images_sizes
+                    if sizeobj != sizeobj2
+                        oe4js = []
+                        for file in entries
+                            type = images.include?(file) ? 'image' : videos.include?(file) ? 'video' : nil
+                            if type
+                                if type == 'image'
+                                    index = images.index(file)
+                                    oe4js << '"' + fullscreen_images[sizeobj2['name']][index] + '"'
+                                elsif sizeobj2['name'] != 'original'
+                                    index = videos.index(file)
+                                    oe4js << '"' + fullscreen_videos[sizeobj2['name']][index] + '"'
+                                end
+                            end
+                        end
+                        otherelements4js += "var elements_#{size2js(sizeobj2['name'])} = new Array(" + oe4js.join(', ') + ");\n"
+                        othersizes << "\"#{size2js(sizeobj2['name'])}\""
+                    end
+                end
+                for i in html
+                    i.gsub!(/~~images~~/, elements4js.join(', '))
+                    i.gsub!(/~~types~~/, types4js.join(', '))
+                    i.gsub!(/~~videos~~/, videos4js.join(', '))
+                    i.gsub!(/~~widths~~/, elemswidths4js.join(', '))
+                    i.gsub!(/~~heights~~/, elemsheights4js.join(', '))
+                    i.gsub!(/~~hidden_images_for_remotes~~/, hiddenimages4remotes)
+                    i.gsub!(/~~other_images~~/, otherelements4js)
+                    i.gsub!(/~~thumbnailspages~~/, element2thumbnailpage4js.collect { |e| "\"#{e}\"" }.join(', '))
+                    i.gsub!(/~~other_sizes~~/, othersizes.join(', '))
+                    i.gsub!(/~~captions~~/, captions4js.join(', '))
+                    i.gsub!(/~~title~~/, quote_caption(xmldir.attributes['thumbnails-caption'] || utf8(File.basename(dir))))
+
+                    i.gsub!(/~~thumbnails~~/, '<a id="thumbnails">' + defer_translation(N_('return to thumbnails')) + '</a>')
+                    i.gsub!(/~~theme~~/, $theme)
+                    i.gsub!(/~~current_size~~/, size2js(sizeobj['name']))
+                    i.gsub!(/~~htmlsuffix~~/, $htmlsuffix)
+                    i.gsub!(/~~madewith~~/, $madewith || '')
+                    i.gsub!(/~~indexlink~~/, $indexlink || '')
+                    if !$indexlink || $indexlink.empty?
+                        i.gsub!(/~~ifindexlink\?~~(.+?)~~fi~~/) { }
+                    else
+                        i.gsub!(/~~ifindexlink\?~~(.+?)~~fi~~/) { $1 }
                     end
-                    save_html(html, "#{dest_dir}/image-#{size2js(sizeobj['name'])}")
+                    substitute_addthis(i)
+                    substitute_html_sizes(i, sizeobj, 'image', '')
+                    substitute_navigation(i, xmldir)
+                    substitute_pathtobase(i, xmldir)
                 end
+                save_html(html, "#{dest_dir}/image-#{size2js(sizeobj['name'])}")
             end
         end
     }
@@ -1257,7 +1471,34 @@ def walk_source_dir
         msg 3, _("\tfixating configuration file...")
         $xmldoc.elements.each('//dir') { |element|
             path = captionpath = element.attributes['path']
-            descendant_element = element.elements['descendant::image'] || element.elements['descendant::video']
+            descendant_element = nil
+            #- search if there is at least one image or video down that dir; use workarounds to rexml slowness
+            #- first, look down only one level, very fast
+            first_desc = nil
+            element.elements.each { |elem|
+                if first_desc.nil?
+                    first_desc = elem
+                end
+                if elem.name == 'image' || elem.name == 'video'
+                    descendant_element = elem
+                    break
+                end
+            }
+            if descendant_element.nil?
+                #- if there was nothing or only directory down one level, look down the first subdir
+                if ! first_desc.nil?
+                    first_desc.elements.each { |elem|
+                        if elem.name == 'image' || elem.name == 'video'
+                            descendant_element = elem
+                            break
+                        end
+                    }
+                end
+                if descendant_element.nil?
+                    #- if there was still nothing found, use complete albeit slow method
+                    descendant_element = element.elements['descendant::image'] || element.elements['descendant::video']
+                end
+            end
             if !descendant_element
                 msg 3, _("\t\tremoving %s, no element in it") % path
                 element.remove  #- means we have a directory with nothing interesting in it
@@ -1287,12 +1528,12 @@ def walk_source_dir
     #- write down to disk config if necessary
     if $config_writeto
         ios = File.open($config_writeto, "w")
-        $xmldoc.write(ios, 0)
+        $xmldoc.write(ios)
         ios.close
     end
 
     if $forgui
-        msg 3, _(" completed necessary stuff for GUI, exiting.")
+        msg 3, _("completed necessary stuff for GUI, exiting.")
         return
     end
 
@@ -1323,7 +1564,7 @@ def walk_source_dir
             iterations = {}
             for i in html
                 caption = xmldir.attributes['subdirs-caption']
-                i.gsub!(/~~title~~/, caption)
+                i.gsub!(/~~title~~/, quote_caption(caption))
                 substitute_navigation(i, xmldir)
                 substitute_pathtobase(i, xmldir)
                 discover_iterations(iterations, i)
@@ -1338,8 +1579,9 @@ def walk_source_dir
                 gen_thumbnails_subdir(from_utf8(xmldir.attributes['thumbnails-captionfile']), xmldir, false,
                                       [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ], 'thumbnails')
                 html_index += run_iterations(iterations, 1)
-                html_index.gsub!(/~~image_iteration~~/, "<a href=\"thumbnails#{$htmlsuffix}\">" + img_element(thumbnail) + '</a>')
-                html_index.gsub!(/~~caption_iteration~~/, xmldir.attributes['thumbnails-caption'])
+                caption = xmldir.attributes['thumbnails-caption']
+                html_index.gsub!(/~~image_iteration~~/, "<a href=\"thumbnails#{$htmlsuffix}\">" + img_element(thumbnail, caption) + '</a>')
+                html_index.gsub!(/~~caption_iteration~~/, quote_caption(caption))
             end
 
             #- deal with sub-albums (direct to subdirs/index.html pages)
@@ -1353,8 +1595,8 @@ def walk_source_dir
                 captionfile, caption = find_subalbum_caption_info(child)
                 gen_thumbnails_subdir(captionfile, child, false,
                                       [ { 'filename' => thumbnail, 'size' => $albums_thumbnail_size } ], find_subalbum_info_type(child))
-                html_index.gsub!(/~~caption_iteration~~/, caption)
-                html_index.gsub!(/~~image_iteration~~/, "<a href=\"#{subdir}/index#{$htmlsuffix}\">" + img_element(thumbnail) + '</a>')
+                html_index.gsub!(/~~caption_iteration~~/, quote_caption(caption))
+                html_index.gsub!(/~~image_iteration~~/, "<a href=\"#{subdir}/index#{$htmlsuffix}\">" + img_element(thumbnail, caption) + '</a>')
             }
 
             html_index += close_iterations(iterations)
@@ -1363,6 +1605,12 @@ def walk_source_dir
                 i.gsub!(/~~thumbnails~~/, html_index)
                 i.gsub!(/~~madewith~~/, $madewith || '')
                 i.gsub!(/~~indexlink~~/, $indexlink || '')
+                if !$indexlink || $indexlink.empty?
+                   i.gsub!(/~~ifindexlink\?~~(.+?)~~fi~~/) { }
+                else
+                   i.gsub!(/~~ifindexlink\?~~(.+?)~~fi~~/) { $1 }
+                end
+                substitute_addthis(i)
             end
             
         else
@@ -1427,3 +1675,4 @@ check_installation
 build_html_skeletons
 
 walk_source_dir
+exit(0)