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