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