set EXIF orientation of source file when rotating
[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 require 'booh/libadds'
28
29 require 'gettext'
30 include GetText
31 bindtextdomain("booh")
32
33 require 'rexml/document'
34 include REXML
35
36 require 'booh/booh-lib'
37 include Booh
38 require 'booh/UndoHandler'
39
40
41 #- options
42 $options = [
43     [ '--help',          '-h', GetoptLong::NO_ARGUMENT,       _("Get help message") ],
44
45     [ '--verbose-level', '-v', GetoptLong::REQUIRED_ARGUMENT, _("Set max verbosity level (0: errors, 1: warnings, 2: important messages, 3: other messages)") ],
46     [ '--sort-by-exif-date', '-s', GetoptLong::NO_ARGUMENT, _("Sort entries by EXIF date") ],
47 ]
48
49 def usage
50     puts _("Usage: %s [OPTION]...") % File.basename($0)
51     $options.each { |ary|
52         printf " %3s, %-15s %s\n", ary[1], ary[0], ary[3]
53     }
54 end
55
56 def handle_options
57     parser = GetoptLong.new
58     parser.set_options(*$options.collect { |ary| ary[0..2] })
59     begin
60         parser.each_option do |name, arg|
61             case name
62             when '--help'
63                 usage
64                 exit(0)
65
66             when '--verbose-level'
67                 $verbose_level = arg.to_i
68
69             when '--sort-by-exif-date'
70                 $sort_by_exif_date = true
71
72             end
73         end
74     rescue
75         puts $!
76         usage
77         exit(1)
78     end
79 end
80
81 def startup_memfree
82     if $startup_memfree.nil?
83         meminfo = IO.readlines('/proc/meminfo').join
84         meminfo =~ /MemFree:.*?(\d+)/ or return -1
85         memfree = $1
86         meminfo =~ /Buffers:.*?(\d+)/ and buffers = $1
87         meminfo =~ /Cached:.*?(\d+)/ and cached = $1
88         $startup_memfree = memfree.to_i + buffers.to_i + cached.to_i
89     end
90     return $startup_memfree
91 end
92
93 def set_cache_memory_use_figure
94     
95     if $config['cache-memory-use'] =~ /memfree_(\d+)/
96         $config['cache-memory-use-figure'] = startup_memfree*$1.to_f/100
97     else
98         $config['cache-memory-use-figure'] = $config['cache-memory-use'].to_i
99     end
100     msg 2, _("Cache memory used: %s kB") % $config['cache-memory-use-figure']
101 end
102
103 def read_config
104     $config = {}
105     $config_file = File.expand_path('~/.booh-classifier-rc')
106     if File.readable?($config_file)
107         $xmldoc = REXML::Document.new(File.new($config_file))
108         $xmldoc.root.elements.each { |element|
109             txt = element.get_text
110             if txt
111                 if txt.value =~ /~~~/
112                     $config[element.name] = txt.value.split(/~~~/)
113                 else
114                     $config[element.name] = txt.value
115                 end
116             elsif element.elements.size == 0
117                 $config[element.name] = ''
118             else
119                 $config[element.name] = {}
120                 element.each { |chld|
121                     txt = chld.get_text
122                     $config[element.name][chld.name] = txt ? txt.value : nil
123                 }
124             end
125         }
126     end
127     $config['video-viewer'] ||= '/usr/bin/mplayer %f'
128     $config['browser'] ||= "/usr/bin/mozilla-firefox -remote 'openURL(%f,new-window)' || /usr/bin/mozilla-firefox %f"
129     $config['preload-distance'] ||= '5'
130     $config['cache-memory-use'] ||= 'memfree_80%'
131     $config['rotate-set-exif'] ||= 'true'
132     set_cache_memory_use_figure
133 end
134
135 def check_config
136     missing = %w(transcode mencoder).delete_if { |prg| system("which #{prg} >/dev/null 2>/dev/null") }
137     if missing != []
138         show_popup($main_window, utf8(_("The following program(s) are needed to handle videos: '%s'. Videos will be ignored.") % missing.join(', ')), { :pos_centered => true })
139     end
140
141     viewer_binary = $config['video-viewer'].split.first
142     if viewer_binary && ! File.executable?(viewer_binary)
143         show_popup($main_window, utf8(_("The configured video viewer seems to be unavailable.
144 You should fix this in Edit/Preferences so that you can view videos.
145
146 Problem was: '%s' is not an executable file.
147 Hint: don't forget to specify the full path to the executable,
148 e.g. '/usr/bin/mplayer' is correct but 'mplayer' only is not.") % viewer_binary), { :pos_centered => true, :not_transient => true })
149     end
150     browser_binary = $config['browser'].split.first
151     if browser_binary && ! File.executable?(browser_binary)
152         show_popup($main_window, utf8(_("The configured browser seems to be unavailable.
153 You should fix this in Edit/Preferences so that you can open URLs.
154
155 Problem was: '%s' is not an executable file.") % browser_binary), { :pos_centered => true, :not_transient => true })
156     end
157 end
158
159 def write_config
160     ios = File.open($config_file, "w")
161     $xmldoc = Document.new "<booh-classifier-rc version='#{$VERSION}'/>"
162     $xmldoc << XMLDecl.new(XMLDecl::DEFAULT_VERSION, $CURRENT_CHARSET)
163     $config.each_pair { |key, value|
164         elem = $xmldoc.root.add_element key
165         if value.is_a? Hash
166             $config[key].each_pair { |subkey, subvalue|
167                 subelem = elem.add_element subkey
168                 subelem.add_text subvalue.to_s
169             }
170         elsif value.is_a? Array
171             elem.add_text value.join('~~~')
172         else
173             if !value
174                 elem.remove
175             else
176                 elem.add_text value.to_s
177             end
178         end
179     }
180     $xmldoc.write(ios, 0)
181     ios.close
182 end
183
184 def save_undo(name, closure, *params)
185     UndoHandler.save_undo(name, closure, [ *params ])
186     $undo_mb.sensitive = true
187     $redo_mb.sensitive = false
188 end
189
190 def get_mem
191     IO.readlines('/proc/self/status').join =~ /VmRSS.*?(\d+)\s*kB/
192     msg 3, "RSS: #{$1}"
193     return $1.to_i
194 end
195
196 def show_mem(*txt)
197     txt.length > 0 and print txt[0]
198     msg 2, "RSS: #{get_mem}"
199 end
200
201 class Gdk::Color
202     def darker
203         color = dup
204         color.red = [ color.red - 10000, 0 ].max
205         color.green = [ color.green - 10000, 0 ].max
206         color.blue = [ color.blue - 10000, 0 ].max
207         return color
208     end
209     def lighter
210         color = dup
211         color.red = [ color.red + 10000, 65535 ].min
212         color.green = [ color.green + 10000, 65535 ].min
213         color.blue = [ color.blue + 10000, 65535 ].min
214         return color
215     end
216 end
217
218 $color_red = Gdk::Color.new(65535, 0, 0)
219 $colors = [ Gdk::Color.new(0, 65535, 0),
220             Gdk::Color.new(0, 0, 65535),
221             Gdk::Color.new(65535, 65535, 0),
222             Gdk::Color.new(0, 65535, 65535),
223             Gdk::Color.new(65535, 0, 65535) ]
224
225 class Label
226     attr_accessor :color, :name, :button
227     def initialize(name)
228         @name = name
229     end
230 end
231
232 class Entry
233     @@thumbnails_height = 64
234     @@max_height = nil
235     def Entry.thumbnails_height
236         return @@thumbnails_height
237     end
238
239     attr_accessor :path, :type, :angle, :button, :image, :alignment, :removed, :labeled
240
241     def initialize(path, type)
242         @path = path
243         @type = type
244         if @@max_height.nil?
245             @@max_height = $main_window.root_window.size[1]
246         end
247         @protect_cleanup = Mutex.new
248     end
249
250     def pixbuf_full
251         @protect_cleanup.synchronize {
252             if @pixbuf_full.nil?
253                 msg 3, ">>> pixbuf_full #{path}"
254                 load_into_pixbuf_full
255             end
256             return @pixbuf_full
257         }
258     end
259     def free_pixbuf_full
260         @protect_cleanup.synchronize {
261             if @pixbuf_full.nil?
262                 return false
263             else
264                 msg 3, ">>> free_pixbuf_full #{path}"
265                 @pixbuf_full = nil
266                 return true
267             end
268         }
269     end
270     def pixbuf_main(width, height)
271         @protect_cleanup.synchronize {
272             if @pixbuf_main.nil? || width != @width || height != @height
273                 msg 3, ">>> pixbuf_main #{path}"
274                 @width = width
275                 @height = height
276                 load_into_pixbuf_full  #- make sure it is loaded
277                 if @pixbuf_full.width.to_f / @pixbuf_full.height > width.to_f / height
278                     resized_height = @pixbuf_full.height * (width.to_f/@pixbuf_full.width)
279                     if @pixbuf_full.width > width || @pixbuf_full.height > resized_height
280                         @pixbuf_main = @pixbuf_full.scale(width, resized_height, Gdk::Pixbuf::INTERP_BILINEAR)
281                     else
282                         @pixbuf_main = @pixbuf_full
283                     end
284                 else
285                     resized_width = @pixbuf_full.width * (height.to_f/@pixbuf_full.height)
286                     if @pixbuf_full.width > resized_width || @pixbuf_full.height > height
287                         @pixbuf_main = @pixbuf_full.scale(resized_width, height, Gdk::Pixbuf::INTERP_BILINEAR)
288                     else
289                         @pixbuf_main = @pixbuf_full
290                     end
291                 end
292             end
293             return @pixbuf_main
294         }
295     end
296     def free_pixbuf_main
297         @protect_cleanup.synchronize {
298             if @pixbuf_main.nil?
299                 return false
300             else
301                 msg 3, ">>> free_pixbuf_main #{path}"
302                 @pixbuf_main = nil
303                 return true
304             end
305         }
306     end
307     def pixbuf_thumbnail
308         return @protect_cleanup.synchronize {
309             if @pixbuf_thumbnail.nil?
310                 msg 3, ">>> pixbuf_thumbnail #{path}"
311                 load_into_pixbuf_full  #- make sure it is loaded
312                 @pixbuf_thumbnail = @pixbuf_full.scale(@pixbuf_full.width * (@@thumbnails_height.to_f/@pixbuf_full.height), @@thumbnails_height, Gdk::Pixbuf::INTERP_BILINEAR)
313             end
314             return @pixbuf_thumbnail
315         }
316     end
317     def free_pixbuf_thumbnail
318         @protect_cleanup.synchronize {
319             if @pixbuf_thumbnail.nil?
320                 return false
321             else
322                 msg 3, ">>> free_pixbuf_thumbnail #{path}"
323                 @pixbuf_thumbnail = nil
324                 return true
325             end
326         }
327     end
328
329     def outline_color
330         if removed
331             return $color_red
332         elsif labeled
333             return labeled.color
334         else
335             return nil
336         end
337     end
338
339     def show_bg
340         if outline_color.nil?
341             button.modify_bg(Gtk::StateType::NORMAL, nil)
342             button.modify_bg(Gtk::StateType::PRELIGHT, nil)
343             button.modify_bg(Gtk::StateType::ACTIVE, nil)
344         else
345             button.modify_bg(Gtk::StateType::NORMAL, outline_color)
346             button.modify_bg(Gtk::StateType::PRELIGHT, outline_color.lighter)
347             button.modify_bg(Gtk::StateType::ACTIVE, outline_color)
348         end
349     end
350
351     def get_beautified_name
352         if type == 'image'
353             size = get_image_size(path)
354             return _("%s (%sx%s, %s KB)") % [File.basename(@path).gsub(/\.[^.]+$/, ''),
355                                              size[:x],
356                                              size[:y],
357                                              commify(file_size(path)/1024)]
358         else
359             return _("%s (video - %s KB)") % [File.basename(@path).gsub(/\.[^.]+$/, ''),
360                                              commify(file_size(path)/1024)]
361         end
362     end
363
364     private
365     def cleanup_dir(dir)
366         Dir.entries(dir).each { |file| file != '.' && file != '..' and File.delete(File.join(dir, file)) }
367         Dir.delete(dir)
368     end
369
370     def load_into_pixbuf_full
371         if @pixbuf_full.nil?
372             msg 3, ">>> load_into_pixbuf_full #{path}"
373             if @type == 'video'
374                 tmp = Tempfile.new("boohclassifiertemp")
375                 tmp.close!
376                 Dir.mkdir(dest_dir = tmp.path)
377                 orig_base = File.basename(path)
378                 if ! gen_video_thumbnail(path, dest_dir, orig_base, false, 0)
379                     cleanup_dir(dest_dir)
380                     return
381                 end
382                 image_path = "#{dest_dir}/#{orig_base}.jpg000000.jpg"
383             else
384                 image_path = @path
385             end
386             begin
387                 @pixbuf_full = Gdk::Pixbuf.new(image_path)
388             rescue Gdk::PixbufError
389                 msg 0, "Cannot load #{image_path}: #{$!}"
390                 return
391             end
392             if @pixbuf_full
393                 if @angle.nil?
394                     if @type == 'image'
395                         @angle = guess_rotate(image_path)
396                     else
397                         @angle = 0
398                     end
399                 end
400                 if @angle != 0
401                     msg 3, ">>> load_into_pixbuf_full #{image_path} => rotate #{@angle}"
402                     @pixbuf_full = rotate_pixbuf(@pixbuf_full, @angle)
403                 end
404                 if @pixbuf_full.height > @@max_height
405                     #- save a lot of memory, don't store in actual full size
406                     @pixbuf_full = @pixbuf_full.scale(@pixbuf_full.width * (@@max_height.to_f/@pixbuf_full.height), @@max_height, Gdk::Pixbuf::INTERP_BILINEAR)
407                 end
408             end
409             if @type == 'video'
410                 cleanup_dir(dest_dir)
411             end
412         end
413     end
414
415     def to_s
416         @path
417     end
418 end
419
420 $allentries = []
421
422 class MainView < Gtk::DrawingArea
423
424     @@borders_thickness = 5
425     @@borders_length = 25
426
427     def MainView.get_usable_width(available_width)
428         return available_width - ($videoborder_pixbuf.width + @@borders_thickness) * 2
429     end
430
431     def MainView.get_usable_height(available_height)
432         return available_height - @@borders_thickness * 2
433     end
434     
435     def initialize
436         super()
437         signal_connect('expose-event') { draw }
438         signal_connect('configure-event') { update_shown; GC.start }
439         signal_connect('realize') {
440             @preloader = Thread.new {
441                 #- background preloading
442                 while true
443                     msg 3, "background main preloading triggered..."
444                     if ! @entry.nil?
445                         index = $allentries.index(@entry)
446                         w, h = window.size
447                         w = MainView.get_usable_width(w)
448                         h = MainView.get_usable_height(h)
449                         for j in 1 .. $config['preload-distance'].to_i
450                             i = index + j
451                             if i < $allentries.size
452                                 $allentries[i].pixbuf_main(w, h)
453                             end
454                             i = index - j
455                             if i >= 0
456                                 $allentries[i].pixbuf_main(w, h)
457                             end
458                             GC.start
459                             mem = get_mem
460                             if mem > $config['cache-memory-use-figure']
461                                 msg 3, "too much RSS, stopping main preloading"
462                                 break
463                             end
464                         end
465                         check_memory_free_cache_if_needed
466                     end
467                     Thread.stop
468                 end
469             }
470             @preloader.priority = -2
471         }
472     end
473
474     def set_shown_entry(entry)
475         if ! entry.nil? && entry == @entry
476             return
477         end
478         if ! entry.nil?
479             if ! entry.button
480                 #- not loaded yet
481                 return
482             else
483                 entry.button.grab_focus
484             end
485         end
486         @entry = entry
487         redraw        
488         @preloader.run
489     end
490
491     def get_shown_entry
492         return @entry
493     end
494
495     def show_next_entry(entry)
496         index = $allentries.index(entry) + 1
497         if index < $allentries.size
498             set_shown_entry($allentries[index])
499         end
500     end
501
502     def redraw
503         update_shown
504         w, h = window.size
505         window.begin_paint(Gdk::Rectangle.new(0, 0, w, h))
506         window.clear
507         draw
508         window.end_paint
509     end
510
511     def update_shown
512         if @entry
513             width, height = window.size 
514             usable_width = MainView.get_usable_width(width)
515             usable_height = MainView.get_usable_height(height)
516             @pixbuf = @entry.pixbuf_main(usable_width, usable_height)
517             @xpos = (width - @pixbuf.width)/2
518             @ypos = (height - @pixbuf.height)/2
519             @preloader.run
520         else
521             @pixbuf = nil
522         end
523     end
524
525     def draw
526         if @pixbuf
527             window.draw_pixbuf(nil, @pixbuf, 0, 0, @xpos, @ypos, -1, -1, Gdk::RGB::DITHER_NONE, -1, -1)
528             if @entry && @entry.type == 'video'
529                 window.draw_borders($videoborder_pixbuf, @xpos - $videoborder_pixbuf.width, @xpos + @pixbuf.width, @ypos, @ypos + @pixbuf.height)
530             end
531             if ! @entry.outline_color.nil?
532                 gc = Gdk::GC.new(window)
533                 colormap.alloc_color(@entry.outline_color, false, true)
534                 gc.set_foreground(@entry.outline_color)
535                 if @entry && @entry.type == 'video'
536                     xleft = @xpos - $videoborder_pixbuf.width
537                     xright = @xpos + @pixbuf.width + $videoborder_pixbuf.width
538                 else
539                     xleft = @xpos
540                     xright = @xpos + @pixbuf.width
541                 end
542                 window.draw_polygon(gc, true, [[xleft - @@borders_thickness, @ypos - @@borders_thickness],
543                                                [xright + @@borders_thickness, @ypos - @@borders_thickness],
544                                                [xright + @@borders_thickness, @ypos + @pixbuf.height + @@borders_thickness],
545                                                [xleft - @@borders_thickness, @ypos + @pixbuf.height + @@borders_thickness],
546                                                [xleft - @@borders_thickness, @ypos - 1],
547                                                [xleft - 1, @ypos - 1],
548                                                [xleft - 1, @ypos + @pixbuf.height + 1],
549                                                [xright + 1, @ypos + @pixbuf.height + 1],
550                                                [xright + 1, @ypos - 1],
551                                                [xleft - @@borders_thickness, @ypos - 1]])
552             end
553         end
554     end
555 end
556
557 def check_memory_free_cache_if_needed
558     GC.start
559     mem = get_mem
560     i = $allentries.index($mainview.get_shown_entry)
561     msg 3, "mem: #{mem} index: #{i}"
562     return if i.nil?
563     ($allentries.size - 1).downto(1) { |j|
564         if mem < $config['cache-memory-use-figure'] * 2 / 3
565             break
566         end
567         index = i + j
568         msg 3, "too much RSS, freeing full size of #{i+j} and #{i-j}..."
569         freedsomething = false
570         if i + j < $allentries.size
571             freedsomething |= $allentries[i+j].free_pixbuf_full
572         end
573         if i - j > 0
574             freedsomething |= $allentries[i-j].free_pixbuf_full
575         end
576         if freedsomething
577             GC.start
578             mem = get_mem
579             msg 3, "\tmem now: #{mem}"
580         end
581     }
582 end
583
584 def autoscroll_if_needed(button)
585     xpos_left = button.allocation.x
586     xpos_right = button.allocation.x + button.allocation.width
587     hadj = $imagesline_sw.hadjustment
588     current_minx_visible = hadj.value
589     current_maxx_visible = hadj.value + hadj.page_size
590     if xpos_left < current_minx_visible
591         #- autoscroll left
592         newval = hadj.value - (current_minx_visible - xpos_left)
593         hadj.value = newval
594         button.queue_draw  #- TOREMOVE: the visual focus is displayed incorrectly
595     elsif xpos_right > current_maxx_visible
596         #- autoscroll right
597         newval = hadj.value + (xpos_right - current_maxx_visible)
598         if newval > hadj.upper - hadj.page_size
599             newval = hadj.upper - hadj.page_size
600         end
601         hadj.value = newval
602         button.queue_draw  #- TOREMOVE: the visual focus is displayed incorrectly
603     end
604 end
605
606 def show_popup(parent, msg, *options)
607     dialog = Gtk::Dialog.new
608     if options[0]
609         options = options[0]
610     else
611         options = {}
612     end
613     if options[:title]
614         dialog.title = options[:title]
615     else
616         dialog.title = utf8(_("Booh message"))
617     end
618     lbl = Gtk::Label.new
619     if options[:nomarkup]
620         lbl.text = msg
621     else
622         lbl.markup = msg
623     end
624     if options[:centered]
625         lbl.set_justify(Gtk::Justification::CENTER)
626     end
627     if options[:selectable]
628         lbl.selectable = true
629     end
630     if options[:topwidget]
631         dialog.vbox.add(options[0][:topwidget])
632     end
633     if options[:scrolled]
634         sw = Gtk::ScrolledWindow.new(nil, nil)
635         sw.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC)
636         sw.add_with_viewport(lbl)
637         dialog.vbox.add(sw)
638         dialog.set_default_size(500, 600)
639     else
640         dialog.vbox.add(lbl)
641         dialog.set_default_size(200, 120)
642     end
643     if options[:bottomwidget]
644         dialog.vbox.add(options[:bottomwidget])
645     end
646     if options[:okcancel]
647         dialog.add_button(Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL)
648     end
649     dialog.add_button(Gtk::Stock::OK, Gtk::Dialog::RESPONSE_OK)
650
651     if options[:pos_centered]
652         dialog.window_position = Gtk::Window::POS_CENTER
653     else
654         dialog.window_position = Gtk::Window::POS_MOUSE
655     end
656
657     if options[:linkurl]
658         linkbut = Gtk::Button.new('')
659         linkbut.child.markup = "<span foreground=\"#00000000FFFF\" underline=\"single\">#{options[0][:linkurl]}</span>"
660         linkbut.signal_connect('clicked') {
661             open_url(options[0][:linkurl] + '/index.html')
662             dialog.response(Gtk::Dialog::RESPONSE_OK)
663             set_mousecursor_normal
664         }
665         linkbut.relief = Gtk::RELIEF_NONE
666         linkbut.signal_connect('enter-notify-event') { set_mousecursor(Gdk::Cursor::HAND2, linkbut); false }
667         linkbut.signal_connect('leave-notify-event') { set_mousecursor(nil, linkbut); false }
668         dialog.vbox.add(Gtk::Alignment.new(0.5, 0.5, 0, 0).add(linkbut))
669     end
670
671     dialog.show_all
672
673     if options[:stuff_connector]
674         options[:stuff_connector].call({ :dialog => dialog })
675     end
676                                         
677     if !options[:not_transient]
678         dialog.transient_for = parent
679         dialog.run { |response|
680             if options[:data_getter]
681                 options[:data_getter].call
682             end
683             dialog.destroy
684             if options[:okcancel]
685                 return response == Gtk::Dialog::RESPONSE_OK
686             end
687         }
688     else
689         dialog.signal_connect('response') { dialog.destroy }
690     end
691 end
692
693 def video_view(entry)
694     cmd = from_utf8($config['video-viewer']).gsub('%f', "'#{entry.path}'") + ' &'
695     msg 2, cmd
696     system(cmd)
697 end
698
699 def thumbnail_keypressed(entry, event)
700     if event.state & Gdk::Window::MOD1_MASK != 0
701         #- ALT pressed: Alt-Left and Alft-Right rotate
702         if event.keyval == Gdk::Keyval::GDK_Left || event.keyval == Gdk::Keyval::GDK_Right
703             if event.keyval == Gdk::Keyval::GDK_Left
704                 entry.angle = (entry.angle - 90) % 360
705             else
706                 entry.angle = (entry.angle + 90) % 360
707             end
708             entry.free_pixbuf_full
709             entry.free_pixbuf_main
710             entry.free_pixbuf_thumbnail
711             $mainview.redraw
712             entry.image.pixbuf = entry.pixbuf_thumbnail
713             if $config['rotate-set-exif'] == 'true'
714                 Exif.set_orientation(entry.path, angle_to_exif_orientation(entry.angle))
715             end
716         end
717
718     elsif event.state & Gdk::Window::CONTROL_MASK != 0
719         #- CONTROL pressed: Ctrl-z and Ctrl-r for undo/redo
720         if event.keyval == Gdk::Keyval::GDK_z
721             perform_undo
722         end
723         if event.keyval == Gdk::Keyval::GDK_r
724             perform_redo
725         end
726
727     else
728         removed_before = entry.removed
729         label_before = entry.labeled
730
731         if event.keyval == Gdk::Keyval::GDK_Delete
732             entry.removed = true
733             entry.labeled = nil
734             entry.show_bg
735             $mainview.show_next_entry(entry)
736             update_visibility(entry)
737
738             save_undo(_("set for removal"),
739                       proc {
740                           entry.removed = removed_before
741                           entry.labeled = label_before
742                           entry.show_bg
743                           update_visibility(entry)
744                           if entry.button.visible?
745                               $mainview.set_shown_entry(entry)
746                           end
747                           proc {
748                               entry.removed = true
749                               entry.labeled = nil
750                               entry.show_bg
751                               update_visibility(entry)
752                               if entry.button.visible?
753                                   $mainview.set_shown_entry(entry)
754                               end
755                           }
756                       })
757
758         elsif event.keyval == Gdk::Keyval::GDK_space
759             if entry.labeled
760                 msg = _("Cleared label")
761             elsif entry.removed
762                 msg = _("Cleared set for removal")
763             end
764             entry.removed = false
765             entry.labeled = nil
766             entry.show_bg
767             $mainview.show_next_entry(entry)
768
769             save_undo(msg,
770                       proc {
771                           entry.removed = removed_before
772                           entry.labeled = label_before
773                           entry.show_bg
774                           $mainview.set_shown_entry(entry)
775                           proc {
776                               entry.removed = false
777                               entry.labeled = nil
778                               entry.show_bg
779                               $mainview.set_shown_entry(entry)
780                           }
781                       })
782
783         elsif event.keyval == Gdk::Keyval::GDK_Return && entry.type == 'video'
784             video_view(entry)
785
786         else
787             char = [ Gdk::Keyval.to_unicode(event.keyval) ].pack("C*")
788             if char =~ /^[a-zA-z0-9]$/
789                 label = $labels[char]
790                 
791                 if label.nil?
792                     vb = Gtk::VBox.new(false, 0)
793                     vb.pack_start(entry = Gtk::Entry.new.set_text(char), false, false)
794                     vb.pack_start(Gtk::Alignment.new(0.5, 0.5, 0, 0).add(bt = Gtk::ColorButton.new))
795                     color = bt.color = Gdk::Color.new(16384 + rand(49151), 16384 + rand(49151), 16384 + rand(49151))
796                     bt.signal_connect('color-set') { color = bt.color }
797                     text = nil
798                     entry.signal_connect('changed') {  #- cannot add a new label with first letter of an existing label
799                         while $labels.has_key?(entry.text[0,1])
800                             entry.text = entry.text.sub(/./, '')
801                         end
802                     }
803                     if show_popup($main_window,
804                                   utf8(_("You typed the text character '%s', which is not associated with a label.\nType in the full name of the label below to create a new one.")) % char,
805                                   { :okcancel => true, :bottomwidget => vb, :data_getter => proc { text = entry.text },
806                                     :stuff_connector => proc { |stuff| entry.select_region(0, 0)
807                                                                        entry.position = -1
808                                                                        entry.signal_connect('activate') { stuff[:dialog].response(Gtk::Dialog::RESPONSE_OK) } } } )
809                         if text.length > 0
810                             char = text[0,1]  #- in case it changed
811                             label = Label.new(text)
812                             label.color = color
813                             $labels[char] = label
814                             lbl = Gtk::Label.new.set_markup('<b>(' + char + ')</b>' + text[1..-1]).set_justify(Gtk::Justification::CENTER)
815                             $labels_vbox.pack_start(label.button = Gtk::CheckButton.new.add(evt = Gtk::EventBox.new.add(lbl)).show_all)
816                             label.button.active = true
817                             label.button.signal_connect('toggled') { update_all_visibilities }
818                             evt.modify_bg(Gtk::StateType::NORMAL, label.color)
819                             evt.modify_bg(Gtk::StateType::PRELIGHT, label.color.lighter.lighter)
820                             evt.modify_bg(Gtk::StateType::ACTIVE, label.color.lighter)
821                         end
822                     end
823
824                 else
825                     entry.removed = false
826                     entry.labeled = label
827                     entry.show_bg
828                     $mainview.show_next_entry(entry)
829                     update_visibility(entry)
830
831                     save_undo(_("set label"),
832                               proc {
833                                   entry.removed = removed_before
834                                   entry.labeled = label_before
835                                   entry.show_bg
836                                   update_visibility(entry)
837                                   if entry.button.visible?
838                                       $mainview.set_shown_entry(entry)
839                                   end
840                                   proc {
841                                       entry.removed = false
842                                       entry.labeled = label
843                                       entry.show_bg
844                                       update_visibility(entry)
845                                       if entry.button.visible?
846                                           $mainview.set_shown_entry(entry)
847                                       end
848                                   }
849                               })
850                 end
851             end
852         end
853     end
854 end
855
856 def sb_msg(msg)
857     $statusbar.pop(0)
858     if msg
859         $statusbar.push(0, utf8(msg))
860     end
861 end
862
863 def real_show_entry(entry, tooltips, grab_focus)
864     #- for scoping the actual reference to 'entry'
865     gtk_thread_protect(proc {
866         msg 3, "using entry #{entry}"
867         entry.image = Gtk::Image.new(entry.pixbuf_thumbnail)
868         if entry.type == 'video'
869             entry.button = Gtk::Button.new.add(Gtk::HBox.new.pack_start(da1 = Gtk::DrawingArea.new.set_size_request($videoborder_pixbuf.width, -1), false, false).
870                                                              pack_start(entry.image).
871                                                              pack_start(da2 = Gtk::DrawingArea.new.set_size_request($videoborder_pixbuf.width, -1), false, false))
872             da1.signal_connect('realize') { da1.window.set_back_pixmap($videoborder_pixmap, false) }
873             da2.signal_connect('realize') { da2.window.set_back_pixmap($videoborder_pixmap, false) }
874         else
875             entry.button = Gtk::Button.new.set_image(entry.image)
876         end
877         tooltips.set_tip(entry.button, entry.get_beautified_name, nil)
878         $imagesline.pack_start(entry.alignment = Gtk::Alignment.new(0.5, 1, 0, 0).add(entry.button).show_all, false, false)
879         entry.button.signal_connect('clicked') {
880             if (last_shown = $mainview.get_shown_entry) != entry
881                 $mainview.set_shown_entry(entry)
882                 entry.alignment.set(0.5, 0, 0, 0)
883                 sb_msg(_("Selected %s") % entry.get_beautified_name)
884                 last_shown.nil? or last_shown.alignment.set(0.5, 1, 0, 0)
885             end
886         }
887         entry.button.signal_connect('button-press-event') { |w, event|
888             if entry.type == 'video' && event.event_type == Gdk::Event::BUTTON2_PRESS
889                 video_view(entry)
890             end
891         }
892         entry.button.signal_connect('focus-in-event') { entry.button.clicked; autoscroll_if_needed(entry.button) }
893         entry.button.signal_connect('key-press-event') { |w, e| thumbnail_keypressed(entry, e) }
894         if grab_focus
895             entry.button.grab_focus
896         end
897         update_visibility(entry)
898     })
899 end
900
901 def show_entries
902     $images_loader = Thread.new {
903         t1 = Time.now
904         sb_msg(_("Loading images..."))
905         tooltips = Gtk::Tooltips.new
906         counter = 0
907         toremove = []
908         grab_focus = true
909         i = 0
910         total_size = 0
911         while i < $allentries.size
912             entry = $allentries[i]
913             if entry.pixbuf_full
914                 total_size += file_size(entry.path)
915                 entry.pixbuf_thumbnail
916                 real_show_entry(entry, tooltips, grab_focus)
917                 grab_focus = false
918                 if i % 4 == 0
919                     check_memory_free_cache_if_needed
920                 end
921                 counter += 1
922                 i = i + 1
923
924             else
925                 $allentries.delete_at(i)
926             end
927         end
928         check_memory_free_cache_if_needed
929         sb_msg(_("%d images of total %s kB loaded in %3.2f seconds.") % [ counter, commify(total_size / 1024), Time.now - t1 ])
930     }
931     $images_loader.priority = -1
932 end
933
934 def reset_all
935     $images_loader and $images_loader.kill
936     reset_labels
937     reset_thumbnails
938     $mainview.set_shown_entry(nil)
939     sb_msg(nil)
940 end
941
942 def open_dir(path)
943     #- remove visual stuff, so that user will see something is happening
944     reset_all
945     sb_msg(_("Scanning source directory..."))
946
947     path = File.expand_path(path.sub(%r|/$|, ''))
948     examined_dirs = `find '#{path}' -type d -follow`.sort.collect { |v| v.chomp }
949     #- validate first
950     examined_dirs.each { |dir|
951         if dir =~ /'/
952             return utf8(_("Source directory or sub-directories can't contain a single-quote character, sorry: %s") % dir)
953         end
954         Dir.entries(dir).each { |file|
955             if file =~ /['"\[\]]/
956                 return utf8(_("Files can't contain any of the characters ', \", [ or ], sorry: %s") % "#{dir}/#{file}")
957             end
958         }
959     }
960
961     #- scan for populate second
962     examined_dirs.each { |dir|
963         if File.basename(dir) =~ /^\./
964             msg 1, _("Ignoring directory %s, begins with a dot (indicating a hidden directory)") % dir
965             next
966         end
967         entries = Dir.entries(dir)
968         if $sort_by_exif_date
969             dates = {}
970             entries.each { |file|
971                 date_time = Exif.datetimeoriginal(File.join(dir, file))
972                 if ! date_time.nil?
973                     dates[file] = date_time
974                 end
975             }
976             entries = smartsort(entries, dates)
977         else
978             entries.sort!
979         end
980         entries.each { |file|
981             type = entry2type(file)
982             if type
983                 $allentries << Entry.new(File.join(dir, file), type)
984             end
985         }
986     }
987     $workingdir = path
988     show_entries
989     $execute.sensitive = true
990     return nil
991 end
992
993 def open_dir_popup
994     fc = Gtk::FileChooserDialog.new(utf8(_("Specify the directory to work with")),
995                                     nil,
996                                     Gtk::FileChooser::ACTION_SELECT_FOLDER,
997                                     nil,
998                                     [Gtk::Stock::OPEN, Gtk::Dialog::RESPONSE_ACCEPT], [Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL])
999     fc.transient_for = $main_window
1000     if $workingdir
1001         fc.current_folder = $workingdir
1002     end
1003     ok = false
1004     while !ok
1005         if fc.run == Gtk::Dialog::RESPONSE_ACCEPT
1006             msg = open_dir(fc.filename)
1007             if msg
1008                 show_popup(fc, msg)
1009                 ok = false
1010             else
1011                 ok = true
1012             end
1013         else
1014             ok = true
1015         end
1016     end
1017     fc.destroy
1018 end
1019
1020 def gtk_thread_protect(proc, *params)
1021     if Thread.current == Thread.main
1022         proc.call(*params)
1023     else
1024         $protect_gtk_pending_calls.synchronize {
1025             $gtk_pending_calls << [ proc, params ]
1026         }
1027     end
1028 end
1029
1030 def gtk_thread_flush
1031     $protect_gtk_pending_calls.synchronize {
1032         if $gtk_pending_calls.size > 0
1033             elem = $gtk_pending_calls.shift
1034             elem[0].call(*elem[1])
1035         end
1036     }
1037 end
1038
1039 def try_quit(*options)
1040     Gtk.main_quit
1041 end
1042
1043 def execute
1044     dialog = Gtk::Dialog.new
1045     dialog.title = utf8(_("Booh message"))
1046
1047     vb1 = Gtk::VBox.new(false, 5)
1048     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!")))
1049     vb1.pack_start(label, false, false)
1050
1051     table = Gtk::Table.new(0, 0, false)
1052     table.set_row_spacings(5)
1053     table.set_column_spacings(5)
1054     table.attach(Gtk::Label.new.set_markup(utf8(_("<b>Label name:</b>"))).set_justify(Gtk::Justification::CENTER), 0, 1, 0, 1, Gtk::FILL, Gtk::FILL, 5, 0)
1055     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)
1056     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)
1057     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)
1058     add_row = proc { |row, name, color, truthproc, normal|
1059         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)),
1060                      0, 1, row, row + 1, Gtk::FILL, Gtk::FILL, 5, 5)
1061         counter = 0
1062         examples = Gtk::HBox.new(false, 5)
1063         $allentries.each { |entry|
1064             if truthproc.call(entry)
1065                 counter += 1
1066                 if counter < 4
1067                     thumbnail = Gtk::Image.new(entry.pixbuf_thumbnail)
1068                     if entry.type == 'video'
1069                         thumbnail = Gtk::HBox.new.pack_start(da1 = Gtk::DrawingArea.new.set_size_request($videoborder_pixbuf.width, -1), false, false).
1070                                                   pack_start(thumbnail).
1071                                                   pack_start(da2 = Gtk::DrawingArea.new.set_size_request($videoborder_pixbuf.width, -1), false, false)
1072                         da1.signal_connect('realize') { da1.window.set_back_pixmap($videoborder_pixmap, false) }
1073                         da2.signal_connect('realize') { da2.window.set_back_pixmap($videoborder_pixmap, false) }
1074                     end
1075                     examples.pack_start(thumbnail, false, false)
1076                 elsif counter == 4
1077                     examples.pack_start(Gtk::Label.new.set_markup("<b>...</b>"), false, false)
1078                 end
1079             end
1080         }
1081         table.attach(Gtk::Label.new(counter.to_s).set_justify(Gtk::Justification::CENTER), 1, 2, row, row + 1, 0, 0, 5, 5)
1082         table.attach(examples, 2, 3, row, row + 1, Gtk::FILL, Gtk::FILL, 5, 5)
1083
1084         combostore = Gtk::ListStore.new(Gdk::Pixbuf, String)
1085         iter = combostore.append
1086         if normal
1087             iter[0] = $main_window.render_icon(Gtk::Stock::GO_FORWARD, Gtk::IconSize::MENU)
1088             iter[1] = utf8(_("Move to:"))
1089             iter = combostore.append
1090             iter[0] = $main_window.render_icon(Gtk::Stock::PASTE, Gtk::IconSize::MENU)
1091             iter[1] = utf8(_("Copy to:"))
1092         else
1093             iter[0] = $main_window.render_icon(Gtk::Stock::DELETE, Gtk::IconSize::MENU)
1094             iter[1] = utf8(_("Permanently remove"))
1095         end
1096         iter = combostore.append
1097         iter[0] = $main_window.render_icon(Gtk::Stock::MEDIA_STOP, Gtk::IconSize::MENU)
1098         iter[1] = utf8(_("Do nothing"))
1099         combo = Gtk::ComboBox.new(combostore)
1100         combo.active = 0
1101         renderer = Gtk::CellRendererPixbuf.new
1102         combo.pack_start(renderer, false)
1103         combo.set_attributes(renderer, :pixbuf => 0)
1104         renderer = Gtk::CellRendererText.new
1105         combo.pack_start(renderer, true)
1106         combo.set_attributes(renderer, :text => 1)
1107
1108         if normal
1109             pathbutton = Gtk::Button.new.add(pathlabel = Gtk::Label.new.set_markup(utf8(_("<i>(unset)</i>"))))
1110             lastpath = $workingdir
1111             pathbutton.signal_connect('clicked') {
1112                 fc = Gtk::FileChooserDialog.new(utf8(_("Specify the directory where to move the pictures to")),
1113                                                 nil,
1114                                                 Gtk::FileChooser::ACTION_SELECT_FOLDER,
1115                                                 nil,
1116                                                 [Gtk::Stock::OPEN, Gtk::Dialog::RESPONSE_ACCEPT], [Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL])
1117                 fc.transient_for = dialog
1118                 fc.current_folder = lastpath
1119                 if fc.run == Gtk::Dialog::RESPONSE_ACCEPT
1120                     pathlabel.text = fc.filename
1121                 end
1122                 lastpath = fc.filename
1123                 fc.destroy
1124             }
1125             combo.signal_connect('changed') {
1126                 pathbutton.sensitive = combo.active <= 1
1127             }
1128             vb = Gtk::VBox.new(false, 5)
1129             vb.pack_start(combo, false, false)
1130             vb.pack_start(pathbutton, false, false)
1131             table.attach(Gtk::Alignment.new(0, 0.5, 1, 0).add(vb), 3, 4, row, row + 1, Gtk::FILL, Gtk::FILL, 5, 5)
1132             { :combo => combo, :pathlabel => pathlabel }
1133         else
1134             table.attach(Gtk::Alignment.new(0, 0.5, 1, 0).add(combo), 3, 4, row, row + 1, Gtk::FILL, Gtk::FILL, 5, 5)
1135             { :combo => combo }
1136         end
1137     }
1138     stuff = {}
1139     stuff['toremove'] = add_row.call(1, utf8(_("<i>to remove</i>")), $color_red, proc { |entry| entry.removed }, false)
1140     $labels.values.each_with_index { |label, row| stuff[label] = add_row.call(row + 2, label.name, label.color, proc { |entry| entry.labeled == label }, true) }
1141     vb1.pack_start(sw = Gtk::ScrolledWindow.new(nil, nil).add_with_viewport(table).set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC), true, true)
1142
1143     toremove_amount = $allentries.find_all { |entry| entry.removed }.size
1144     toremove_size = commify($allentries.find_all { |entry| entry.removed }.collect { |entry| file_size(entry.path) }.sum / 1024)
1145     check_removal = Gtk::CheckButton.new(utf8(_("I have noticed I am about to permanently remove the %d above mentioned pictures (total %s kB).") % [ toremove_amount, toremove_size ]))
1146     if toremove_amount > 0
1147         vb1.pack_start(check_removal, false, false)
1148         stuff['toremove'][:combo].signal_connect('changed') { |widget|
1149             check_removal.sensitive = widget.active == 0
1150         }
1151     end
1152
1153     dialog.vbox.add(vb1)
1154
1155     dialog.set_default_size(800, 600)
1156     dialog.add_button(Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL)
1157     dialog.add_button(Gtk::Stock::OK, Gtk::Dialog::RESPONSE_OK)
1158     dialog.window_position = Gtk::Window::POS_MOUSE
1159     dialog.transient_for = $main_window
1160
1161     dialog.show_all
1162
1163     while true
1164         dialog.run { |response|        
1165             if response == Gtk::Dialog::RESPONSE_OK
1166                 if toremove_amount > 0 && ! check_removal.active? && stuff['toremove'][:combo].active == 0
1167                     show_popup(dialog, utf8(_("You have not confirmed that you noticed the permanent removal of the pictures marked for deletion.")))
1168                     break
1169                 end
1170                 problem = false
1171                 label2entries = {}
1172                 $labels.values.each { |label| label2entries[label] = [] }
1173                 $allentries.each { |entry| entry.labeled and label2entries[entry.labeled] << entry }
1174                 stuff.keys.each { |key|
1175                     if key.is_a?(Label) && stuff[key][:combo].active <= 1
1176                         destination = stuff[key][:pathlabel].text
1177                         if destination[0] != ?/
1178                             show_popup(dialog, utf8(_("You have not selected a directory where to move/copy %s.") % key.name))
1179                             problem = true
1180                             break
1181                         end
1182                         begin
1183                             Dir.mkdir(destination)
1184                         rescue Errno::EEXIST
1185                         end
1186                         begin
1187                             st = File.stat(destination)
1188                         rescue
1189                             show_popup(dialog, utf8(_("Directory %s, where to move/copy %s, is not valid or not createable.") % [destination, key.name]))
1190                             problem = true
1191                             break
1192                         end
1193                         if ! st.directory? || ! st.writable?
1194                             show_popup(dialog, utf8(_("Directory %s, where to move/copy %s, is not valid or not writable.") % [destination, key.name]))
1195                             problem = true
1196                             break
1197                         end
1198                         label2entries[key].each { |entry|
1199                             begin
1200                                 File.stat(File.join(destination, File.basename(entry.path)))
1201                                 show_popup(dialog, utf8(_("Sorry, a file '%s' already exists in directory '%s'.") % [ File.basename(entry.path), destination ]))
1202                                 problem = true
1203                                 break
1204                             rescue
1205                             end
1206                         }
1207                         if problem
1208                             break
1209                         end
1210                     end
1211                 }
1212                 if ! problem
1213                     begin
1214                         moved = 0
1215                         copied = 0
1216                         stuff.keys.each { |key|
1217                             if key.is_a?(Label) && stuff[key][:combo].active <= 1
1218                                 destination = stuff[key][:pathlabel].text
1219                                 label2entries[key].each { |entry|
1220                                     if stuff[key][:combo].active == 0
1221                                         File.rename(entry.path, File.join(destination, File.basename(entry.path)))
1222                                         moved += 1
1223                                     elsif stuff[key][:combo].active == 1
1224                                         system("cp -dp '#{entry.path}' '#{destination}'")
1225                                         copied += 1
1226                                     end
1227                                 }
1228                             end
1229                         }
1230                         removed = 0
1231                         if stuff['toremove'][:combo].active == 0
1232                             $allentries.each { |entry|
1233                                 if entry.removed
1234                                     File.delete(entry.path)
1235                                     removed += 1
1236                                 end
1237                             }
1238                         end
1239                     rescue
1240                         msg 1, "woops: #{$!}"
1241                         show_popup(dialog, utf8(_("Unexpected system call error: '%s'.") % $!))
1242                     end
1243                     show_popup(dialog, utf8(_("Successfully moved %d files, copied %d file, and removed %d files.") % [ moved, copied, removed ]))
1244                     dialog.destroy
1245                     reset_all
1246                     return
1247                 end
1248
1249             else
1250                 dialog.destroy
1251                 return
1252             end
1253         }
1254     end
1255 end
1256
1257 def update_visibility(entry)
1258     if ! entry.button
1259         #- not yet loaded
1260         return
1261     end
1262     if entry.labeled
1263         if entry.labeled.button.active?
1264             entry.button.show
1265         else
1266             entry.button.hide
1267         end
1268     elsif entry.removed
1269         if $toremove_button.active?
1270             entry.button.show
1271         else
1272             entry.button.hide
1273         end
1274     else
1275         if $unlabelled_button.active?
1276             entry.button.show
1277         else
1278             entry.button.hide
1279         end
1280     end
1281 end
1282         
1283 def update_all_visibilities
1284     $allentries.each { |entry|
1285         update_visibility(entry)
1286     }
1287     shown = $mainview.get_shown_entry
1288     if shown.nil?
1289         return
1290     end
1291     while shown.button && ! shown.button.visible? && shown != $allentries.last
1292         shown = $allentries[$allentries.index(shown) + 1]
1293     end 
1294     if shown.button && shown.button.visible?
1295         shown.button.grab_focus
1296         return
1297     end
1298     $allentries.reverse.each { |entry|
1299         if entry.button && entry.button.visible?
1300             entry.button.grab_focus
1301             return
1302         end
1303     }
1304 end
1305
1306 def preferences
1307     dialog = Gtk::Dialog.new(utf8(_("Edit preferences")),
1308                              $main_window,
1309                              Gtk::Dialog::MODAL | Gtk::Dialog::DESTROY_WITH_PARENT,
1310                              [Gtk::Stock::OK, Gtk::Dialog::RESPONSE_OK],
1311                              [Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL])
1312
1313     tooltips = Gtk::Tooltips.new
1314     
1315     dialog.vbox.add(tbl = Gtk::Table.new(0, 0, false))
1316     tbl.attach(Gtk::Alignment.new(1, 0.5, 0, 0).add(Gtk::Label.new.set_markup(utf8(_("Command for watching videos: ")))),
1317                0, 1, 0, 1, Gtk::FILL, Gtk::SHRINK, 2, 2)
1318     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)),
1319                1, 2, 0, 1, Gtk::FILL, Gtk::SHRINK, 2, 2)
1320     tooltips.set_tip(video_viewer_entry, utf8(_("Use %f to specify the filename;\nfor example: /usr/bin/mplayer %f")), nil)
1321
1322     tbl.attach(Gtk::Alignment.new(1, 0.5, 0, 0).add(Gtk::Label.new.set_markup(utf8(_("Browser's command: ")))),
1323                0, 1, 1, 2, Gtk::FILL, Gtk::SHRINK, 2, 2)
1324     tbl.attach(Gtk::Alignment.new(0, 0.5, 1, 0).add(browser_entry = Gtk::Entry.new.set_text($config['browser'])),
1325                1, 2, 1, 2, Gtk::FILL, Gtk::SHRINK, 2, 2)
1326     tooltips.set_tip(browser_entry, utf8(_("Use %f to specify the filename;\nfor example: /usr/bin/mozilla-firefox -remote 'openURL(%f,new-window)' || /usr/bin/mozilla-firefox %f")), nil)
1327
1328     tbl.attach(Gtk::Alignment.new(1, 0.5, 0, 0).add(Gtk::Label.new.set_markup(utf8(_("Preloading distance: ")))),
1329                0, 1, 2, 3, Gtk::FILL, Gtk::SHRINK, 2, 2)
1330     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)),
1331                1, 2, 2, 3, Gtk::FILL, Gtk::SHRINK, 2, 2)
1332     tooltips.set_tip(preload_distance, utf8(_("Amount of pictures preloaded left and right to the currently shown")), nil)
1333
1334     tbl.attach(Gtk::Alignment.new(1, 0.5, 0, 0).add(Gtk::Label.new.set_markup(utf8(_("Cache memory use: ")))),
1335                0, 1, 3, 4, Gtk::FILL, Gtk::SHRINK, 2, 2)
1336     tbl.attach(Gtk::Alignment.new(0, 0.5, 1, 0).add(cache_vbox = Gtk::VBox.new(false, 0)),
1337                1, 2, 3, 4, Gtk::FILL, Gtk::SHRINK, 2, 2)
1338     cache_vbox.pack_start(Gtk::HBox.new(false, 0).pack_start(cache_memfree_radio = Gtk::RadioButton.new(''), false, false).
1339                                                   pack_start(cache_memfree_spin = Gtk::SpinButton.new(0, 100, 10), false, false).
1340                                                   pack_start(cache_memfree_label = Gtk::Label.new(utf8(_("% of free memory"))), false, false), false, false)
1341     cache_memfree_spin.signal_connect('value-changed') { cache_memfree_radio.active = true }
1342     tooltips.set_tip(cache_memfree_spin, utf8(_("Percentage of free memory (+ buffers/cache) measured at startup")), nil)
1343     cache_vbox.pack_start(Gtk::HBox.new(false, 0).pack_start(cache_specify_radio = Gtk::RadioButton.new(cache_memfree_radio, ''), false, false).
1344                                                   pack_start(cache_specify_spin = Gtk::SpinButton.new(0, 4000, 50), false, false).
1345                                                   pack_start(cache_specify_label = Gtk::Label.new(utf8(_("MB"))).set_sensitive(false), false, false), false, false)
1346     cache_specify_spin.signal_connect('value-changed') { cache_specify_radio.active = true }
1347     cache_memfree_radio.signal_connect('toggled') {
1348         if cache_memfree_radio.active?
1349             cache_memfree_label.sensitive = true
1350             cache_specify_label.sensitive = false
1351         else
1352             cache_specify_label.sensitive = true
1353             cache_memfree_label.sensitive = false
1354         end
1355     }
1356     tooltips.set_tip(cache_specify_spin, utf8(_("Amount of memory in megabytes")), nil)
1357     if $config['cache-memory-use'] =~ /memfree_(\d+)/
1358         cache_memfree_spin.value = $1.to_i
1359     else
1360         cache_specify_spin.value = $config['cache-memory-use'].to_i
1361     end
1362
1363     tbl.attach(update_exif_orientation_check = Gtk::CheckButton.new(utf8(_("Update file's EXIF orientation when rotating a picture"))),
1364                0, 2, 4, 5, Gtk::FILL, Gtk::SHRINK, 2, 2)
1365     tooltips.set_tip(update_exif_orientation_check, utf8(_("When rotating a picture (Alt-Right/Left), also update EXIF orientation in the file itself")), nil)
1366     update_exif_orientation_check.active = $config['rotate-set-exif'] == 'true'
1367
1368     dialog.vbox.show_all
1369     dialog.run { |response|
1370         if response == Gtk::Dialog::RESPONSE_OK
1371             $config['video-viewer'] = from_utf8(video_viewer_entry.text)
1372             $config['browser'] = from_utf8(browser_entry.text)
1373             $config['preload-distance'] = preload_distance.value
1374             $config['rotate-set-exif'] = update_exif_orientation_check.active?.to_s
1375             if cache_memfree_radio.active?
1376                 $config['cache-memory-use'] = "memfree_#{cache_memfree_spin.value}%"
1377             else
1378                 $config['cache-memory-use'] = cache_specify_spin.value
1379             end
1380             set_cache_memory_use_figure
1381         end
1382     }
1383     dialog.destroy
1384 end
1385
1386 def perform_undo
1387     if $undo_mb.sensitive?
1388         $redo_mb.sensitive = true
1389         if not more_undoes = UndoHandler.undo($statusbar)
1390             $undo_mb.sensitive = false
1391         end
1392     end
1393 end
1394
1395 def perform_redo
1396     if $redo_mb.sensitive?
1397         $undo_mb.sensitive = true
1398         if not more_redoes = UndoHandler.redo($statusbar)
1399             $redo_mb.sensitive = false
1400         end
1401     end
1402 end
1403
1404 def create_menubar    
1405     #- menu
1406     mb = Gtk::MenuBar.new
1407
1408     filemenu = Gtk::MenuItem.new(utf8(_("_File")))
1409     filesubmenu = Gtk::Menu.new
1410     filesubmenu.append(open      = Gtk::ImageMenuItem.new(Gtk::Stock::OPEN))
1411     filesubmenu.append(            Gtk::SeparatorMenuItem.new)
1412     filesubmenu.append($execute  = Gtk::ImageMenuItem.new(Gtk::Stock::EXECUTE).set_sensitive(false))
1413     filesubmenu.append(            Gtk::SeparatorMenuItem.new)
1414     filesubmenu.append(quit      = Gtk::ImageMenuItem.new(Gtk::Stock::QUIT))
1415     filemenu.set_submenu(filesubmenu)
1416     mb.append(filemenu)
1417
1418     open.signal_connect('activate') { open_dir_popup }
1419     $execute.signal_connect('activate') { execute }
1420     quit.signal_connect('activate') { try_quit }
1421
1422     editmenu = Gtk::MenuItem.new(utf8(_("_Edit")))
1423     editsubmenu = Gtk::Menu.new
1424     editsubmenu.append($undo_mb    = Gtk::ImageMenuItem.new(Gtk::Stock::UNDO).set_sensitive(false))
1425     editsubmenu.append($redo_mb    = Gtk::ImageMenuItem.new(Gtk::Stock::REDO).set_sensitive(false))
1426     editsubmenu.append(              Gtk::SeparatorMenuItem.new)
1427     editsubmenu.append(prefs       = Gtk::ImageMenuItem.new(Gtk::Stock::PREFERENCES))
1428     editmenu.set_submenu(editsubmenu)
1429     mb.append(editmenu)
1430
1431     $undo_mb.signal_connect('activate') { perform_undo }
1432     $redo_mb.signal_connect('activate') { perform_redo }
1433     prefs.signal_connect('activate') { preferences }
1434     
1435     helpmenu = Gtk::MenuItem.new(utf8(_("_Help")))
1436     helpsubmenu = Gtk::Menu.new
1437     helpsubmenu.append(tutos = Gtk::ImageMenuItem.new(utf8(_("Online tutorials (opens a web-browser)"))))
1438     tutos.image = Gtk::Image.new("#{$FPATH}/images/stock-web-16.png")
1439     helpsubmenu.append(Gtk::SeparatorMenuItem.new)
1440     helpsubmenu.append(about = Gtk::ImageMenuItem.new(Gtk::Stock::ABOUT))
1441     helpmenu.set_submenu(helpsubmenu)
1442     mb.append(helpmenu)
1443
1444     tutos.signal_connect('activate') { open_url('http://booh.org/tutorial.html') }
1445     about.signal_connect('activate') { call_about }
1446
1447
1448     #- no toolbar, to save height
1449
1450     return mb
1451 end
1452
1453 def reset_labels
1454     for child in $labels_vbox.children
1455         $labels_vbox.remove(child)
1456     end
1457     $labels_vbox.pack_start(Gtk::Label.new(utf8(_("Labels list:"))).set_justify(Gtk::Justification::CENTER), false, false).show_all
1458     $labels = {}
1459     lbl = Gtk::Label.new.set_markup(utf8(_("<i>unlabelled</i>")))
1460     $labels_vbox.pack_start($unlabelled_button = Gtk::CheckButton.new.add(Gtk::EventBox.new.add(lbl)).show_all)
1461     $unlabelled_button.active = true
1462     $unlabelled_button.signal_connect('toggled') { update_all_visibilities }
1463     lbl = Gtk::Label.new.set_markup(utf8(_("<i>to remove</i>")))
1464     $labels_vbox.pack_start($toremove_button = Gtk::CheckButton.new.add(evt = Gtk::EventBox.new.add(lbl)).show_all)
1465     $toremove_button.active = true
1466     $toremove_button.signal_connect('toggled') { update_all_visibilities }
1467     evt.modify_bg(Gtk::StateType::NORMAL, $color_red)
1468     evt.modify_bg(Gtk::StateType::PRELIGHT, $color_red.lighter.lighter)
1469     evt.modify_bg(Gtk::StateType::ACTIVE, $color_red.lighter)
1470 end
1471
1472 def reset_thumbnails
1473     $allentries = []
1474     for child in $imagesline.children
1475         $imagesline.remove(child)
1476     end
1477 end
1478
1479 def create_main_window
1480
1481     $videoborder_pixbuf = Gdk::Pixbuf.new("#{$FPATH}/images/video_border.png")
1482     $videoborder_pixmap, = $videoborder_pixbuf.render_pixmap_and_mask(0)
1483
1484     mb = create_menubar
1485
1486     main_vbox = Gtk::VBox.new(false, 0)
1487     main_vbox.pack_start(mb, false, false)
1488     mainview_hbox = Gtk::HBox.new
1489     mainview_hbox.pack_start(Gtk::Alignment.new(0.5, 0, 0, 0).add($labels_vbox = Gtk::VBox.new(false, 5)), false, true)
1490     reset_labels
1491     mainview_hbox.pack_start($mainview = MainView.new, true, true)
1492     main_vbox.pack_start(mainview_hbox, true, true)
1493     $imagesline_sw = Gtk::ScrolledWindow.new(nil, nil)
1494     $imagesline_sw.set_policy(Gtk::POLICY_ALWAYS, Gtk::POLICY_NEVER)
1495     $imagesline_sw.add_with_viewport($imagesline = Gtk::HBox.new(false, 0).show)
1496     main_vbox.pack_start($imagesline_sw, false, false)
1497     main_vbox.pack_end($statusbar = Gtk::Statusbar.new, false, false)
1498
1499     $imagesline.set_size_request(-1, Gtk::Button.new.size_request[1] + Entry.thumbnails_height + 15)
1500
1501     $main_window = Gtk::Window.new
1502     $main_window.add(main_vbox)
1503     $main_window.signal_connect('delete-event') {
1504         try_quit({ :disallow_cancel => true })
1505     }
1506
1507     #- read/save size and position of window
1508     if $config['pos-x'] && $config['pos-y']
1509         $main_window.move($config['pos-x'].to_i, $config['pos-y'].to_i)
1510     else
1511         $main_window.window_position = Gtk::Window::POS_CENTER
1512     end
1513     msg 3, "size: #{$config['width']}x#{$config['height']}"
1514     $main_window.set_default_size(($config['width'] || 700).to_i, ($config['height'] || 600).to_i)
1515     $main_window.signal_connect('configure-event') {
1516         msg 3, "configure: pos: #{$main_window.window.root_origin.inspect} size: #{$main_window.window.size.inspect}"
1517         x, y = $main_window.window.root_origin
1518         width, height = $main_window.window.size
1519         $config['pos-x'] = x
1520         $config['pos-y'] = y
1521         $config['width'] = width
1522         $config['height'] = height
1523         false
1524     }
1525
1526     $protect_gtk_pending_calls = Mutex.new
1527     $gtk_pending_calls = []
1528     Gtk.timeout_add(50) {
1529         gtk_thread_flush
1530         true
1531     }
1532
1533     $main_window.show_all
1534 end
1535
1536
1537 handle_options
1538 Thread.abort_on_exception = true
1539 read_config
1540 Gtk.init
1541
1542
1543 create_main_window
1544 check_config
1545
1546 if ARGV[0]
1547     open_dir(ARGV[0])
1548 end
1549 Gtk.main
1550
1551 write_config