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