add classifier
authorgc <gc>
Sun, 8 Jul 2007 13:01:25 +0000 (13:01 +0000)
committergc <gc>
Sun, 8 Jul 2007 13:01:25 +0000 (13:01 +0000)
bin/booh-classifier [new file with mode: 0644]

diff --git a/bin/booh-classifier b/bin/booh-classifier
new file mode 100644 (file)
index 0000000..891918a
--- /dev/null
@@ -0,0 +1,672 @@
+#! /usr/bin/ruby
+#
+#                         *  BOOH  *
+#
+# A.k.a 'Best web-album Of the world, Or your money back, Humerus'.
+#
+# The acronyn sucks, however this is a tribute to Dragon Ball by
+# Akira Toriyama, where the last enemy beaten by heroes of Dragon
+# Ball is named "Boo". But there was already a free software project
+# called Boo, so this one will be it "Booh". Or whatever.
+#
+#
+# Copyright (c) 2004-2006 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.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+
+require 'getoptlong'
+require 'tempfile'
+require 'thread'
+
+require 'gtk2'
+
+require 'gettext'
+include GetText
+bindtextdomain("booh")
+
+require 'rexml/document'
+include REXML
+
+require 'booh/booh-lib'
+include Booh
+require 'booh/UndoHandler'
+
+
+#- options
+$options = [
+    [ '--help',          '-h', GetoptLong::NO_ARGUMENT,       _("Get help message") ],
+
+    [ '--verbose-level', '-v', GetoptLong::REQUIRED_ARGUMENT, _("Set max verbosity level (0: errors, 1: warnings, 2: important messages, 3: other messages)") ],
+]
+
+def usage
+    puts _("Usage: %s [OPTION]...") % File.basename($0)
+    $options.each { |ary|
+        printf " %3s, %-15s %s\n", ary[1], ary[0], ary[3]
+    }
+end
+
+def handle_options
+    parser = GetoptLong.new
+    parser.set_options(*$options.collect { |ary| ary[0..2] })
+    begin
+        parser.each_option do |name, arg|
+            case name
+            when '--help'
+                usage
+                exit(0)
+
+            when '--verbose-level'
+                $verbose_level = arg.to_i
+
+            end
+        end
+        puts "args: #{ARGV}"
+    rescue
+        puts $!
+        usage
+        exit(1)
+    end
+end
+
+def memfree
+    meminfo = IO.readlines('/proc/meminfo').join
+    meminfo =~ /MemFree:.*?(\d+)/ or return -1
+    memfree = $1
+    meminfo =~ /Buffers:.*?(\d+)/ and buffers = $1
+    meminfo =~ /Cached:.*?(\d+)/ and cached = $1
+    return memfree.to_i + buffers.to_i + cached.to_i
+end
+
+def read_config
+    $config = {}
+    $config_file = File.expand_path('~/.booh-classifier-rc')
+    if File.readable?($config_file)
+        $xmldoc = REXML::Document.new(File.new($config_file))
+        $xmldoc.root.elements.each { |element|
+            txt = element.get_text
+            if txt
+                if txt.value =~ /~~~/
+                    $config[element.name] = txt.value.split(/~~~/)
+                else
+                    $config[element.name] = txt.value
+                end
+            elsif element.elements.size == 0
+                $config[element.name] = ''
+            else
+                $config[element.name] = {}
+                element.each { |chld|
+                    txt = chld.get_text
+                    $config[element.name][chld.name] = txt ? txt.value : nil
+                }
+            end
+        }
+    end
+    $config['video-viewer'] ||= '/usr/bin/mplayer %f'
+    $config['display-mode'] ||= 'one-image'
+    $config['cache-memory-use'] ||= 'memfree_50%'
+    if $config['cache-memory-use'] =~ /memfree_(\d+)/
+        $config['cache-memory-use-figure'] = memfree*$1.to_f/100
+    else
+        $config['cache-memory-use-figure'] = $config['cache-memory-use'].to_i
+    end
+    msg 2, "Set cache memory use figure: #{$config['cache-memory-use-figure']} kB"
+end
+
+def check_config
+    if !system("which identify >/dev/null 2>/dev/null")
+        show_popup($main_window, utf8(_("The program 'identify' is needed to get images sizes and EXIF data. Please install it.
+It is generally available with the 'ImageMagick' software package.")), { :pos_centered => true })
+    end
+    missing = %w(transcode mencoder).delete_if { |prg| system("which #{prg} >/dev/null 2>/dev/null") }
+    if missing != []
+        show_popup($main_window, utf8(_("The following program(s) are needed to handle videos: '%s'. Videos will be ignored.") % missing.join(', ')), { :pos_centered => true })
+    end
+
+    viewer_binary = $config['video-viewer'].split.first
+    if viewer_binary && !File.executable?(viewer_binary)
+        show_popup($main_window, utf8(_("The configured video viewer seems to be unavailable.
+You should fix this in Edit/Preferences so that you can view videos.
+
+Problem was: '%s' is not an executable file.
+Hint: don't forget to specify the full path to the executable,
+e.g. '/usr/bin/mplayer' is correct but 'mplayer' only is not.") % viewer_binary), { :pos_centered => true, :not_transient => true })
+    end
+end
+
+def write_config
+    ios = File.open($config_file, "w")
+    $xmldoc = Document.new "<booh-classifier-rc version='#{$VERSION}'/>"
+    $xmldoc << XMLDecl.new(XMLDecl::DEFAULT_VERSION, $CURRENT_CHARSET)
+    $config.each_pair { |key, value|
+        elem = $xmldoc.root.add_element key
+        if value.is_a? Hash
+            $config[key].each_pair { |subkey, subvalue|
+                subelem = elem.add_element subkey
+                subelem.add_text subvalue.to_s
+            }
+        elsif value.is_a? Array
+            elem.add_text value.join('~~~')
+        else
+            if !value
+                elem.remove
+            else
+                elem.add_text value.to_s
+            end
+        end
+    }
+    $xmldoc.write(ios, 0)
+    ios.close
+end
+
+def save_undo(name, closure, *params)
+    UndoHandler.save_undo(name, closure, [ *params ])
+    $undo_tb.sensitive = $undo_mb.sensitive = true
+    $redo_tb.sensitive = $redo_mb.sensitive = false
+end
+
+def get_mem
+    IO.readlines('/proc/self/status').join =~ /VmRSS.*?(\d+)\s*kB/
+    puts $1
+    return $1.to_i
+end
+
+def show_mem(*txt)
+    txt.length > 0 and print txt[0]
+    puts get_mem
+end
+
+class Entry
+    @@thumbnails_height = 64
+    @@max_height = nil
+    def Entry.thumbnails_height
+        return @@thumbnails_height
+    end
+
+    attr_accessor :path, :type, :button
+
+    def initialize(path, type)
+        @path = path
+        @type = type
+        if @@max_height.nil?
+            @@max_height = $main_window.root_window.size[1]
+        end
+        @protect_cleanup = Mutex.new
+    end
+
+    def pixbuf_full
+        @protect_cleanup.synchronize {
+            if @pixbuf_full.nil?
+                puts ">>> pixbuf_full #{path}"
+                load_into_pixbuf_full
+            end
+            return @pixbuf_full
+        }
+    end
+    def free_pixbuf_full
+        @protect_cleanup.synchronize {
+            if @pixbuf_full.nil?
+                return false
+            else
+                puts ">>> free_pixbuf_full #{path}"
+                @pixbuf_full = nil
+                return true
+            end
+        }
+    end
+    def pixbuf_main(width, height)
+        @protect_cleanup.synchronize {
+            if @pixbuf_main.nil? || width != @width || height != @height
+                puts ">>> pixbuf_main #{path}"
+                @width = width
+                @height = height
+                load_into_pixbuf_full  #- make sure it is loaded
+                if @pixbuf_full.width.to_f / @pixbuf_full.height > width.to_f / height
+                    resized_height = @pixbuf_full.height * (width.to_f/@pixbuf_full.width)
+                    if @pixbuf_full.width > width || @pixbuf_full.height > resized_height
+                        @pixbuf_main = @pixbuf_full.scale(width, resized_height, Gdk::Pixbuf::INTERP_BILINEAR)
+                    else
+                        @pixbuf_main = @pixbuf_full
+                    end
+                else
+                    resized_width = @pixbuf_full.width * (height.to_f/@pixbuf_full.height)
+                    if @pixbuf_full.width > resized_width || @pixbuf_full.height > height
+                        @pixbuf_main = @pixbuf_full.scale(resized_width, height, Gdk::Pixbuf::INTERP_BILINEAR)
+                    else
+                        @pixbuf_main = @pixbuf_full
+                    end
+                end
+            end
+            return @pixbuf_main
+        }
+    end
+    def free_pixbuf_main
+        @protect_cleanup.synchronize {
+            if @pixbuf_main.nil?
+                return false
+            else
+                puts ">>> free_pixbuf_main #{path}"
+                @pixbuf_main = nil
+                return true
+            end
+        }
+    end
+    def pixbuf_thumbnail
+        return @protect_cleanup.synchronize {
+            if @pixbuf_thumbnail.nil?
+                puts ">>> pixbuf_thumbnail #{path}"
+                load_into_pixbuf_full  #- make sure it is loaded
+                @pixbuf_thumbnail = @pixbuf_full.scale(@pixbuf_full.width * (@@thumbnails_height.to_f/@pixbuf_full.height), @@thumbnails_height, Gdk::Pixbuf::INTERP_BILINEAR)
+            end
+            return @pixbuf_thumbnail
+        }
+    end
+
+    private
+    def load_into_pixbuf_full
+        if @pixbuf_full.nil?
+            puts ">>> load_into_pixbuf_full #{path}"
+            begin
+                @pixbuf_full = Gdk::Pixbuf.new(@path)
+            rescue Gdk::PixbufError
+                puts "Cannot load #{@path}: #{$!}"
+                return
+            end
+            if @pixbuf_full
+                angle = guess_rotate(path)
+                if angle != 0
+                    puts ">>> load_into_pixbuf_full #{path} => rotate #{angle}"
+                    @pixbuf_full = rotate_pixbuf(@pixbuf_full, angle)
+                end
+                if @pixbuf_full.height > @@max_height
+                    #- save a lot of memory, don't store in actual full size
+                    @pixbuf_full = @pixbuf_full.scale(@pixbuf_full.width * (@@max_height.to_f/@pixbuf_full.height), @@max_height, Gdk::Pixbuf::INTERP_BILINEAR)
+                end
+            end
+        end
+    end
+
+    def to_s
+        @path
+    end
+end
+
+class MainView < Gtk::DrawingArea
+
+    def initialize
+        super()
+        signal_connect('expose-event') { draw }
+        signal_connect('configure-event') { update_shown; GC.start }
+        signal_connect('realize') {
+            @preloader = Thread.new {
+                #- background preloading
+                while true
+                    puts "background main preloading triggered..."
+                    if ! @index.nil?
+                        w, h = window.size
+                        for j in 1 .. 5
+                            i = @index + j
+                            if i < $allentries.size
+                                $allentries[i].pixbuf_main(w, h)
+                            end
+                            i = @index - j
+                            if i >= 0
+                                $allentries[i].pixbuf_main(w, h)
+                            end
+                            GC.start
+                            mem = get_mem
+                            if mem > $config['cache-memory-use-figure']
+                                puts "too much RSS, stopping main preloading"
+                                break
+                            end
+                        end
+                        check_memory_free_cache_if_needed
+                    end
+                    Thread.stop
+                end
+            }
+            @preloader.priority = -2
+        }
+    end
+
+    def set_shown_entry(index)
+        if index == @index
+            return
+        end
+        @index = index
+        if index.nil?
+            @entry = nil
+        else
+            @entry = $allentries[index]
+        end
+        update_shown
+        #- should "freeze" or something to prevent blinking
+        window.clear
+        draw
+        @preloader.run
+    end
+
+    def get_shown_entry
+        return @index
+    end
+
+    def update_shown
+        if @entry
+            width, height = window.size 
+            @pixbuf = @entry.pixbuf_main(width, height)
+            if @pixbuf.width == width
+                @xpos = 0
+                @ypos = (height-@pixbuf.height)/2
+            else
+                @xpos = (width-@pixbuf.width)/2
+                @ypos = 0
+            end
+            @preloader.run
+        else
+            @pixbuf = nil
+        end
+    end
+
+    def draw
+        if @pixbuf
+            window.draw_pixbuf(nil, @pixbuf, 0, 0, @xpos, @ypos, -1, -1, Gdk::RGB::DITHER_NONE, -1, -1)
+        end
+    end
+
+end
+
+def autoscroll_if_needed(img)
+    xpos_left = img.window.position[0]
+    xpos_right = img.window.position[0] + img.window.size[0]
+    current_minx_visible = $imagesline_sw.hadjustment.value
+    current_maxx_visible = $imagesline_sw.hadjustment.value + $imagesline_sw.hadjustment.page_size
+#    puts "xpos left: #{xpos_left}"
+#    puts "xpos right: #{xpos_right}"
+#    puts "current minx visible: #{current_minx_visible}"
+#    puts "current maxx visible: #{current_maxx_visible}"
+    if xpos_left < current_minx_visible
+        puts 'scroll_upper(scrolledwindow, ypos_top)'
+    elsif xpos_right > current_maxx_visible
+        puts 'scroll_lower(scrolledwindow, ypos_bottom)'
+    end
+end
+
+def check_memory_free_cache_if_needed
+    GC.start
+    mem = get_mem
+    i = $mainview.get_shown_entry
+    puts "mem: #{mem} index: #{i}"
+    return if i.nil?
+    ($allentries.size - 1).downto(1) { |j|
+        if mem < $config['cache-memory-use-figure'] * 2 / 3
+            break
+        end
+        index = i + j
+        puts "too much RSS, freeing full size of #{i+j} and #{i-j}..."
+        freedsomething = false
+        if i + j < $allentries.size
+            freedsomething |= $allentries[i+j].free_pixbuf_full
+        end
+        if i - j > 0
+            freedsomething |= $allentries[i-j].free_pixbuf_full
+        end
+        if freedsomething
+            GC.start
+            mem = get_mem
+            puts "\tmem now: #{mem}"
+        end
+    }
+end
+
+def show_entries
+    e = Thread.new {
+        t1 = Time.now
+        show_mem
+        ctid = $statusbar.get_context_id('images loading')
+        $statusbar.push(ctid, utf8(_("Loading images...")))
+        tooltips = Gtk::Tooltips.new
+        $allentries.each_with_index { |entry, i|
+            if entry.pixbuf_full
+                entry.pixbuf_thumbnail
+                gtk_thread_protect(proc { |i|
+                                       entry = $allentries[i]
+                                       entry.button = Gtk::Button.new.set_image(img = Gtk::Image.new(entry.pixbuf_thumbnail)).show_all
+                                       tooltips.set_tip(entry.button, File.basename(entry.path).gsub(/\.[^.]+$/, ''), nil)
+                                       $imagesline.pack_start(entry.button, false, false)
+                                       entry.button.signal_connect('clicked') { $mainview.set_shown_entry(i) }
+                                       entry.button.signal_connect('focus-in-event') { entry.button.clicked; autoscroll_if_needed(img) }
+                                       if i == 0
+                                           entry.button.grab_focus
+                                       end
+                                   }, i)
+                if i % 4 == 0
+                    check_memory_free_cache_if_needed
+                end
+            end
+        }
+        check_memory_free_cache_if_needed
+        $statusbar.pop(ctid)
+        puts "time: #{Time.now - t1}"
+    }
+    e.priority = -1
+end
+
+def open_dir(path)
+    path = File.expand_path(path.sub(%r|/$|, ''))
+    examined_dirs = `find '#{path}' -type d -follow`.sort.collect { |v| v.chomp }
+    #- validate first
+    examined_dirs.each { |dir|
+        if dir =~ /'/
+            show_popup($main_window, utf8(_("Source directory or sub-directories can't contain a single-quote character, sorry: %s") % dir))
+        end
+        Dir.entries(dir).each { |file|
+            if file =~ /['"\[\]]/
+                show_popup($main_window, utf8(_("Files can't contain any of the characters ', \", [ or ], sorry: %s") % "#{dir}/#{file}"))
+            end
+        }
+    }
+    #- scan for populate second
+    $allentries = []
+    examined_dirs.each { |dir|
+        if File.basename(dir) =~ /^\./
+            msg 1, _("Ignoring directory %s, begins with a dot (indicating a hidden directory)") % dir
+            next
+        end
+        Dir.entries(dir).each { |file|
+            type = entry2type(file)
+            if type
+#&& $allentries.size < 8
+                $allentries << Entry.new(File.join(dir, file), type)
+            end
+        }
+    }
+    show_entries
+end
+
+def open_dir_popup
+    fc = Gtk::FileChooserDialog.new(utf8(_("Specify the directory to work with")),
+                                    nil,
+                                    Gtk::FileChooser::ACTION_SELECT_FOLDER,
+                                    nil,
+                                    [Gtk::Stock::OPEN, Gtk::Dialog::RESPONSE_ACCEPT], [Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL])
+    fc.transient_for = $main_window
+    ok = false
+    while !ok
+        if fc.run == Gtk::Dialog::RESPONSE_ACCEPT
+            msg = open_dir(fc.filename)
+            if msg
+                show_popup(fc, msg)
+                ok = false
+            else
+                ok = true
+            end
+        else
+            ok = true
+        end
+    end
+    fc.destroy
+end
+
+def gtk_thread_protect(proc, *params)
+    if Thread.current == Thread.main
+        proc.call(*params)
+    else
+        $protect_gtk_pending_calls.synchronize {
+            $gtk_pending_calls << [ proc, params ]
+        }
+    end
+end
+
+def gtk_thread_flush
+    $protect_gtk_pending_calls.synchronize {
+        if $gtk_pending_calls.size > 0
+            elem = $gtk_pending_calls.shift
+            elem[0].call(*elem[1])
+        end
+    }
+end
+
+def try_quit(*options)
+    Gtk.main_quit
+end
+
+def create_menubar
+    
+    #- menu
+    mb = Gtk::MenuBar.new
+
+    filemenu = Gtk::MenuItem.new(utf8(_("_File")))
+    filesubmenu = Gtk::Menu.new
+    filesubmenu.append(open      = Gtk::ImageMenuItem.new(Gtk::Stock::OPEN))
+    filesubmenu.append(            Gtk::SeparatorMenuItem.new)
+    filesubmenu.append($execute  = Gtk::ImageMenuItem.new(Gtk::Stock::EXECUTE).set_sensitive(false))
+    filesubmenu.append(            Gtk::SeparatorMenuItem.new)
+    filesubmenu.append(quit      = Gtk::ImageMenuItem.new(Gtk::Stock::QUIT))
+    filemenu.set_submenu(filesubmenu)
+    mb.append(filemenu)
+
+    open.signal_connect('activate') { open_dir_popup }
+    $execute.signal_connect('activate') { execute }
+    quit.signal_connect('activate') { try_quit }
+
+    editmenu = Gtk::MenuItem.new(utf8(_("_Edit")))
+    editsubmenu = Gtk::Menu.new
+    editsubmenu.append($undo_mb = Gtk::ImageMenuItem.new(Gtk::Stock::UNDO).set_sensitive(false))
+    editsubmenu.append($redo_mb = Gtk::ImageMenuItem.new(Gtk::Stock::REDO).set_sensitive(false))
+    editsubmenu.append(           Gtk::SeparatorMenuItem.new)
+    editsubmenu.append(prefs    = Gtk::ImageMenuItem.new(Gtk::Stock::PREFERENCES))
+    editmenu.set_submenu(editsubmenu)
+    mb.append(editmenu)
+
+    $undo_mb.signal_connect('activate') { perform_undo }
+    $redo_mb.signal_connect('activate') { perform_redo }
+    prefs.signal_connect('activate') { preferences }
+    
+    helpmenu = Gtk::MenuItem.new(utf8(_("_Help")))
+    helpsubmenu = Gtk::Menu.new
+    helpsubmenu.append(tutos = Gtk::ImageMenuItem.new(utf8(_("Online tutorials (opens a web-browser)"))))
+    tutos.image = Gtk::Image.new("#{$FPATH}/images/stock-web-16.png")
+    helpsubmenu.append(Gtk::SeparatorMenuItem.new)
+    helpsubmenu.append(about = Gtk::ImageMenuItem.new(Gtk::Stock::ABOUT))
+    helpmenu.set_submenu(helpsubmenu)
+    mb.append(helpmenu)
+
+    tutos.signal_connect('activate') { open_url('http://booh.org/tutorial.html') }
+    about.signal_connect('activate') { share }
+
+
+    #- no toolbar, to save height
+
+    return mb
+end
+
+def create_main_window
+
+    mb = create_menubar
+
+    main_vbox = Gtk::VBox.new(false, 0)
+    main_vbox.pack_start(mb, false, false)
+    main_vbox.pack_start($mainview = MainView.new, true, true)
+    $imagesline_sw = Gtk::ScrolledWindow.new(nil, nil)
+    $imagesline_sw.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_NEVER)
+    $imagesline_sw.add_with_viewport($imagesline = Gtk::HBox.new(false, 0))
+    main_vbox.pack_start($imagesline_sw, false, false)
+    main_vbox.pack_end($statusbar = Gtk::Statusbar.new, false, false)
+
+    $imagesline.set_size_request(-1, Entry.thumbnails_height)
+
+    $main_window = Gtk::Window.new
+    $main_window.add(main_vbox)
+    $main_window.signal_connect('delete-event') {
+        try_quit({ :disallow_cancel => true })
+    }
+
+    #- read/save size and position of window
+    if $config['pos-x'] && $config['pos-y']
+        $main_window.move($config['pos-x'].to_i, $config['pos-y'].to_i)
+    else
+        $main_window.window_position = Gtk::Window::POS_CENTER
+    end
+    msg 3, "size: #{$config['width']}x#{$config['height']}"
+    $main_window.set_default_size(($config['width'] || 600).to_i, ($config['height'] || 400).to_i)
+    $main_window.signal_connect('configure-event') {
+        msg 3, "configure: pos: #{$main_window.window.root_origin.inspect} size: #{$main_window.window.size.inspect}"
+        x, y = $main_window.window.root_origin
+        width, height = $main_window.window.size
+        $config['pos-x'] = x
+        $config['pos-y'] = y
+        $config['width'] = width
+        $config['height'] = height
+        false
+    }
+
+    $protect_gtk_pending_calls = Mutex.new
+    $gtk_pending_calls = []
+    Gtk.timeout_add(50) {
+        gtk_thread_flush
+        true
+    }
+
+    Gtk.timeout_add(10000) {
+        show_mem
+        true
+    }
+    $statusbar.push(0, utf8(_("Ready.")))
+    $main_window.show_all
+end
+
+
+Thread.abort_on_exception = true
+read_config
+Gtk.init
+
+
+#- Gdk::Pixbuf#rotate memory leak check (in ruby-gnome2 <= 0.16.0)
+pb = Gdk::Pixbuf.new("#{$FPATH}/images/logo.png")
+1.upto(5) { pb = pb.rotate(Gdk::Pixbuf::ROTATE_CLOCKWISE) }
+GC.start
+mem = get_mem
+1.upto(5) { pb = pb.rotate(Gdk::Pixbuf::ROTATE_CLOCKWISE) }
+GC.start
+mem2 = get_mem
+if mem2 != mem
+    puts _("Gdk::Pixbuf#scale memory leak detected (this is normal with unpatched ruby-gnome2 <= 0.16.0). Application would slow down to a crawl, won't proceed.")
+    exit 1
+end
+
+
+create_main_window
+check_config
+
+if ARGV[0]
+    open_dir(ARGV[0])
+end
+Gtk.main
+
+write_config