#!/usr/bin/env ruby

class Ui2rb

def initialize ( uifile)
   @doc = QDomDocument.new( "ui" )
   if ( !(f = File::open( uifile,"r" ) ) )
      STDERR.print "can't open file:#{uifile}\n"
      exit(1)
   end

   if ( !(@doc.setContent( f.read )) )
      STDERR.print "can't read file:#{uifile}\n"
      f.close()
      exit (1)
   end
end

def setI18nFunc( i18nfunc )
   @i18nfunc = i18nfunc
end

def getSource( withMain=true)
   form = FormMaker.new(@doc,true,@i18nfunc)
   source = form.getHeader
   source += form.getComment
   if(@enableUtfTr)
      source += @utfTrCode
   end
   source += form.rootForm.toString
   if(withMain)
      source += form.getMainProgram
   end
   source
end

def printSource(withMain=true)
   source = getSource(withMain)
   print source
end

def saveSource( output ,withMain=true)
   file = File.new(output,"w")
   file << getSource(withMain)
   file.close
end

def execSource
   form = FormMaker.new(@doc,true,@i18nfunc)
   source = form.rootForm.getExtraRequires
   if(@enableUtfTr)
      source += @utfTrCode
   end 
   source += form.rootForm.toString
   source += form.getMainProgram
   source
   #eval(source)
end
end

#main part

def usage
   STDERR.print ("Usage: #{$0}  [options] <uifile>\n\nOptions:\n",
                       "-o, --output file 	write output to file rather than stdout\n",
                       "-tr func		User func(...) rather than tr(...) for i18n\n",
                       "-x, --execute		Generate extra code to test the class\n",
                       "-h, --help		print help\n" ,
                       "-e, --test		launch test form.\n",
                       "-ns --no_source	suppress output of source to stdout\n")
end

separator = "\n"
if(ARGV.size == 0)
   usage
   exit 1
end

outfile = nil
withMain = false
i18nfunc = "tr"
outsource = true

while ARGV[0] =~ /^-/
   case ARGV.shift
   when '-h', '--help'
      usage
      exit 1
   when '-o', '--output'
      outfile = ARGV.shift
   when '-x', '--execute'
      withMain = true
   when '-tr'
      i18nfunc = ARGV.shift
   when '-e', '--test'
      launchForm = true
   when '-ns','--no_source'
      outsource = false
   end
end

require "qt2"
include Qt2
require "qt2xml"
include Qt2xml
require "formmaker.rb"

uifile = ARGV.shift
if(uifile == nil)
   STDERR.print("Error: no ui file\n")
   usage
   exit 1
end

ui2rb = Ui2rb.new(uifile)
ui2rb.setI18nFunc(i18nfunc)

if(outfile != nil)
   ui2rb.saveSource(outfile,withMain)
elsif(outsource)
   ui2rb.printSource(withMain)
end

if(launchForm)
   eval(ui2rb.execSource)
end

exit 0









