sync
[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'].to_i
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                     entry.signal_connect('changed') {  #- cannot add a new tag with first letter of an existing tag
653                         while $tags.has_key?(entry.text[0,1])
654                             entry.text = entry.text.sub(/./, '')
655                         end
656                     }
657                     if show_popup($main_window,
658                                   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,
659                                   { :okcancel => true, :bottomwidget => vb, :data_getter => proc { text = entry.text },
660                                     :stuff_connector => proc { |stuff| entry.select_region(0, 0)
661                                                                        entry.position = -1
662                                                                        entry.signal_connect('activate') { stuff[:dialog].response(Gtk::Dialog::RESPONSE_OK) } } } )
663                         if text.length > 0
664                             char = text[0,1]  #- in case it changed
665                             tag = Tag.new(text)
666                             tag.color = color
667                             $tags[char] = tag
668                             label = Gtk::Label.new.set_markup('<b>(' + char + ')</b>' + text[1..-1]).set_justify(Gtk::Justification::CENTER)
669                             $tags_vbox.pack_start(evt = Gtk::EventBox.new.add(label).modify_bg(Gtk::StateType::NORMAL, tag.color).show_all)
670                         end
671                     end
672
673                 else
674                     entry.removed = false
675                     entry.tagged = tag
676                     entry.show_bg
677                     $mainview.show_next
678                 end
679             end
680         end
681     end
682 end
683
684 def sb_msg(msg)
685     $statusbar.pop(0)
686     if msg
687         $statusbar.push(0, utf8(msg))
688     end
689 end
690     
691 def show_entries
692     e = Thread.new {
693         t1 = Time.now
694         show_mem
695         sb_msg(_("Loading images..."))
696         tooltips = Gtk::Tooltips.new
697         counter = 0
698         $allentries.each_with_index { |entry, i|
699             if entry.pixbuf_full
700                 entry.pixbuf_thumbnail
701                 gtk_thread_protect(proc { |i|
702                                        entry = $allentries[i]
703                                        entry.button = Gtk::Button.new.set_image(img = Gtk::Image.new(entry.pixbuf_thumbnail))
704                                        tooltips.set_tip(entry.button, File.basename(entry.path).gsub(/\.[^.]+$/, ''), nil)
705                                        $imagesline.pack_start(entry.button.show_all, false, false)
706                                        entry.button.signal_connect('clicked') { $mainview.set_shown_entry(i) }
707                                        entry.button.signal_connect('focus-in-event') { entry.button.clicked; autoscroll_if_needed(entry.button) }
708                                        entry.button.signal_connect('key-press-event') { |w, e| thumbnail_keypressed(entry, e) }
709                                        if i == 0
710                                            entry.button.grab_focus
711                                        end
712                                    }, i)
713                 if i % 4 == 0
714                     check_memory_free_cache_if_needed
715                 end
716                 counter += 1
717             end
718         }
719         check_memory_free_cache_if_needed
720         sb_msg(_("%d images loaded.") % counter)
721         puts "time: #{Time.now - t1}"
722     }
723     e.priority = -1
724 end
725
726 def open_dir(path)
727     #- remove visual stuff, so that user will see something is happening
728     reset_tags
729     reset_thumbnails
730     $mainview.set_shown_entry(nil)
731     sb_msg(_("Scanning source directory..."))
732
733     path = File.expand_path(path.sub(%r|/$|, ''))
734     examined_dirs = `find '#{path}' -type d -follow`.sort.collect { |v| v.chomp }
735     #- validate first
736     examined_dirs.each { |dir|
737         if dir =~ /'/
738             return utf8(_("Source directory or sub-directories can't contain a single-quote character, sorry: %s") % dir)
739         end
740         Dir.entries(dir).each { |file|
741             if file =~ /['"\[\]]/
742                 return utf8(_("Files can't contain any of the characters ', \", [ or ], sorry: %s") % "#{dir}/#{file}")
743             end
744         }
745     }
746
747     #- scan for populate second
748     examined_dirs.each { |dir|
749         if File.basename(dir) =~ /^\./
750             msg 1, _("Ignoring directory %s, begins with a dot (indicating a hidden directory)") % dir
751             next
752         end
753         Dir.entries(dir).each { |file|
754             type = entry2type(file)
755            if type && $allentries.size < 10
756                 $allentries << Entry.new(File.join(dir, file), type)
757             end
758         }
759     }
760     show_entries
761     $execute.sensitive = true
762     return nil
763 end
764
765 def open_dir_popup
766     fc = Gtk::FileChooserDialog.new(utf8(_("Specify the directory to work with")),
767                                     nil,
768                                     Gtk::FileChooser::ACTION_SELECT_FOLDER,
769                                     nil,
770                                     [Gtk::Stock::OPEN, Gtk::Dialog::RESPONSE_ACCEPT], [Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL])
771     fc.transient_for = $main_window
772     ok = false
773     while !ok
774         if fc.run == Gtk::Dialog::RESPONSE_ACCEPT
775             msg = open_dir(fc.filename)
776             if msg
777                 show_popup(fc, msg)
778                 ok = false
779             else
780                 ok = true
781             end
782         else
783             ok = true
784         end
785     end
786     fc.destroy
787 end
788
789 def gtk_thread_protect(proc, *params)
790     if Thread.current == Thread.main
791         proc.call(*params)
792     else
793         $protect_gtk_pending_calls.synchronize {
794             $gtk_pending_calls << [ proc, params ]
795         }
796     end
797 end
798
799 def gtk_thread_flush
800     $protect_gtk_pending_calls.synchronize {
801         if $gtk_pending_calls.size > 0
802             elem = $gtk_pending_calls.shift
803             elem[0].call(*elem[1])
804         end
805     }
806 end
807
808 def try_quit(*options)
809     Gtk.main_quit
810 end
811
812 def execute
813     dialog = Gtk::Dialog.new
814     dialog.title = utf8(_("Booh message"))
815
816     vb1 = Gtk::VBox.new(false, 5)
817     label = Gtk::Label.new.set_markup(utf8(_("You're about to <b>execute</b> actions on the marked images.\nPlease confirm below the actions. This operation is not undoable!")))
818     vb1.pack_start(label, false, false)
819
820     table = Gtk::Table.new(0, 0, false)
821     table.set_row_spacings(5)
822     table.set_column_spacings(5)
823     table.attach(Gtk::Label.new.set_markup(utf8(_("<b>Tag name:</b>"))).set_justify(Gtk::Justification::CENTER), 0, 1, 0, 1, Gtk::FILL, Gtk::FILL, 5, 0)
824     table.attach(Gtk::Label.new.set_markup(utf8(_("<b>Amount of pictures:</b>"))).set_justify(Gtk::Justification::CENTER), 1, 2, 0, 1, Gtk::FILL, Gtk::FILL, 5, 0)
825     table.attach(Gtk::Label.new.set_markup(utf8(_("<b>Pictures examples:</b>"))).set_justify(Gtk::Justification::CENTER), 2, 3, 0, 1, Gtk::FILL, Gtk::FILL, 5, 0)
826     table.attach(Gtk::Label.new.set_markup(utf8(_("<b>Action to perform:</b>"))).set_justify(Gtk::Justification::CENTER), 3, 4, 0, 1, Gtk::FILL, Gtk::FILL, 5, 0)
827     add_row = proc { |row, name, color, truthproc, normal|
828         table.attach(Gtk::Alignment.new(0, 0.5, 1, 0).add(Gtk::EventBox.new.add(Gtk::Label.new.set_markup(name)).modify_bg(Gtk::StateType::NORMAL, color)),
829                      0, 1, row, row + 1, Gtk::FILL, Gtk::FILL, 5, 5)
830         counter = 0
831         examples = Gtk::HBox.new(false, 5)
832         $allentries.each { |entry|
833             if truthproc.call(entry)
834                 counter += 1
835                 if counter < 4
836                     examples.pack_start(Gtk::Image.new(entry.pixbuf_thumbnail), false, false)
837                 elsif counter == 4
838                     examples.pack_start(Gtk::Label.new.set_markup("<b>...</b>"), false, false)
839                 end
840             end
841         }
842         table.attach(Gtk::Label.new(counter.to_s).set_justify(Gtk::Justification::CENTER), 1, 2, row, row + 1, 0, 0, 5, 5)
843         table.attach(examples, 2, 3, row, row + 1, Gtk::FILL, Gtk::FILL, 5, 5)
844
845         combostore = Gtk::ListStore.new(Gdk::Pixbuf, String)
846         iter = combostore.append
847         if normal
848             iter[0] = $main_window.render_icon(Gtk::Stock::GO_FORWARD, Gtk::IconSize::MENU)
849             iter[1] = utf8(_("Move to:"))
850         else
851             iter[0] = $main_window.render_icon(Gtk::Stock::DELETE, Gtk::IconSize::MENU)
852             iter[1] = utf8(_("Permanently remove"))
853         end
854         iter = combostore.append
855         iter[0] = $main_window.render_icon(Gtk::Stock::MEDIA_STOP, Gtk::IconSize::MENU)
856         iter[1] = utf8(_("Do nothing"))
857         combo = Gtk::ComboBox.new(combostore)
858         combo.active = 0
859         renderer = Gtk::CellRendererPixbuf.new
860         combo.pack_start(renderer, false)
861         combo.set_attributes(renderer, :pixbuf => 0)
862         renderer = Gtk::CellRendererText.new
863         combo.pack_start(renderer, true)
864         combo.set_attributes(renderer, :text => 1)
865
866         if normal
867             pathbutton = Gtk::Button.new.add(pathlabel = Gtk::Label.new.set_markup(utf8(_("<i>(unset)</i>"))))
868             pathbutton.signal_connect('clicked') {
869                 fc = Gtk::FileChooserDialog.new(utf8(_("Specify the directory where to move the pictures to")),
870                                                 nil,
871                                                 Gtk::FileChooser::ACTION_SELECT_FOLDER,
872                                                 nil,
873                                                 [Gtk::Stock::OPEN, Gtk::Dialog::RESPONSE_ACCEPT], [Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL])
874                 fc.transient_for = dialog
875                 if fc.run == Gtk::Dialog::RESPONSE_ACCEPT
876                     pathlabel.text = fc.filename
877                 end    
878                 fc.destroy
879             }
880             combo.signal_connect('changed') {
881                 pathbutton.sensitive = combo.active == 0
882             }
883             vb = Gtk::VBox.new(false, 5)
884             vb.pack_start(combo, false, false)
885             vb.pack_start(pathbutton, false, false)
886             table.attach(Gtk::Alignment.new(0, 0.5, 1, 0).add(vb), 3, 4, row, row + 1, Gtk::FILL, Gtk::FILL, 5, 5)
887             { :combo => combo, :pathlabel => pathlabel }
888         else
889             table.attach(Gtk::Alignment.new(0, 0.5, 1, 0).add(combo), 3, 4, row, row + 1, Gtk::FILL, Gtk::FILL, 5, 5)
890             { :combo => combo }
891         end
892     }
893     stuff = {}
894     stuff['toremove'] = add_row.call(1, utf8(_("<i>to remove</i>")), Gdk::Color.new(65535, 0, 0), proc { |entry| entry.removed }, false)
895     $tags.values.each_with_index { |tag, row| stuff[tag] = add_row.call(row + 2, tag.name, tag.color, proc { |entry| entry.tagged == tag }, true) }
896     vb1.pack_start(sw = Gtk::ScrolledWindow.new(nil, nil).add_with_viewport(table).set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC), true, true)
897
898     toremove_amount = $allentries.find_all { |entry| entry.removed }.size
899     check_removal = Gtk::CheckButton.new(utf8(_("I have noticed I am about to permanently remove the %d above mentioned pictures.") % toremove_amount))
900     if toremove_amount > 0
901         vb1.pack_start(check_removal, false, false)
902         stuff['toremove'][:combo].signal_connect('changed') { |widget|
903             check_removal.sensitive = widget.active == 0
904         }
905     end
906
907     dialog.vbox.add(vb1)
908
909     dialog.set_default_size(800, 600)
910     dialog.add_button(Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL)
911     dialog.add_button(Gtk::Stock::OK, Gtk::Dialog::RESPONSE_OK)
912     dialog.window_position = Gtk::Window::POS_MOUSE
913     dialog.transient_for = $main_window
914
915     dialog.show_all
916
917     while true
918         dialog.run { |response|        
919             if response == Gtk::Dialog::RESPONSE_OK
920                 if toremove_amount > 0 && ! check_removal.active? && check_removal.sensitive?
921                     show_popup(dialog, utf8(_("You have not confirmed that you noticed the permanent removal of the pictures marked for deletion.")))
922                     break
923                 end
924                 stuff.keys.each { |key|
925                     if key.is_a?(Tag) && stuff[key][:combo].active == 0
926                         path = stuff[key][:pathlabel].text
927                         puts path
928                         puts stuff[key][:pathlabel].markup
929                         if path == utf8(_("<i>(unset)</i>"))
930                             show_popup(dialog, utf8(_("You have not selected a directory where to move %s.") % key.name))
931                             break
932                         end
933                         st = File.stat(path)
934                         if ! st.directory? || ! st.writable?
935                             show_popup(dialog, utf8(_("Directory where to move %s is not valid or not writable.") % key.name))
936                             break
937                         end
938                     end
939                 }
940             end
941             dialog.destroy
942             return
943         }
944     end
945 end
946
947 def create_menubar    
948     #- menu
949     mb = Gtk::MenuBar.new
950
951     filemenu = Gtk::MenuItem.new(utf8(_("_File")))
952     filesubmenu = Gtk::Menu.new
953     filesubmenu.append(open      = Gtk::ImageMenuItem.new(Gtk::Stock::OPEN))
954     filesubmenu.append(            Gtk::SeparatorMenuItem.new)
955     filesubmenu.append($execute  = Gtk::ImageMenuItem.new(Gtk::Stock::EXECUTE).set_sensitive(false))
956     filesubmenu.append(            Gtk::SeparatorMenuItem.new)
957     filesubmenu.append(quit      = Gtk::ImageMenuItem.new(Gtk::Stock::QUIT))
958     filemenu.set_submenu(filesubmenu)
959     mb.append(filemenu)
960
961     open.signal_connect('activate') { open_dir_popup }
962     $execute.signal_connect('activate') { execute }
963     quit.signal_connect('activate') { try_quit }
964
965     editmenu = Gtk::MenuItem.new(utf8(_("_Edit")))
966     editsubmenu = Gtk::Menu.new
967     editsubmenu.append($undo_mb = Gtk::ImageMenuItem.new(Gtk::Stock::UNDO).set_sensitive(false))
968     editsubmenu.append($redo_mb = Gtk::ImageMenuItem.new(Gtk::Stock::REDO).set_sensitive(false))
969     editsubmenu.append(           Gtk::SeparatorMenuItem.new)
970     editsubmenu.append(prefs    = Gtk::ImageMenuItem.new(Gtk::Stock::PREFERENCES))
971     editmenu.set_submenu(editsubmenu)
972     mb.append(editmenu)
973
974     $undo_mb.signal_connect('activate') { perform_undo }
975     $redo_mb.signal_connect('activate') { perform_redo }
976     prefs.signal_connect('activate') { preferences }
977     
978     helpmenu = Gtk::MenuItem.new(utf8(_("_Help")))
979     helpsubmenu = Gtk::Menu.new
980     helpsubmenu.append(tutos = Gtk::ImageMenuItem.new(utf8(_("Online tutorials (opens a web-browser)"))))
981     tutos.image = Gtk::Image.new("#{$FPATH}/images/stock-web-16.png")
982     helpsubmenu.append(Gtk::SeparatorMenuItem.new)
983     helpsubmenu.append(about = Gtk::ImageMenuItem.new(Gtk::Stock::ABOUT))
984     helpmenu.set_submenu(helpsubmenu)
985     mb.append(helpmenu)
986
987     tutos.signal_connect('activate') { open_url('http://booh.org/tutorial.html') }
988     about.signal_connect('activate') { share }
989
990
991     #- no toolbar, to save height
992
993     return mb
994 end
995
996 def reset_tags
997     for child in $tags_vbox.children
998         $tags_vbox.remove(child)
999     end
1000     $tags_vbox.pack_start(Gtk::Label.new(utf8(_("Tags list:"))).set_justify(Gtk::Justification::CENTER), false, false).show_all
1001 end
1002
1003 def reset_thumbnails
1004     $allentries = []
1005     for child in $imagesline.children
1006         $imagesline.remove(child)
1007     end
1008 end
1009
1010 def create_main_window
1011
1012     mb = create_menubar
1013
1014     main_vbox = Gtk::VBox.new(false, 0)
1015     main_vbox.pack_start(mb, false, false)
1016     mainview_hbox = Gtk::HBox.new
1017     mainview_hbox.pack_start(Gtk::Alignment.new(0.5, 0, 0, 0).add($tags_vbox = Gtk::VBox.new(false, 5)), false, true)
1018     reset_tags
1019     mainview_hbox.pack_start($mainview = MainView.new, true, true)
1020     main_vbox.pack_start(mainview_hbox, true, true)
1021     $imagesline_sw = Gtk::ScrolledWindow.new(nil, nil)
1022     $imagesline_sw.set_policy(Gtk::POLICY_ALWAYS, Gtk::POLICY_NEVER)
1023     $imagesline_sw.add_with_viewport($imagesline = Gtk::HBox.new(false, 0).show)
1024     main_vbox.pack_start($imagesline_sw, false, false)
1025     main_vbox.pack_end($statusbar = Gtk::Statusbar.new, false, false)
1026
1027     $imagesline.set_size_request(-1, Entry.thumbnails_height + $imagesline_sw.hscrollbar.size_request[1])
1028
1029     $main_window = Gtk::Window.new
1030     $main_window.add(main_vbox)
1031     $main_window.signal_connect('delete-event') {
1032         try_quit({ :disallow_cancel => true })
1033     }
1034
1035     #- read/save size and position of window
1036     if $config['pos-x'] && $config['pos-y']
1037         $main_window.move($config['pos-x'].to_i, $config['pos-y'].to_i)
1038     else
1039         $main_window.window_position = Gtk::Window::POS_CENTER
1040     end
1041     msg 3, "size: #{$config['width']}x#{$config['height']}"
1042     $main_window.set_default_size(($config['width'] || 700).to_i, ($config['height'] || 600).to_i)
1043     $main_window.signal_connect('configure-event') {
1044         msg 3, "configure: pos: #{$main_window.window.root_origin.inspect} size: #{$main_window.window.size.inspect}"
1045         x, y = $main_window.window.root_origin
1046         width, height = $main_window.window.size
1047         $config['pos-x'] = x
1048         $config['pos-y'] = y
1049         $config['width'] = width
1050         $config['height'] = height
1051         false
1052     }
1053
1054     $protect_gtk_pending_calls = Mutex.new
1055     $gtk_pending_calls = []
1056     Gtk.timeout_add(50) {
1057         gtk_thread_flush
1058         true
1059     }
1060
1061     Gtk.timeout_add(10000) {
1062         show_mem
1063         true
1064     }
1065  
1066     $main_window.show_all
1067 end
1068
1069
1070 Thread.abort_on_exception = true
1071 read_config
1072 Gtk.init
1073
1074
1075 #- Gdk::Pixbuf#rotate memory leak check (in ruby-gnome2 <= 0.16.0)
1076 #pb = Gdk::Pixbuf.new("#{$FPATH}/images/logo.png")
1077 #1.upto(5) { pb = pb.rotate(Gdk::Pixbuf::ROTATE_CLOCKWISE) }
1078 #GC.start
1079 #mem = get_mem
1080 #1.upto(5) { pb = pb.rotate(Gdk::Pixbuf::ROTATE_CLOCKWISE) }
1081 #GC.start
1082 #mem2 = get_mem
1083 #if mem2 != mem
1084 #    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.")
1085 #    exit 1
1086 #end
1087
1088
1089 create_main_window
1090 check_config
1091
1092 if ARGV[0]
1093     open_dir(ARGV[0])
1094 end
1095 Gtk.main
1096
1097 write_config