85abed92982bf93f875b903b91a1bdca29bbf204
[booh] / bin / booh-gui
1 #!/usredo/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 Guillaume Cottenceau <gc3 at bluewin.ch>
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., 675 Mass Ave, Cambridge, MA 02139, USA.
21
22 require 'getoptlong'
23 require 'tempfile'
24
25 require 'gtk2'
26 require 'booh/GtkAutoTable'
27
28 require 'gettext'
29 include GetText
30 bindtextdomain("booh")
31
32 require 'rexml/document'
33 include REXML
34
35 require 'booh/booh-lib'
36 include Booh
37 require 'booh/UndoHandler'
38
39
40 #- options
41 $options = [
42     [ '--help',          '-h', GetoptLong::NO_ARGUMENT,       _("Get help message") ],
43
44     [ '--verbose-level', '-v', GetoptLong::REQUIRED_ARGUMENT, _("Set max verbosity level (0: errors, 1: warnings, 2: important messages, 3: other messages)") ],
45 ]
46
47 def usage
48     puts _("Usage: %s [OPTION]...") % File.basename($0)
49     $options.each { |ary|
50         printf " %3s, %-15s %s\n", ary[1], ary[0], ary[3]
51     }
52 end
53
54 def handle_options
55     parser = GetoptLong.new
56     parser.set_options(*$options.collect { |ary| ary[0..2] })
57     begin
58         parser.each_option do |name, arg|
59             case name
60             when '--help'
61                 usage
62                 exit(0)
63
64             when '--verbose-level'
65                 $verbose_level = arg.to_i
66
67             end
68         end
69     rescue
70         puts $!
71         usage
72         exit(1)
73     end
74 end
75
76 def read_config
77     $config = {}
78     $config_file = File.expand_path('~/.booh-gui-rc')
79     if File.readable?($config_file)
80         $xmldoc = REXML::Document.new(File.new($config_file))
81         $xmldoc.root.elements.each { |element|
82             txt = element.get_text
83             if txt 
84                 if txt.value =~ /~~~/ || element.name == 'last-opens'
85                     $config[element.name] = txt.value.split(/~~~/)
86                 else
87                     $config[element.name] = txt.value
88                 end
89             else
90                 $config[element.name] = {}
91                 element.each { |chld|
92                     txt = chld.get_text
93                     $config[element.name][chld.name] = txt ? txt.value : nil
94                 }
95             end
96         }
97     end
98     if !FileTest.directory?(File.expand_path('~/.booh'))
99         system("mkdir ~/.booh")
100     end
101 end
102
103 def write_config
104     if $config['last-opens'] && $config['last-opens'].size > 5
105         $config['last-opens'] = $config['last-opens'][-5, 5]
106     end
107
108     ios = File.open($config_file, "w")
109     $xmldoc = Document.new "<booh-gui-rc version='#{$VERSION}'/>"
110     $xmldoc << XMLDecl.new(XMLDecl::DEFAULT_VERSION, $CURRENT_CHARSET)
111     $config.each_pair { |key, value|
112         elem = $xmldoc.root.add_element key
113         if value.is_a? Hash
114             $config[key].each_pair { |subkey, subvalue|
115                 subelem = elem.add_element subkey
116                 subelem.add_text subvalue.to_s
117             }
118         elsif value.is_a? Array
119             elem.add_text value.join('~~~')
120         else
121             elem.add_text value.to_s
122         end
123     }
124     $xmldoc.write(ios, 0)
125     ios.close
126 end
127
128 def set_mousecursor(what, *widget)
129     if widget[0] && widget[0].window
130         widget[0].window.set_cursor(Gdk::Cursor.new(what))
131     end
132     if $main_window.window
133         $main_window.window.set_cursor(Gdk::Cursor.new(what))
134     end
135     $current_cursor = what
136 end
137 def set_mousecursor_wait(*widget)
138     set_mousecursor(Gdk::Cursor::WATCH, *widget)
139     if Thread.current == Thread.main
140         Gtk.main_iteration while Gtk.events_pending?
141     end
142 end
143 def set_mousecursor_normal(*widget)
144     set_mousecursor(Gdk::Cursor::LEFT_PTR, *widget)
145 end
146 def push_mousecursor_wait(*widget)
147     if $current_cursor != Gdk::Cursor::WATCH
148         $save_cursor = $current_cursor
149         set_mousecursor_wait(*widget)
150     end
151 end
152 def pop_mousecursor(*widget)
153     set_mousecursor($save_cursor || Gdk::Cursor::LEFT_PTR, *widget)
154 end
155
156 def current_dest_dir
157     source = $xmldoc.root.attributes['source']
158     dest = $xmldoc.root.attributes['destination']
159     return make_dest_filename(from_utf8($current_path).sub(/^#{Regexp.quote(source)}/, dest))
160 end
161
162 def build_full_dest_filename(filename)
163     return current_dest_dir + '/' + make_dest_filename(from_utf8(filename))
164 end
165
166 def save_undo(name, closure, *params)
167     UndoHandler.save_undo(name, closure, [ *params ])
168     $undo_tb.sensitive = $undo_mb.sensitive = true
169 end
170
171 def view_element(filename)
172     if entry2type(filename) == 'video'
173         system("mplayer #{$current_path + '/' + filename}")
174         return
175     end
176
177     w = Gtk::Window.new
178
179     msg 3, "filename: #{filename}"
180     dest_img = build_full_dest_filename(filename).sub(/\.[^\.]+$/, '') + "-#{$default_size['fullscreen']}.jpg"
181     #- typically this file won't exist in case of videos; try with the largest thumbnail around
182     if !File.exists?(dest_img)
183         if entry2type(filename) == 'video'
184             alternatives = Dir[build_full_dest_filename(filename).sub(/\.[^\.]+$/, '') + '-*'].sort
185             if not alternatives.empty?
186                 dest_img = alternatives[-1]
187             end
188         else
189             push_mousecursor_wait
190             gen_thumbnails_element(from_utf8("#{$current_path}/#{filename}"), $xmldir, false, [ { 'filename' => dest_img, 'size' => $default_size['fullscreen'] } ])
191             pop_mousecursor
192             if !File.exists?(dest_img)
193                 msg 2, _("Could not generate fullscreen thumbnail!")
194                 return
195                 end
196         end
197     end
198     evt = Gtk::EventBox.new.add(Gtk::Alignment.new(0.5, 0.5, 0, 0).add(Gtk::Frame.new.add(Gtk::Image.new(dest_img)).set_shadow_type(Gtk::SHADOW_ETCHED_OUT)))
199
200     tooltips = Gtk::Tooltips.new
201     tooltips.set_tip(evt, utf8(File.basename(filename).gsub(/\.jpg/, '')), nil)
202
203     bottom = Gtk::Alignment.new(0.5, 0.5, 0, 0).add(b = Gtk::Button.new(Gtk::Stock::CLOSE))
204     b.signal_connect('clicked') { w.destroy }
205
206     vb = Gtk::VBox.new
207     vb.pack_start(evt, false, false)
208     vb.pack_end(bottom, false, false)
209
210     w.add(vb)
211     w.signal_connect('delete-event') { w.destroy }
212     w.window_position = Gtk::Window::POS_CENTER
213     w.show_all
214 end
215
216 def create_editzone(scrolledwindow, pagenum)
217     frame = Gtk::Frame.new
218     frame.add(textview = Gtk::TextView.new.set_wrap_mode(Gtk::TextTag::WRAP_WORD))
219     frame.set_shadow_type(Gtk::SHADOW_IN)
220     textview.signal_connect('key-press-event') { |w, event|
221         textview.set_editable(event.keyval != Gdk::Keyval::GDK_Tab)
222         if event.keyval == Gdk::Keyval::GDK_Page_Up || event.keyval == Gdk::Keyval::GDK_Page_Down
223             scrolledwindow.signal_emit('key-press-event', event)
224         end
225         false  #- propagate
226     }
227     textview.signal_connect('focus-in-event') { |w, event|
228         textview.buffer.select_range(textview.buffer.get_iter_at_offset(0), textview.buffer.get_iter_at_offset(-1))
229         false  #- propagate
230     }
231
232     candidate_undo_text = nil
233     textview.signal_connect('focus-in-event') { |w, event|
234         candidate_undo_text = textview.buffer.text
235         false  #- propagate
236     }
237     textview.signal_connect('key-release-event') { |w, event|
238         if candidate_undo_text && candidate_undo_text != textview.buffer.text
239             $modified = true
240             save_undo(_("text edit"),
241                       Proc.new { |text|
242                           save_text = textview.buffer.text
243                           textview.buffer.text = text
244                           textview.grab_focus
245                           $notebook.set_page(pagenum)
246                           Proc.new {
247                               textview.buffer.text = save_text
248                               textview.grab_focus
249                               $notebook.set_page(pagenum)
250                           }
251                       }, candidate_undo_text)
252             candidate_undo_text = nil
253         end
254         false  #- propagate
255     }
256
257     return [ frame, textview ]
258 end
259
260 def rotate_real(angle, thumbnail_img, img, xmlelem, attributes_prefix, desired_x, desired_y)
261     $modified = true
262
263     #- update rotate attribute
264     xmlelem.add_attribute("#{attributes_prefix}rotate", current_angle = ( xmlelem.attributes["#{attributes_prefix}rotate"].to_i + angle ) % 360)
265
266     if !$rotated_pixbufs[thumbnail_img]
267         $rotated_pixbufs[thumbnail_img] = { :orig => img.pixbuf, :angle_to_orig => angle % 360 }
268     else
269         $rotated_pixbufs[thumbnail_img][:angle_to_orig] = ( $rotated_pixbufs[thumbnail_img][:angle_to_orig] + angle ) % 360
270     end
271     msg 3, "angle: #{angle}, angle to orig: #{$rotated_pixbufs[thumbnail_img][:angle_to_orig]}"
272
273     #- rotate shown thumbnail
274     pixbuf = rotate_pixbuf($rotated_pixbufs[thumbnail_img][:orig], $rotated_pixbufs[thumbnail_img][:angle_to_orig])
275     msg 3, "sizes: #{pixbuf.width} #{pixbuf.height} - desired #{desired_x}x#{desired_x}"
276     if pixbuf.height > desired_y
277         img.pixbuf = $rotated_pixbufs[thumbnail_img][:pixbuf] = pixbuf.scale(pixbuf.width * (desired_y.to_f/pixbuf.height), desired_y,
278                                                                              Gdk::Pixbuf::INTERP_BILINEAR)
279     elsif pixbuf.width < desired_x && pixbuf.height < desired_y
280         img.pixbuf = $rotated_pixbufs[thumbnail_img][:pixbuf] = pixbuf.scale(desired_x, pixbuf.height * (desired_x.to_f/pixbuf.width),
281                                                                              Gdk::Pixbuf::INTERP_BILINEAR)
282     else
283         img.pixbuf = $rotated_pixbufs[thumbnail_img][:pixbuf] = pixbuf
284     end
285 end
286
287 def rotate(angle, thumbnail_img, img, xmlelem, attributes_prefix, desired_x, desired_y)
288     $modified = true
289
290     rotate_real(angle, thumbnail_img, img, xmlelem, attributes_prefix, desired_x, desired_y)
291
292     save_undo(angle == 90 ? _("rotate clockwise") : angle == -90 ? _("rotate counter-clockwise") : _("flip upside-down"),
293               Proc.new { |angle|
294                   rotate_real(angle, thumbnail_img, img, xmlelem, attributes_prefix, desired_x, desired_y)
295                   $notebook.set_page(attributes_prefix != '' ? 0 : 1)
296                   Proc.new {
297                       rotate_real(-angle, thumbnail_img, img, xmlelem, attributes_prefix, desired_x, desired_y)
298                       $notebook.set_page(0)
299                       $notebook.set_page(attributes_prefix != '' ? 0 : 1)
300                   }
301               }, -angle)
302 end
303
304 def color_swap(xmldir, attributes_prefix)
305     $modified = true
306     if xmldir.attributes["#{attributes_prefix}color-swap"]
307         xmldir.delete_attribute("#{attributes_prefix}color-swap")
308     else
309         xmldir.add_attribute("#{attributes_prefix}color-swap", '1')
310     end
311 end
312
313 def enhance(xmldir, attributes_prefix)
314     $modified = true
315     if xmldir.attributes["#{attributes_prefix}enhance"]
316         xmldir.delete_attribute("#{attributes_prefix}enhance")
317     else
318         xmldir.add_attribute("#{attributes_prefix}enhance", '1')
319     end
320 end
321
322 def change_frame_offset(xmldir, attributes_prefix, value)
323     $modified = true
324     xmldir.add_attribute("#{attributes_prefix}frame-offset", value)
325 end
326
327 def ask_new_frame_offset(xmldir, attributes_prefix)
328     value = xmldir.attributes["#{attributes_prefix}frame-offset"]
329
330     dialog = Gtk::Dialog.new(utf8(_("Change frame offset")),
331                              $main_window,
332                              Gtk::Dialog::MODAL | Gtk::Dialog::DESTROY_WITH_PARENT,
333                              [Gtk::Stock::OK, Gtk::Dialog::RESPONSE_OK],
334                              [Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL])
335
336     lbl = Gtk::Label.new
337     lbl.markup = utf8(
338 _("Please specify the <b>frame offset</b> of the video, to take the thumbnail
339 from. There are approximately 25 frames per second in a video.
340 "))
341     dialog.vbox.add(lbl)
342     dialog.vbox.add(entry = Gtk::Entry.new.set_text(value))
343     entry.signal_connect('key-press-event') { |w, event|
344         if event.keyval == Gdk::Keyval::GDK_Return
345             dialog.response(Gtk::Dialog::RESPONSE_OK)
346             true
347         elsif event.keyval == Gdk::Keyval::GDK_Escape
348             dialog.response(Gtk::Dialog::RESPONSE_CANCEL)
349             true
350         else
351             false  #- propagate if needed
352         end
353     }
354     
355     dialog.window_position = Gtk::Window::POS_MOUSE
356     dialog.show_all
357
358     dialog.run { |response|
359         $modified = true
360         newval = entry.text
361         dialog.destroy
362         if response == Gtk::Dialog::RESPONSE_OK
363             msg 3, "changing frame offset top #{newval}"
364             return { :old => value, :new => newval }
365         else
366             return nil
367         end
368     }
369 end
370
371 def gen_real_thumbnail(type, origfile, destfile, xmldir, size, img)
372     Thread.new {
373         push_mousecursor_wait
374         system("rm -f '#{destfile}'")
375         #- type can be 'element' or 'subdir'
376         if type == 'element'
377             gen_thumbnails_element(origfile, xmldir, false, [ { 'filename' => destfile, 'size' => size } ])
378         else
379             gen_thumbnails_subdir(origfile, xmldir, false, [ { 'filename' => destfile, 'size' => size } ], find_subalbum_info_type(xmldir))
380         end
381         img.set(destfile)
382         $rotated_pixbufs[destfile] = { :orig => img.pixbuf, :pixbuf => img.pixbuf, :angle_to_orig => 0 }
383         if entry2type(origfile) == 'video'
384             #- cleanup temp for videos
385             system("rm -f #{current_dest_dir}/screenshot.jpg000000.jpg")
386         end
387         pop_mousecursor
388     }
389 end
390
391 def popup_thumbnail_menu(event, optionals, type, xmldir, attributes_prefix, closures)
392     menu = Gtk::Menu.new
393     if optionals.include?('change_image')
394         menu.append(changeimg = Gtk::ImageMenuItem.new(utf8(_("Change image"))))
395         changeimg.image = Gtk::Image.new("#{$FPATH}/images/stock-images-16.png")
396         changeimg.signal_connect('activate') { closures[:change].call }
397         menu.append(            Gtk::SeparatorMenuItem.new)
398     end
399     menu.append(    r90 = Gtk::ImageMenuItem.new(utf8(_("Rotate clockwise"))))
400     r90.image = Gtk::Image.new("#{$FPATH}/images/stock-rotate-90-16.png")
401     r90.signal_connect('activate') { closures[:rotate].call(90) }
402     menu.append(   r270 = Gtk::ImageMenuItem.new(utf8(_("Rotate counter-clockwise"))))
403     r270.image = Gtk::Image.new("#{$FPATH}/images/stock-rotate-270-16.png")
404     r270.signal_connect('activate') { closures[:rotate].call(-90) }
405     if type == 'video'
406         menu.append(               Gtk::SeparatorMenuItem.new)
407         menu.append(  color_swap = Gtk::ImageMenuItem.new(utf8(_("Red/blue color swap"))))
408         color_swap.image = Gtk::Image.new("#{$FPATH}/images/stock-color-triangle-16.png")
409         color_swap.signal_connect('activate') { closures[:color_swap].call }
410         menu.append(        flip = Gtk::ImageMenuItem.new(utf8(_("Flip upside-down"))))
411         flip.image = Gtk::Image.new("#{$FPATH}/images/stock-rotate-180-16.png")
412         flip.signal_connect('activate') { closures[:rotate].call(180) }
413         menu.append(frame_offset = Gtk::ImageMenuItem.new(utf8(_("Specify frame offset"))))
414         frame_offset.image = Gtk::Image.new("#{$FPATH}/images/stock-video-16.png")
415         frame_offset.signal_connect('activate') { closures[:frame_offset].call }
416     end
417     menu.append(               Gtk::SeparatorMenuItem.new)
418     menu.append(enhance      = Gtk::ImageMenuItem.new(utf8(xmldir.attributes["#{attributes_prefix}enhance"] ? _("Original contrast") :
419                                                                                                               _("Enhance constrast"))))
420     enhance.image = Gtk::Image.new("#{$FPATH}/images/stock-channels-16.png")
421     enhance.signal_connect('activate') { closures[:enhance].call }
422     if optionals.include?('delete')
423         menu.append(               Gtk::SeparatorMenuItem.new)
424         menu.append(delete_item  = Gtk::ImageMenuItem.new(Gtk::Stock::DELETE))
425         delete_item.signal_connect('activate') { closures[:delete].call }
426     end
427     menu.show_all
428     menu.popup(nil, nil, event.button, event.time)
429 end
430
431 def add_thumbnail(autotable, filename, type, thumbnail_img, caption)
432
433     img = nil
434     frame1 = Gtk::Frame.new
435
436     my_gen_real_thumbnail = proc {
437         gen_real_thumbnail('element', from_utf8("#{$current_path}/#{filename}"), thumbnail_img, $xmldir, $default_size['thumbnails'], img)
438     }
439
440     #- generate the thumbnail if missing (if image was rotated but booh was not relaunched)
441     if !$rotated_pixbufs[thumbnail_img] && !File.exists?(thumbnail_img)
442         frame1.add(img = Gtk::Image.new)
443         my_gen_real_thumbnail.call
444     else
445         frame1.add(img = Gtk::Image.new($rotated_pixbufs[thumbnail_img] ? $rotated_pixbufs[thumbnail_img][:pixbuf] : thumbnail_img))
446     end
447     evtbox = Gtk::EventBox.new.add(Gtk::Alignment.new(0.5, 0.5, 0, 0).add(frame1.set_shadow_type(Gtk::SHADOW_ETCHED_OUT)))
448
449     tooltips = Gtk::Tooltips.new
450     tipname = File.basename(thumbnail_img).gsub(/-\d+x\d+\.jpg/, '')
451     tooltips.set_tip(evtbox, utf8(type == 'video' ? (_("%s (video - %s KB)") % [tipname, commify(File.size(from_utf8("#{$current_path}/#{filename}"))/1024)]) : tipname), nil)
452
453     frame2, textview = create_editzone($autotable_sw, 1)
454     textview.buffer.text = utf8(caption)
455     textview.set_justification(Gtk::Justification::CENTER)
456
457     vbox = Gtk::VBox.new(false, 5)
458     vbox.pack_start(evtbox, false, false)
459     vbox.pack_start(frame2, false, false)
460     autotable.append(vbox, filename)
461
462     #- to be able to grab focus of textview when retrieving vbox's position from AutoTable
463     $vbox2textview[vbox] = textview
464
465     #- to be able to find widgets by name
466     $name2widgets[filename] = { :textview => textview }
467
468     cleanup_all_thumbnails = Proc.new {
469         #- remove out of sync images
470         dest_img_base = build_full_dest_filename(filename).sub(/\.[^\.]+$/, '')
471         for sizeobj in $images_size
472             system("rm -f #{dest_img_base}-#{sizeobj['fullscreen']}.jpg #{dest_img_base}-#{sizeobj['thumbnails']}.jpg")
473         end
474
475     }
476
477     rotate_and_cleanup = Proc.new { |angle|
478         rotate(angle, thumbnail_img, img, $xmldir.elements["[@filename='#{filename}']"], '', $default_thumbnails[:x], $default_thumbnails[:y])
479         cleanup_all_thumbnails.call
480     }
481
482     color_swap_and_cleanup = Proc.new {
483         perform_color_swap_and_cleanup = Proc.new {
484             color_swap($xmldir.elements["[@filename='#{filename}']"], '')
485             my_gen_real_thumbnail.call
486         }
487
488         cleanup_all_thumbnails.call
489         perform_color_swap_and_cleanup.call
490
491         save_undo(_("color swap"),
492                   Proc.new {
493                       perform_color_swap_and_cleanup.call
494                       $notebook.set_page(1)
495                       Proc.new {
496                           perform_color_swap_and_cleanup.call
497                           $notebook.set_page(1)
498                       }
499                   })
500     }
501
502     change_frame_offset_and_cleanup = Proc.new {
503         if values = ask_new_frame_offset($xmldir.elements["[@filename='#{filename}']"], '')
504             perform_change_frame_offset_and_cleanup = Proc.new { |val|
505                 change_frame_offset($xmldir.elements["[@filename='#{filename}']"], '', val)
506                 my_gen_real_thumbnail.call
507             }
508             perform_change_frame_offset_and_cleanup.call(values[:new])
509
510             save_undo(_("specify frame offset"),
511                       Proc.new {
512                           perform_change_frame_offset_and_cleanup.call(values[:old])
513                           $notebook.set_page(1)
514                           Proc.new {
515                               perform_change_frame_offset_and_cleanup.call(values[:new])
516                               $notebook.set_page(1)
517                           }
518                       })
519         end
520     }
521
522     enhance_and_cleanup = Proc.new {
523         perform_enhance_and_cleanup = Proc.new {
524             enhance($xmldir.elements["[@filename='#{filename}']"], '')
525             my_gen_real_thumbnail.call
526         }
527
528         cleanup_all_thumbnails.call
529         perform_enhance_and_cleanup.call
530
531         save_undo(_("enhance"),
532                   Proc.new {
533                       perform_enhance_and_cleanup.call
534                       $notebook.set_page(1)
535                       Proc.new {
536                           perform_enhance_and_cleanup.call
537                           $notebook.set_page(1)
538                       }
539                   })
540     }
541
542     delete = Proc.new {
543         $modified = true
544         perform_delete = Proc.new {
545             after = autotable.get_next_widget(vbox)
546             if !after
547                 after = autotable.get_previous_widget(vbox)
548             end
549             autotable.remove(vbox)
550             if after
551                 $vbox2textview[after].grab_focus
552             end
553         }
554
555         save_undo(_("delete"),
556                   Proc.new { |pos|
557                       autotable.reinsert(pos, vbox, filename)
558                       $notebook.set_page(1)
559                       Proc.new {
560                           perform_delete.call
561                           $notebook.set_page(1)
562                       }
563                   }, autotable.get_current_number(vbox))
564
565         perform_delete.call
566     }
567
568     textview.signal_connect('key-press-event') { |w, event|
569         propagate = true
570         if event.keyval == Gdk::Keyval::GDK_Page_Up || event.keyval == Gdk::Keyval::GDK_Page_Down
571             $autotable_sw.signal_emit('key-press-event', event)
572         end
573         if event.state != 0
574             x, y = autotable.get_current_pos(vbox)
575             control_pressed = event.state & Gdk::Window::CONTROL_MASK != 0
576             shift_pressed = event.state & Gdk::Window::SHIFT_MASK != 0
577             alt_pressed = event.state & Gdk::Window::MOD1_MASK != 0
578             if event.keyval == Gdk::Keyval::GDK_Up && y > 0
579                 if control_pressed
580                     $vbox2textview[autotable.get_widget_at_pos(x, y - 1)].grab_focus
581                 end
582                 if shift_pressed
583                     autotable.move_up(vbox)
584                     textview.grab_focus  #- because if moving, focus is stolen
585                 end
586             end
587             if event.keyval == Gdk::Keyval::GDK_Down && y < autotable.get_max_y
588                 if control_pressed
589                     $vbox2textview[autotable.get_widget_at_pos(x, y + 1)].grab_focus
590                 end
591                 if shift_pressed
592                     autotable.move_down(vbox)
593                     textview.grab_focus  #- because if moving, focus is stolen
594                 end
595             end
596             if event.keyval == Gdk::Keyval::GDK_Left
597                 previous = autotable.get_previous_widget(vbox)
598                 if previous && autotable.get_current_pos(previous)[0] < x
599                     if control_pressed
600                         $vbox2textview[previous].grab_focus
601                     end
602                     if shift_pressed
603                         autotable.move_left(vbox)
604                         textview.grab_focus  #- because if moving, focus is stolen
605                     end
606                 end
607                 if alt_pressed
608                     rotate_and_cleanup.call(-90)
609                 end
610             end
611             if event.keyval == Gdk::Keyval::GDK_Right
612                 next_ = autotable.get_next_widget(vbox)
613                 if next_ && autotable.get_current_pos(next_)[0] > x
614                     if control_pressed
615                         $vbox2textview[next_].grab_focus
616                     end
617                     if shift_pressed
618                         autotable.move_right(vbox)
619                         textview.grab_focus  #- because if moving, focus is stolen
620                     end
621                 end
622                 if alt_pressed
623                     rotate_and_cleanup.call(90)
624                 end
625             end
626             if event.keyval == Gdk::Keyval::GDK_Delete && control_pressed
627                 delete.call
628             end
629             if event.keyval == Gdk::Keyval::GDK_Return && control_pressed
630                 view_element(filename)
631                 propagate = false
632             end
633         end
634         !propagate  #- propagate if needed
635     }
636
637     evtbox.signal_connect('button-press-event') { |w, event|
638         retval = true
639         if event.event_type == Gdk::Event::BUTTON_PRESS && event.button == 1
640             if $r90.active?
641                 rotate_and_cleanup.call(90)
642             elsif $r270.active?
643                 rotate_and_cleanup.call(-90)
644             elsif $enhance.active?
645                 enhance_and_cleanup.call
646             elsif $delete.active?
647                 delete.call
648             else
649                 textview.grab_focus
650             end
651         end
652         if event.event_type == Gdk::Event::BUTTON_PRESS && event.button == 3
653             popup_thumbnail_menu(event, ['delete'], type, $xmldir.elements["[@filename='#{filename}']"], '',
654                                  { :rotate => rotate_and_cleanup, :color_swap => color_swap_and_cleanup, :enhance => enhance_and_cleanup,
655                                    :frame_offset => change_frame_offset_and_cleanup, :delete => delete })
656         end
657         if event.event_type == Gdk::Event::BUTTON2_PRESS && event.button == 1
658             view_element(filename)
659         else
660             retval = false  #- propagate
661         end
662         retval
663     }
664
665     vbox.signal_connect('button-press-event') { |w, event|
666         if event.event_type == Gdk::Event::BUTTON_PRESS && event.button == 1
667             $gesture_press = { :filename => filename, :x => event.x, :y => event.y }
668         end
669         false
670     }
671     vbox.signal_connect('drag-data-received') { |w, ctxt, x, y, selection_data, info, time|
672         if $gesture_press && $gesture_press[:filename] == filename
673             if (($gesture_press[:x]-x)/($gesture_press[:y]-y)).abs > 2 && ($gesture_press[:x]-x).abs > 5
674                 angle = x-$gesture_press[:x] > 0 ? 90 : -90
675                 msg 3, "gesture rotate: #{angle}"
676                 rotate_and_cleanup.call(angle)
677             end
678         end
679         $gesture_press = nil
680     }
681
682     #- handle reordering with drag and drop
683     Gtk::Drag.source_set(vbox, Gdk::Window::BUTTON1_MASK, [['reorder-elements', Gtk::Drag::TARGET_SAME_APP, 1]], Gdk::DragContext::ACTION_MOVE)
684     Gtk::Drag.dest_set(vbox, Gtk::Drag::DEST_DEFAULT_ALL, [['reorder-elements', Gtk::Drag::TARGET_SAME_APP, 1]], Gdk::DragContext::ACTION_MOVE)
685     vbox.signal_connect('drag-data-get') { |w, ctxt, selection_data, info, time|
686         selection_data.set(Gdk::Selection::TYPE_STRING, autotable.get_current_number(vbox).to_s)
687     }
688     vbox.signal_connect('drag-data-received') { |w, ctxt, x, y, selection_data, info, time|
689         ctxt.targets.each { |target|
690             if target.name == 'reorder-elements'
691                 from, to = selection_data.data.to_i, autotable.get_current_number(vbox)
692                 if from != to
693                     $modified = true
694                     autotable.move(from, to)
695                     save_undo(_("reorder"),
696                               Proc.new { |from, to|
697                                   if to > from
698                                       autotable.move(to - 1, from)
699                                   else
700                                       autotable.move(to, from + 1)
701                                   end
702                                   $notebook.set_page(1)
703                                   Proc.new {
704                                       autotable.move(from, to)
705                                       $notebook.set_page(1)
706                                   }
707                               }, from, to)
708                 end
709             end
710         }
711     }
712
713     vbox.show_all
714 end
715
716 def create_auto_table
717
718     $autotable = Gtk::AutoTable.new(5)
719
720     $autotable_sw = Gtk::ScrolledWindow.new(nil, nil)
721     $autotable_sw.set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_ALWAYS)
722     $autotable_sw.add_with_viewport($autotable)
723 end
724
725 def create_subalbums_page
726
727     subalbums_hb = Gtk::HBox.new
728     $subalbums_vb = Gtk::VBox.new(false, 5)
729     subalbums_hb.pack_start($subalbums_vb, false, false)
730     $subalbums_sw = Gtk::ScrolledWindow.new(nil, nil)
731     $subalbums_sw.set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC)
732     $subalbums_sw.add_with_viewport(subalbums_hb)
733 end
734
735 def save_current_file
736     save_changes
737     if $filename
738         ios = File.open($filename, "w")
739         $xmldoc.write(ios, 0)
740         ios.close
741         $modified = false
742     end
743 end
744
745 def try_quit
746     if $modified
747         dialog = Gtk::Dialog.new(utf8(_("Save before quitting?")),
748                                  $main_window,
749                                  Gtk::Dialog::MODAL | Gtk::Dialog::DESTROY_WITH_PARENT,
750                                  [Gtk::Stock::CLOSE, Gtk::Dialog::RESPONSE_NO],
751                                  [Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL],
752                                  [Gtk::Stock::SAVE, Gtk::Dialog::RESPONSE_YES])
753         dialog.vbox.add(Gtk::Label.new(utf8(_("Do you want to save your changes before quitting?"))))
754         dialog.window_position = Gtk::Window::POS_CENTER
755         dialog.show_all
756         
757         dialog.run { |response|
758             dialog.destroy
759             if response == Gtk::Dialog::RESPONSE_CANCEL
760                 return
761             elsif response == Gtk::Dialog::RESPONSE_YES
762                 save_current_file
763             end
764         }
765     end
766
767     Gtk.main_quit
768 end
769
770 def show_popup(parent, msg, *options)
771     dialog = Gtk::Dialog.new
772     dialog.title = utf8(_("Booh message"))
773     lbl = Gtk::Label.new
774     lbl.markup = msg
775     if options[0] && options[0][:centered]
776         lbl.set_justify(Gtk::Justification::CENTER)
777     end
778     dialog.vbox.add(lbl)
779     if options[0] && options[0][:okcancel]
780         dialog.add_button(Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL)
781     end
782     dialog.add_button(Gtk::Stock::OK, Gtk::Dialog::RESPONSE_OK)
783
784     dialog.transient_for = parent
785     dialog.set_default_size(200, 120)
786     if options[0] && options[0][:pos_centered]
787         dialog.window_position = Gtk::Window::POS_CENTER
788     else
789         dialog.window_position = Gtk::Window::POS_MOUSE
790     end
791     dialog.show_all
792
793     dialog.run { |response|
794         dialog.destroy
795         if options[0] && options[0][:okcancel]
796             return response == Gtk::Dialog::RESPONSE_OK
797         end
798     }
799 end
800
801 def wait_message(parent, msg)
802     w = Gtk::Window.new
803     w.set_transient_for(parent)
804     w.modal = true
805
806     vb = Gtk::VBox.new(false, 5)
807     vb.pack_start(Gtk::Label.new(msg), false, false)
808     bottom = Gtk::Alignment.new(0.5, 0.5, 0, 0).add(b = Gtk::Button.new(utf8(_("_Abort"))))
809     b.image = Gtk::Image.new("#{$FPATH}/images/stock-close-24.png")
810     vb.pack_start(pb = Gtk::ProgressBar.new.set_pulse_step(0.05), false, false)
811     vb.pack_start(Gtk::HSeparator.new, false, false)
812     vb.pack_end(bottom, false, false)
813
814     timeout = Gtk.timeout_add(200) { pb.pulse }
815
816     w.add(vb)
817     w.signal_connect('delete-event') { w.destroy }
818     w.signal_connect('destroy') { Gtk.timeout_remove(timeout) }
819     w.window_position = Gtk::Window::POS_CENTER
820     w.show_all
821
822     return [ b, w ]
823 end
824
825 def perform_in_background(cmd, waitmsg, params)
826     button, w8 = wait_message($main_window, waitmsg)
827     pid = nil
828     Thread.new {
829         msg 2, cmd
830         if pid = fork
831             id, exitstatus = Process.waitpid2(pid)
832             w8.destroy
833             if exitstatus == 0
834                 if params[:successmsg]
835                     show_popup($main_window, params[:successmsg])
836                 end
837                 if params[:closure_after]
838                     params[:closure_after].call
839                 end
840             elsif exitstatus == 15
841                 #- say nothing, user aborted
842             else
843                 if params[:failuremsg]
844                     show_popup($main_window, params[:failuremsg])
845                 end
846             end
847         else
848             exec(cmd)
849         end
850     }
851     button.signal_connect('clicked') {
852         Process.kill('SIGTERM', pid)
853     }
854 end
855
856 def save_changes
857     if !$current_path
858         return
859     end
860
861     if $xmldir.elements['dir']
862         $xmldir.add_attribute('subdirs-caption', $subalbums_title.buffer.text)
863         $xmldir.elements.each('dir') { |element|
864             path = element.attributes['path']
865             if element.attributes['subdirs-caption']
866                 element.add_attribute('subdirs-caption',     $subalbums_edits[path][:editzone].buffer.text)
867                 element.add_attribute('subdirs-captionfile', $subalbums_edits[path][:captionfile])
868             else
869                 element.add_attribute('thumbnails-caption',     $subalbums_edits[path][:editzone].buffer.text)
870                 element.add_attribute('thumbnails-captionfile', $subalbums_edits[path][:captionfile])
871             end
872         }
873         if $xmldir.attributes['thumbnails-caption']
874             path = $xmldir.attributes['path']
875             $xmldir.add_attribute('thumbnails-caption', $subalbums_edits[path][:editzone].buffer.text)
876         end
877     end
878
879     #- remove and reinsert elements to reflect new ordering
880     save_attributes = {}
881     save_types = {}
882     $xmldir.elements.each { |element|
883         if element.name == 'image' || element.name == 'video'
884             save_types[element.attributes['filename']] = element.name
885             save_attributes[element.attributes['filename']] = element.attributes
886             element.remove
887         end
888     }
889     $autotable.current_order.each { |path|
890         chld = $xmldir.add_element save_types[path], save_attributes[path]
891         chld.add_attribute('caption', $name2widgets[File.basename(path)][:textview].buffer.text)
892     }
893 end
894
895 def change_dir
896     $autotable.clear
897     $vbox2textview = {}
898     $name2widgets = {}
899     UndoHandler.cleanup
900     $undo_tb.sensitive = $undo_mb.sensitive = false
901     $redo_tb.sensitive = $redo_mb.sensitive = false
902
903     if !$current_path
904         return
905     end
906
907     $subalbums_vb.children.each { |chld|
908         $subalbums_vb.remove(chld)
909     }
910     $subalbums = Gtk::Table.new(0, 0, true)
911     current_y_sub_albums = 0
912
913     $xmldir = $xmldoc.elements["//dir[@path='#{$current_path}']"]
914     $subalbums_edits = {}
915
916     add_subalbum = Proc.new { |xmldir|
917         if xmldir == $xmldir
918             thumbnail_file = "#{current_dest_dir}/thumbnails-thumbnail.jpg"
919             caption = xmldir.attributes['thumbnails-caption']
920             captionfile, dummy = find_subalbum_caption_info(xmldir)
921             infotype = 'thumbnails'
922         else
923             thumbnail_file = "#{current_dest_dir}/thumbnails-#{from_utf8(File.basename(xmldir.attributes['path']))}.jpg"
924             captionfile, caption = find_subalbum_caption_info(xmldir)
925             infotype = find_subalbum_info_type(xmldir)
926         end
927         msg 3, "add subdir: #{xmldir.attributes['path']} with file: #{thumbnail_file}"
928         hbox = Gtk::HBox.new
929         hbox.pack_start(Gtk::Alignment.new(1, 0.5, 0, 0).add(Gtk::Label.new.set_markup('<i>' + File.basename(xmldir.attributes['path']) + ':</i>')))
930         f = Gtk::Frame.new
931         f.set_shadow_type(Gtk::SHADOW_ETCHED_OUT)
932
933         img = nil
934         my_gen_real_thumbnail = proc {
935             gen_real_thumbnail('subdir', from_utf8(captionfile), thumbnail_file, xmldir, $albums_thumbnail_size, img)
936         }
937
938         if !$rotated_pixbufs[thumbnail_file] && !File.exists?(thumbnail_file)
939             f.add(img = Gtk::Image.new)
940             my_gen_real_thumbnail.call
941         else
942             f.add(img = Gtk::Image.new($rotated_pixbufs[thumbnail_file] ? $rotated_pixbufs[thumbnail_file][:pixbuf] : thumbnail_file))
943         end
944         hbox.pack_end(Gtk::Alignment.new(0.5, 0.5, 0, 0).add(evtbox = Gtk::EventBox.new.add(f)), false, false)
945         $subalbums.attach(hbox,
946                           0, 1, current_y_sub_albums, current_y_sub_albums + 1, Gtk::FILL, Gtk::FILL, 2, 2)
947
948         change_image = Proc.new {
949             fc = Gtk::FileChooserDialog.new(utf8(_("Select image for caption")),
950                                             nil,
951                                             Gtk::FileChooser::ACTION_OPEN,
952                                             nil,
953                                             [Gtk::Stock::OPEN, Gtk::Dialog::RESPONSE_ACCEPT], [Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL])
954             fc.set_current_folder(xmldir.attributes['path'])
955             fc.transient_for = $main_window
956             fc.preview_widget = preview = Gtk::Alignment.new(0.5, 0.5, 0, 0).add(f = Gtk::Frame.new.set_shadow_type(Gtk::SHADOW_ETCHED_OUT))
957             f.add(preview_img = Gtk::Image.new)
958             preview.show_all
959             fc.signal_connect('update-preview') { |w|
960                 begin
961                     if fc.preview_filename
962                         preview_img.pixbuf = rotate_pixbuf(Gdk::Pixbuf.new(fc.preview_filename, 240, 180), guess_rotate(fc.preview_filename))
963                         fc.preview_widget_active = true
964                     end
965                 rescue Gdk::PixbufError
966                     fc.preview_widget_active = false
967                 end
968             }
969             if fc.run == Gtk::Dialog::RESPONSE_ACCEPT
970                 msg 3, "new captionfile is: #{fc.filename}"
971                 $subalbums_edits[xmldir.attributes['path']][:captionfile] = captionfile = utf8(fc.filename)
972                 $rotated_pixbufs.delete(thumbnail_file)
973                 xmldir.delete_attribute("#{infotype}-rotate")
974                 xmldir.delete_attribute("#{infotype}-color-swap")
975                 xmldir.delete_attribute("#{infotype}-enhance")
976                 xmldir.delete_attribute("#{infotype}-frame-offset")
977                 my_gen_real_thumbnail.call
978             end
979             fc.destroy
980         }
981
982         rotate_and_cleanup = Proc.new { |angle|
983             rotate(angle, thumbnail_file, img, xmldir, "#{infotype}-", $default_albums_thumbnails[:x], $default_albums_thumbnails[:y])
984             system("rm -f '#{thumbnail_file}'")
985         }
986
987         color_swap_and_cleanup = Proc.new {
988             perform_color_swap_and_cleanup = Proc.new {
989                 color_swap(xmldir, "#{infotype}-")
990                 my_gen_real_thumbnail.call
991             }
992             perform_color_swap_and_cleanup.call
993
994             save_undo(_("color swap"),
995                       Proc.new {
996                           perform_color_swap_and_cleanup.call
997                           $notebook.set_page(0)
998                           Proc.new {
999                               perform_color_swap_and_cleanup.call
1000                               $notebook.set_page(0)
1001                           }
1002                       })
1003         }
1004
1005         change_frame_offset_and_cleanup = Proc.new {
1006             if values = ask_new_frame_offset(xmldir, "#{infotype}-")
1007                 perform_change_frame_offset_and_cleanup = Proc.new { |val|
1008                     change_frame_offset(xmldir, "#{infotype}-", val)
1009                     my_gen_real_thumbnail.call
1010                 }
1011                 perform_change_frame_offset_and_cleanup.call(values[:new])
1012
1013                 save_undo(_("specify frame offset"),
1014                           Proc.new {
1015                               perform_change_frame_offset_and_cleanup.call(values[:old])
1016                               $notebook.set_page(0)
1017                               Proc.new {
1018                                   perform_change_frame_offset_and_cleanup.call(values[:new])
1019                                   $notebook.set_page(0)
1020                               }
1021                           })
1022             end
1023         }
1024
1025         enhance_and_cleanup = Proc.new {
1026             perform_enhance_and_cleanup = Proc.new {
1027                 enhance(xmldir, "#{infotype}-")
1028                 my_gen_real_thumbnail.call
1029             }
1030             
1031             perform_enhance_and_cleanup.call
1032             
1033             save_undo(_("enhance"),
1034                       Proc.new {
1035                           perform_enhance_and_cleanup.call
1036                           $notebook.set_page(0)
1037                           Proc.new {
1038                               perform_enhance_and_cleanup.call
1039                               $notebook.set_page(0)
1040                           }
1041                       })
1042         }
1043
1044         evtbox.signal_connect('button-press-event') { |w, event|
1045             if event.event_type == Gdk::Event::BUTTON_PRESS && event.button == 1
1046                 if $r90.active?
1047                     rotate_and_cleanup.call(90)
1048                 elsif $r270.active?
1049                     rotate_and_cleanup.call(-90)
1050                 elsif $enhance.active?
1051                     enhance_and_cleanup.call
1052                 end
1053             end
1054             if event.event_type == Gdk::Event::BUTTON_PRESS && event.button == 3
1055                 popup_thumbnail_menu(event, ['change_image'], entry2type(captionfile), xmldir, "#{infotype}-",
1056                                      { :change => change_image, :rotate => rotate_and_cleanup, :enhance => enhance_and_cleanup,
1057                                        :color_swap => color_swap_and_cleanup, :frame_offset => change_frame_offset_and_cleanup })
1058             end
1059             if event.event_type == Gdk::Event::BUTTON2_PRESS && event.button == 1
1060                 change_image.call
1061                 true   #- handled
1062             end
1063         }
1064         evtbox.signal_connect('button-press-event') { |w, event|
1065             $gesture_press = { :filename => thumbnail_file, :x => event.x, :y => event.y }
1066             false
1067         }
1068
1069         evtbox.signal_connect('button-release-event') { |w, event|
1070             if !$r90.active? && !$r270.active? && $gesture_press && $gesture_press[:filename] == thumbnail_file
1071                 msg 3, "press: #{$gesture_press[:x]} release: #{event.x}"
1072                 if (($gesture_press[:x]-event.x)/($gesture_press[:y]-event.y)).abs > 2 && ($gesture_press[:x]-event.x).abs > 5
1073                     angle = event.x-$gesture_press[:x] > 0 ? 90 : -90
1074                     msg 3, "gesture rotate: #{angle}"
1075                     rotate_and_cleanup.call(angle)
1076                 end
1077             end
1078             $gesture_press = nil
1079         }
1080         
1081         frame, textview = create_editzone($subalbums_sw, 0)
1082         textview.buffer.text = caption
1083         $subalbums.attach(Gtk::Alignment.new(0, 0.5, 0.5, 0).add(frame),
1084                           1, 2, current_y_sub_albums, current_y_sub_albums + 1, Gtk::FILL, Gtk::FILL, 2, 2)
1085         
1086         $subalbums_edits[xmldir.attributes['path']] = { :editzone => textview, :captionfile => captionfile }
1087         current_y_sub_albums += 1
1088     }
1089
1090     if $xmldir.elements['dir']
1091         #- title edition
1092         frame, $subalbums_title = create_editzone($subalbums_sw, 0)
1093         $subalbums_title.buffer.text = $xmldir.attributes['subdirs-caption']
1094         $subalbums_title.set_justification(Gtk::Justification::CENTER)
1095         $subalbums_vb.pack_start(Gtk::Alignment.new(0.5, 0.5, 0.5, 0).add(frame), false, false)
1096         #- this album image/caption
1097         if $xmldir.attributes['thumbnails-caption']
1098             add_subalbum.call($xmldir)
1099         end
1100     end
1101     $xmldir.elements.each { |element|
1102         if element.name == 'image' || element.name == 'video'
1103             #- element (image or video) of this album
1104             dest_img = build_full_dest_filename(element.attributes['filename']).sub(/\.[^\.]+$/, '') + "-#{$default_size['thumbnails']}.jpg"
1105             msg 3, "dest_img: #{dest_img}"
1106             add_thumbnail($autotable, element.attributes['filename'], element.name, dest_img, from_utf8(element.attributes['caption']))
1107         end
1108         if element.name == 'dir'
1109             #- sub-album image/caption
1110             add_subalbum.call(element)
1111         end
1112     }
1113     $subalbums_vb.add($subalbums)
1114     $subalbums_vb.show_all
1115
1116     if !$xmldir.elements['image'] && !$xmldir.elements['video']
1117         $notebook.get_tab_label($autotable_sw).sensitive = false
1118         $notebook.set_page(0)
1119     else
1120         $notebook.get_tab_label($autotable_sw).sensitive = true
1121     end
1122
1123     if !$xmldir.elements['dir']
1124         $notebook.get_tab_label($subalbums_sw).sensitive = false
1125         $notebook.set_page(1)
1126     else
1127         $notebook.get_tab_label($subalbums_sw).sensitive = true
1128     end
1129 end
1130
1131 def pixbuf_or_nil(filename)
1132     begin
1133         return Gdk::Pixbuf.new(filename)
1134     rescue
1135         return nil
1136     end
1137 end
1138
1139 def theme_choose(current)
1140     dialog = Gtk::Dialog.new(utf8(_("Select your preferred theme")),
1141                              $main_window,
1142                              Gtk::Dialog::MODAL | Gtk::Dialog::DESTROY_WITH_PARENT,
1143                              [Gtk::Stock::OK, Gtk::Dialog::RESPONSE_OK],
1144                              [Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL])
1145
1146     model = Gtk::ListStore.new(String, Gdk::Pixbuf, Gdk::Pixbuf, Gdk::Pixbuf)
1147     treeview = Gtk::TreeView.new(model).set_rules_hint(true)
1148     treeview.append_column(Gtk::TreeViewColumn.new(utf8(_("Theme name")), Gtk::CellRendererText.new, { :text => 0 }).set_alignment(0.5).set_spacing(5))
1149     treeview.append_column(Gtk::TreeViewColumn.new(utf8(_("Sub-albums page look")), Gtk::CellRendererPixbuf.new, { :pixbuf => 1 }).set_alignment(0.5).set_spacing(5))
1150     treeview.append_column(Gtk::TreeViewColumn.new(utf8(_("Thumbnails page look")), Gtk::CellRendererPixbuf.new, { :pixbuf => 2 }).set_alignment(0.5).set_spacing(5))
1151     treeview.append_column(Gtk::TreeViewColumn.new(utf8(_("Fullscreen page look")), Gtk::CellRendererPixbuf.new, { :pixbuf => 3 }).set_alignment(0.5).set_spacing(5))
1152     treeview.append_column(Gtk::TreeViewColumn.new('', Gtk::CellRendererText.new, {}))
1153     treeview.signal_connect('button-press-event') { |w, event|
1154         if event.event_type == Gdk::Event::BUTTON2_PRESS && event.button == 1
1155             dialog.response(Gtk::Dialog::RESPONSE_OK)
1156         end
1157     }
1158
1159     dialog.vbox.add(sw = Gtk::ScrolledWindow.new(nil, nil).add(treeview).set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC))
1160
1161     `find '#{$FPATH}/themes' -mindepth 1 -maxdepth 1 -type d`.each { |dir|
1162         dir.chomp!
1163         iter = model.append
1164         iter[0] = File.basename(dir)
1165         iter[1] = pixbuf_or_nil("#{dir}/metadata/screenshot-1.png")
1166         iter[2] = pixbuf_or_nil("#{dir}/metadata/screenshot-2.png")
1167         iter[3] = pixbuf_or_nil("#{dir}/metadata/screenshot-3.png")
1168         if File.basename(dir) == current
1169             treeview.selection.select_iter(iter)
1170         end
1171     }
1172
1173     dialog.set_default_size(700, 400)
1174     dialog.vbox.show_all
1175     dialog.run { |response|
1176         iter = treeview.selection.selected
1177         dialog.destroy
1178         if response == Gtk::Dialog::RESPONSE_OK && iter
1179             return model.get_value(iter, 0)
1180         end
1181     }
1182     return nil
1183 end
1184
1185 def open_file(filename)
1186
1187     $filename = nil
1188     $modified = false
1189     $current_path = nil   #- invalidate
1190     $rotated_pixbufs = {}
1191     $albums_ts.clear
1192     $autotable.clear
1193     $subalbums_vb.children.each { |chld|
1194         $subalbums_vb.remove(chld)
1195     }
1196
1197     if !File.exists?(filename)
1198         return utf8(_("File not found."))
1199     end
1200
1201     begin
1202         $xmldoc = REXML::Document.new File.new(filename)
1203     rescue
1204         $xmldoc = nil
1205     end
1206
1207     if !$xmldoc || !$xmldoc.root || $xmldoc.root.name != 'booh'
1208         return utf8(_("Not a booh file!"))
1209     end
1210
1211     if !source = $xmldoc.root.attributes['source']
1212         return utf8(_("Corrupted booh file..."))
1213     end
1214
1215     if !dest = $xmldoc.root.attributes['destination']
1216         return utf8(_("Corrupted booh file..."))
1217     end
1218
1219     if !theme = $xmldoc.root.attributes['theme']
1220         return utf8(_("Corrupted booh file..."))
1221     end
1222
1223     limit_sizes = $xmldoc.root.attributes['limit-sizes']
1224
1225     $filename = filename
1226     select_theme(theme, limit_sizes)
1227     $default_size['thumbnails'] =~ /(.*)x(.*)/
1228     $default_thumbnails = { :x => $1.to_i, :y => $2.to_i }
1229     $albums_thumbnail_size =~ /(.*)x(.*)/
1230     $default_albums_thumbnails = { :x => $1.to_i, :y => $2.to_i }
1231
1232     msg 3, "source: #{source}"
1233
1234     xmldir = $xmldoc.elements["//dir[@path='#{source}']"]
1235     if !xmldir
1236         return utf8(_("Corrupted booh file..."))
1237     end
1238
1239     append_dir_elem = Proc.new { |parent_iter, location|
1240         child_iter = $albums_ts.append(parent_iter)
1241         child_iter[0] = File.basename(location)
1242         child_iter[1] = location
1243         msg 3, "puttin location: #{location}"
1244         $xmldoc.elements.each("//dir[@path='#{location}']/dir") { |elem|
1245             append_dir_elem.call(child_iter, elem.attributes['path'])
1246         }
1247     }
1248     append_dir_elem.call(nil, source)
1249
1250     $albums_tv.expand_all
1251     $albums_tv.selection.select_iter($albums_ts.iter_first)
1252
1253     $config['last-opens'] ||= []
1254     $config['last-opens'] << filename
1255     $save.sensitive = $save_as.sensitive = $generate.sensitive = true
1256     return nil
1257 end
1258
1259 def open_file_popup
1260     fc = Gtk::FileChooserDialog.new(utf8(_("Open file")),
1261                                     nil,
1262                                     Gtk::FileChooser::ACTION_OPEN,
1263                                     nil,
1264                                     [Gtk::Stock::OPEN, Gtk::Dialog::RESPONSE_ACCEPT], [Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL])
1265     fc.add_shortcut_folder(File.expand_path("~/.booh"))
1266     fc.set_current_folder(File.expand_path("~/.booh"))
1267     fc.transient_for = $main_window
1268     ok = false
1269     while !ok
1270         if fc.run == Gtk::Dialog::RESPONSE_ACCEPT
1271             push_mousecursor_wait(fc)
1272             msg = open_file(from_utf8(fc.filename))
1273             pop_mousecursor(fc)
1274             if msg
1275                 show_popup(fc, msg)
1276                 ok = false
1277             else
1278                 ok = true
1279             end
1280         else
1281             ok = true
1282         end
1283     end
1284     fc.destroy
1285 end
1286
1287 def additional_booh_options
1288     options = ''
1289     if $config['mproc']
1290         options += "--mproc #{$config['mproc'].to_i} "
1291     end
1292     return options
1293 end
1294
1295 def new_album
1296     dialog = Gtk::Dialog.new(utf8(_("Create a new album")),
1297                              $main_window,
1298                              Gtk::Dialog::MODAL | Gtk::Dialog::DESTROY_WITH_PARENT,
1299                              [Gtk::Stock::OK, Gtk::Dialog::RESPONSE_OK],
1300                              [Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL])
1301     
1302     frame1 = Gtk::Frame.new(utf8(_("Locations"))).add(tbl = Gtk::Table.new(0, 0, false))
1303     tbl.attach(Gtk::Label.new(utf8(_("Directory of images/videos: "))),
1304                0, 1, 0, 1, Gtk::SHRINK, Gtk::SHRINK, 2, 2)
1305     tbl.attach(src = Gtk::Entry.new,
1306                1, 2, 0, 1, Gtk::FILL, Gtk::SHRINK, 2, 2)
1307     tbl.attach(src_browse = Gtk::Button.new(utf8(_("browse..."))),
1308                2, 3, 0, 1, Gtk::SHRINK, Gtk::SHRINK, 2, 2)
1309     tbl.attach(Gtk::Label.new.set_markup(utf8(_("<span size='small'><i>number of images/videos down this directory:</i></span> "))),
1310                0, 1, 1, 2, Gtk::SHRINK, Gtk::SHRINK, 2, 2)
1311     tbl.attach(src_nb = Gtk::Label.new.set_markup(utf8(_("<span size='small'><i>N/A</i></span>"))),
1312                1, 2, 1, 2, Gtk::FILL, Gtk::SHRINK, 2, 2)
1313     tbl.attach(Gtk::Label.new(utf8(_("Directory where to put the web-album: "))),
1314                0, 1, 2, 3, Gtk::SHRINK, Gtk::SHRINK, 2, 2)
1315     tbl.attach(dest = Gtk::Entry.new,
1316                1, 2, 2, 3, Gtk::FILL, Gtk::SHRINK, 2, 2)
1317     tbl.attach(dest_browse = Gtk::Button.new(utf8(_("browse..."))),
1318                2, 3, 2, 3, Gtk::SHRINK, Gtk::SHRINK, 2, 2)
1319     tbl.attach(Gtk::Label.new(utf8(_("Filename to store this album's properties: "))),
1320                0, 1, 3, 4, Gtk::SHRINK, Gtk::SHRINK, 2, 2)
1321     tbl.attach(conf = Gtk::Entry.new.set_size_request(250, -1),
1322                1, 2, 3, 4, Gtk::FILL, Gtk::SHRINK, 2, 2)
1323     tbl.attach(conf_browse = Gtk::Button.new(utf8(_("browse..."))),
1324                2, 3, 3, 4, Gtk::SHRINK, Gtk::SHRINK, 2, 2)
1325
1326     frame2 = Gtk::Frame.new(utf8(_("Configuration"))).add(tbl = Gtk::Table.new(0, 0, false))
1327     tbl.attach(Gtk::Label.new(utf8(_("Theme: "))),
1328                0, 1, 0, 1, Gtk::SHRINK, Gtk::SHRINK, 2, 2)
1329     tbl.attach(theme_button = Gtk::Button.new($config['default-theme'] || 'simple'),
1330                1, 2, 0, 1, Gtk::FILL, Gtk::SHRINK, 2, 2)
1331     tbl.attach(Gtk::Label.new(utf8(_("Sizes of images to generate: "))),
1332                0, 1, 1, 2, Gtk::SHRINK, Gtk::SHRINK, 2, 2)
1333     tbl.attach(sizes = Gtk::HBox.new,
1334                1, 3, 1, 2, Gtk::SHRINK, Gtk::SHRINK, 2, 2)
1335
1336     src_nb_calculated_for = ''
1337     src_nb_thread = nil
1338     process_src_nb = Proc.new {
1339         if src.text != src_nb_calculated_for
1340             src_nb_calculated_for = src.text
1341             if src_nb_thread
1342                 Thread.kill(src_nb_thread)
1343                 src_nb_thread = nil
1344             end
1345             if File.directory?(from_utf8(src_nb_calculated_for)) && src_nb_calculated_for != '/'
1346                 if File.readable?(from_utf8(src_nb_calculated_for))
1347                     src_nb_thread = Thread.new {
1348                         src_nb.set_markup(utf8(_("<span size='small'><i>processing...</i></span>")))
1349                         total = { 'image' => 0, 'video' => 0, nil => 0 }
1350                         `find #{from_utf8(src_nb_calculated_for)} -type d`.each { |dir|
1351                             begin
1352                                 Dir.entries(dir.chomp).each { |file|
1353                                     total[entry2type(file)] += 1
1354                                 }
1355                             rescue Errno::EACCES, Errno::ENOENT
1356                             end
1357                         }
1358                         src_nb.set_markup(utf8(_("<span size='small'><i>%s images and %s videos</i></span>") % [ total['image'], total['video'] ]))
1359                         src_nb_thread = nil
1360                     }
1361                 else
1362                     src_nb.set_markup(utf8(_("<span size='small'><i>permission denied</i></span>")))
1363                 end
1364             else
1365                 src_nb.set_markup(utf8(_("<span size='small'><i>N/A</i></span>")))
1366             end
1367         end
1368         true
1369     }
1370     timeout_src_nb = Gtk.timeout_add(100) {
1371         process_src_nb.call
1372     }
1373
1374     src_browse.signal_connect('clicked') {
1375         fc = Gtk::FileChooserDialog.new(utf8(_("Select the directory of images/videos")),
1376                                         nil,
1377                                         Gtk::FileChooser::ACTION_SELECT_FOLDER,
1378                                         nil,
1379                                         [Gtk::Stock::OPEN, Gtk::Dialog::RESPONSE_ACCEPT], [Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL])
1380         fc.transient_for = $main_window
1381         if fc.run == Gtk::Dialog::RESPONSE_ACCEPT
1382             src.text = utf8(fc.filename)
1383             process_src_nb.call
1384             conf.text = File.expand_path("~/.booh/#{File.basename(src.text)}")
1385         end
1386         fc.destroy
1387     }
1388
1389     dest_browse.signal_connect('clicked') {
1390         fc = Gtk::FileChooserDialog.new(utf8(_("Select a new directory where to put the web-album")),
1391                                         nil,
1392                                         Gtk::FileChooser::ACTION_CREATE_FOLDER,
1393                                         nil,
1394                                         [Gtk::Stock::OPEN, Gtk::Dialog::RESPONSE_ACCEPT], [Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL])
1395         fc.transient_for = $main_window
1396         if fc.run == Gtk::Dialog::RESPONSE_ACCEPT
1397             dest.text = fc.filename
1398         end
1399         fc.destroy
1400     }
1401
1402     conf_browse.signal_connect('clicked') {
1403         fc = Gtk::FileChooserDialog.new(utf8(_("Select a new file to store this album's properties")),
1404                                         nil,
1405                                         Gtk::FileChooser::ACTION_SAVE,
1406                                         nil,
1407                                         [Gtk::Stock::OPEN, Gtk::Dialog::RESPONSE_ACCEPT], [Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL])
1408         fc.transient_for = $main_window
1409         fc.add_shortcut_folder(File.expand_path("~/.booh"))
1410         fc.set_current_folder(File.expand_path("~/.booh"))
1411         if fc.run == Gtk::Dialog::RESPONSE_ACCEPT
1412             conf.text = fc.filename
1413         end
1414         fc.destroy
1415     }
1416
1417     theme_sizes = []
1418     recreate_theme_config = proc {
1419         theme_sizes.each { |e| sizes.remove(e[:widget]) }
1420         theme_sizes = []
1421         select_theme(theme_button.label, nil)
1422         $images_size.each { |s|
1423             sizes.add(cb = Gtk::CheckButton.new(sizename(s['name'])).set_active(true))
1424             tooltips = Gtk::Tooltips.new
1425             tooltips.set_tip(cb, utf8(s['description']), nil)
1426             theme_sizes << { :widget => cb, :value => s['name'] }
1427         }
1428         sizes.add(cb = Gtk::CheckButton.new(utf8(_('original'))))
1429         theme_sizes << { :widget => cb, :value => 'original' }
1430         sizes.show_all
1431     }
1432     recreate_theme_config.call
1433
1434     theme_button.signal_connect('clicked') {
1435         if newtheme = theme_choose(theme_button.label)
1436             theme_button.label = newtheme
1437             recreate_theme_config.call
1438         end
1439     }
1440
1441     dialog.vbox.add(frame1)
1442     dialog.vbox.add(frame2)
1443     dialog.window_position = Gtk::Window::POS_MOUSE
1444     dialog.show_all
1445
1446     keepon = true
1447     ok = true
1448     while keepon
1449         dialog.run { |response|
1450             if response == Gtk::Dialog::RESPONSE_OK
1451                 srcdir = from_utf8(src.text)
1452                 destdir = from_utf8(dest.text)
1453                 if !File.directory?(srcdir)
1454                     show_popup(dialog, utf8(_("The directory of images/videos doesn't exist. Please check your input.")))
1455                     src.grab_focus
1456                 elsif conf.text == ''
1457                     show_popup(dialog, utf8(_("Please specify a filename to store the album's properties.")))
1458                     conf.grab_focus
1459                 elsif File.directory?(destdir)
1460                     keepon = !show_popup(dialog, utf8(_("The destination directory already exists. Are you sure you want to continue?")), { :okcancel => true })
1461                     dest.grab_focus
1462                 elsif File.exists?(destdir)
1463                     show_popup(dialog, utf8(_("There is already a file by the name of the destination directory. Please choose another one.")))
1464                     dest.grab_focus
1465                 elsif !theme_sizes.detect { |e| e[:value] != 'original' && e[:widget].active? }
1466                     show_popup(dialog, utf8(_("You need to select at least one size (not counting original).")))
1467                 else
1468                     system("mkdir '#{destdir}'")
1469                     if !File.directory?(destdir)
1470                         show_popup(dialog, utf8(_("Could not create destination directory. Permission denied?")))
1471                         dest.grab_focus
1472                     else
1473                         keepon = false
1474                     end
1475                 end
1476             else
1477                 keepon = ok = false
1478             end
1479         }
1480     end
1481     srcdir = from_utf8(src.text)
1482     destdir = from_utf8(dest.text)
1483     configskel = from_utf8(conf.text)
1484     theme = theme_button.label
1485     sizes = theme_sizes.find_all { |e| e[:widget].active? }.collect { |e| e[:value] }.join(',')
1486     dialog.destroy
1487     if src_nb_thread
1488         Thread.kill(src_nb_thread)
1489     end
1490     Gtk.timeout_remove(timeout_src_nb)
1491
1492     if ok
1493         perform_in_background("booh --source #{srcdir} --destination #{destdir} --config-skel #{configskel} --for-gui " +
1494                                   "--verbose-level #{$verbose_level} --theme #{theme} --sizes #{sizes} #{additional_booh_options}",
1495                               utf8(_("Please wait while scanning source directory...")),
1496                               { :closure_after => proc { open_file(configskel) } })
1497     end
1498 end
1499
1500 def save_as_do
1501     fc = Gtk::FileChooserDialog.new(utf8(_("Select a new filename to store this album's properties")),
1502                                     nil,
1503                                     Gtk::FileChooser::ACTION_SAVE,
1504                                     nil,
1505                                     [Gtk::Stock::OPEN, Gtk::Dialog::RESPONSE_ACCEPT], [Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL])
1506     fc.transient_for = $main_window
1507     fc.add_shortcut_folder(File.expand_path("~/.booh"))
1508     fc.set_current_folder(File.expand_path("~/.booh"))
1509     fc.filename = $filename
1510     if fc.run == Gtk::Dialog::RESPONSE_ACCEPT
1511         $filename = from_utf8(fc.filename)
1512         save_current_file
1513     end
1514     fc.destroy
1515 end
1516
1517 def preferences
1518     dialog = Gtk::Dialog.new(utf8(_("Edit preferences")),
1519                              $main_window,
1520                              Gtk::Dialog::MODAL | Gtk::Dialog::DESTROY_WITH_PARENT,
1521                              [Gtk::Stock::OK, Gtk::Dialog::RESPONSE_OK],
1522                              [Gtk::Stock::CANCEL, Gtk::Dialog::RESPONSE_CANCEL])
1523
1524     dialog.vbox.add(notebook = Gtk::Notebook.new)
1525     notebook.append_page(tbl = Gtk::Table.new(0, 0, false), Gtk::Label.new(utf8(_("Options"))))
1526     tbl.attach(smp_check = Gtk::CheckButton.new(utf8(_("Use symmetric multi-processing"))),
1527                0, 1, 0, 1, Gtk::SHRINK, Gtk::SHRINK, 2, 2)
1528     tbl.attach(smp_hbox = Gtk::HBox.new.add(smp_spin = Gtk::SpinButton.new(2, 16, 1)).add(Gtk::Label.new(utf8(_("processors")))).set_sensitive(false),
1529                1, 2, 0, 1, Gtk::SHRINK, Gtk::SHRINK, 2, 2)
1530     smp_check.signal_connect('toggled') {
1531         if smp_check.active?
1532             smp_hbox.sensitive = true
1533         else
1534             smp_hbox.sensitive = false
1535         end
1536     }
1537     if $config['mproc']
1538         smp_check.active = true
1539         smp_spin.value = $config['mproc'].to_i
1540     end
1541
1542     notebook.append_page(tbl = Gtk::Table.new(0, 0, false), Gtk::Label.new(utf8(_("Advanced"))))
1543     tbl.attach(Gtk::Label.new.set_markup(utf8(_("Options to pass to <i>convert</i> when\nperforming 'enhance contrast': "))),
1544                0, 1, 0, 1, Gtk::SHRINK, Gtk::SHRINK, 2, 2)
1545     tbl.attach(enhance_entry = Gtk::Entry.new.set_text($config['convert-enhance'] || $convert_enhance).set_size_request(250, -1),
1546                1, 2, 0, 1, Gtk::FILL, Gtk::SHRINK, 2, 2)
1547
1548     dialog.vbox.show_all
1549     dialog.run { |response|
1550         if response == Gtk::Dialog::RESPONSE_OK
1551             if smp_check.active?
1552                 $config['mproc'] = smp_spin.value.to_i
1553             else
1554                 $config.delete('mproc')
1555             end
1556
1557             $config['convert-enhance'] = enhance_entry.text
1558         end
1559     }
1560     dialog.destroy
1561 end
1562
1563 def create_menu_and_toolbar
1564
1565     #- menu
1566     mb = Gtk::MenuBar.new
1567
1568     filemenu = Gtk::MenuItem.new(utf8(_("_File")))
1569     filesubmenu = Gtk::Menu.new
1570     filesubmenu.append(new       = Gtk::ImageMenuItem.new(Gtk::Stock::NEW))
1571     filesubmenu.append(open      = Gtk::ImageMenuItem.new(Gtk::Stock::OPEN))
1572     filesubmenu.append(            Gtk::SeparatorMenuItem.new)
1573     filesubmenu.append($save     = Gtk::ImageMenuItem.new(Gtk::Stock::SAVE).set_sensitive(false))
1574     filesubmenu.append($save_as  = Gtk::ImageMenuItem.new(Gtk::Stock::SAVE_AS).set_sensitive(false))
1575     filesubmenu.append(            Gtk::SeparatorMenuItem.new)
1576     filesubmenu.append($generate = Gtk::ImageMenuItem.new(utf8(_("Generate web-album"))).set_sensitive(false))
1577     $generate.image = Gtk::Image.new("#{$FPATH}/images/stock-web-16.png")
1578     filesubmenu.append(            Gtk::SeparatorMenuItem.new)
1579     filesubmenu.append(quit      = Gtk::ImageMenuItem.new(Gtk::Stock::QUIT))
1580     filemenu.set_submenu(filesubmenu)
1581     mb.append(filemenu)
1582
1583     new.signal_connect('activate') { new_album }
1584     open.signal_connect('activate') { open_file_popup }
1585     $save.signal_connect('activate') { save_current_file }
1586     $save_as.signal_connect('activate') { save_as_do }
1587     $generate.signal_connect('activate') {
1588         save_current_file
1589         perform_in_background("booh --config #{$filename} --verbose-level #{$verbose_level} #{additional_booh_options}",
1590                               utf8(_("Please wait while generating web-album...\nThis may take a while, please be patient.")),
1591                               { :successmsg => utf8(_("Your web-album is now ready in directory `%s'.") % $xmldoc.root.attributes['destination'] ),
1592                                 :failuremsg => utf8(_("There was something wrong when generating the web-album, sorry.")) })
1593     }
1594
1595     quit.signal_connect('activate') { try_quit }
1596
1597     editmenu = Gtk::MenuItem.new(utf8(_("_Edit")))
1598     editsubmenu = Gtk::Menu.new
1599     editsubmenu.append($undo_mb = Gtk::ImageMenuItem.new(Gtk::Stock::UNDO).set_sensitive(false))
1600     editsubmenu.append($redo_mb = Gtk::ImageMenuItem.new(Gtk::Stock::REDO).set_sensitive(false))
1601     editsubmenu.append(           Gtk::SeparatorMenuItem.new)
1602     editsubmenu.append(prefs    = Gtk::ImageMenuItem.new(Gtk::Stock::PREFERENCES))
1603     editmenu.set_submenu(editsubmenu)
1604     mb.append(editmenu)
1605
1606     prefs.signal_connect('activate') { preferences }
1607
1608     helpmenu = Gtk::MenuItem.new(utf8(_("_Help")))
1609     helpsubmenu = Gtk::Menu.new
1610     helpsubmenu.append(about = Gtk::ImageMenuItem.new(Gtk::Stock::ABOUT))
1611     helpmenu.set_submenu(helpsubmenu)
1612     mb.append(helpmenu)
1613
1614     about.signal_connect('activate') {
1615             show_popup($main_window, utf8(_("<span size='x-large' weight='bold'>Booh %s</span>
1616
1617 <i>``The Web-Album of choice for discriminating Linux users''</i>
1618
1619 Copyright (c) 2005 Guillaume Cottenceau") % $VERSION), { :centered => true, :pos_centered => true })
1620     }
1621
1622
1623     #- toolbar
1624     tb = Gtk::Toolbar.new
1625
1626     tb.insert(-1, open = Gtk::MenuToolButton.new(Gtk::Stock::OPEN))
1627     open.label = utf8(_("Open"))  #- to avoid missing gtk2 l10n catalogs
1628     open.menu = Gtk::Menu.new
1629     open.signal_connect('clicked') { open_file_popup }
1630     open.signal_connect('show-menu') {
1631         lastopens = Gtk::Menu.new
1632         j = 0
1633         if $config['last-opens']
1634             $config['last-opens'].reverse.each { |e|
1635                 lastopens.attach(item = Gtk::ImageMenuItem.new(e, false), 0, 1, j, j + 1)
1636                 item.signal_connect('activate') {
1637                     push_mousecursor_wait
1638                     msg = open_file(e)
1639                     pop_mousecursor
1640                     if msg
1641                         show_popup($main_window, msg)
1642                     end
1643                 }
1644                 j += 1
1645             }
1646             lastopens.show_all
1647         end
1648         open.menu = lastopens
1649     }
1650
1651     tb.insert(-1, Gtk::SeparatorToolItem.new)
1652
1653     tb.insert(-1, $r90 = Gtk::ToggleToolButton.new)
1654     $r90.icon_widget = Gtk::Image.new("#{$FPATH}/images/stock-rotate-90-16.png")
1655     $r90.label = utf8(_("Rotate"))
1656     tb.insert(-1, $r270 = Gtk::ToggleToolButton.new)
1657     $r270.icon_widget = Gtk::Image.new("#{$FPATH}/images/stock-rotate-270-16.png")
1658     $r270.label = utf8(_("Rotate"))
1659     tb.insert(-1, $enhance = Gtk::ToggleToolButton.new)
1660     $enhance.icon_widget = Gtk::Image.new("#{$FPATH}/images/stock-channels-16.png")
1661     $enhance.label = utf8(_("Enhance"))
1662     tb.insert(-1, $delete = Gtk::ToggleToolButton.new(Gtk::Stock::DELETE))
1663     $delete.label = utf8(_("Delete"))  #- to avoid missing gtk2 l10n catalogs
1664     tb.insert(-1, nothing = Gtk::ToolButton.new('').set_sensitive(false))
1665     nothing.icon_widget = Gtk::Image.new("#{$FPATH}/images/stock-none-16.png")
1666     nothing.label = utf8(_("None"))
1667
1668     tb.insert(-1, Gtk::SeparatorToolItem.new)
1669
1670     tb.insert(-1, $undo_tb = Gtk::ToolButton.new(Gtk::Stock::UNDO).set_sensitive(false))
1671     tb.insert(-1, $redo_tb = Gtk::ToolButton.new(Gtk::Stock::REDO).set_sensitive(false))
1672
1673     perform_undo = Proc.new {
1674         $redo_tb.sensitive = $redo_mb.sensitive = true
1675         if not more_undoes = UndoHandler.undo($statusbar)
1676             $undo_tb.sensitive = $undo_mb.sensitive = false
1677         end
1678     }
1679     perform_redo = Proc.new {
1680         $undo_tb.sensitive = $undo_mb.sensitive = true
1681         if not more_redoes = UndoHandler.redo($statusbar)
1682             $redo_tb.sensitive = $redo_mb.sensitive = false
1683         end
1684     }
1685
1686     $undo_tb.signal_connect('clicked')  { perform_undo.call }
1687     $undo_mb.signal_connect('activate') { perform_undo.call }
1688     $redo_tb.signal_connect('clicked')  { perform_redo.call }
1689     $redo_mb.signal_connect('activate') { perform_redo.call }
1690
1691     one_click_explain_try = Proc.new {
1692         if !$config['one-click-explained']
1693             show_popup($main_window, utf8(_("<b>One-Click tools.</b>
1694
1695 You have just clicked on a One-Click tool. When such a tool is activated
1696 (<span foreground='darkblue'>Rotate clockwise</span>, <span foreground='darkblue'>Rotate counter-clockwise</span>, or <span foreground='darkblue'>Delete</span>), clicking on a
1697 thumbnail will immediately apply the desired action.
1698
1699 Click the <span foreground='darkblue'>None</span> icon when you're finished with One-Click tools.
1700 ")))
1701             $config['one-click-explained'] = true
1702         end
1703     }
1704
1705     $r90.signal_connect('toggled') {
1706         if $r90.active?
1707             set_mousecursor(Gdk::Cursor::SB_RIGHT_ARROW)
1708             one_click_explain_try.call
1709             $r270.active = false
1710             $enhance.active = false
1711             $delete.active = false
1712             nothing.sensitive = true
1713         else
1714             if !$r270.active? && !$enhance.active? && !$delete.active?
1715                 set_mousecursor_normal
1716                 nothing.sensitive = false
1717             else
1718                 nothing.sensitive = true
1719             end
1720         end
1721     }
1722     $r270.signal_connect('toggled') {
1723         if $r270.active?
1724             set_mousecursor(Gdk::Cursor::SB_LEFT_ARROW)
1725             one_click_explain_try.call
1726             $r90.active = false
1727             $enhance.active = false
1728             $delete.active = false
1729             nothing.sensitive = true
1730         else
1731             if !$r90.active? && !$enhance.active? && !$delete.active?
1732                 set_mousecursor_normal
1733                 nothing.sensitive = false
1734             else
1735                 nothing.sensitive = true
1736             end
1737         end
1738     }
1739     $enhance.signal_connect('toggled') {
1740         if $enhance.active?
1741             set_mousecursor(Gdk::Cursor::SPRAYCAN)
1742             one_click_explain_try.call
1743             $r90.active = false
1744             $r270.active = false
1745             $delete.active = false
1746             nothing.sensitive = true
1747         else
1748             if !$r90.active? && !$r270.active? && !$delete.active?
1749                 set_mousecursor_normal
1750                 nothing.sensitive = false
1751             else
1752                 nothing.sensitive = true
1753             end
1754         end
1755     }
1756     $delete.signal_connect('toggled') {
1757         if $delete.active?
1758             set_mousecursor(Gdk::Cursor::PIRATE)
1759             one_click_explain_try.call
1760             $r90.active = false
1761             $r270.active = false
1762             $enhance.active = false
1763             nothing.sensitive = true
1764         else
1765             if !$r90.active? && !$r270.active? && !$enhance.active?
1766                 set_mousecursor_normal
1767                 nothing.sensitive = false
1768             else
1769                 nothing.sensitive = true
1770             end
1771         end
1772     }
1773     nothing.signal_connect('clicked') {
1774         $r90.active = $r270.active = $enhance.active = $delete.active = false
1775         set_mousecursor_normal
1776     }
1777
1778     return [ mb, tb ]
1779 end
1780
1781 def create_main_window
1782
1783     mb, tb = create_menu_and_toolbar
1784
1785 #    open_file('/home/gc/booh/foo')
1786
1787     $albums_tv = Gtk::TreeView.new
1788     $albums_tv.set_size_request(120, -1)
1789     renderer = Gtk::CellRendererText.new
1790     column = Gtk::TreeViewColumn.new('', renderer, { :text => 0 })
1791     $albums_tv.append_column(column)
1792     $albums_tv.set_headers_visible(false)
1793     $albums_tv.selection.signal_connect('changed') { |w|
1794         push_mousecursor_wait
1795         save_changes
1796         iter = w.selected
1797         if !iter
1798             msg 3, "no selection"
1799         else
1800             $current_path = $albums_ts.get_value(iter, 1)
1801             change_dir
1802         end
1803         pop_mousecursor
1804     }
1805     $albums_ts = Gtk::TreeStore.new(String, String)
1806     $albums_tv.set_model($albums_ts)
1807     $albums_tv.signal_connect('realize') { $albums_tv.grab_focus }
1808
1809     $notebook = Gtk::Notebook.new
1810     create_subalbums_page
1811     $notebook.append_page($subalbums_sw, Gtk::Label.new(utf8(_("Sub-albums page"))))
1812     create_auto_table
1813     $notebook.append_page($autotable_sw, Gtk::Label.new(utf8(_("Thumbnails page"))))
1814     $notebook.show_all
1815     $notebook.signal_connect('switch-page') { |w, page, num|
1816         if num == 0
1817             $delete.active = false
1818             $delete.sensitive = false
1819         else
1820             $delete.sensitive = true
1821         end
1822     }
1823
1824     paned = Gtk::HPaned.new
1825     paned.pack1($albums_tv, false, false)
1826     paned.pack2($notebook, true, true)
1827
1828     main_vbox = Gtk::VBox.new(false, 0)
1829     main_vbox.pack_start(mb, false, false)
1830     main_vbox.pack_start(tb, false, false)
1831     main_vbox.pack_start(paned, true, true)
1832     main_vbox.pack_end($statusbar = Gtk::Statusbar.new, false, false)
1833
1834     $main_window = Gtk::Window.new
1835     $main_window.add(main_vbox)
1836     $main_window.signal_connect('delete-event') {
1837         try_quit
1838     }
1839
1840     #- read/save size and position of window
1841     if $config['pos-x'] && $config['pos-y']
1842         $main_window.move($config['pos-x'].to_i, $config['pos-y'].to_i)
1843     else
1844         $main_window.window_position = Gtk::Window::POS_CENTER
1845     end
1846     msg 3, "size: #{$config['width']}x#{$config['height']}"
1847     $main_window.set_default_size(($config['width'] || 600).to_i, ($config['height'] || 400).to_i)
1848     $main_window.signal_connect('configure-event') {
1849         msg 3, "configure: pos: #{$main_window.window.root_origin.inspect} size: #{$main_window.window.size.inspect}"
1850         x, y = $main_window.window.root_origin
1851         width, height = $main_window.window.size
1852         $config['pos-x'] = x
1853         $config['pos-y'] = y
1854         $config['width'] = width
1855         $config['height'] = height
1856         false
1857     }
1858
1859     $statusbar.push(0, utf8(_("Ready.")))
1860     $main_window.show_all
1861 end
1862
1863 Thread.abort_on_exception = true
1864 handle_options
1865 read_config
1866
1867 Gtk.init
1868 create_main_window
1869 if ARGV[0]
1870     open_file(ARGV[0])
1871 end
1872 Gtk.main
1873
1874 write_config