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
43 #- fake for gettext to find these; if themes need more sizes, english name for them should be added here
44 sizenames = { 'small' => utf8(_("small")), 'medium' => utf8(_("medium")), 'large' => utf8(_("large")),
45 'x-large' => utf8(_("x-large")), 'xx-large' => utf8(_("xx-large")),
46 'original' => utf8(_("original")) }
47 return sizenames[key] || key
51 return Iconv::iconv($CURRENT_CHARSET, "UTF-8", string).to_s
54 def make_dest_filename(orig_filename)
55 #- we remove non alphanumeric characters but need to do that
56 #- cleverly to not end up with two similar dest filenames. we won't
57 #- urlencode because urldecode might happen in the browser.
58 return orig_filename.unpack("C*").collect { |v| v.chr =~ /[a-zA-Z\-_0-9\.\/]/ ? v.chr : sprintf("%2X", v) }.to_s
61 def msg(verbose_level, msg)
62 if verbose_level <= $verbose_level
64 warn _("\t***ERROR***: %s\n") % msg
65 elsif verbose_level == 1
66 warn _("\tWarning: %s\n") % msg
73 def msg_(verbose_level, msg)
74 if verbose_level <= $verbose_level
76 warn _("\t***ERROR***: %s") % msg
77 elsif verbose_level == 1
78 warn _("\tWarning: %s") % msg
90 def select_theme(name, limit_sizes, optimizefor32, nperrow)
92 msg 3, _("Selecting theme '%s'") % $theme
93 themedir = "#{$FPATH}/themes/#{$theme}"
94 if !File.directory?(themedir)
95 die _("Theme was not found (tried %s directory).") % themedir
97 eval File.open("#{themedir}/metadata/parameters.rb").readlines.join
100 if limit_sizes != 'all'
101 sizes = limit_sizes.split(/,/)
102 $images_size = $images_size.find_all { |e| sizes.include?(e['name']) }
103 if $images_size.length == 0
104 die _("Can't carry on, no valid size selected.")
108 $images_size = $images_size.find_all { |e| !e['optional'] }
112 $images_size.each { |e|
113 e['fullscreen'].gsub!(/(\d+x)(\d+)/) { $1 + ($2.to_f*8/9).to_i.to_s }
114 e['thumbnails'].gsub!(/(\d+x)(\d+)/) { $1 + ($2.to_f*8/9).to_i.to_s }
116 $albums_thumbnail_size.gsub!(/(\d+x)(\d+)/) { $1 + ($2.to_f*8/9).to_i.to_s }
119 if nperrow && nperrow != $default_N
120 ratio = nperrow.to_f / $default_N.to_f
121 $images_size.each { |e|
122 e['thumbnails'].gsub!(/(\d+)x(\d+)/) { ($1.to_f/ratio).to_i.to_s + 'x' + ($2.to_f/ratio).to_i.to_s }
126 $default_size = $images_size.detect { |sizeobj| sizeobj['default'] }
127 if $default_size == nil
128 $default_size = $images_size[0]
132 def entry2type(entry)
133 if entry =~ /\.(jpg|jpeg|jpe|gif|bmp|png)$/i && entry !~ /['"\[\]]/
135 elsif !$ignore_videos && entry =~ /\.(mov|avi|mpg|mpeg|mpe|wmv|asx|3gp|mp4)$/i && entry !~ /['"\[\]]/
136 #- might consider using file magic later..
149 finished = Process.wait2
150 $pids.delete(finished[0])
151 $pids = $pids.find_all { |pid| Process.waitpid(pid, Process::WNOHANG) == nil }
155 while $pids && $pids.length > 0
160 #- parallelizable sys
170 if $pids.length == $mproc
178 #- grab the results of a command but don't sleep forever on a runaway process
179 def subproc_runaway_aware(command)
184 rescue Timeout::Error
185 msg 1, _("forgetting runaway process (transcode sucks again?)")
186 #- todo should slay transcode but dunno how to do that
191 def get_image_size(fullpath)
192 if !$no_identify && `identify '#{fullpath}'` =~ / JPEG (\d+)x(\d+) /
193 return { :x => $1.to_i, :y => $2.to_i }
199 #- commify from http://pleac.sourceforge.net/ (pleac rulz)
201 n.to_s =~ /([^\.]*)(\..*)?/
202 int, dec = $1.reverse, $2 ? $2 : ""
203 while int.gsub!(/(,|\.|^)(\d{3})(\d)/, '\1\2' + _(",") + '\3')
208 def guess_rotate(filename)
213 orientation = `identify -format "%[EXIF:orientation]" '#{filename}'`.chomp
214 if orientation == '6'
216 elsif orientation == '8'
221 size = get_image_size(filename)
222 #- remove rotate if image is obviously already in portrait (situation can come from gthumb)
223 if size && size[:x] < size[:y]
230 def rotate_pixbuf(pixbuf, angle)
231 return pixbuf.rotate(angle == 90 ? Gdk::Pixbuf::ROTATE_CLOCKWISE :
232 angle == 180 ? Gdk::Pixbuf::ROTATE_UPSIDEDOWN :
233 angle == 270 ? Gdk::Pixbuf::ROTATE_COUNTERCLOCKWISE :
234 Gdk::Pixbuf::ROTATE_NONE)
237 def gen_thumbnails_element(orig, xmldirorelem, allow_background, dests)
238 if xmldirorelem.name == 'dir'
239 xmldirorelem = xmldirorelem.elements["*[@filename='#{utf8(File.basename(orig))}']"]
241 gen_thumbnails(orig, allow_background, dests, xmldirorelem, '')
244 def gen_thumbnails_subdir(orig, xmldirorelem, allow_background, dests, type)
245 #- type can be `subdirs' or `thumbnails'
246 gen_thumbnails(orig, allow_background, dests, xmldirorelem, type + '-')
249 def gen_thumbnails(orig, allow_background, dests, felem, attributes_prefix)
250 if !dests.detect { |dest| !File.exists?(dest['filename']) }
255 dest_dir = make_dest_filename(File.dirname(dests[0]['filename']))
257 if entry2type(orig) == 'image'
259 if whitebalance = felem.attributes["#{attributes_prefix}white-balance"]
260 neworig = "#{dest_dir}/#{File.basename(orig)}-whitebalance#{whitebalance}.jpg"
261 cmd = "booh-fix-whitebalance '#{orig}' '#{neworig}' #{whitebalance}"
263 if File.exists?(neworig)
267 rotate = felem.attributes["#{attributes_prefix}rotate"]
269 felem.add_attribute("#{attributes_prefix}rotate", rotate = guess_rotate(orig).to_i)
271 convert_options += "-rotate #{rotate} "
272 if felem.attributes["#{attributes_prefix}enhance"]
273 convert_options += ($config['convert-enhance'] || $convert_enhance) + " "
277 if !File.exists?(dest['filename'])
279 cmd ||= "#{$convert} #{convert_options}-size #{dest['size']} -resize '#{dest['size']}>' '#{orig}' '#{dest['filename']}'"
291 system("rm -f '#{neworig}'")
295 elsif entry2type(orig) == 'video'
297 #- frame-offset is an attribute that allows to specify which frame to use for the thumbnail
298 frame_offset = felem.attributes["#{attributes_prefix}frame-offset"]
300 felem.add_attribute("#{attributes_prefix}frame-offset", frame_offset = "0")
302 frame_offset = frame_offset.to_i
303 if rotate = felem.attributes["#{attributes_prefix}rotate"]
304 convert_options += "-rotate #{rotate} "
306 if felem.attributes["#{attributes_prefix}enhance"]
307 convert_options += ($config['convert-enhance'] || $convert_enhance) + " "
310 orig_base = File.basename(dests[0]['filename']) + File.basename(orig)
311 orig_image = "#{dest_dir}/#{orig_base}.jpg000000.jpg"
312 system("rm -f '#{orig_image}'")
314 if !File.exists?(orig_image)
315 transcode_options = ''
317 if felem.attributes["#{attributes_prefix}color-swap"]
318 transcode_options += '-k '
321 cmd = "transcode -a 0 -c #{frame_offset}-#{frame_offset+1} -i '#{orig}' -y jpg -o '#{dest_dir}/#{orig_base}.jpg' #{transcode_options} 2>&1"
323 results = subproc_runaway_aware(cmd)
324 if results =~ /skipping frames/ && results =~ /encoded 0 frames/
325 msg 0, _("specified frame-offset too large? max frame was: %s. that may also be another problem. try another value.") %
326 results.scan(/skipping frames \[000000-(\d+)\]/)[-1]
328 elsif results =~ /V: import format.*unknown/ || !File.exists?(orig_image)
329 msg 2, _("* could not extract first image of video %s with transcode, will try first converting with mencoder") % orig
330 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"
333 if File.exists?("#{dest_dir}/#{orig_base}.avi")
334 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"
336 results = subproc_runaway_aware(cmd)
337 system("rm -f '#{dest_dir}/#{orig_base}.avi'")
338 if results =~ /skipping frames/ && results =~ /encoded 0 frames/
339 msg 0, _("specified frame-offset too large? max frame was: %s. that may also be another probleme. try another value.") %
340 results.scan(/skipping frames \[000000-(\d+)\]/)[-1]
342 elsif results =~ /V: import format.*unknown/ || !File.exists?(orig_image)
343 msg 0, _("could not extract first image of video %s encoded by mencoder") % "#{dest_dir}/#{orig_base}.avi"
347 msg 0, _("could not make mencoder to encode %s to mpeg4") % orig
351 if felem && whitebalance = felem.attributes["#{attributes_prefix}white-balance"]
352 if whitebalance.to_f != 0
353 neworig = "#{dest_dir}/#{orig_base}-whitebalance#{whitebalance}.jpg"
354 cmd = "booh-fix-whitebalance '#{orig_image}' '#{neworig}' #{whitebalance}"
356 if File.exists?(neworig)
362 if !File.exists?(dest['filename'])
363 sys("#{$convert} #{convert_options}-size #{dest['size']} -resize #{dest['size']} '#{orig_image}' '#{dest['filename']}'")
367 system("rm -f '#{neworig}'")
373 def invornil(obj, methodname)
377 return obj.method(methodname).call
381 def find_subalbum_info_type(xmldir)
382 #- first look for subdirs info; if not, means there is no subdir
383 if xmldir.attributes['subdirs-caption']
390 def find_subalbum_caption_info(xmldir)
391 type = find_subalbum_info_type(xmldir)
392 return [ from_utf8(xmldir.attributes["#{type}-captionfile"]), xmldir.attributes["#{type}-caption"] ]
397 return File.size(path)
408 n < a ? a : n > b ? b : n
411 def pano_amount(elem)
412 if pano_amount = elem.attributes['pano-amount']
414 return clamp(pano_amount.to_f, 1, $N_per_row.to_i)
416 return clamp(pano_amount.to_f, 1, $default_N.to_i)
423 def substInFile(name)
424 newcontent = IO.readlines(name).collect { |l| yield l }
425 ios = File.open(name, "w")
426 ios.write(newcontent)
432 def File.reduce_path(path)
433 return path.gsub(/\w+\/\.\.\//, '')
438 def previous_element_byname(name)
440 while n = n.previous_element
448 def previous_element_byname_notattr(name, attr)
450 while n = n.previous_element
451 if n.name == name && !n.attributes[attr]
458 def next_element_byname(name)
460 while n = n.next_element
468 def next_element_byname_notattr(name, attr)
470 while n = n.next_element
471 if n.name == name && !n.attributes[attr]
478 def child_byname_notattr(name, attr)
479 elements.each(name) { |element|
480 if !element.attributes[attr]