much more
[booh] / bin / booh-classifier
1 #! /usr/bin/ruby
2 #
3 #                         *  BOOH  *
4 #
5 # A.k.a 'Best web-album Of the world, Or your money back, Humerus'.
6 #
7 # The acronyn sucks, however this is a tribute to Dragon Ball by
8 # Akira Toriyama, where the last enemy beaten by heroes of Dragon
9 # Ball is named "Boo". But there was already a free software project
10 # called Boo, so this one will be it "Booh". Or whatever.
11 #
12 #
13 # Copyright (c) 2004-2006 Guillaume Cottenceau <http://zarb.org/~gc/resource/gc_mail.png>
14 #
15 # This software may be freely redistributed under the terms of the GNU
16 # public license version 2.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program; if not, write to the Free Software
20 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
22 require 'getoptlong'
23 require 'tempfile'
24 require 'thread'
25
26 require 'gtk2'
27
28 require 'gettext'
29 include GetText
30 bindtextdomain("booh")
31
32 require 'rexml/document'
33 include REXML
34
35 require 'booh/booh-lib'
36 include Booh
37 require 'booh/UndoHandler'
38
39
40 #- options
41 $options = [
42     [ '--help',          '-h', GetoptLong::NO_ARGUMENT,       _("Get help message") ],
43
44     [ '--verbose-level', '-v', GetoptLong::REQUIRED_ARGUMENT, _("Set max verbosity level (0: errors, 1: warnings, 2: important messages, 3: other messages)") ],
45 ]
46
47 def usage
48     puts _("Usage: %s [OPTION]...") % File.basename($0)
49     $options.each { |ary|
50         printf " %3s, %-15s %s\n", ary[1], ary[0], ary[3]
51     }
52 end
53
54 def handle_options
55     parser = GetoptLong.new
56     parser.set_options(*$options.collect { |ary| ary[0..2] })
57     begin
58         parser.each_option do |name, arg|
59             case name
60             when '--help'
61                 usage
62                 exit(0)
63
64             when '--verbose-level'
65                 $verbose_level = arg.to_i
66
67             end
68         end
69         puts "args: #{ARGV}"
70     rescue
71         puts $!
72         usage
73         exit(1)
74     end
75 end
76
77 def memfree
78     meminfo = IO.readlines('/proc/meminfo').join
79     meminfo =~ /MemFree:.*?(\d+)/ or return -1
80     memfree = $1
81     meminfo =~ /Buffers:.*?(\d+)/ and buffers = $1
82     meminfo =~ /Cached:.*?(\d+)/ and cached = $1
83     return memfree.to_i + buffers.to_i + cached.to_i
84 end
85
86 def read_config
87     $config = {}
88     $config_file = File.expand_path('~/.booh-classifier-rc')
89     if File.readable?($config_file)
90         $xmldoc = REXML::Document.new(File.new($config_file))
91         $xmldoc.root.elements.each { |element|
92             txt = element.get_text
93             if txt
94                 if txt.value =~ /~~~/
95                     $config[element.name] = txt.value.split(/~~~/)
96                 else
97                     $config[element.name] = txt.value
98                 end
99             elsif element.elements.size == 0
100                 $config[element.name] = ''
101             else
102                 $config[element.name] = {}
103                 element.each { |chld|
104                     txt = chld.get_text
105                     $config[element.name][chld.name] = txt ? txt.value : nil
106                 }
107             end
108         }
109     end
110     $config['video-viewer'] ||= '/usr/bin/mplayer %f'
111     $config['preload-distance'] ||= 5
112     $config['cache-memory-use'] ||= 'memfree_50%'
113     if $config['cache-memory-use'] =~ /memfree_(\d+)/
114         $config['cache-memory-use-figure'] = memfree*$1.to_f/100
115     else
116         $config['cache-memory-use-figure'] = $config['cache-memory-use'].to_i
117     end
118     msg 2, "Set cache memory use figure: #{$config['cache-memory-use-figure']} kB"
119 end
120
121 def check_config
122     if !system("which identify >/dev/null 2>/dev/null")
123         show_popup($main_window, utf8(_("The program 'identify' is needed to get images sizes and EXIF data. Please install it.
124 It is generally available with the 'ImageMagick' software package.")), { :pos_centered => true })
125     end
126     missing = %w(transcode mencoder).delete_if { |prg| system("which #{prg} >/dev/null 2>/dev/null") }
127     if missing != []
128         show_popup($main_window, utf8(_("The following program(s) are needed to handle videos: '%s'. Videos will be ignored.") % missing.join(', ')), { :pos_centered => true })
129     end
130
131     viewer_binary = $config['video-viewer'].split.first
132     if viewer_binary && !File.executable?(viewer_binary)
133         show_popup($main_window, utf8(_("The configured video viewer seems to be unavailable.
134 You should fix this in Edit/Preferences so that you can view videos.
135
136 Problem was: '%s' is not an executable file.
137 Hint: don't forget to specify the full path to the executable,
138 e.g. '/usr/bin/mplayer' is correct but 'mplayer' only is not.") % viewer_binary), { :pos_centered => true, :not_transient => true })
139     end
140 end
141
142 def write_config
143     ios = File.open($config_file, "w")
144     $xmldoc = Document.new "<booh-classifier-rc version='#{$VERSION}'/>"
145     $xmldoc << XMLDecl.new(XMLDecl::DEFAULT_VERSION, $CURRENT_CHARSET)
146     $config.each_pair { |key, value|
147         elem = $xmldoc.root.add_element key
148         if value.is_a? Hash
149             $config[key].each_pair { |subkey, subvalue|
150                 subelem = elem.add_element subkey
151                 subelem.add_text subvalue.to_s
152             }
153         elsif value.is_a? Array
154             elem.add_text value.join('~~~')
155         else
156             if !value
157                 elem.remove
158             else
159                 elem.add_text value.to_s
160             end
161         end
162     }
163     $xmldoc.write(ios, 0)
164     ios.close
165 end
166
167 def save_undo(name, closure, *params)
168     UndoHandler.save_undo(name, closure, [ *params ])
169     $undo_tb.sensitive = $undo_mb.sensitive = true
170     $redo_tb.sensitive = $redo_mb.sensitive = false
171 end
172
173 def get_mem
174     IO.readlines('/proc/self/status').join =~ /VmRSS.*?(\d+)\s*kB/
175     puts $1
176     return $1.to_i
177 end
178
179 def show_mem(*txt)
180     txt.length > 0 and print txt[0]
181     puts get_mem
182 end
183
184 def min(v1, v2)
185     return v1 < v2 ? v1 : v2
186 end
187 def max(v1, v2)
188     return v1 > v2 ? v1 : v2
189 end
190
191 class Gdk::Color
192     def darker
193         color = dup
194         color.red = max(color.red - 10000, 0)
195         color.green = max(color.green - 10000, 0)
196         color.blue = max(color.blue - 10000, 0)
197         return color
198     end
199     def lighter
200         color = dup
201         color.red = min(color.red + 10000, 65535)
202         color.green = min(color.green + 10000, 65535)
203         color.blue = min(color.blue + 10000, 65535)
204         return color
205     end
206 end
207
208 $colors = [ Gdk::Color.new(0, 65535, 0),
209             Gdk::Color.new(0, 0, 65535),
210             Gdk::Color.new(65535, 65535, 0),
211             Gdk::Color.new(0, 65535, 65535),
212             Gdk::Color.new(65535, 0, 65535) ]
213
214 class Tag
215     attr_accessor :color, :name
216     def initialize(name)
217         @name = name
218     end
219 end
220 $tags = {}
221
222 class Entry
223     @@thumbnails_height = 64
224     @@max_height = nil
225     def Entry.thumbnails_height
226         return @@thumbnails_height
227     end
228
229     attr_accessor :path, :type, :angle, :button, :removed, :tagged
230
231     def initialize(path, type)
232         @path = path
233         @type = type
234         if @@max_height.nil?
235             @@max_height = $main_window.root_window.size[1]
236         end
237         @protect_cleanup = Mutex.new
238     end
239
240     def pixbuf_full
241         @protect_cleanup.synchronize {
242             if @pixbuf_full.nil?
243                 puts ">>> pixbuf_full #{path}"
244                 load_into_pixbuf_full
245             end
246             return @pixbuf_full
247         }
248     end
249     def free_pixbuf_full
250         @protect_cleanup.synchronize {
251             if @pixbuf_full.nil?
252                 return false
253             else
254                 puts ">>> free_pixbuf_full #{path}"
255                 @pixbuf_full = nil
256                 return true
257             end
258         }
259     end
260     def pixbuf_main(width, height)
261         @protect_cleanup.synchronize {
262             if @pixbuf_main.nil? || width != @width || height != @height
263                 puts ">>> pixbuf_main #{path}"
264                 @width = width
265                 @height = height
266                 load_into_pixbuf_full  #- make sure it is loaded
267                 if @pixbuf_full.width.to_f / @pixbuf_full.height > width.to_f / height
268                     resized_height = @pixbuf_full.height * (width.to_f/@pixbuf_full.width)
269                     if @pixbuf_full.width > width || @pixbuf_full.height > resized_height
270                         @pixbuf_main = @pixbuf_full.scale(width, resized_height, Gdk::Pixbuf::INTERP_BILINEAR)
271                     else
272                         @pixbuf_main = @pixbuf_full
273                     end
274                 else
275                     resized_width = @pixbuf_full.width * (height.to_f/@pixbuf_full.height)
276                     if @pixbuf_full.width > resized_width || @pixbuf_full.height > height
277                         @pixbuf_main = @pixbuf_full.scale(resized_width, height, Gdk::Pixbuf::INTERP_BILINEAR)
278                     else
279                         @pixbuf_main = @pixbuf_full
280                     end
281                 end
282             end
283             return @pixbuf_main
284         }
285     end
286     def free_pixbuf_main
287         @protect_cleanup.synchronize {
288             if @pixbuf_main.nil?
289                 return false
290             else
291                 puts ">>> free_pixbuf_main #{path}"
292                 @pixbuf_main = nil
293                 return true
294             end
295         }
296     end
297     def pixbuf_thumbnail
298         return @protect_cleanup.synchronize {
299             if @pixbuf_thumbnail.nil?
300                 puts ">>> pixbuf_thumbnail #{path}"
301                 load_into_pixbuf_full  #- make sure it is loaded
302                 @pixbuf_thumbnail = @pixbuf_full.scale(@pixbuf_full.width * (@@thumbnails_height.to_f/@pixbuf_full.height), @@thumbnails_height, Gdk::Pixbuf::INTERP_BILINEAR)
303             end
304             return @pixbuf_thumbnail
305         }
306     end
307     def free_pixbuf_thumbnail
308         @protect_cleanup.synchronize {
309             if @pixbuf_thumbnail.nil?
310                 return false
311             else
312                 puts ">>> free_pixbuf_thumbnail #{path}"
313                 @pixbuf_thumbnail = nil
314                 return true
315             end
316         }
317     end
318
319     def show_bg
320         if removed
321             red = Gdk::Color.new(65535, 0, 0)
322             button.modify_bg(Gtk::StateType::NORMAL, red)
323             button.modify_bg(Gtk::StateType::PRELIGHT, red.lighter)
324             button.modify_bg(Gtk::StateType::ACTIVE, red)
325         elsif tagged
326             button.modify_bg(Gtk::StateType::NORMAL, tagged.color)
327             button.modify_bg(Gtk::StateType::PRELIGHT, tagged.color.lighter)
328             button.modify_bg(Gtk::StateType::ACTIVE, tagged.color)
329         else
330             # TODO need to add proper undo support :/
331             white = Gdk::Color.new(55535, 55535, 55535)
332             button.modify_bg(Gtk::StateType::NORMAL, white)
333             button.modify_bg(Gtk::StateType::PRELIGHT, white.lighter)
334             button.modify_bg(Gtk::StateType::ACTIVE, white)
335         end
336     end
337
338     private
339     def load_into_pixbuf_full
340         if @pixbuf_full.nil?
341             puts ">>> load_into_pixbuf_full #{path}"
342             begin
343                 @pixbuf_full = Gdk::Pixbuf.new(@path)
344             rescue Gdk::PixbufError
345                 puts "Cannot load #{@path}: #{$!}"
346                 return
347             end
348             if @pixbuf_full
349                 if @angle.nil?
350                     @angle = guess_rotate(path)
351                 end
352                 if @angle != 0
353                     puts ">>> load_into_pixbuf_full #{path} => rotate #{@angle}"
354                     @pixbuf_full = rotate_pixbuf(@pixbuf_full, @angle)
355                 end
356                 if @pixbuf_full.height > @@max_height
357                     #- save a lot of memory, don't store in actual full size
358                     @pixbuf_full = @pixbuf_full.scale(@pixbuf_full.width * (@@max_height.to_f/@pixbuf_full.height), @@max_height, Gdk::Pixbuf::INTERP_BILINEAR)
359                 end
360             end
361         end
362     end
363
364     def to_s
365         @path
366     end
367 end
368
369 class MainView < Gtk::DrawingArea
370
371     def initialize
372         super()
373         signal_connect('expose-event') { draw }
374         signal_connect('configure-event') { update_shown; GC.start }
375         signal_connect('realize') {
376             @preloader = Thread.new {
377                 #- background preloading
378                 while true
379                     puts "background main preloading triggered..."
380                     if ! @index.nil?
381                         w, h = window.size
382                         for j in 1 .. $config['preload-distance']
383                             i = @index + j
384                             if i < $allentries.size
385                                 $allentries[i].pixbuf_main(w, h)
386                             end
387                             i = @index - j
388                             if i >= 0
389                                 $allentries[i].pixbuf_main(w, h)
390                             end
391                             GC.start
392                             mem = get_mem
393                             if mem > $config['cache-memory-use-figure']
394                                 puts "too much RSS, stopping main preloading"
395                                 break
396                             end
397                         end
398                         check_memory_free_cache_if_needed
399                     end
400                     Thread.stop
401                 end
402             }
403             @preloader.priority = -2
404         }
405     end
406
407     def set_shown_entry(index)
408         if index == @index
409             return
410         end
411         @index = index
412         if index.nil?
413             @entry = nil
414         else
415             @entry = $allentries[index]
416         end
417         redraw        
418         @preloader.run
419     end
420
421     def get_shown_entry
422         return @index
423     end
424
425     def redraw
426         update_shown
427         w, h = window.size
428         window.begin_paint(Gdk::Rectangle.new(0, 0, w, h))
429         window.clear
430         draw
431         window.end_paint
432     end
433
434     def update_shown
435         if @entry
436             width, height = window.size 
437             @pixbuf = @entry.pixbuf_main(width, height)
438             if @pixbuf.width == width
439                 @xpos = 0
440                 @ypos = (height-@pixbuf.height)/2
441             else
442                 @xpos = (width-@pixbuf.width)/2
443                 @ypos = 0
444             end
445             @preloader.run
446         else
447             @pixbuf = nil
448         end
449     end
450
451     def draw
452         if @pixbuf
453             window.draw_pixbuf(nil, @pixbuf, 0, 0, @xpos, @ypos, -1, -1, Gdk::RGB::DITHER_NONE, -1, -1)
454         end
455     end
456
457     def show_next
458         if @index < $allentries.size - 1
459             next_entry = $allentries[get_shown_entry + 1]
460             next_entry.button.grab_focus
461         end
462     end
463
464 end
465
466 def check_memory_free_cache_if_needed
467     GC.start
468     mem = get_mem
469     i = $mainview.get_shown_entry
470     puts "mem: #{mem} index: #{i}"
471     return if i.nil?
472     ($allentries.size - 1).downto(1) { |j|
473         if mem < $config['cache-memory-use-figure'] * 2 / 3
474             break
475         end
476         index = i + j
477         puts "too much RSS, freeing full size of #{i+j} and #{i-j}..."
478         freedsomething = false
479         if i + j < $allentries.size
480             freedsomething |= $allentries[i+j].free_pixbuf_full
481         end
482         if i - j > 0
483             freedsomething |= $allentries[i-j].free_pixbuf_full
484         end
485         if freedsomething
486             GC.start
487             mem = get_mem
488             puts "\tmem now: #{mem}"
489         end
490     }
491 end
492
493 def autoscroll_if_needed(button)
494     xpos_left = button.allocation.x
495     xpos_right = button.allocation.x + button.allocation.width
496     hadj = $imagesline_sw.hadjustment
497     current_minx_visible = hadj.value
498     current_maxx_visible = hadj.value + hadj.page_size
499     if xpos_left < current_minx_visible
500         #- autoscroll left
501         newval = hadj.value - (current_minx_visible - xpos_left)
502         hadj.value = newval
503         button.queue_draw  #- TOREMOVE: the visual focus is displayed incorrectly
504     elsif xpos_right > current_maxx_visible
505         #- autoscroll right
506         newval = hadj.value + (xpos_right - current_maxx_visible)
507         if newval > hadj.upper - hadj.page_size
508             newval = hadj.upper - hadj.page_size
509         end
510         hadj.value = newval
511         button.queue_draw  #- TOREMOVE: the visual focus is displayed incorrectly
512     end
513 end
514
515 def show_popup(parent, msg, *options)
516     dialog = Gtk::Dialog.new
517     if options[0]
518         options = options[0]
519     else
520         options = {}
521     end
522     if options[:title]
523         dialog.title = options[:title]
524     else
525         dialog.title = utf8(_("Booh message"))
526     end
527     lbl = Gtk::Label.new
528     if options[:nomarkup]
529         lbl.text = msg
530     else
531         lbl.markup = msg
532     end
533     if options[:centered]
534         lbl.set_justify(Gtk::Justification::CENTER)
535     end
536     if options[:selectable]
537         lbl.selectable = true
538     end
539     if options[:topwidget]
540         dialog.vbox.add(options[0][:topwidget])
541     end
542     if options[:scrolled]
543         sw = Gtk::ScrolledWindow.new(nil, nil)
544         sw.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC)
545         sw.add_with_viewport(lbl)
546         dialog.vbox.add(sw)
547         dialog.set_default_size(500, 600)
548     else
549         dialog.vbox.add(lbl)
550         dialog.set_default_size(200, 120)
551     end
552     if options[:bottomwidget]
553         dialog.vbox.add(options[:bottomwidget])
554     end
555     if options[:okcancel]
556         dialog.add_button(Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL)
557     end
558     dialog.add_button(Gtk::Stock::OK, Gtk::Dialog::RESPONSE_OK)
559
560     if options[:pos_centered]
561         dialog.window_position = Gtk::Window::POS_CENTER
562     else
563         dialog.window_position = Gtk::Window::POS_MOUSE
564     end
565
566     if options[:linkurl]
567         linkbut = Gtk::Button.new('')
568         linkbut.child.markup = "<span foreground=\"#00000000FFFF\" underline=\"single\">#{options[0][:linkurl]}</span>"
569         linkbut.signal_connect('clicked') {
570             open_url(options[0][:linkurl] + '/index.html')
571             dialog.response(Gtk::Dialog::RESPONSE_OK)
572             set_mousecursor_normal
573         }
574         linkbut.relief = Gtk::RELIEF_NONE
575         linkbut.signal_connect('enter-notify-event') { set_mousecursor(Gdk::Cursor::HAND2, linkbut); false }
576         linkbut.signal_connect('leave-notify-event') { set_mousecursor(nil, linkbut); false }
577         dialog.vbox.add(Gtk::Alignment.new(0.5, 0.5, 0, 0).add(linkbut))
578     end
579
580     dialog.show_all
581
582     if options[:stuff_connector]
583         options[:stuff_connector].call({ :dialog => dialog })
584     end
585                                         
586     if !options[:not_transient]
587         dialog.transient_for = parent
588         dialog.run { |response|
589             if options[:data_getter]
590                 options[:data_getter].call
591             end
592             dialog.destroy
593             if options[:okcancel]
594                 return response == Gtk::Dialog::RESPONSE_OK
595             end
596         }
597     else
598         dialog.signal_connect('response') { dialog.destroy }
599     end
600 end
601
602 def thumbnail_keypressed(entry, event)
603     if event.state & Gdk::Window::MOD1_MASK != 0
604         #- ALT pressed: Alt-Left and Alft-Right rotate
605         if event.keyval == Gdk::Keyval::GDK_Left || event.keyval == Gdk::Keyval::GDK_Right
606             if event.keyval == Gdk::Keyval::GDK_Left
607                 entry.angle = (entry.angle - 90) % 360
608             else
609                 entry.angle = (entry.angle + 90) % 360
610             end
611             entry.free_pixbuf_full
612             entry.free_pixbuf_main
613             entry.free_pixbuf_thumbnail
614             $mainview.redraw
615             entry.button.set_image(img = Gtk::Image.new(entry.pixbuf_thumbnail))
616         end
617
618     else
619         if event.keyval == Gdk::Keyval::GDK_Delete
620             entry.removed = true
621             entry.tagged = nil
622             entry.show_bg
623             $mainview.show_next
624
625         elsif event.keyval == Gdk::Keyval::GDK_space
626             entry.removed = false
627             entry.tagged = nil
628             entry.show_bg
629             $mainview.show_next
630
631         else
632             char = [ Gdk::Keyval.to_unicode(event.keyval) ].pack("C*")
633             if char =~ /^[a-zA-z0-9]$/
634                 tag = $tags[char]
635                 
636                 if tag.nil?
637                     vb = Gtk::VBox.new(false, 0)
638                     vb.pack_start(entry = Gtk::Entry.new.set_text(char), false, false)
639                     vb.pack_start(Gtk::Alignment.new(0.5, 0.5, 0, 0).add(bt = Gtk::Button.new(utf8(_("  Change color  ")))))
640                     text = nil
641                     color = nil
642                     bt.signal_connect('clicked') {
643                         color = $colors.shift
644                         if color.nil?
645                             color = Gdk::Color.new(16384 + rand(49151), 16384 + rand(49151), 16384 + rand(49151))
646                         end
647                         bt.modify_bg(Gtk::StateType::NORMAL, color)
648                         bt.modify_bg(Gtk::StateType::PRELIGHT, color)
649                         bt.modify_bg(Gtk::StateType::ACTIVE, color.darker)
650                     }
651                     bt.clicked
652                     if show_popup($main_window,
653                                   utf8(_("You typed the text character '%s', which is not associated with a tag.\nType in the full name of the tag below to create a new one.")) % char,
654                                   { :okcancel => true, :bottomwidget => vb, :data_getter => proc { text = entry.text },
655                                     :stuff_connector => proc { |stuff| entry.select_region(0, 0); entry.position = -1;
656                                           entry.signal_connect('activate') { stuff[:dialog].response(Gtk::Dialog::RESPONSE_OK) } } } )
657                         if text.length > 0
658                             char = text[0,1]  #- in case it changed
659                             tag = Tag.new(text)
660                             tag.color = color
661                             $tags[char] = tag
662                             label = Gtk::Label.new.set_markup('<b>(' + char + ')</b>' + text[1..-1]).set_justify(Gtk::Justification::CENTER)
663                             $tags_vbox.pack_start(evt = Gtk::EventBox.new.add(label).modify_bg(Gtk::StateType::NORMAL, tag.color).show_all)
664                         end
665                     end
666
667                 else
668                     entry.removed = false
669                     entry.tagged = tag
670                     entry.show_bg
671                     $mainview.show_next
672                 end
673             end
674         end
675     end
676 end
677
678 def show_entries
679     e = Thread.new {
680         t1 = Time.now
681         show_mem
682         ctid = $statusbar.get_context_id('images loading')
683         $statusbar.push(ctid, utf8(_("Loading images...")))
684         tooltips = Gtk::Tooltips.new
685         counter = 0
686         $allentries.each_with_index { |entry, i|
687             if entry.pixbuf_full
688                 entry.pixbuf_thumbnail
689                 gtk_thread_protect(proc { |i|
690                                        entry = $allentries[i]
691                                        entry.button = Gtk::Button.new.set_image(img = Gtk::Image.new(entry.pixbuf_thumbnail))
692                                        tooltips.set_tip(entry.button, File.basename(entry.path).gsub(/\.[^.]+$/, ''), nil)
693                                        $imagesline.pack_start(entry.button.show_all, false, false)
694                                        entry.button.signal_connect('clicked') { $mainview.set_shown_entry(i) }
695                                        entry.button.signal_connect('focus-in-event') { entry.button.clicked; autoscroll_if_needed(entry.button) }
696                                        entry.button.signal_connect('key-press-event') { |w, e| thumbnail_keypressed(entry, e) }
697                                        if i == 0
698                                            entry.button.grab_focus
699                                        end
700                                    }, i)
701                 if i % 4 == 0
702                     check_memory_free_cache_if_needed
703                 end
704                 counter += 1
705             end
706         }
707         check_memory_free_cache_if_needed
708         $statusbar.pop(ctid)
709         $statusbar.push(0, utf8(_("%d images loaded.") % counter))
710         puts "time: #{Time.now - t1}"
711     }
712     e.priority = -1
713 end
714
715 def open_dir(path)
716     path = File.expand_path(path.sub(%r|/$|, ''))
717     examined_dirs = `find '#{path}' -type d -follow`.sort.collect { |v| v.chomp }
718     #- validate first
719     examined_dirs.each { |dir|
720         if dir =~ /'/
721             show_popup($main_window, utf8(_("Source directory or sub-directories can't contain a single-quote character, sorry: %s") % dir))
722         end
723         Dir.entries(dir).each { |file|
724             if file =~ /['"\[\]]/
725                 show_popup($main_window, utf8(_("Files can't contain any of the characters ', \", [ or ], sorry: %s") % "#{dir}/#{file}"))
726             end
727         }
728     }
729     #- scan for populate second
730     $allentries = []
731     examined_dirs.each { |dir|
732         if File.basename(dir) =~ /^\./
733             msg 1, _("Ignoring directory %s, begins with a dot (indicating a hidden directory)") % dir
734             next
735         end
736         Dir.entries(dir).each { |file|
737             type = entry2type(file)
738            if type && $allentries.size < 2
739                 $allentries << Entry.new(File.join(dir, file), type)
740             end
741         }
742     }
743     show_entries
744 end
745
746 def open_dir_popup
747     fc = Gtk::FileChooserDialog.new(utf8(_("Specify the directory to work with")),
748                                     nil,
749                                     Gtk::FileChooser::ACTION_SELECT_FOLDER,
750                                     nil,
751                                     [Gtk::Stock::OPEN, Gtk::Dialog::RESPONSE_ACCEPT], [Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL])
752     fc.transient_for = $main_window
753     ok = false
754     while !ok
755         if fc.run == Gtk::Dialog::RESPONSE_ACCEPT
756             msg = open_dir(fc.filename)
757             if msg
758                 show_popup(fc, msg)
759                 ok = false
760             else
761                 ok = true
762             end
763         else
764             ok = true
765         end
766     end
767     fc.destroy
768 end
769
770 def gtk_thread_protect(proc, *params)
771     if Thread.current == Thread.main
772         proc.call(*params)
773     else
774         $protect_gtk_pending_calls.synchronize {
775             $gtk_pending_calls << [ proc, params ]
776         }
777     end
778 end
779
780 def gtk_thread_flush
781     $protect_gtk_pending_calls.synchronize {
782         if $gtk_pending_calls.size > 0
783             elem = $gtk_pending_calls.shift
784             elem[0].call(*elem[1])
785         end
786     }
787 end
788
789 def try_quit(*options)
790     Gtk.main_quit
791 end
792
793 def create_menubar
794     
795     #- menu
796     mb = Gtk::MenuBar.new
797
798     filemenu = Gtk::MenuItem.new(utf8(_("_File")))
799     filesubmenu = Gtk::Menu.new
800     filesubmenu.append(open      = Gtk::ImageMenuItem.new(Gtk::Stock::OPEN))
801     filesubmenu.append(            Gtk::SeparatorMenuItem.new)
802     filesubmenu.append($execute  = Gtk::ImageMenuItem.new(Gtk::Stock::EXECUTE).set_sensitive(false))
803     filesubmenu.append(            Gtk::SeparatorMenuItem.new)
804     filesubmenu.append(quit      = Gtk::ImageMenuItem.new(Gtk::Stock::QUIT))
805     filemenu.set_submenu(filesubmenu)
806     mb.append(filemenu)
807
808     open.signal_connect('activate') { open_dir_popup }
809     $execute.signal_connect('activate') { execute }
810     quit.signal_connect('activate') { try_quit }
811
812     editmenu = Gtk::MenuItem.new(utf8(_("_Edit")))
813     editsubmenu = Gtk::Menu.new
814     editsubmenu.append($undo_mb = Gtk::ImageMenuItem.new(Gtk::Stock::UNDO).set_sensitive(false))
815     editsubmenu.append($redo_mb = Gtk::ImageMenuItem.new(Gtk::Stock::REDO).set_sensitive(false))
816     editsubmenu.append(           Gtk::SeparatorMenuItem.new)
817     editsubmenu.append(prefs    = Gtk::ImageMenuItem.new(Gtk::Stock::PREFERENCES))
818     editmenu.set_submenu(editsubmenu)
819     mb.append(editmenu)
820
821     $undo_mb.signal_connect('activate') { perform_undo }
822     $redo_mb.signal_connect('activate') { perform_redo }
823     prefs.signal_connect('activate') { preferences }
824     
825     helpmenu = Gtk::MenuItem.new(utf8(_("_Help")))
826     helpsubmenu = Gtk::Menu.new
827     helpsubmenu.append(tutos = Gtk::ImageMenuItem.new(utf8(_("Online tutorials (opens a web-browser)"))))
828     tutos.image = Gtk::Image.new("#{$FPATH}/images/stock-web-16.png")
829     helpsubmenu.append(Gtk::SeparatorMenuItem.new)
830     helpsubmenu.append(about = Gtk::ImageMenuItem.new(Gtk::Stock::ABOUT))
831     helpmenu.set_submenu(helpsubmenu)
832     mb.append(helpmenu)
833
834     tutos.signal_connect('activate') { open_url('http://booh.org/tutorial.html') }
835     about.signal_connect('activate') { share }
836
837
838     #- no toolbar, to save height
839
840     return mb
841 end
842
843 def reset_tags
844     for child in $tags_vbox.children
845         $tags_vbox.remove(child)
846     end
847     $tags_vbox.pack_start(Gtk::Label.new(utf8(_("Tags list:"))).set_justify(Gtk::Justification::CENTER), false, false)
848 end
849
850 def create_main_window
851
852     mb = create_menubar
853
854     main_vbox = Gtk::VBox.new(false, 0)
855     main_vbox.pack_start(mb, false, false)
856     mainview_hbox = Gtk::HBox.new
857     mainview_hbox.pack_start(tags_vbox_vbox = Gtk::VBox.new(false, 0), false, true)
858     tags_vbox_vbox.pack_start($tags_vbox = Gtk::VBox.new(false, 5), false, false)
859     reset_tags
860     mainview_hbox.pack_start($mainview = MainView.new, true, true)
861     main_vbox.pack_start(mainview_hbox, true, true)
862     $imagesline_sw = Gtk::ScrolledWindow.new(nil, nil)
863     $imagesline_sw.set_policy(Gtk::POLICY_ALWAYS, Gtk::POLICY_NEVER)
864     $imagesline_sw.add_with_viewport($imagesline = Gtk::HBox.new(false, 0))
865     main_vbox.pack_start($imagesline_sw, false, false)
866     main_vbox.pack_end($statusbar = Gtk::Statusbar.new, false, false)
867
868     $imagesline.set_size_request(-1, Entry.thumbnails_height + $imagesline_sw.hscrollbar.size_request[1])
869
870     $main_window = Gtk::Window.new
871     $main_window.add(main_vbox)
872     $main_window.signal_connect('delete-event') {
873         try_quit({ :disallow_cancel => true })
874     }
875
876     #- read/save size and position of window
877     if $config['pos-x'] && $config['pos-y']
878         $main_window.move($config['pos-x'].to_i, $config['pos-y'].to_i)
879     else
880         $main_window.window_position = Gtk::Window::POS_CENTER
881     end
882     msg 3, "size: #{$config['width']}x#{$config['height']}"
883     $main_window.set_default_size(($config['width'] || 700).to_i, ($config['height'] || 600).to_i)
884     $main_window.signal_connect('configure-event') {
885         msg 3, "configure: pos: #{$main_window.window.root_origin.inspect} size: #{$main_window.window.size.inspect}"
886         x, y = $main_window.window.root_origin
887         width, height = $main_window.window.size
888         $config['pos-x'] = x
889         $config['pos-y'] = y
890         $config['width'] = width
891         $config['height'] = height
892         false
893     }
894
895     $protect_gtk_pending_calls = Mutex.new
896     $gtk_pending_calls = []
897     Gtk.timeout_add(50) {
898         gtk_thread_flush
899         true
900     }
901
902     Gtk.timeout_add(10000) {
903         show_mem
904         true
905     }
906  
907     $main_window.show_all
908 end
909
910
911 Thread.abort_on_exception = true
912 read_config
913 Gtk.init
914
915
916 #- Gdk::Pixbuf#rotate memory leak check (in ruby-gnome2 <= 0.16.0)
917 #pb = Gdk::Pixbuf.new("#{$FPATH}/images/logo.png")
918 #1.upto(5) { pb = pb.rotate(Gdk::Pixbuf::ROTATE_CLOCKWISE) }
919 #GC.start
920 #mem = get_mem
921 #1.upto(5) { pb = pb.rotate(Gdk::Pixbuf::ROTATE_CLOCKWISE) }
922 #GC.start
923 #mem2 = get_mem
924 #if mem2 != mem
925 #    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.")
926 #    exit 1
927 #end
928
929
930 create_main_window
931 check_config
932
933 if ARGV[0]
934     open_dir(ARGV[0])
935 end
936 Gtk.main
937
938 write_config