*** empty log message ***
[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 set_cache_memory_use_figure
87     if $config['cache-memory-use'] =~ /memfree_(\d+)/
88         $config['cache-memory-use-figure'] = memfree*$1.to_f/100
89     else
90         $config['cache-memory-use-figure'] = $config['cache-memory-use'].to_i
91     end
92     msg 2, "Set cache memory use figure: #{$config['cache-memory-use-figure']} kB"
93 end
94
95 def read_config
96     $config = {}
97     $config_file = File.expand_path('~/.booh-classifier-rc')
98     if File.readable?($config_file)
99         $xmldoc = REXML::Document.new(File.new($config_file))
100         $xmldoc.root.elements.each { |element|
101             txt = element.get_text
102             if txt
103                 if txt.value =~ /~~~/
104                     $config[element.name] = txt.value.split(/~~~/)
105                 else
106                     $config[element.name] = txt.value
107                 end
108             elsif element.elements.size == 0
109                 $config[element.name] = ''
110             else
111                 $config[element.name] = {}
112                 element.each { |chld|
113                     txt = chld.get_text
114                     $config[element.name][chld.name] = txt ? txt.value : nil
115                 }
116             end
117         }
118     end
119     $config['video-viewer'] ||= '/usr/bin/mplayer %f'
120     $config['preload-distance'] ||= '5'
121     $config['cache-memory-use'] ||= 'memfree_50%'
122     $config['rotate-set-exif'] ||= 'true'
123     set_cache_memory_use_figure
124 end
125
126 def check_config
127     if !system("which identify >/dev/null 2>/dev/null")
128         show_popup($main_window, utf8(_("The program 'identify' is needed to get images sizes and EXIF data. Please install it.
129 It is generally available with the 'ImageMagick' software package.")), { :pos_centered => true })
130     end
131     missing = %w(transcode mencoder).delete_if { |prg| system("which #{prg} >/dev/null 2>/dev/null") }
132     if missing != []
133         show_popup($main_window, utf8(_("The following program(s) are needed to handle videos: '%s'. Videos will be ignored.") % missing.join(', ')), { :pos_centered => true })
134     end
135
136     viewer_binary = $config['video-viewer'].split.first
137     if viewer_binary && !File.executable?(viewer_binary)
138         show_popup($main_window, utf8(_("The configured video viewer seems to be unavailable.
139 You should fix this in Edit/Preferences so that you can view videos.
140
141 Problem was: '%s' is not an executable file.
142 Hint: don't forget to specify the full path to the executable,
143 e.g. '/usr/bin/mplayer' is correct but 'mplayer' only is not.") % viewer_binary), { :pos_centered => true, :not_transient => true })
144     end
145 end
146
147 def write_config
148     ios = File.open($config_file, "w")
149     $xmldoc = Document.new "<booh-classifier-rc version='#{$VERSION}'/>"
150     $xmldoc << XMLDecl.new(XMLDecl::DEFAULT_VERSION, $CURRENT_CHARSET)
151     $config.each_pair { |key, value|
152         elem = $xmldoc.root.add_element key
153         if value.is_a? Hash
154             $config[key].each_pair { |subkey, subvalue|
155                 subelem = elem.add_element subkey
156                 subelem.add_text subvalue.to_s
157             }
158         elsif value.is_a? Array
159             elem.add_text value.join('~~~')
160         else
161             if !value
162                 elem.remove
163             else
164                 elem.add_text value.to_s
165             end
166         end
167     }
168     $xmldoc.write(ios, 0)
169     ios.close
170 end
171
172 def save_undo(name, closure, *params)
173     UndoHandler.save_undo(name, closure, [ *params ])
174     $undo_mb.sensitive = true
175     $redo_mb.sensitive = false
176 end
177
178 def get_mem
179     IO.readlines('/proc/self/status').join =~ /VmRSS.*?(\d+)\s*kB/
180     puts $1
181     return $1.to_i
182 end
183
184 def show_mem(*txt)
185     txt.length > 0 and print txt[0]
186     puts get_mem
187 end
188
189 def min(v1, v2)
190     return v1 < v2 ? v1 : v2
191 end
192 def max(v1, v2)
193     return v1 > v2 ? v1 : v2
194 end
195
196 class Gdk::Color
197     def darker
198         color = dup
199         color.red = max(color.red - 10000, 0)
200         color.green = max(color.green - 10000, 0)
201         color.blue = max(color.blue - 10000, 0)
202         return color
203     end
204     def lighter
205         color = dup
206         color.red = min(color.red + 10000, 65535)
207         color.green = min(color.green + 10000, 65535)
208         color.blue = min(color.blue + 10000, 65535)
209         return color
210     end
211 end
212
213 $colors = [ Gdk::Color.new(0, 65535, 0),
214             Gdk::Color.new(0, 0, 65535),
215             Gdk::Color.new(65535, 65535, 0),
216             Gdk::Color.new(0, 65535, 65535),
217             Gdk::Color.new(65535, 0, 65535) ]
218
219 class Tag
220     attr_accessor :color, :name
221     def initialize(name)
222         @name = name
223     end
224 end
225 $tags = {}
226
227 class Entry
228     @@thumbnails_height = 64
229     @@max_height = nil
230     def Entry.thumbnails_height
231         return @@thumbnails_height
232     end
233
234     attr_accessor :path, :type, :angle, :button, :removed, :tagged
235
236     def initialize(path, type)
237         @path = path
238         @type = type
239         if @@max_height.nil?
240             @@max_height = $main_window.root_window.size[1]
241         end
242         @protect_cleanup = Mutex.new
243     end
244
245     def pixbuf_full
246         @protect_cleanup.synchronize {
247             if @pixbuf_full.nil?
248                 puts ">>> pixbuf_full #{path}"
249                 load_into_pixbuf_full
250             end
251             return @pixbuf_full
252         }
253     end
254     def free_pixbuf_full
255         @protect_cleanup.synchronize {
256             if @pixbuf_full.nil?
257                 return false
258             else
259                 puts ">>> free_pixbuf_full #{path}"
260                 @pixbuf_full = nil
261                 return true
262             end
263         }
264     end
265     def pixbuf_main(width, height)
266         @protect_cleanup.synchronize {
267             if @pixbuf_main.nil? || width != @width || height != @height
268                 puts ">>> pixbuf_main #{path}"
269                 @width = width
270                 @height = height
271                 load_into_pixbuf_full  #- make sure it is loaded
272                 if @pixbuf_full.width.to_f / @pixbuf_full.height > width.to_f / height
273                     resized_height = @pixbuf_full.height * (width.to_f/@pixbuf_full.width)
274                     if @pixbuf_full.width > width || @pixbuf_full.height > resized_height
275                         @pixbuf_main = @pixbuf_full.scale(width, resized_height, Gdk::Pixbuf::INTERP_BILINEAR)
276                     else
277                         @pixbuf_main = @pixbuf_full
278                     end
279                 else
280                     resized_width = @pixbuf_full.width * (height.to_f/@pixbuf_full.height)
281                     if @pixbuf_full.width > resized_width || @pixbuf_full.height > height
282                         @pixbuf_main = @pixbuf_full.scale(resized_width, height, Gdk::Pixbuf::INTERP_BILINEAR)
283                     else
284                         @pixbuf_main = @pixbuf_full
285                     end
286                 end
287             end
288             return @pixbuf_main
289         }
290     end
291     def free_pixbuf_main
292         @protect_cleanup.synchronize {
293             if @pixbuf_main.nil?
294                 return false
295             else
296                 puts ">>> free_pixbuf_main #{path}"
297                 @pixbuf_main = nil
298                 return true
299             end
300         }
301     end
302     def pixbuf_thumbnail
303         return @protect_cleanup.synchronize {
304             if @pixbuf_thumbnail.nil?
305                 puts ">>> pixbuf_thumbnail #{path}"
306                 load_into_pixbuf_full  #- make sure it is loaded
307                 @pixbuf_thumbnail = @pixbuf_full.scale(@pixbuf_full.width * (@@thumbnails_height.to_f/@pixbuf_full.height), @@thumbnails_height, Gdk::Pixbuf::INTERP_BILINEAR)
308             end
309             return @pixbuf_thumbnail
310         }
311     end
312     def free_pixbuf_thumbnail
313         @protect_cleanup.synchronize {
314             if @pixbuf_thumbnail.nil?
315                 return false
316             else
317                 puts ">>> free_pixbuf_thumbnail #{path}"
318                 @pixbuf_thumbnail = nil
319                 return true
320             end
321         }
322     end
323
324     def show_bg
325         if removed
326             red = Gdk::Color.new(65535, 0, 0)
327             button.modify_bg(Gtk::StateType::NORMAL, red)
328             button.modify_bg(Gtk::StateType::PRELIGHT, red.lighter)
329             button.modify_bg(Gtk::StateType::ACTIVE, red)
330         elsif tagged
331             button.modify_bg(Gtk::StateType::NORMAL, tagged.color)
332             button.modify_bg(Gtk::StateType::PRELIGHT, tagged.color.lighter)
333             button.modify_bg(Gtk::StateType::ACTIVE, tagged.color)
334         else
335             # TODO need to add proper undo support :/
336             white = Gdk::Color.new(55535, 55535, 55535)
337             button.modify_bg(Gtk::StateType::NORMAL, white)
338             button.modify_bg(Gtk::StateType::PRELIGHT, white.lighter)
339             button.modify_bg(Gtk::StateType::ACTIVE, white)
340         end
341     end
342
343     private
344     def load_into_pixbuf_full
345         if @pixbuf_full.nil?
346             puts ">>> load_into_pixbuf_full #{path}"
347             begin
348                 @pixbuf_full = Gdk::Pixbuf.new(@path)
349             rescue Gdk::PixbufError
350                 puts "Cannot load #{@path}: #{$!}"
351                 return
352             end
353             if @pixbuf_full
354                 if @angle.nil?
355                     @angle = guess_rotate(path)
356                 end
357                 if @angle != 0
358                     puts ">>> load_into_pixbuf_full #{path} => rotate #{@angle}"
359                     @pixbuf_full = rotate_pixbuf(@pixbuf_full, @angle)
360                 end
361                 if @pixbuf_full.height > @@max_height
362                     #- save a lot of memory, don't store in actual full size
363                     @pixbuf_full = @pixbuf_full.scale(@pixbuf_full.width * (@@max_height.to_f/@pixbuf_full.height), @@max_height, Gdk::Pixbuf::INTERP_BILINEAR)
364                 end
365             end
366         end
367     end
368
369     def to_s
370         @path
371     end
372 end
373
374 class MainView < Gtk::DrawingArea
375
376     def initialize
377         super()
378         signal_connect('expose-event') { draw }
379         signal_connect('configure-event') { update_shown; GC.start }
380         signal_connect('realize') {
381             @preloader = Thread.new {
382                 #- background preloading
383                 while true
384                     puts "background main preloading triggered..."
385                     if ! @index.nil?
386                         w, h = window.size
387                         for j in 1 .. $config['preload-distance'].to_i
388                             i = @index + j
389                             if i < $allentries.size
390                                 $allentries[i].pixbuf_main(w, h)
391                             end
392                             i = @index - j
393                             if i >= 0
394                                 $allentries[i].pixbuf_main(w, h)
395                             end
396                             GC.start
397                             mem = get_mem
398                             if mem > $config['cache-memory-use-figure']
399                                 puts "too much RSS, stopping main preloading"
400                                 break
401                             end
402                         end
403                         check_memory_free_cache_if_needed
404                     end
405                     Thread.stop
406                 end
407             }
408             @preloader.priority = -2
409         }
410     end
411
412     def set_shown_entry(index)
413         if index == @index || index < 0 || index >= $allentries.size
414             return
415         end
416         old_index = @index
417         @index = index
418         if index.nil?
419             @entry = nil
420         else
421             @entry = $allentries[index]
422         end
423         if ! @entry.button
424             #- not loaded yet
425             @index = old_index
426             return
427         end
428         redraw        
429         @preloader.run
430         @entry.button.grab_focus
431     end
432
433
434     def get_shown_entry
435         return @index
436     end
437
438     def redraw
439         update_shown
440         w, h = window.size
441         window.begin_paint(Gdk::Rectangle.new(0, 0, w, h))
442         window.clear
443         draw
444         window.end_paint
445     end
446
447     def update_shown
448         if @entry
449             width, height = window.size 
450             @pixbuf = @entry.pixbuf_main(width, height)
451             if @pixbuf.width == width
452                 @xpos = 0
453                 @ypos = (height-@pixbuf.height)/2
454             else
455                 @xpos = (width-@pixbuf.width)/2
456                 @ypos = 0
457             end
458             @preloader.run
459         else
460             @pixbuf = nil
461         end
462     end
463
464     def draw
465         if @pixbuf
466             window.draw_pixbuf(nil, @pixbuf, 0, 0, @xpos, @ypos, -1, -1, Gdk::RGB::DITHER_NONE, -1, -1)
467         end
468     end
469 end
470
471 def check_memory_free_cache_if_needed
472     GC.start
473     mem = get_mem
474     i = $mainview.get_shown_entry
475     puts "mem: #{mem} index: #{i}"
476     return if i.nil?
477     ($allentries.size - 1).downto(1) { |j|
478         if mem < $config['cache-memory-use-figure'] * 2 / 3
479             break
480         end
481         index = i + j
482         puts "too much RSS, freeing full size of #{i+j} and #{i-j}..."
483         freedsomething = false
484         if i + j < $allentries.size
485             freedsomething |= $allentries[i+j].free_pixbuf_full
486         end
487         if i - j > 0
488             freedsomething |= $allentries[i-j].free_pixbuf_full
489         end
490         if freedsomething
491             GC.start
492             mem = get_mem
493             puts "\tmem now: #{mem}"
494         end
495     }
496 end
497
498 def autoscroll_if_needed(button)
499     xpos_left = button.allocation.x
500     xpos_right = button.allocation.x + button.allocation.width
501     hadj = $imagesline_sw.hadjustment
502     current_minx_visible = hadj.value
503     current_maxx_visible = hadj.value + hadj.page_size
504     if xpos_left < current_minx_visible
505         #- autoscroll left
506         newval = hadj.value - (current_minx_visible - xpos_left)
507         hadj.value = newval
508         button.queue_draw  #- TOREMOVE: the visual focus is displayed incorrectly
509     elsif xpos_right > current_maxx_visible
510         #- autoscroll right
511         newval = hadj.value + (xpos_right - current_maxx_visible)
512         if newval > hadj.upper - hadj.page_size
513             newval = hadj.upper - hadj.page_size
514         end
515         hadj.value = newval
516         button.queue_draw  #- TOREMOVE: the visual focus is displayed incorrectly
517     end
518 end
519
520 def show_popup(parent, msg, *options)
521     dialog = Gtk::Dialog.new
522     if options[0]
523         options = options[0]
524     else
525         options = {}
526     end
527     if options[:title]
528         dialog.title = options[:title]
529     else
530         dialog.title = utf8(_("Booh message"))
531     end
532     lbl = Gtk::Label.new
533     if options[:nomarkup]
534         lbl.text = msg
535     else
536         lbl.markup = msg
537     end
538     if options[:centered]
539         lbl.set_justify(Gtk::Justification::CENTER)
540     end
541     if options[:selectable]
542         lbl.selectable = true
543     end
544     if options[:topwidget]
545         dialog.vbox.add(options[0][:topwidget])
546     end
547     if options[:scrolled]
548         sw = Gtk::ScrolledWindow.new(nil, nil)
549         sw.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC)
550         sw.add_with_viewport(lbl)
551         dialog.vbox.add(sw)
552         dialog.set_default_size(500, 600)
553     else
554         dialog.vbox.add(lbl)
555         dialog.set_default_size(200, 120)
556     end
557     if options[:bottomwidget]
558         dialog.vbox.add(options[:bottomwidget])
559     end
560     if options[:okcancel]
561         dialog.add_button(Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL)
562     end
563     dialog.add_button(Gtk::Stock::OK, Gtk::Dialog::RESPONSE_OK)
564
565     if options[:pos_centered]
566         dialog.window_position = Gtk::Window::POS_CENTER
567     else
568         dialog.window_position = Gtk::Window::POS_MOUSE
569     end
570
571     if options[:linkurl]
572         linkbut = Gtk::Button.new('')
573         linkbut.child.markup = "<span foreground=\"#00000000FFFF\" underline=\"single\">#{options[0][:linkurl]}</span>"
574         linkbut.signal_connect('clicked') {
575             open_url(options[0][:linkurl] + '/index.html')
576             dialog.response(Gtk::Dialog::RESPONSE_OK)
577             set_mousecursor_normal
578         }
579         linkbut.relief = Gtk::RELIEF_NONE
580         linkbut.signal_connect('enter-notify-event') { set_mousecursor(Gdk::Cursor::HAND2, linkbut); false }
581         linkbut.signal_connect('leave-notify-event') { set_mousecursor(nil, linkbut); false }
582         dialog.vbox.add(Gtk::Alignment.new(0.5, 0.5, 0, 0).add(linkbut))
583     end
584
585     dialog.show_all
586
587     if options[:stuff_connector]
588         options[:stuff_connector].call({ :dialog => dialog })
589     end
590                                         
591     if !options[:not_transient]
592         dialog.transient_for = parent
593         dialog.run { |response|
594             if options[:data_getter]
595                 options[:data_getter].call
596             end
597             dialog.destroy
598             if options[:okcancel]
599                 return response == Gtk::Dialog::RESPONSE_OK
600             end
601         }
602     else
603         dialog.signal_connect('response') { dialog.destroy }
604     end
605 end
606
607 def thumbnail_keypressed(entry, i, event)
608     if event.state & Gdk::Window::MOD1_MASK != 0
609         #- ALT pressed: Alt-Left and Alft-Right rotate
610         if event.keyval == Gdk::Keyval::GDK_Left || event.keyval == Gdk::Keyval::GDK_Right
611             if event.keyval == Gdk::Keyval::GDK_Left
612                 entry.angle = (entry.angle - 90) % 360
613             else
614                 entry.angle = (entry.angle + 90) % 360
615             end
616             entry.free_pixbuf_full
617             entry.free_pixbuf_main
618             entry.free_pixbuf_thumbnail
619             $mainview.redraw
620             entry.button.set_image(img = Gtk::Image.new(entry.pixbuf_thumbnail))
621         end
622
623     elsif event.state & Gdk::Window::CONTROL_MASK != 0
624         #- CONTROL pressed: Ctrl-z and Ctrl-r for undo/redo
625         if event.keyval == Gdk::Keyval::GDK_z
626             perform_undo
627         end
628         if event.keyval == Gdk::Keyval::GDK_r
629             perform_redo
630         end
631
632     else
633         removed_before = entry.removed
634         tag_before = entry.tagged
635
636         if event.keyval == Gdk::Keyval::GDK_Delete
637             entry.removed = true
638             entry.tagged = nil
639             entry.show_bg
640             $mainview.set_shown_entry(i + 1)
641
642             save_undo(_("set for removal"),
643                       proc {
644                           entry.removed = removed_before
645                           entry.tagged = tag_before
646                           entry.show_bg
647                           $mainview.set_shown_entry(i)
648                           proc {
649                               entry.removed = true
650                               entry.tagged = nil
651                               entry.show_bg
652                               $mainview.set_shown_entry(i)
653                           }
654                       })
655
656         elsif event.keyval == Gdk::Keyval::GDK_space
657             entry.removed = false
658             entry.tagged = nil
659             entry.show_bg
660             $mainview.set_shown_entry(i + 1)
661
662             save_undo(_("remove tag"),
663                       proc {
664                           entry.removed = removed_before
665                           entry.tagged = tag_before
666                           entry.show_bg
667                           $mainview.set_shown_entry(i)
668                           proc {
669                               entry.removed = false
670                               entry.tagged = nil
671                               entry.show_bg
672                               $mainview.set_shown_entry(i)
673                           }
674                       })
675
676         else
677             char = [ Gdk::Keyval.to_unicode(event.keyval) ].pack("C*")
678             if char =~ /^[a-zA-z0-9]$/
679                 tag = $tags[char]
680                 
681                 if tag.nil?
682                     vb = Gtk::VBox.new(false, 0)
683                     vb.pack_start(entry = Gtk::Entry.new.set_text(char), false, false)
684                     vb.pack_start(Gtk::Alignment.new(0.5, 0.5, 0, 0).add(bt = Gtk::Button.new(utf8(_("  Change color  ")))))
685                     text = nil
686                     color = nil
687                     bt.signal_connect('clicked') {
688                         color = $colors.shift
689                         if color.nil?
690                             color = Gdk::Color.new(16384 + rand(49151), 16384 + rand(49151), 16384 + rand(49151))
691                         end
692                         bt.modify_bg(Gtk::StateType::NORMAL, color)
693                         bt.modify_bg(Gtk::StateType::PRELIGHT, color)
694                         bt.modify_bg(Gtk::StateType::ACTIVE, color.darker)
695                     }
696                     bt.clicked
697                     entry.signal_connect('changed') {  #- cannot add a new tag with first letter of an existing tag
698                         while $tags.has_key?(entry.text[0,1])
699                             entry.text = entry.text.sub(/./, '')
700                         end
701                     }
702                     if show_popup($main_window,
703                                   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,
704                                   { :okcancel => true, :bottomwidget => vb, :data_getter => proc { text = entry.text },
705                                     :stuff_connector => proc { |stuff| entry.select_region(0, 0)
706                                                                        entry.position = -1
707                                                                        entry.signal_connect('activate') { stuff[:dialog].response(Gtk::Dialog::RESPONSE_OK) } } } )
708                         if text.length > 0
709                             char = text[0,1]  #- in case it changed
710                             tag = Tag.new(text)
711                             tag.color = color
712                             $tags[char] = tag
713                             label = Gtk::Label.new.set_markup('<b>(' + char + ')</b>' + text[1..-1]).set_justify(Gtk::Justification::CENTER)
714                             $tags_vbox.pack_start(evt = Gtk::EventBox.new.add(label).modify_bg(Gtk::StateType::NORMAL, tag.color).show_all)
715                         end
716                     end
717
718                 else
719                     entry.removed = false
720                     entry.tagged = tag
721                     entry.show_bg
722                     $mainview.set_shown_entry(i + 1)
723
724                     save_undo(_("set tag"),
725                               proc {
726                                   entry.removed = removed_before
727                                   entry.tagged = tag_before
728                                   entry.show_bg
729                                   $mainview.set_shown_entry(i)
730                                   proc {
731                                       entry.removed = false
732                                       entry.tagged = tag
733                                       entry.show_bg
734                                       $mainview.set_shown_entry(i)
735                                   }
736                               })
737                 end
738             end
739         end
740     end
741 end
742
743 def sb_msg(msg)
744     $statusbar.pop(0)
745     if msg
746         $statusbar.push(0, utf8(msg))
747     end
748 end
749     
750 def show_entries
751     e = Thread.new {
752         t1 = Time.now
753         show_mem
754         sb_msg(_("Loading images..."))
755         tooltips = Gtk::Tooltips.new
756         counter = 0
757         $allentries.each_with_index { |entry, i|
758             if entry.pixbuf_full
759                 entry.pixbuf_thumbnail
760                 gtk_thread_protect(proc { |i|
761                                        entry = $allentries[i]
762                                        entry.button = Gtk::Button.new.set_image(img = Gtk::Image.new(entry.pixbuf_thumbnail))
763                                        tooltips.set_tip(entry.button, File.basename(entry.path).gsub(/\.[^.]+$/, ''), nil)
764                                        $imagesline.pack_start(entry.button.show_all, false, false)
765                                        entry.button.signal_connect('clicked') { $mainview.set_shown_entry(i) }
766                                        entry.button.signal_connect('focus-in-event') { entry.button.clicked; autoscroll_if_needed(entry.button) }
767                                        entry.button.signal_connect('key-press-event') { |w, e| thumbnail_keypressed(entry, i, e) }
768                                        if i == 0
769                                            entry.button.grab_focus
770                                        end
771                                    }, i)
772                 if i % 4 == 0
773                     check_memory_free_cache_if_needed
774                 end
775                 counter += 1
776             end
777         }
778         check_memory_free_cache_if_needed
779         sb_msg(_("%d images loaded.") % counter)
780         puts "time: #{Time.now - t1}"
781     }
782     e.priority = -1
783 end
784
785 def open_dir(path)
786     #- remove visual stuff, so that user will see something is happening
787     reset_tags
788     reset_thumbnails
789     $mainview.set_shown_entry(nil)
790     sb_msg(_("Scanning source directory..."))
791
792     path = File.expand_path(path.sub(%r|/$|, ''))
793     examined_dirs = `find '#{path}' -type d -follow`.sort.collect { |v| v.chomp }
794     #- validate first
795     examined_dirs.each { |dir|
796         if dir =~ /'/
797             return utf8(_("Source directory or sub-directories can't contain a single-quote character, sorry: %s") % dir)
798         end
799         Dir.entries(dir).each { |file|
800             if file =~ /['"\[\]]/
801                 return utf8(_("Files can't contain any of the characters ', \", [ or ], sorry: %s") % "#{dir}/#{file}")
802             end
803         }
804     }
805
806     #- scan for populate second
807     examined_dirs.each { |dir|
808         if File.basename(dir) =~ /^\./
809             msg 1, _("Ignoring directory %s, begins with a dot (indicating a hidden directory)") % dir
810             next
811         end
812         Dir.entries(dir).each { |file|
813             type = entry2type(file)
814            if type && $allentries.size < 10
815                 $allentries << Entry.new(File.join(dir, file), type)
816             end
817         }
818     }
819     $workingdir = path
820     show_entries
821     $execute.sensitive = true
822     return nil
823 end
824
825 def open_dir_popup
826     fc = Gtk::FileChooserDialog.new(utf8(_("Specify the directory to work with")),
827                                     nil,
828                                     Gtk::FileChooser::ACTION_SELECT_FOLDER,
829                                     nil,
830                                     [Gtk::Stock::OPEN, Gtk::Dialog::RESPONSE_ACCEPT], [Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL])
831     fc.transient_for = $main_window
832     if $workingdir
833         fc.current_folder = $workingdir
834     end
835     ok = false
836     while !ok
837         if fc.run == Gtk::Dialog::RESPONSE_ACCEPT
838             msg = open_dir(fc.filename)
839             if msg
840                 show_popup(fc, msg)
841                 ok = false
842             else
843                 ok = true
844             end
845         else
846             ok = true
847         end
848     end
849     fc.destroy
850 end
851
852 def gtk_thread_protect(proc, *params)
853     if Thread.current == Thread.main
854         proc.call(*params)
855     else
856         $protect_gtk_pending_calls.synchronize {
857             $gtk_pending_calls << [ proc, params ]
858         }
859     end
860 end
861
862 def gtk_thread_flush
863     $protect_gtk_pending_calls.synchronize {
864         if $gtk_pending_calls.size > 0
865             elem = $gtk_pending_calls.shift
866             elem[0].call(*elem[1])
867         end
868     }
869 end
870
871 def try_quit(*options)
872     Gtk.main_quit
873 end
874
875 def execute
876     dialog = Gtk::Dialog.new
877     dialog.title = utf8(_("Booh message"))
878
879     vb1 = Gtk::VBox.new(false, 5)
880     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!")))
881     vb1.pack_start(label, false, false)
882
883     table = Gtk::Table.new(0, 0, false)
884     table.set_row_spacings(5)
885     table.set_column_spacings(5)
886     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)
887     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)
888     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)
889     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)
890     add_row = proc { |row, name, color, truthproc, normal|
891         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)),
892                      0, 1, row, row + 1, Gtk::FILL, Gtk::FILL, 5, 5)
893         counter = 0
894         examples = Gtk::HBox.new(false, 5)
895         $allentries.each { |entry|
896             if truthproc.call(entry)
897                 counter += 1
898                 if counter < 4
899                     examples.pack_start(Gtk::Image.new(entry.pixbuf_thumbnail), false, false)
900                 elsif counter == 4
901                     examples.pack_start(Gtk::Label.new.set_markup("<b>...</b>"), false, false)
902                 end
903             end
904         }
905         table.attach(Gtk::Label.new(counter.to_s).set_justify(Gtk::Justification::CENTER), 1, 2, row, row + 1, 0, 0, 5, 5)
906         table.attach(examples, 2, 3, row, row + 1, Gtk::FILL, Gtk::FILL, 5, 5)
907
908         combostore = Gtk::ListStore.new(Gdk::Pixbuf, String)
909         iter = combostore.append
910         if normal
911             iter[0] = $main_window.render_icon(Gtk::Stock::GO_FORWARD, Gtk::IconSize::MENU)
912             iter[1] = utf8(_("Move to:"))
913         else
914             iter[0] = $main_window.render_icon(Gtk::Stock::DELETE, Gtk::IconSize::MENU)
915             iter[1] = utf8(_("Permanently remove"))
916         end
917         iter = combostore.append
918         iter[0] = $main_window.render_icon(Gtk::Stock::MEDIA_STOP, Gtk::IconSize::MENU)
919         iter[1] = utf8(_("Do nothing"))
920         combo = Gtk::ComboBox.new(combostore)
921         combo.active = 0
922         renderer = Gtk::CellRendererPixbuf.new
923         combo.pack_start(renderer, false)
924         combo.set_attributes(renderer, :pixbuf => 0)
925         renderer = Gtk::CellRendererText.new
926         combo.pack_start(renderer, true)
927         combo.set_attributes(renderer, :text => 1)
928
929         if normal
930             pathbutton = Gtk::Button.new.add(pathlabel = Gtk::Label.new.set_markup(utf8(_("<i>(unset)</i>"))))
931             lastpath = $workingdir
932             pathbutton.signal_connect('clicked') {
933                 fc = Gtk::FileChooserDialog.new(utf8(_("Specify the directory where to move the pictures to")),
934                                                 nil,
935                                                 Gtk::FileChooser::ACTION_SELECT_FOLDER,
936                                                 nil,
937                                                 [Gtk::Stock::OPEN, Gtk::Dialog::RESPONSE_ACCEPT], [Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL])
938                 fc.transient_for = dialog
939                 fc.current_folder = lastpath
940                 if fc.run == Gtk::Dialog::RESPONSE_ACCEPT
941                     pathlabel.text = fc.filename
942                 end
943                 lastpath = fc.filename
944                 fc.destroy
945             }
946             combo.signal_connect('changed') {
947                 pathbutton.sensitive = combo.active == 0
948             }
949             vb = Gtk::VBox.new(false, 5)
950             vb.pack_start(combo, false, false)
951             vb.pack_start(pathbutton, false, false)
952             table.attach(Gtk::Alignment.new(0, 0.5, 1, 0).add(vb), 3, 4, row, row + 1, Gtk::FILL, Gtk::FILL, 5, 5)
953             { :combo => combo, :pathlabel => pathlabel }
954         else
955             table.attach(Gtk::Alignment.new(0, 0.5, 1, 0).add(combo), 3, 4, row, row + 1, Gtk::FILL, Gtk::FILL, 5, 5)
956             { :combo => combo }
957         end
958     }
959     stuff = {}
960     stuff['toremove'] = add_row.call(1, utf8(_("<i>to remove</i>")), Gdk::Color.new(65535, 0, 0), proc { |entry| entry.removed }, false)
961     $tags.values.each_with_index { |tag, row| stuff[tag] = add_row.call(row + 2, tag.name, tag.color, proc { |entry| entry.tagged == tag }, true) }
962     vb1.pack_start(sw = Gtk::ScrolledWindow.new(nil, nil).add_with_viewport(table).set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC), true, true)
963
964     toremove_amount = $allentries.find_all { |entry| entry.removed }.size
965     check_removal = Gtk::CheckButton.new(utf8(_("I have noticed I am about to permanently remove the %d above mentioned pictures.") % toremove_amount))
966     if toremove_amount > 0
967         vb1.pack_start(check_removal, false, false)
968         stuff['toremove'][:combo].signal_connect('changed') { |widget|
969             check_removal.sensitive = widget.active == 0
970         }
971     end
972
973     dialog.vbox.add(vb1)
974
975     dialog.set_default_size(800, 600)
976     dialog.add_button(Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL)
977     dialog.add_button(Gtk::Stock::OK, Gtk::Dialog::RESPONSE_OK)
978     dialog.window_position = Gtk::Window::POS_MOUSE
979     dialog.transient_for = $main_window
980
981     dialog.show_all
982
983     while true
984         dialog.run { |response|        
985             if response == Gtk::Dialog::RESPONSE_OK
986                 if toremove_amount > 0 && ! check_removal.active? && check_removal.sensitive?
987                     show_popup(dialog, utf8(_("You have not confirmed that you noticed the permanent removal of the pictures marked for deletion.")))
988                     break
989                 end
990                 problem = false
991                 tag2entries = {}
992                 $tags.values.each { |tag| tag2entries[tag] = [] }
993                 $allentries.each { |entry| entry.tagged and tag2entries[entry.tagged] << entry }
994                 stuff.keys.each { |key|
995                     if key.is_a?(Tag) && stuff[key][:combo].active == 0
996                         path = stuff[key][:pathlabel].text
997                         if path[0] != ?/
998                             show_popup(dialog, utf8(_("You have not selected a directory where to move %s.") % key.name))
999                             problem = true
1000                             break
1001                         end
1002                         st = File.stat(path)
1003                         if ! st.directory? || ! st.writable?
1004                             show_popup(dialog, utf8(_("Directory where to move %s is not valid or not writable.") % key.name))
1005                             problem = true
1006                             break
1007                         end
1008                         tag2entries[key].each { |entry|
1009                             begin
1010                                 File.stat(File.join(path, File.basename(entry.path)))
1011                                 show_popup(dialog, utf8(_("Sorry, a file '%s' already exists in '%s'.") % [ File.basename(entry.path), path ]))
1012                                 problem = true
1013                                 break
1014                             rescue
1015                             end
1016                         }
1017                         if problem
1018                             break
1019                         end
1020                     end
1021                 }
1022                 if ! problem
1023                     puts "execute!"
1024                     dialog.destroy
1025                     return
1026                 end
1027
1028             else
1029                 dialog.destroy
1030                 return
1031             end
1032         }
1033     end
1034 end
1035
1036 def preferences
1037     dialog = Gtk::Dialog.new(utf8(_("Edit preferences")),
1038                              $main_window,
1039                              Gtk::Dialog::MODAL | Gtk::Dialog::DESTROY_WITH_PARENT,
1040                              [Gtk::Stock::OK, Gtk::Dialog::RESPONSE_OK],
1041                              [Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL])
1042
1043 #    $config['cache-memory-use'] ||= 'memfree_50%'
1044 #    if $config['cache-memory-use'] =~ /memfree_(\d+)/
1045 #        $config['cache-memory-use-figure'] = memfree*$1.to_f/100
1046 #    else
1047 #        $config['cache-memory-use-figure'] = $config['cache-memory-use'].to_i
1048 #    end
1049     tooltips = Gtk::Tooltips.new
1050     
1051     dialog.vbox.add(tbl = Gtk::Table.new(0, 0, false))
1052     tbl.attach(Gtk::Alignment.new(1, 0.5, 0, 0).add(Gtk::Label.new.set_markup(utf8(_("Command for watching videos: ")))),
1053                0, 1, 0, 1, Gtk::FILL, Gtk::SHRINK, 2, 2)
1054     tbl.attach(Gtk::Alignment.new(0, 0.5, 1, 0).add(video_viewer_entry = Gtk::Entry.new.set_text($config['video-viewer']).set_size_request(250, -1)),
1055                1, 2, 0, 1, Gtk::FILL, Gtk::SHRINK, 2, 2)
1056     tooltips.set_tip(video_viewer_entry, utf8(_("Use %f to specify the filename;\nfor example: /usr/bin/mplayer %f")), nil)
1057
1058     tbl.attach(Gtk::Alignment.new(1, 0.5, 0, 0).add(Gtk::Label.new.set_markup(utf8(_("Preloading distance: ")))),
1059                0, 1, 1, 2, Gtk::FILL, Gtk::SHRINK, 2, 2)
1060     tbl.attach(Gtk::Alignment.new(0, 0.5, 1, 0).add(preload_distance = Gtk::SpinButton.new(0, 50, 1).set_value($config['preload-distance'].to_i)),
1061                1, 2, 1, 2, Gtk::FILL, Gtk::SHRINK, 2, 2)
1062     tooltips.set_tip(preload_distance, utf8(_("Amount of pictures preloaded left and right to the currently shown")), nil)
1063
1064     tbl.attach(Gtk::Alignment.new(1, 0.5, 0, 0).add(Gtk::Label.new.set_markup(utf8(_("Cache memory use: ")))),
1065                0, 1, 2, 3, Gtk::FILL, Gtk::SHRINK, 2, 2)
1066     tbl.attach(Gtk::Alignment.new(0, 0.5, 1, 0).add(cache_vbox = Gtk::VBox.new(false, 0)),
1067                1, 2, 2, 3, Gtk::FILL, Gtk::SHRINK, 2, 2)
1068     cache_vbox.pack_start(Gtk::HBox.new(false, 0).pack_start(cache_memfree_radio = Gtk::RadioButton.new(''), false, false).
1069                                                   pack_start(cache_memfree_spin = Gtk::SpinButton.new(0, 100, 10), false, false).
1070                                                   pack_start(cache_memfree_label = Gtk::Label.new(utf8(_("% of free memory"))), false, false), false, false)
1071     cache_memfree_spin.signal_connect('value-changed') { cache_memfree_radio.active = true }
1072     tooltips.set_tip(cache_memfree_spin, utf8(_("Percentage of free memory (+ buffers/cache) measured at startup")), nil)
1073     cache_vbox.pack_start(Gtk::HBox.new(false, 0).pack_start(cache_specify_radio = Gtk::RadioButton.new(cache_memfree_radio, ''), false, false).
1074                                                   pack_start(cache_specify_spin = Gtk::SpinButton.new(0, 4000, 50), false, false).
1075                                                   pack_start(cache_specify_label = Gtk::Label.new(utf8(_("MB"))).set_sensitive(false), false, false), false, false)
1076     cache_specify_spin.signal_connect('value-changed') { cache_specify_radio.active = true }
1077     cache_memfree_radio.signal_connect('toggled') {
1078         if cache_memfree_radio.active?
1079             cache_memfree_label.sensitive = true
1080             cache_specify_label.sensitive = false
1081         else
1082             cache_specify_label.sensitive = true
1083             cache_memfree_label.sensitive = false
1084         end
1085     }
1086     tooltips.set_tip(cache_specify_spin, utf8(_("Amount of memory in megabytes")), nil)
1087     if $config['cache-memory-use'] =~ /memfree_(\d+)/
1088         cache_memfree_spin.value = $1.to_i
1089     else
1090         cache_specify_spin.value = $config['cache-memory-use'].to_i
1091     end
1092
1093     tbl.attach(update_exif_orientation_check = Gtk::CheckButton.new(utf8(_("Update file's EXIF orientation when rotating a picture"))),
1094                0, 2, 3, 4, Gtk::FILL, Gtk::SHRINK, 2, 2)
1095     tooltips.set_tip(update_exif_orientation_check, utf8(_("")), nil)
1096     update_exif_orientation_check.active = $config['rotate-set-exif']
1097
1098     dialog.vbox.show_all
1099     dialog.run { |response|
1100         if response == Gtk::Dialog::RESPONSE_OK
1101             $config['video-viewer'] = from_utf8(video_viewer_entry.text)
1102             $config['preload-distance'] = preload_distance.value
1103             $config['rotate-set-exif'] = update_exif_orientation_check.active?
1104             if cache_memfree_radio.active?
1105                 $config['cache-memory-use'] = "memfree_#{cache_memfree_spin.value}%"
1106             else
1107                 $config['cache-memory-use'] = cache_specify_spin.value
1108             end
1109             set_cache_memory_use_figure
1110             p $config
1111         end
1112     }
1113     dialog.destroy
1114 end
1115
1116 def perform_undo
1117     if $undo_mb.sensitive?
1118         $redo_mb.sensitive = true
1119         if not more_undoes = UndoHandler.undo($statusbar)
1120             $undo_mb.sensitive = false
1121         end
1122     end
1123 end
1124
1125 def perform_redo
1126     if $redo_mb.sensitive?
1127         $undo_mb.sensitive = true
1128         if not more_redoes = UndoHandler.redo($statusbar)
1129             $redo_mb.sensitive = false
1130         end
1131     end
1132 end
1133
1134 def create_menubar    
1135     #- menu
1136     mb = Gtk::MenuBar.new
1137
1138     filemenu = Gtk::MenuItem.new(utf8(_("_File")))
1139     filesubmenu = Gtk::Menu.new
1140     filesubmenu.append(open      = Gtk::ImageMenuItem.new(Gtk::Stock::OPEN))
1141     filesubmenu.append(            Gtk::SeparatorMenuItem.new)
1142     filesubmenu.append($execute  = Gtk::ImageMenuItem.new(Gtk::Stock::EXECUTE).set_sensitive(false))
1143     filesubmenu.append(            Gtk::SeparatorMenuItem.new)
1144     filesubmenu.append(quit      = Gtk::ImageMenuItem.new(Gtk::Stock::QUIT))
1145     filemenu.set_submenu(filesubmenu)
1146     mb.append(filemenu)
1147
1148     open.signal_connect('activate') { open_dir_popup }
1149     $execute.signal_connect('activate') { execute }
1150     quit.signal_connect('activate') { try_quit }
1151
1152     editmenu = Gtk::MenuItem.new(utf8(_("_Edit")))
1153     editsubmenu = Gtk::Menu.new
1154     editsubmenu.append($undo_mb = Gtk::ImageMenuItem.new(Gtk::Stock::UNDO).set_sensitive(false))
1155     editsubmenu.append($redo_mb = Gtk::ImageMenuItem.new(Gtk::Stock::REDO).set_sensitive(false))
1156     editsubmenu.append(           Gtk::SeparatorMenuItem.new)
1157     editsubmenu.append(prefs    = Gtk::ImageMenuItem.new(Gtk::Stock::PREFERENCES))
1158     editmenu.set_submenu(editsubmenu)
1159     mb.append(editmenu)
1160
1161     $undo_mb.signal_connect('activate') { perform_undo }
1162     $redo_mb.signal_connect('activate') { perform_redo }
1163     prefs.signal_connect('activate') { preferences }
1164     
1165     helpmenu = Gtk::MenuItem.new(utf8(_("_Help")))
1166     helpsubmenu = Gtk::Menu.new
1167     helpsubmenu.append(tutos = Gtk::ImageMenuItem.new(utf8(_("Online tutorials (opens a web-browser)"))))
1168     tutos.image = Gtk::Image.new("#{$FPATH}/images/stock-web-16.png")
1169     helpsubmenu.append(Gtk::SeparatorMenuItem.new)
1170     helpsubmenu.append(about = Gtk::ImageMenuItem.new(Gtk::Stock::ABOUT))
1171     helpmenu.set_submenu(helpsubmenu)
1172     mb.append(helpmenu)
1173
1174     tutos.signal_connect('activate') { open_url('http://booh.org/tutorial.html') }
1175     about.signal_connect('activate') { share }
1176
1177
1178     #- no toolbar, to save height
1179
1180     return mb
1181 end
1182
1183 def reset_tags
1184     for child in $tags_vbox.children
1185         $tags_vbox.remove(child)
1186     end
1187     $tags_vbox.pack_start(Gtk::Label.new(utf8(_("Tags list:"))).set_justify(Gtk::Justification::CENTER), false, false).show_all
1188 end
1189
1190 def reset_thumbnails
1191     $allentries = []
1192     for child in $imagesline.children
1193         $imagesline.remove(child)
1194     end
1195 end
1196
1197 def create_main_window
1198
1199     mb = create_menubar
1200
1201     main_vbox = Gtk::VBox.new(false, 0)
1202     main_vbox.pack_start(mb, false, false)
1203     mainview_hbox = Gtk::HBox.new
1204     mainview_hbox.pack_start(Gtk::Alignment.new(0.5, 0, 0, 0).add($tags_vbox = Gtk::VBox.new(false, 5)), false, true)
1205     reset_tags
1206     mainview_hbox.pack_start($mainview = MainView.new, true, true)
1207     main_vbox.pack_start(mainview_hbox, true, true)
1208     $imagesline_sw = Gtk::ScrolledWindow.new(nil, nil)
1209     $imagesline_sw.set_policy(Gtk::POLICY_ALWAYS, Gtk::POLICY_NEVER)
1210     $imagesline_sw.add_with_viewport($imagesline = Gtk::HBox.new(false, 0).show)
1211     main_vbox.pack_start($imagesline_sw, false, false)
1212     main_vbox.pack_end($statusbar = Gtk::Statusbar.new, false, false)
1213
1214     $imagesline.set_size_request(-1, Entry.thumbnails_height + $imagesline_sw.hscrollbar.size_request[1])
1215
1216     $main_window = Gtk::Window.new
1217     $main_window.add(main_vbox)
1218     $main_window.signal_connect('delete-event') {
1219         try_quit({ :disallow_cancel => true })
1220     }
1221
1222     #- read/save size and position of window
1223     if $config['pos-x'] && $config['pos-y']
1224         $main_window.move($config['pos-x'].to_i, $config['pos-y'].to_i)
1225     else
1226         $main_window.window_position = Gtk::Window::POS_CENTER
1227     end
1228     msg 3, "size: #{$config['width']}x#{$config['height']}"
1229     $main_window.set_default_size(($config['width'] || 700).to_i, ($config['height'] || 600).to_i)
1230     $main_window.signal_connect('configure-event') {
1231         msg 3, "configure: pos: #{$main_window.window.root_origin.inspect} size: #{$main_window.window.size.inspect}"
1232         x, y = $main_window.window.root_origin
1233         width, height = $main_window.window.size
1234         $config['pos-x'] = x
1235         $config['pos-y'] = y
1236         $config['width'] = width
1237         $config['height'] = height
1238         false
1239     }
1240
1241     $protect_gtk_pending_calls = Mutex.new
1242     $gtk_pending_calls = []
1243     Gtk.timeout_add(50) {
1244         gtk_thread_flush
1245         true
1246     }
1247
1248     Gtk.timeout_add(10000) {
1249         show_mem
1250         true
1251     }
1252  
1253     $main_window.show_all
1254 end
1255
1256
1257 Thread.abort_on_exception = true
1258 read_config
1259 Gtk.init
1260
1261
1262 #- Gdk::Pixbuf#rotate memory leak check (in ruby-gnome2 <= 0.16.0)
1263 #pb = Gdk::Pixbuf.new("#{$FPATH}/images/logo.png")
1264 #1.upto(5) { pb = pb.rotate(Gdk::Pixbuf::ROTATE_CLOCKWISE) }
1265 #GC.start
1266 #mem = get_mem
1267 #1.upto(5) { pb = pb.rotate(Gdk::Pixbuf::ROTATE_CLOCKWISE) }
1268 #GC.start
1269 #mem2 = get_mem
1270 #if mem2 != mem
1271 #    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.")
1272 #    exit 1
1273 #end
1274
1275
1276 create_main_window
1277 check_config
1278
1279 if ARGV[0]
1280     open_dir(ARGV[0])
1281 end
1282 Gtk.main
1283
1284 write_config