classifier: allow to sort by EXIF dates
[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         end
714
715     elsif event.state & Gdk::Window::CONTROL_MASK != 0
716         #- CONTROL pressed: Ctrl-z and Ctrl-r for undo/redo
717         if event.keyval == Gdk::Keyval::GDK_z
718             perform_undo
719         end
720         if event.keyval == Gdk::Keyval::GDK_r
721             perform_redo
722         end
723
724     else
725         removed_before = entry.removed
726         label_before = entry.labeled
727
728         if event.keyval == Gdk::Keyval::GDK_Delete
729             entry.removed = true
730             entry.labeled = nil
731             entry.show_bg
732             $mainview.show_next_entry(entry)
733             update_visibility(entry)
734
735             save_undo(_("set for removal"),
736                       proc {
737                           entry.removed = removed_before
738                           entry.labeled = label_before
739                           entry.show_bg
740                           update_visibility(entry)
741                           if entry.button.visible?
742                               $mainview.set_shown_entry(entry)
743                           end
744                           proc {
745                               entry.removed = true
746                               entry.labeled = nil
747                               entry.show_bg
748                               update_visibility(entry)
749                               if entry.button.visible?
750                                   $mainview.set_shown_entry(entry)
751                               end
752                           }
753                       })
754
755         elsif event.keyval == Gdk::Keyval::GDK_space
756             if entry.labeled
757                 msg = _("Cleared label")
758             elsif entry.removed
759                 msg = _("Cleared set for removal")
760             end
761             entry.removed = false
762             entry.labeled = nil
763             entry.show_bg
764             $mainview.show_next_entry(entry)
765
766             save_undo(msg,
767                       proc {
768                           entry.removed = removed_before
769                           entry.labeled = label_before
770                           entry.show_bg
771                           $mainview.set_shown_entry(entry)
772                           proc {
773                               entry.removed = false
774                               entry.labeled = nil
775                               entry.show_bg
776                               $mainview.set_shown_entry(entry)
777                           }
778                       })
779
780         elsif event.keyval == Gdk::Keyval::GDK_Return && entry.type == 'video'
781             video_view(entry)
782
783         else
784             char = [ Gdk::Keyval.to_unicode(event.keyval) ].pack("C*")
785             if char =~ /^[a-zA-z0-9]$/
786                 label = $labels[char]
787                 
788                 if label.nil?
789                     vb = Gtk::VBox.new(false, 0)
790                     vb.pack_start(entry = Gtk::Entry.new.set_text(char), false, false)
791                     vb.pack_start(Gtk::Alignment.new(0.5, 0.5, 0, 0).add(bt = Gtk::ColorButton.new))
792                     color = bt.color = Gdk::Color.new(16384 + rand(49151), 16384 + rand(49151), 16384 + rand(49151))
793                     bt.signal_connect('color-set') { color = bt.color }
794                     text = nil
795                     entry.signal_connect('changed') {  #- cannot add a new label with first letter of an existing label
796                         while $labels.has_key?(entry.text[0,1])
797                             entry.text = entry.text.sub(/./, '')
798                         end
799                     }
800                     if show_popup($main_window,
801                                   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,
802                                   { :okcancel => true, :bottomwidget => vb, :data_getter => proc { text = entry.text },
803                                     :stuff_connector => proc { |stuff| entry.select_region(0, 0)
804                                                                        entry.position = -1
805                                                                        entry.signal_connect('activate') { stuff[:dialog].response(Gtk::Dialog::RESPONSE_OK) } } } )
806                         if text.length > 0
807                             char = text[0,1]  #- in case it changed
808                             label = Label.new(text)
809                             label.color = color
810                             $labels[char] = label
811                             lbl = Gtk::Label.new.set_markup('<b>(' + char + ')</b>' + text[1..-1]).set_justify(Gtk::Justification::CENTER)
812                             $labels_vbox.pack_start(label.button = Gtk::CheckButton.new.add(evt = Gtk::EventBox.new.add(lbl)).show_all)
813                             label.button.active = true
814                             label.button.signal_connect('toggled') { update_all_visibilities }
815                             evt.modify_bg(Gtk::StateType::NORMAL, label.color)
816                             evt.modify_bg(Gtk::StateType::PRELIGHT, label.color.lighter.lighter)
817                             evt.modify_bg(Gtk::StateType::ACTIVE, label.color.lighter)
818                         end
819                     end
820
821                 else
822                     entry.removed = false
823                     entry.labeled = label
824                     entry.show_bg
825                     $mainview.show_next_entry(entry)
826                     update_visibility(entry)
827
828                     save_undo(_("set label"),
829                               proc {
830                                   entry.removed = removed_before
831                                   entry.labeled = label_before
832                                   entry.show_bg
833                                   update_visibility(entry)
834                                   if entry.button.visible?
835                                       $mainview.set_shown_entry(entry)
836                                   end
837                                   proc {
838                                       entry.removed = false
839                                       entry.labeled = label
840                                       entry.show_bg
841                                       update_visibility(entry)
842                                       if entry.button.visible?
843                                           $mainview.set_shown_entry(entry)
844                                       end
845                                   }
846                               })
847                 end
848             end
849         end
850     end
851 end
852
853 def sb_msg(msg)
854     $statusbar.pop(0)
855     if msg
856         $statusbar.push(0, utf8(msg))
857     end
858 end
859
860 def real_show_entry(entry, tooltips, grab_focus)
861     #- for scoping the actual reference to 'entry'
862     gtk_thread_protect(proc {
863         msg 3, "using entry #{entry}"
864         entry.image = Gtk::Image.new(entry.pixbuf_thumbnail)
865         if entry.type == 'video'
866             entry.button = Gtk::Button.new.add(Gtk::HBox.new.pack_start(da1 = Gtk::DrawingArea.new.set_size_request($videoborder_pixbuf.width, -1), false, false).
867                                                              pack_start(entry.image).
868                                                              pack_start(da2 = Gtk::DrawingArea.new.set_size_request($videoborder_pixbuf.width, -1), false, false))
869             da1.signal_connect('realize') { da1.window.set_back_pixmap($videoborder_pixmap, false) }
870             da2.signal_connect('realize') { da2.window.set_back_pixmap($videoborder_pixmap, false) }
871         else
872             entry.button = Gtk::Button.new.set_image(entry.image)
873         end
874         tooltips.set_tip(entry.button, entry.get_beautified_name, nil)
875         $imagesline.pack_start(entry.alignment = Gtk::Alignment.new(0.5, 1, 0, 0).add(entry.button).show_all, false, false)
876         entry.button.signal_connect('clicked') {
877             if (last_shown = $mainview.get_shown_entry) != entry
878                 $mainview.set_shown_entry(entry)
879                 entry.alignment.set(0.5, 0, 0, 0)
880                 sb_msg(_("Selected %s") % entry.get_beautified_name)
881                 last_shown.nil? or last_shown.alignment.set(0.5, 1, 0, 0)
882             end
883         }
884         entry.button.signal_connect('button-press-event') { |w, event|
885             if entry.type == 'video' && event.event_type == Gdk::Event::BUTTON2_PRESS
886                 video_view(entry)
887             end
888         }
889         entry.button.signal_connect('focus-in-event') { entry.button.clicked; autoscroll_if_needed(entry.button) }
890         entry.button.signal_connect('key-press-event') { |w, e| thumbnail_keypressed(entry, e) }
891         if grab_focus
892             entry.button.grab_focus
893         end
894         update_visibility(entry)
895     })
896 end
897
898 def show_entries
899     $images_loader = Thread.new {
900         t1 = Time.now
901         sb_msg(_("Loading images..."))
902         tooltips = Gtk::Tooltips.new
903         counter = 0
904         toremove = []
905         grab_focus = true
906         i = 0
907         total_size = 0
908         while i < $allentries.size
909             entry = $allentries[i]
910             if entry.pixbuf_full
911                 total_size += file_size(entry.path)
912                 entry.pixbuf_thumbnail
913                 real_show_entry(entry, tooltips, grab_focus)
914                 grab_focus = false
915                 if i % 4 == 0
916                     check_memory_free_cache_if_needed
917                 end
918                 counter += 1
919                 i = i + 1
920
921             else
922                 $allentries.delete_at(i)
923             end
924         end
925         check_memory_free_cache_if_needed
926         sb_msg(_("%d images of total %s kB loaded in %3.2f seconds.") % [ counter, commify(total_size / 1024), Time.now - t1 ])
927     }
928     $images_loader.priority = -1
929 end
930
931 def reset_all
932     $images_loader and $images_loader.kill
933     reset_labels
934     reset_thumbnails
935     $mainview.set_shown_entry(nil)
936     sb_msg(nil)
937 end
938
939 def open_dir(path)
940     #- remove visual stuff, so that user will see something is happening
941     reset_all
942     sb_msg(_("Scanning source directory..."))
943
944     path = File.expand_path(path.sub(%r|/$|, ''))
945     examined_dirs = `find '#{path}' -type d -follow`.sort.collect { |v| v.chomp }
946     #- validate first
947     examined_dirs.each { |dir|
948         if dir =~ /'/
949             return utf8(_("Source directory or sub-directories can't contain a single-quote character, sorry: %s") % dir)
950         end
951         Dir.entries(dir).each { |file|
952             if file =~ /['"\[\]]/
953                 return utf8(_("Files can't contain any of the characters ', \", [ or ], sorry: %s") % "#{dir}/#{file}")
954             end
955         }
956     }
957
958     #- scan for populate second
959     examined_dirs.each { |dir|
960         if File.basename(dir) =~ /^\./
961             msg 1, _("Ignoring directory %s, begins with a dot (indicating a hidden directory)") % dir
962             next
963         end
964         entries = Dir.entries(dir)
965         if $sort_by_exif_date
966             dates = {}
967             entries.each { |file|
968                 date_time = Exif.datetimeoriginal(File.join(dir, file))
969                 if ! date_time.nil?
970                     dates[file] = date_time
971                 end
972             }
973             entries = smartsort(entries, dates)
974         else
975             entries.sort!
976         end
977         entries.each { |file|
978             type = entry2type(file)
979             if type
980                 $allentries << Entry.new(File.join(dir, file), type)
981             end
982         }
983     }
984     $workingdir = path
985     show_entries
986     $execute.sensitive = true
987     return nil
988 end
989
990 def open_dir_popup
991     fc = Gtk::FileChooserDialog.new(utf8(_("Specify the directory to work with")),
992                                     nil,
993                                     Gtk::FileChooser::ACTION_SELECT_FOLDER,
994                                     nil,
995                                     [Gtk::Stock::OPEN, Gtk::Dialog::RESPONSE_ACCEPT], [Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL])
996     fc.transient_for = $main_window
997     if $workingdir
998         fc.current_folder = $workingdir
999     end
1000     ok = false
1001     while !ok
1002         if fc.run == Gtk::Dialog::RESPONSE_ACCEPT
1003             msg = open_dir(fc.filename)
1004             if msg
1005                 show_popup(fc, msg)
1006                 ok = false
1007             else
1008                 ok = true
1009             end
1010         else
1011             ok = true
1012         end
1013     end
1014     fc.destroy
1015 end
1016
1017 def gtk_thread_protect(proc, *params)
1018     if Thread.current == Thread.main
1019         proc.call(*params)
1020     else
1021         $protect_gtk_pending_calls.synchronize {
1022             $gtk_pending_calls << [ proc, params ]
1023         }
1024     end
1025 end
1026
1027 def gtk_thread_flush
1028     $protect_gtk_pending_calls.synchronize {
1029         if $gtk_pending_calls.size > 0
1030             elem = $gtk_pending_calls.shift
1031             elem[0].call(*elem[1])
1032         end
1033     }
1034 end
1035
1036 def try_quit(*options)
1037     Gtk.main_quit
1038 end
1039
1040 def execute
1041     dialog = Gtk::Dialog.new
1042     dialog.title = utf8(_("Booh message"))
1043
1044     vb1 = Gtk::VBox.new(false, 5)
1045     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!")))
1046     vb1.pack_start(label, false, false)
1047
1048     table = Gtk::Table.new(0, 0, false)
1049     table.set_row_spacings(5)
1050     table.set_column_spacings(5)
1051     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)
1052     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)
1053     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)
1054     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)
1055     add_row = proc { |row, name, color, truthproc, normal|
1056         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)),
1057                      0, 1, row, row + 1, Gtk::FILL, Gtk::FILL, 5, 5)
1058         counter = 0
1059         examples = Gtk::HBox.new(false, 5)
1060         $allentries.each { |entry|
1061             if truthproc.call(entry)
1062                 counter += 1
1063                 if counter < 4
1064                     thumbnail = Gtk::Image.new(entry.pixbuf_thumbnail)
1065                     if entry.type == 'video'
1066                         thumbnail = Gtk::HBox.new.pack_start(da1 = Gtk::DrawingArea.new.set_size_request($videoborder_pixbuf.width, -1), false, false).
1067                                                   pack_start(thumbnail).
1068                                                   pack_start(da2 = Gtk::DrawingArea.new.set_size_request($videoborder_pixbuf.width, -1), false, false)
1069                         da1.signal_connect('realize') { da1.window.set_back_pixmap($videoborder_pixmap, false) }
1070                         da2.signal_connect('realize') { da2.window.set_back_pixmap($videoborder_pixmap, false) }
1071                     end
1072                     examples.pack_start(thumbnail, false, false)
1073                 elsif counter == 4
1074                     examples.pack_start(Gtk::Label.new.set_markup("<b>...</b>"), false, false)
1075                 end
1076             end
1077         }
1078         table.attach(Gtk::Label.new(counter.to_s).set_justify(Gtk::Justification::CENTER), 1, 2, row, row + 1, 0, 0, 5, 5)
1079         table.attach(examples, 2, 3, row, row + 1, Gtk::FILL, Gtk::FILL, 5, 5)
1080
1081         combostore = Gtk::ListStore.new(Gdk::Pixbuf, String)
1082         iter = combostore.append
1083         if normal
1084             iter[0] = $main_window.render_icon(Gtk::Stock::GO_FORWARD, Gtk::IconSize::MENU)
1085             iter[1] = utf8(_("Move to:"))
1086             iter = combostore.append
1087             iter[0] = $main_window.render_icon(Gtk::Stock::PASTE, Gtk::IconSize::MENU)
1088             iter[1] = utf8(_("Copy to:"))
1089         else
1090             iter[0] = $main_window.render_icon(Gtk::Stock::DELETE, Gtk::IconSize::MENU)
1091             iter[1] = utf8(_("Permanently remove"))
1092         end
1093         iter = combostore.append
1094         iter[0] = $main_window.render_icon(Gtk::Stock::MEDIA_STOP, Gtk::IconSize::MENU)
1095         iter[1] = utf8(_("Do nothing"))
1096         combo = Gtk::ComboBox.new(combostore)
1097         combo.active = 0
1098         renderer = Gtk::CellRendererPixbuf.new
1099         combo.pack_start(renderer, false)
1100         combo.set_attributes(renderer, :pixbuf => 0)
1101         renderer = Gtk::CellRendererText.new
1102         combo.pack_start(renderer, true)
1103         combo.set_attributes(renderer, :text => 1)
1104
1105         if normal
1106             pathbutton = Gtk::Button.new.add(pathlabel = Gtk::Label.new.set_markup(utf8(_("<i>(unset)</i>"))))
1107             lastpath = $workingdir
1108             pathbutton.signal_connect('clicked') {
1109                 fc = Gtk::FileChooserDialog.new(utf8(_("Specify the directory where to move the pictures to")),
1110                                                 nil,
1111                                                 Gtk::FileChooser::ACTION_SELECT_FOLDER,
1112                                                 nil,
1113                                                 [Gtk::Stock::OPEN, Gtk::Dialog::RESPONSE_ACCEPT], [Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL])
1114                 fc.transient_for = dialog
1115                 fc.current_folder = lastpath
1116                 if fc.run == Gtk::Dialog::RESPONSE_ACCEPT
1117                     pathlabel.text = fc.filename
1118                 end
1119                 lastpath = fc.filename
1120                 fc.destroy
1121             }
1122             combo.signal_connect('changed') {
1123                 pathbutton.sensitive = combo.active <= 1
1124             }
1125             vb = Gtk::VBox.new(false, 5)
1126             vb.pack_start(combo, false, false)
1127             vb.pack_start(pathbutton, false, false)
1128             table.attach(Gtk::Alignment.new(0, 0.5, 1, 0).add(vb), 3, 4, row, row + 1, Gtk::FILL, Gtk::FILL, 5, 5)
1129             { :combo => combo, :pathlabel => pathlabel }
1130         else
1131             table.attach(Gtk::Alignment.new(0, 0.5, 1, 0).add(combo), 3, 4, row, row + 1, Gtk::FILL, Gtk::FILL, 5, 5)
1132             { :combo => combo }
1133         end
1134     }
1135     stuff = {}
1136     stuff['toremove'] = add_row.call(1, utf8(_("<i>to remove</i>")), $color_red, proc { |entry| entry.removed }, false)
1137     $labels.values.each_with_index { |label, row| stuff[label] = add_row.call(row + 2, label.name, label.color, proc { |entry| entry.labeled == label }, true) }
1138     vb1.pack_start(sw = Gtk::ScrolledWindow.new(nil, nil).add_with_viewport(table).set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC), true, true)
1139
1140     toremove_amount = $allentries.find_all { |entry| entry.removed }.size
1141     toremove_size = commify($allentries.find_all { |entry| entry.removed }.collect { |entry| file_size(entry.path) }.sum / 1024)
1142     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 ]))
1143     if toremove_amount > 0
1144         vb1.pack_start(check_removal, false, false)
1145         stuff['toremove'][:combo].signal_connect('changed') { |widget|
1146             check_removal.sensitive = widget.active == 0
1147         }
1148     end
1149
1150     dialog.vbox.add(vb1)
1151
1152     dialog.set_default_size(800, 600)
1153     dialog.add_button(Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL)
1154     dialog.add_button(Gtk::Stock::OK, Gtk::Dialog::RESPONSE_OK)
1155     dialog.window_position = Gtk::Window::POS_MOUSE
1156     dialog.transient_for = $main_window
1157
1158     dialog.show_all
1159
1160     while true
1161         dialog.run { |response|        
1162             if response == Gtk::Dialog::RESPONSE_OK
1163                 if toremove_amount > 0 && ! check_removal.active? && stuff['toremove'][:combo].active == 0
1164                     show_popup(dialog, utf8(_("You have not confirmed that you noticed the permanent removal of the pictures marked for deletion.")))
1165                     break
1166                 end
1167                 problem = false
1168                 label2entries = {}
1169                 $labels.values.each { |label| label2entries[label] = [] }
1170                 $allentries.each { |entry| entry.labeled and label2entries[entry.labeled] << entry }
1171                 stuff.keys.each { |key|
1172                     if key.is_a?(Label) && stuff[key][:combo].active <= 1
1173                         destination = stuff[key][:pathlabel].text
1174                         if destination[0] != ?/
1175                             show_popup(dialog, utf8(_("You have not selected a directory where to move/copy %s.") % key.name))
1176                             problem = true
1177                             break
1178                         end
1179                         begin
1180                             Dir.mkdir(destination)
1181                         rescue Errno::EEXIST
1182                         end
1183                         begin
1184                             st = File.stat(destination)
1185                         rescue
1186                             show_popup(dialog, utf8(_("Directory %s, where to move/copy %s, is not valid or not createable.") % [destination, key.name]))
1187                             problem = true
1188                             break
1189                         end
1190                         if ! st.directory? || ! st.writable?
1191                             show_popup(dialog, utf8(_("Directory %s, where to move/copy %s, is not valid or not writable.") % [destination, key.name]))
1192                             problem = true
1193                             break
1194                         end
1195                         label2entries[key].each { |entry|
1196                             begin
1197                                 File.stat(File.join(destination, File.basename(entry.path)))
1198                                 show_popup(dialog, utf8(_("Sorry, a file '%s' already exists in directory '%s'.") % [ File.basename(entry.path), destination ]))
1199                                 problem = true
1200                                 break
1201                             rescue
1202                             end
1203                         }
1204                         if problem
1205                             break
1206                         end
1207                     end
1208                 }
1209                 if ! problem
1210                     begin
1211                         moved = 0
1212                         copied = 0
1213                         stuff.keys.each { |key|
1214                             if key.is_a?(Label) && stuff[key][:combo].active <= 1
1215                                 destination = stuff[key][:pathlabel].text
1216                                 label2entries[key].each { |entry|
1217                                     if stuff[key][:combo].active == 0
1218                                         File.rename(entry.path, File.join(destination, File.basename(entry.path)))
1219                                         moved += 1
1220                                     elsif stuff[key][:combo].active == 1
1221                                         system("cp -dp '#{entry.path}' '#{destination}'")
1222                                         copied += 1
1223                                     end
1224                                 }
1225                             end
1226                         }
1227                         removed = 0
1228                         if stuff['toremove'][:combo].active == 0
1229                             $allentries.each { |entry|
1230                                 if entry.removed
1231                                     File.delete(entry.path)
1232                                     removed += 1
1233                                 end
1234                             }
1235                         end
1236                     rescue
1237                         msg 1, "woops: #{$!}"
1238                         show_popup(dialog, utf8(_("Unexpected system call error: '%s'.") % $!))
1239                     end
1240                     show_popup(dialog, utf8(_("Successfully moved %d files, copied %d file, and removed %d files.") % [ moved, copied, removed ]))
1241                     dialog.destroy
1242                     reset_all
1243                     return
1244                 end
1245
1246             else
1247                 dialog.destroy
1248                 return
1249             end
1250         }
1251     end
1252 end
1253
1254 def update_visibility(entry)
1255     if ! entry.button
1256         #- not yet loaded
1257         return
1258     end
1259     if entry.labeled
1260         if entry.labeled.button.active?
1261             entry.button.show
1262         else
1263             entry.button.hide
1264         end
1265     elsif entry.removed
1266         if $toremove_button.active?
1267             entry.button.show
1268         else
1269             entry.button.hide
1270         end
1271     else
1272         if $unlabelled_button.active?
1273             entry.button.show
1274         else
1275             entry.button.hide
1276         end
1277     end
1278 end
1279         
1280 def update_all_visibilities
1281     $allentries.each { |entry|
1282         update_visibility(entry)
1283     }
1284     shown = $mainview.get_shown_entry
1285     if shown.nil?
1286         return
1287     end
1288     while shown.button && ! shown.button.visible? && shown != $allentries.last
1289         shown = $allentries[$allentries.index(shown) + 1]
1290     end 
1291     if shown.button && shown.button.visible?
1292         shown.button.grab_focus
1293         return
1294     end
1295     $allentries.reverse.each { |entry|
1296         if entry.button && entry.button.visible?
1297             entry.button.grab_focus
1298             return
1299         end
1300     }
1301 end
1302
1303 def preferences
1304     dialog = Gtk::Dialog.new(utf8(_("Edit preferences")),
1305                              $main_window,
1306                              Gtk::Dialog::MODAL | Gtk::Dialog::DESTROY_WITH_PARENT,
1307                              [Gtk::Stock::OK, Gtk::Dialog::RESPONSE_OK],
1308                              [Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL])
1309
1310     tooltips = Gtk::Tooltips.new
1311     
1312     dialog.vbox.add(tbl = Gtk::Table.new(0, 0, false))
1313     tbl.attach(Gtk::Alignment.new(1, 0.5, 0, 0).add(Gtk::Label.new.set_markup(utf8(_("Command for watching videos: ")))),
1314                0, 1, 0, 1, Gtk::FILL, Gtk::SHRINK, 2, 2)
1315     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)),
1316                1, 2, 0, 1, Gtk::FILL, Gtk::SHRINK, 2, 2)
1317     tooltips.set_tip(video_viewer_entry, utf8(_("Use %f to specify the filename;\nfor example: /usr/bin/mplayer %f")), nil)
1318
1319     tbl.attach(Gtk::Alignment.new(1, 0.5, 0, 0).add(Gtk::Label.new.set_markup(utf8(_("Browser's command: ")))),
1320                0, 1, 1, 2, Gtk::FILL, Gtk::SHRINK, 2, 2)
1321     tbl.attach(Gtk::Alignment.new(0, 0.5, 1, 0).add(browser_entry = Gtk::Entry.new.set_text($config['browser'])),
1322                1, 2, 1, 2, Gtk::FILL, Gtk::SHRINK, 2, 2)
1323     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)
1324
1325     tbl.attach(Gtk::Alignment.new(1, 0.5, 0, 0).add(Gtk::Label.new.set_markup(utf8(_("Preloading distance: ")))),
1326                0, 1, 2, 3, Gtk::FILL, Gtk::SHRINK, 2, 2)
1327     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)),
1328                1, 2, 2, 3, Gtk::FILL, Gtk::SHRINK, 2, 2)
1329     tooltips.set_tip(preload_distance, utf8(_("Amount of pictures preloaded left and right to the currently shown")), nil)
1330
1331     tbl.attach(Gtk::Alignment.new(1, 0.5, 0, 0).add(Gtk::Label.new.set_markup(utf8(_("Cache memory use: ")))),
1332                0, 1, 3, 4, Gtk::FILL, Gtk::SHRINK, 2, 2)
1333     tbl.attach(Gtk::Alignment.new(0, 0.5, 1, 0).add(cache_vbox = Gtk::VBox.new(false, 0)),
1334                1, 2, 3, 4, Gtk::FILL, Gtk::SHRINK, 2, 2)
1335     cache_vbox.pack_start(Gtk::HBox.new(false, 0).pack_start(cache_memfree_radio = Gtk::RadioButton.new(''), false, false).
1336                                                   pack_start(cache_memfree_spin = Gtk::SpinButton.new(0, 100, 10), false, false).
1337                                                   pack_start(cache_memfree_label = Gtk::Label.new(utf8(_("% of free memory"))), false, false), false, false)
1338     cache_memfree_spin.signal_connect('value-changed') { cache_memfree_radio.active = true }
1339     tooltips.set_tip(cache_memfree_spin, utf8(_("Percentage of free memory (+ buffers/cache) measured at startup")), nil)
1340     cache_vbox.pack_start(Gtk::HBox.new(false, 0).pack_start(cache_specify_radio = Gtk::RadioButton.new(cache_memfree_radio, ''), false, false).
1341                                                   pack_start(cache_specify_spin = Gtk::SpinButton.new(0, 4000, 50), false, false).
1342                                                   pack_start(cache_specify_label = Gtk::Label.new(utf8(_("MB"))).set_sensitive(false), false, false), false, false)
1343     cache_specify_spin.signal_connect('value-changed') { cache_specify_radio.active = true }
1344     cache_memfree_radio.signal_connect('toggled') {
1345         if cache_memfree_radio.active?
1346             cache_memfree_label.sensitive = true
1347             cache_specify_label.sensitive = false
1348         else
1349             cache_specify_label.sensitive = true
1350             cache_memfree_label.sensitive = false
1351         end
1352     }
1353     tooltips.set_tip(cache_specify_spin, utf8(_("Amount of memory in megabytes")), nil)
1354     if $config['cache-memory-use'] =~ /memfree_(\d+)/
1355         cache_memfree_spin.value = $1.to_i
1356     else
1357         cache_specify_spin.value = $config['cache-memory-use'].to_i
1358     end
1359
1360 #    tbl.attach(update_exif_orientation_check = Gtk::CheckButton.new(utf8(_("Update file's EXIF orientation when rotating a picture"))),
1361 #               0, 2, 4, 5, Gtk::FILL, Gtk::SHRINK, 2, 2)
1362 #    tooltips.set_tip(update_exif_orientation_check, utf8(_("When rotating a picture (Alt-Right/Left), also update EXIF orientation in the file itself")), nil)
1363 #    update_exif_orientation_check.active = $config['rotate-set-exif']
1364
1365     dialog.vbox.show_all
1366     dialog.run { |response|
1367         if response == Gtk::Dialog::RESPONSE_OK
1368             $config['video-viewer'] = from_utf8(video_viewer_entry.text)
1369             $config['browser'] = from_utf8(browser_entry.text)
1370             $config['preload-distance'] = preload_distance.value
1371 #            $config['rotate-set-exif'] = update_exif_orientation_check.active?
1372             if cache_memfree_radio.active?
1373                 $config['cache-memory-use'] = "memfree_#{cache_memfree_spin.value}%"
1374             else
1375                 $config['cache-memory-use'] = cache_specify_spin.value
1376             end
1377             set_cache_memory_use_figure
1378         end
1379     }
1380     dialog.destroy
1381 end
1382
1383 def perform_undo
1384     if $undo_mb.sensitive?
1385         $redo_mb.sensitive = true
1386         if not more_undoes = UndoHandler.undo($statusbar)
1387             $undo_mb.sensitive = false
1388         end
1389     end
1390 end
1391
1392 def perform_redo
1393     if $redo_mb.sensitive?
1394         $undo_mb.sensitive = true
1395         if not more_redoes = UndoHandler.redo($statusbar)
1396             $redo_mb.sensitive = false
1397         end
1398     end
1399 end
1400
1401 def create_menubar    
1402     #- menu
1403     mb = Gtk::MenuBar.new
1404
1405     filemenu = Gtk::MenuItem.new(utf8(_("_File")))
1406     filesubmenu = Gtk::Menu.new
1407     filesubmenu.append(open      = Gtk::ImageMenuItem.new(Gtk::Stock::OPEN))
1408     filesubmenu.append(            Gtk::SeparatorMenuItem.new)
1409     filesubmenu.append($execute  = Gtk::ImageMenuItem.new(Gtk::Stock::EXECUTE).set_sensitive(false))
1410     filesubmenu.append(            Gtk::SeparatorMenuItem.new)
1411     filesubmenu.append(quit      = Gtk::ImageMenuItem.new(Gtk::Stock::QUIT))
1412     filemenu.set_submenu(filesubmenu)
1413     mb.append(filemenu)
1414
1415     open.signal_connect('activate') { open_dir_popup }
1416     $execute.signal_connect('activate') { execute }
1417     quit.signal_connect('activate') { try_quit }
1418
1419     editmenu = Gtk::MenuItem.new(utf8(_("_Edit")))
1420     editsubmenu = Gtk::Menu.new
1421     editsubmenu.append($undo_mb    = Gtk::ImageMenuItem.new(Gtk::Stock::UNDO).set_sensitive(false))
1422     editsubmenu.append($redo_mb    = Gtk::ImageMenuItem.new(Gtk::Stock::REDO).set_sensitive(false))
1423     editsubmenu.append(              Gtk::SeparatorMenuItem.new)
1424     editsubmenu.append(prefs       = Gtk::ImageMenuItem.new(Gtk::Stock::PREFERENCES))
1425     editmenu.set_submenu(editsubmenu)
1426     mb.append(editmenu)
1427
1428     $undo_mb.signal_connect('activate') { perform_undo }
1429     $redo_mb.signal_connect('activate') { perform_redo }
1430     prefs.signal_connect('activate') { preferences }
1431     
1432     helpmenu = Gtk::MenuItem.new(utf8(_("_Help")))
1433     helpsubmenu = Gtk::Menu.new
1434     helpsubmenu.append(tutos = Gtk::ImageMenuItem.new(utf8(_("Online tutorials (opens a web-browser)"))))
1435     tutos.image = Gtk::Image.new("#{$FPATH}/images/stock-web-16.png")
1436     helpsubmenu.append(Gtk::SeparatorMenuItem.new)
1437     helpsubmenu.append(about = Gtk::ImageMenuItem.new(Gtk::Stock::ABOUT))
1438     helpmenu.set_submenu(helpsubmenu)
1439     mb.append(helpmenu)
1440
1441     tutos.signal_connect('activate') { open_url('http://booh.org/tutorial.html') }
1442     about.signal_connect('activate') { call_about }
1443
1444
1445     #- no toolbar, to save height
1446
1447     return mb
1448 end
1449
1450 def reset_labels
1451     for child in $labels_vbox.children
1452         $labels_vbox.remove(child)
1453     end
1454     $labels_vbox.pack_start(Gtk::Label.new(utf8(_("Labels list:"))).set_justify(Gtk::Justification::CENTER), false, false).show_all
1455     $labels = {}
1456     lbl = Gtk::Label.new.set_markup(utf8(_("<i>unlabelled</i>")))
1457     $labels_vbox.pack_start($unlabelled_button = Gtk::CheckButton.new.add(Gtk::EventBox.new.add(lbl)).show_all)
1458     $unlabelled_button.active = true
1459     $unlabelled_button.signal_connect('toggled') { update_all_visibilities }
1460     lbl = Gtk::Label.new.set_markup(utf8(_("<i>to remove</i>")))
1461     $labels_vbox.pack_start($toremove_button = Gtk::CheckButton.new.add(evt = Gtk::EventBox.new.add(lbl)).show_all)
1462     $toremove_button.active = true
1463     $toremove_button.signal_connect('toggled') { update_all_visibilities }
1464     evt.modify_bg(Gtk::StateType::NORMAL, $color_red)
1465     evt.modify_bg(Gtk::StateType::PRELIGHT, $color_red.lighter.lighter)
1466     evt.modify_bg(Gtk::StateType::ACTIVE, $color_red.lighter)
1467 end
1468
1469 def reset_thumbnails
1470     $allentries = []
1471     for child in $imagesline.children
1472         $imagesline.remove(child)
1473     end
1474 end
1475
1476 def create_main_window
1477
1478     $videoborder_pixbuf = Gdk::Pixbuf.new("#{$FPATH}/images/video_border.png")
1479     $videoborder_pixmap, = $videoborder_pixbuf.render_pixmap_and_mask(0)
1480
1481     mb = create_menubar
1482
1483     main_vbox = Gtk::VBox.new(false, 0)
1484     main_vbox.pack_start(mb, false, false)
1485     mainview_hbox = Gtk::HBox.new
1486     mainview_hbox.pack_start(Gtk::Alignment.new(0.5, 0, 0, 0).add($labels_vbox = Gtk::VBox.new(false, 5)), false, true)
1487     reset_labels
1488     mainview_hbox.pack_start($mainview = MainView.new, true, true)
1489     main_vbox.pack_start(mainview_hbox, true, true)
1490     $imagesline_sw = Gtk::ScrolledWindow.new(nil, nil)
1491     $imagesline_sw.set_policy(Gtk::POLICY_ALWAYS, Gtk::POLICY_NEVER)
1492     $imagesline_sw.add_with_viewport($imagesline = Gtk::HBox.new(false, 0).show)
1493     main_vbox.pack_start($imagesline_sw, false, false)
1494     main_vbox.pack_end($statusbar = Gtk::Statusbar.new, false, false)
1495
1496     $imagesline.set_size_request(-1, Gtk::Button.new.size_request[1] + Entry.thumbnails_height + 15)
1497
1498     $main_window = Gtk::Window.new
1499     $main_window.add(main_vbox)
1500     $main_window.signal_connect('delete-event') {
1501         try_quit({ :disallow_cancel => true })
1502     }
1503
1504     #- read/save size and position of window
1505     if $config['pos-x'] && $config['pos-y']
1506         $main_window.move($config['pos-x'].to_i, $config['pos-y'].to_i)
1507     else
1508         $main_window.window_position = Gtk::Window::POS_CENTER
1509     end
1510     msg 3, "size: #{$config['width']}x#{$config['height']}"
1511     $main_window.set_default_size(($config['width'] || 700).to_i, ($config['height'] || 600).to_i)
1512     $main_window.signal_connect('configure-event') {
1513         msg 3, "configure: pos: #{$main_window.window.root_origin.inspect} size: #{$main_window.window.size.inspect}"
1514         x, y = $main_window.window.root_origin
1515         width, height = $main_window.window.size
1516         $config['pos-x'] = x
1517         $config['pos-y'] = y
1518         $config['width'] = width
1519         $config['height'] = height
1520         false
1521     }
1522
1523     $protect_gtk_pending_calls = Mutex.new
1524     $gtk_pending_calls = []
1525     Gtk.timeout_add(50) {
1526         gtk_thread_flush
1527         true
1528     }
1529
1530     $main_window.show_all
1531 end
1532
1533
1534 handle_options
1535 Thread.abort_on_exception = true
1536 read_config
1537 Gtk.init
1538
1539
1540 create_main_window
1541 check_config
1542
1543 if ARGV[0]
1544     open_dir(ARGV[0])
1545 end
1546 Gtk.main
1547
1548 write_config