#!/usr/bin/env ruby
#  Copyright (C) 1999 Kikutani Makoto <g@kondara.org>
#  Copyright (C) 2000 Kondara Project <http://www.kondara.org>
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 
require "parsearg"

Xinit = '/etc/X11/xinit'
Outs = ['lang', 'xim', 'session']
Outdir = File.expand_path('~/.xinit.d')

$deflt_vars = {}
$mouse_region = []
$selecters = []

$files = {}
$cbs = {}
$labels = {}
$labels['lang'] = 'Language'
$labels['xim'] = 'Input Method'
$labels['session'] = 'Session'
$hash = {}
$hash2 = {}

  def save
    # unless FileTest.directory?(Outdir)
    #  len, str = sl_read_mini(sprintf("want to create %s ? (Y/n)", Outdir))
    #  if len == 0 or str !~ /^[Nn]/
    #    Dir.mkdir(Outdir)
    #  end
    # end
    Outs.each do |category|
      v = $cbs[category].entry.text
      outpath = Outdir + '/' + category
      open(outpath, "w") do |out|
        printf(out, "%s\n", $hash2[v])
      end
    end
    save_gdm()
  end

  def save_gdm
    outpath = File.expand_path('~/') + '/.dmrc'
    open(outpath, "w") do |gdm|
      printf(gdm, "[Desktop]\n")
      printf(gdm, "Session=%s\n",$hash2[$cbs["session"].entry.text])
      printf(gdm, "Language=%s\n",$hash2[$cbs["lang"].entry.text])
    end
  end

  def about
    d = Gtk::Dialog::new()
    d.set_title("About")

    mtextwin = Gtk::ScrolledWindow.new(nil,nil)
    d.vbox.pack_start(mtextwin, TRUE, TRUE, 0)
    mtextwin.show

    mtext = Gtk::TextView.new(nil)
    mtext.editable = false
    mtextwin.add(mtext)
    mtext.buffer.insert(mtext.buffer.get_iter_at_offset(0),
                   "SDR 0.9.5\n" +
                   "Copyright (C) 1999 Kikutani Makoto <g@kondara.org>\n" +
                   "Copyright (C) 2000 Kondara Project <http://www.kondara.org>\n" +
                   "\n" +
                   "This program is free software; you can redistribute it and/or modify\n" +
                   "it under the terms of the GNU General Public License as published by\n" +
                   "the Free Software Foundation; either version 2 of the License, or\n" +
                   "(at your option) any later version.\n" +
                   "\n" +
                   "This program is distributed in the hope that it will be useful,\n" +
                   "but WITHOUT ANY WARRANTY; without even the implied warranty of\n" +
                   "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n" +
                   "GNU General Public License for more details.\n" +
                   "\n" +
                   "You should have received a copy of the GNU General Public License\n" +
                   "along with this program; if not, write to the Free Software\n" +
                   "Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n" +
                   "\n" +
                   "$Id: sdr.rb,v 1.34 2000/11/02 03:57:24 g Exp $\n")
    mtext.show

    button = Gtk::Button::new("OK")
    d.action_area.pack_start(button, TRUE, TRUE, 0)
    button.signal_connect("clicked") { Gtk::main_quit() }
    button.set_flags(Gtk::Widget::CAN_DEFAULT)
    button.grab_default
    button.show

    d.set_default_size(640, 480)
    d.show
  
    d.set_modal(TRUE);
    Gtk.main
    d.destroy
  end

  def gtkmain
    Outs.each do |f|
      inpath = Outdir + '/' + f
      begin
        dflt = nil
        open(inpath, "r") do |inp|
          dflt = inp.read.chop
        end
        $deflt_vars[f] = dflt
      rescue
        # do nothing
      end
    end

    w = Gtk::Window::new(Gtk::Window::TOPLEVEL)
    w.set_default_size(384, 240)
    w.signal_connect("delete_event") { exit }
    w.signal_connect("destroy") { exit }
    w.set_title("SDR")
#    w.set_policy(false, true, false)

    main = Gtk::VBox::new(false, 0)
    main.set_border_width(1)
    w.add(main)
    main.show

    menubar = Gtk::MenuBar::new()
    main.pack_start(menubar, false, true, 0)
    menubar.show

    menu = Gtk::Menu::new()
    menuitem = Gtk::MenuItem::new("File")
    menuitem.set_submenu(menu)
    menubar.append(menuitem)
    menuitem.show

    menuitem = Gtk::MenuItem::new("Exit")
    menuitem.signal_connect("activate") { exit }
    menu.append(menuitem)
    menuitem.show
    menu.show

    menu3 = Gtk::Menu::new()
    menuitem3 = Gtk::MenuItem::new("Help")
    menuitem3.set_submenu(menu3)
    menubar.append(menuitem3)
    menuitem3.show
    
    menuitem3 = Gtk::MenuItem::new("About SDR...")
    menuitem3.signal_connect("activate") { about }
    menu3.append(menuitem3)
    menuitem3.show
    menu3.show

    table = Gtk::Table::new(3, 2, FALSE)
    table.set_row_spacings(20)
    table.set_column_spacings(30)
    table.set_border_width(20)

    main.pack_start(table, true, true, 0)
    table.show

    i = 0
    Outs.each do |category|
      label = Gtk::Label::new($labels[category])
      label.set_alignment(0, 0.5)
      table.attach(label, 0, 1, i, i + 1, Gtk::FILL, Gtk::FILL, 0, 0)
      label.show

      $cbs[category]= Gtk::Combo::new()
      table.attach($cbs[category], 1, 2, i, i + 1, nil, nil, 0, 0)
      $cbs[category].show
      i = i + 1
    end

    hsep = Gtk::HSeparator::new()
    main.pack_start(hsep, false, false, 0)
    hsep.show

    hbox = Gtk::HButtonBox::new()
    hbox.set_border_width(10)
    main.pack_start(hbox, false, false, 0)
    hbox.show

    button = Gtk::Button::new("OK")
    button.signal_connect("clicked") { save(); exit }
    hbox.add(button)
    button.set_flags(Gtk::Widget::CAN_DEFAULT)
    button.grab_default
    button.show

    button = Gtk::Button::new("Cancel")
    button.signal_connect("clicked") { exit }
    hbox.pack_end(button, true, true, 0)
    button.set_flags(Gtk::Widget::CAN_DEFAULT)
    button.show

    Outs.each do |category|
      $files[category] = []
      if /^session$/ =~ category then
        f = "UserDefined"
      else
        f = "None"
      end
      $files[category] << f
      $hash[f] = f
      $hash2[f] = f;
      Dir.foreach(Xinit + '/' + category + '.d') do |f|
        next if f == '.' or f == '..'
        name = f
        ifexists = []
        File.foreach(Xinit + '/' + category + '.d/' + f) do |line|
          if /^NAME="(.*)"$/ =~ line then
            name = $1
          elsif /^NAME=(.*)$/ =~ line then
            name = $1
	  elsif /^IFEXISTS="(.*)"$/ =~ line then
	    ifexists = $1.split(/:/)
          elsif /^IFEXISTS=(.*)$/ =~ line then
	    ifexists = $1.split(/:/)
	  end
        end
        next if ifexists.find{|ff| !FileTest.exist?(ff)}
	$files[category] << name
	$hash[f] = name;
	$hash2[name] = f;
      end
      $files[category].sort!
      $cbs[category].set_popdown_strings($files[category])
      if $deflt_vars.has_key?(category)
	if dflt = $hash[$deflt_vars[category]]
	  $cbs[category].entry.set_text(dflt) if dflt != nil
	end
      end
    end

    main.show
    w.show
    Gtk::main()
  end

def show_usage()
  printf("Usage: %s\n", $0)
  printf("       you can not execute console mode.\n", $0)
end
$USAGE='show_usage'

gtk = nil

begin
  gtk = true if ENV['DISPLAY'] =~ /.+/
rescue
  # do nothing
end

require 'gtk2'
Gtk.init
gtkmain
