3 # A.k.a `Best web-album Of the world, Or your money back, Humerus'.
5 # The acronyn sucks, however this is a tribute to Dragon Ball by
6 # Akira Toriyama, where the last enemy beaten by heroes of Dragon
7 # Ball is named "Boo". But there was already a free software project
8 # called Boo, so this one will be it "Booh". Or whatever.
11 # Copyright (c) 2004 Guillaume Cottenceau <gc3 at bluewin.ch>
13 # This software may be freely redistributed under the terms of the GNU
14 # public license version 2.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23 require 'rexml/document'
27 bindtextdomain("booh")
29 require 'booh/config.rb'
30 require 'booh/version.rb'
34 $CURRENT_CHARSET = `locale charmap`.chomp
35 $convert = 'convert -interlace line +profile "*"'
36 $convert_enhance = '-contrast -enhance -normalize'
39 return Iconv::iconv("UTF-8", $CURRENT_CHARSET, string).to_s
42 def utf8cut(string, maxlen)
44 return Iconv::iconv("UTF-8", $CURRENT_CHARSET, string[0..maxlen-1]).to_s
45 rescue Iconv::InvalidCharacter
46 return utf8cut(string, maxlen-1)
51 #- fake for gettext to find these; if themes need more sizes, english name for them should be added here
52 sizenames = { 'small' => utf8(_("small")), 'medium' => utf8(_("medium")), 'large' => utf8(_("large")),
53 'x-large' => utf8(_("x-large")), 'xx-large' => utf8(_("xx-large")),
54 'original' => utf8(_("original")) }
55 return sizenames[key] || key
59 return Iconv::iconv($CURRENT_CHARSET, "UTF-8", string).to_s
62 def from_utf8_safe(string)
64 return Iconv::iconv($CURRENT_CHARSET, "UTF-8", string).to_s
65 rescue Iconv::IllegalSequence
70 def make_dest_filename_old(orig_filename)
71 #- we remove non alphanumeric characters but need to do that
72 #- cleverly to not end up with two similar dest filenames. we won't
73 #- urlencode because urldecode might happen in the browser.
74 return orig_filename.unpack("C*").collect { |v| v.chr =~ /[a-zA-Z\-_0-9\.\/]/ ? v.chr : sprintf("%2X", v) }.to_s
77 def make_dest_filename(orig_filename)
78 #- we remove non alphanumeric characters but need to do that
79 #- cleverly to not end up with two similar dest filenames. we won't
80 #- urlencode because urldecode might happen in the browser.
81 return orig_filename.unpack("C*").collect { |v| v.chr =~ /[a-zA-Z\-_0-9\.\/]/ ? v.chr : sprintf("~%02X", v) }.to_s
84 def msg(verbose_level, msg)
85 if verbose_level <= $verbose_level
87 warn _("\t***ERROR***: %s\n") % msg
88 elsif verbose_level == 1
89 warn _("\tWarning: %s\n") % msg
96 def msg_(verbose_level, msg)
97 if verbose_level <= $verbose_level
99 warn _("\t***ERROR***: %s") % msg
100 elsif verbose_level == 1
101 warn _("\tWarning: %s") % msg
113 def select_theme(name, limit_sizes, optimizefor32, nperrow)
115 msg 3, _("Selecting theme '%s'") % $theme
116 themedir = "#{$FPATH}/themes/#{$theme}"
117 if !File.directory?(themedir)
118 die _("Theme was not found (tried %s directory).") % themedir
120 eval File.open("#{themedir}/metadata/parameters.rb").readlines.join
123 if limit_sizes != 'all'
124 sizes = limit_sizes.split(/,/)
125 $images_size = $images_size.find_all { |e| sizes.include?(e['name']) }
126 if $images_size.length == 0
127 die _("Can't carry on, no valid size selected.")
131 $images_size = $images_size.find_all { |e| !e['optional'] }
135 $images_size.each { |e|
136 e['fullscreen'].gsub!(/(\d+x)(\d+)/) { $1 + ($2.to_f*8/9).to_i.to_s }
137 e['thumbnails'].gsub!(/(\d+x)(\d+)/) { $1 + ($2.to_f*8/9).to_i.to_s }
139 $albums_thumbnail_size.gsub!(/(\d+x)(\d+)/) { $1 + ($2.to_f*8/9).to_i.to_s }
142 if nperrow && nperrow != $default_N
143 ratio = nperrow.to_f / $default_N.to_f
144 $images_size.each { |e|
145 e['thumbnails'].gsub!(/(\d+)x(\d+)/) { ($1.to_f/ratio).to_i.to_s + 'x' + ($2.to_f/ratio).to_i.to_s }
149 $default_size = $images_size.detect { |sizeobj| sizeobj['default'] }
150 if $default_size == nil
151 $default_size = $images_size[0]
155 def entry2type(entry)
156 if entry =~ /\.(jpg|jpeg|jpe|gif|bmp|png)$/i && entry !~ /['"\[\]]/
158 elsif !$ignore_videos && entry =~ /\.(mov|avi|mpg|mpeg|mpe|wmv|asx|3gp|mp4)$/i && entry !~ /['"\[\]]/
159 #- might consider using file magic later..
172 finished = Process.wait2
173 $pids.delete(finished[0])
174 $pids = $pids.find_all { |pid| Process.waitpid(pid, Process::WNOHANG) == nil }
178 while $pids && $pids.length > 0
183 #- parallelizable sys
193 if $pids.length == $mproc
201 #- grab the results of a command but don't sleep forever on a runaway process
202 def subproc_runaway_aware(command)
207 rescue Timeout::Error
208 msg 1, _("forgetting runaway process (transcode sucks again?)")
209 #- todo should slay transcode but dunno how to do that
214 def get_image_size(fullpath)
215 if !$no_identify && `identify '#{fullpath}'` =~ / JPEG (\d+)x(\d+) /
216 return { :x => $1.to_i, :y => $2.to_i }
222 #- commify from http://pleac.sourceforge.net/ (pleac rulz)
224 n.to_s =~ /([^\.]*)(\..*)?/
225 int, dec = $1.reverse, $2 ? $2 : ""
226 while int.gsub!(/(,|\.|^)(\d{3})(\d)/, '\1\2' + _(",") + '\3')
231 def guess_rotate(filename)
236 orientation = `identify -format "%[EXIF:orientation]" '#{filename}'`.chomp
237 if orientation == '6'
239 elsif orientation == '8'
244 size = get_image_size(filename)
245 #- remove rotate if image is obviously already in portrait (situation can come from gthumb)
246 if size && size[:x] < size[:y]
253 def rotate_pixbuf(pixbuf, angle)
254 return pixbuf.rotate(angle == 90 ? Gdk::Pixbuf::ROTATE_CLOCKWISE :
255 angle == 180 ? Gdk::Pixbuf::ROTATE_UPSIDEDOWN :
256 angle == 270 ? Gdk::Pixbuf::ROTATE_COUNTERCLOCKWISE :
257 Gdk::Pixbuf::ROTATE_NONE)
260 def gen_thumbnails_element(orig, xmldirorelem, allow_background, dests)
261 if xmldirorelem.name == 'dir'
262 xmldirorelem = xmldirorelem.elements["*[@filename='#{utf8(File.basename(orig))}']"]
264 gen_thumbnails(orig, allow_background, dests, xmldirorelem, '')
267 def gen_thumbnails_subdir(orig, xmldirorelem, allow_background, dests, type)
268 #- type can be `subdirs' or `thumbnails'
269 gen_thumbnails(orig, allow_background, dests, xmldirorelem, type + '-')
272 def gen_thumbnails(orig, allow_background, dests, felem, attributes_prefix)
273 if !dests.detect { |dest| !File.exists?(dest['filename']) }
278 dest_dir = make_dest_filename(File.dirname(dests[0]['filename']))
280 if entry2type(orig) == 'image'
282 if whitebalance = felem.attributes["#{attributes_prefix}white-balance"]
283 neworig = "#{dest_dir}/#{File.basename(orig)}-whitebalance#{whitebalance}.jpg"
284 cmd = "booh-fix-whitebalance '#{orig}' '#{neworig}' #{whitebalance}"
286 if File.exists?(neworig)
290 rotate = felem.attributes["#{attributes_prefix}rotate"]
292 felem.add_attribute("#{attributes_prefix}rotate", rotate = guess_rotate(orig).to_i)
294 convert_options += "-rotate #{rotate} "
295 if felem.attributes["#{attributes_prefix}enhance"]
296 convert_options += ($config['convert-enhance'] || $convert_enhance) + " "
300 if !File.exists?(dest['filename'])
302 cmd ||= "#{$convert} #{convert_options}-size #{dest['size']} -resize '#{dest['size']}>' '#{orig}' '#{dest['filename']}'"
314 system("rm -f '#{neworig}'")
318 elsif entry2type(orig) == 'video'
320 #- frame-offset is an attribute that allows to specify which frame to use for the thumbnail
321 frame_offset = felem.attributes["#{attributes_prefix}frame-offset"]
323 felem.add_attribute("#{attributes_prefix}frame-offset", frame_offset = "0")
325 frame_offset = frame_offset.to_i
326 if rotate = felem.attributes["#{attributes_prefix}rotate"]
327 convert_options += "-rotate #{rotate} "
329 if felem.attributes["#{attributes_prefix}enhance"]
330 convert_options += ($config['convert-enhance'] || $convert_enhance) + " "
333 orig_base = File.basename(dests[0]['filename']) + File.basename(orig)
334 orig_image = "#{dest_dir}/#{orig_base}.jpg000000.jpg"
335 system("rm -f '#{orig_image}'")
337 if !File.exists?(orig_image)
338 transcode_options = ''
340 if felem.attributes["#{attributes_prefix}color-swap"]
341 transcode_options += '-k '
344 cmd = "transcode -a 0 -c #{frame_offset}-#{frame_offset+1} -i '#{orig}' -y jpg -o '#{dest_dir}/#{orig_base}.jpg' #{transcode_options} 2>&1"
346 results = subproc_runaway_aware(cmd)
347 if results =~ /skipping frames/ && results =~ /encoded 0 frames/
348 msg 0, _("specified frame-offset too large? max frame was: %s. that may also be another problem. try another value.") %
349 results.scan(/skipping frames \[000000-(\d+)\]/)[-1]
351 elsif results =~ /V: import format.*unknown/ || !File.exists?(orig_image)
352 msg 2, _("* could not extract first image of video %s with transcode, will try first converting with mencoder") % orig
353 cmd = "mencoder '#{orig}' -nosound -ovc lavc -lavcopts vcodec=mjpeg -o '#{dest_dir}/#{orig_base}.avi' -frames #{frame_offset+26} -fps 25 >/dev/null 2>/dev/null"
356 if File.exists?("#{dest_dir}/#{orig_base}.avi")
357 cmd = "transcode -a 0 -c #{frame_offset}-#{frame_offset+1} -i '#{dest_dir}/#{orig_base}.avi' -y jpg -o '#{dest_dir}/#{orig_base}.jpg' #{transcode_options} 2>&1"
359 results = subproc_runaway_aware(cmd)
360 system("rm -f '#{dest_dir}/#{orig_base}.avi'")
361 if results =~ /skipping frames/ && results =~ /encoded 0 frames/
362 msg 0, _("specified frame-offset too large? max frame was: %s. that may also be another probleme. try another value.") %
363 results.scan(/skipping frames \[000000-(\d+)\]/)[-1]
365 elsif results =~ /V: import format.*unknown/ || !File.exists?(orig_image)
366 msg 0, _("could not extract first image of video %s encoded by mencoder") % "#{dest_dir}/#{orig_base}.avi"
370 msg 0, _("could not make mencoder to encode %s to mpeg4") % orig
374 if felem && whitebalance = felem.attributes["#{attributes_prefix}white-balance"]
375 if whitebalance.to_f != 0
376 neworig = "#{dest_dir}/#{orig_base}-whitebalance#{whitebalance}.jpg"
377 cmd = "booh-fix-whitebalance '#{orig_image}' '#{neworig}' #{whitebalance}"
379 if File.exists?(neworig)
385 if !File.exists?(dest['filename'])
386 sys("#{$convert} #{convert_options}-size #{dest['size']} -resize #{dest['size']} '#{orig_image}' '#{dest['filename']}'")
390 system("rm -f '#{neworig}'")
396 def invornil(obj, methodname)
400 return obj.method(methodname).call
404 def find_subalbum_info_type(xmldir)
405 #- first look for subdirs info; if not, means there is no subdir
406 if xmldir.attributes['subdirs-caption']
413 def find_subalbum_caption_info(xmldir)
414 type = find_subalbum_info_type(xmldir)
415 return [ from_utf8(xmldir.attributes["#{type}-captionfile"]), xmldir.attributes["#{type}-caption"] ]
420 return File.size(path)
431 n < a ? a : n > b ? b : n
434 def pano_amount(elem)
435 if pano_amount = elem.attributes['pano-amount']
437 return clamp(pano_amount.to_f, 1, $N_per_row.to_i)
439 return clamp(pano_amount.to_f, 1, $default_N.to_i)
446 def substInFile(name)
447 newcontent = IO.readlines(name).collect { |l| yield l }
448 ios = File.open(name, "w")
449 ios.write(newcontent)
455 def File.reduce_path(path)
456 return path.gsub(/\w+\/\.\.\//, '')
461 def previous_element_byname(name)
463 while n = n.previous_element
471 def previous_element_byname_notattr(name, attr)
473 while n = n.previous_element
474 if n.name == name && !n.attributes[attr]
481 def next_element_byname(name)
483 while n = n.next_element
491 def next_element_byname_notattr(name, attr)
493 while n = n.next_element
494 if n.name == name && !n.attributes[attr]
501 def child_byname_notattr(name, attr)
502 elements.each(name) { |element|
503 if !element.attributes[attr]