#!/usr/bin/env ruby
#
# ruby-glade-create-template
#
# Create a ruby-glade template .rb file from a .glade file.
#
# Usage: ruby ruby-glade-create-template.rb yourgladefile.glade > file.rb
#
# $Id: ruby-glade-create-template,v 1.6 2004/03/05 16:34:24 mutoh Exp $
#
# Copyright (c) 2002-2004 Masao Mutoh <mutoh@highway.ne.jp>
#

$DISABLE_RUBY_LIBGLADE_CUSTOM_WIDGET_HANDLER = true
require 'libglade2'

class GladeXML
  attr_reader :signals
  def connect(source, target, signal_name, handler, data, after)
    @signals = [] unless @signals
    @signals << [source.class.signal(signal_name), self.canonical_handler(handler)]
  end
end

LG_VERSION = %Q[$Revision: 1.6 $].scan(/\d/).join(".")

begin
  $EXIST_GNOME = true
  require 'gnome2'
rescue LoadError
  $EXIST_GNOME = false
  puts "Ruby/GNOME2 is not supported." if $DEBUG
end

unless ARGV.size == 1
  puts "ruby-glade-create-template #{LG_VERSION}"
  puts "\nUsage: ruby ruby-glade-create-template.rb yourgladefile.glade > file.rb\n\n"
  exit(-1)
end

#
# Analyse .glade file.
#
path = ARGV[0]
filename = File.basename(path, ".*")
classname = filename.split(/[_-]/).collect{|item| item.capitalize}.join("")

if $EXIST_GNOME
  Gnome::Program.new("ruby-glade-create-template", LG_VERSION)
else
  Gtk.init
end

glade = GladeXML.new(path) 

#
# Print template.
#
# Header part: Initialize method.
puts <<HEADER
#!/usr/bin/env ruby
require 'libglade2'
HEADER

puts <<INITIALIZE
class #{classname}
  def initialize(path)
    @glade = GladeXML.new(path) {|handler| method(handler)}
  end
INITIALIZE

# Handler methods.
if glade.signals
  glade.signals.each do |signal, handler|
    args = "widget"
    (0...signal.param_types.size).each do |i|
      args << ", arg#{i}"
    end
    puts "  def #{handler}(#{args})"
    puts "    puts \"#{handler}() is not implemented yet.\""
    puts "  end"
  end
end

puts "end\n\n"

if $EXIST_GNOME
puts <<FOOTER_GNOME
#If you use only Ruby/GTK2 widgets, call Gtk.init here. 
#Gtk.init
#If you use Ruby/GNOME2 widgets, call Gnome::Program.new here. 
Gnome::Program.new("YOUR_APPLICATION_NAME", "YOUR_APPLICATION_VERSION")
FOOTER_GNOME
else
    puts "Gtk.init"
end
puts <<FOOTER

#Set correct path by yourself.
#{classname}.new("#{path}")
Gtk.main
FOOTER

if glade.custom_creation_methods.size > 0
  puts "#You may need to implement some custom creation methods which return new widget."
  glade.custom_creation_methods.each do |v|
    puts "#" + v
  end
end

