#!/usr/bin/env ruby

# mdnd.rb

ProgName = 'mdnd.rb'
Version = '20070704'

require 'gtk2'
require 'uri'
require 'optparse'

parser = OptionParser.new
parser.program_name = ProgName
parser.version = Version
parser.banner = <<EOS
#{parser.program_name}  version #{parser.version}

Usage #{parser.program_name} [options] [filename...]
EOS

parser.parse!

if ARGV.empty?
  puts parser.to_s
  exit 0
end

class MainWin < Gtk::Window
  def initialize
    super ::ProgName
    @urilist = []

    self.border_width = 8
    Gtk::Drag.source_set(self, Gdk::Window::BUTTON1_MASK |
				 Gdk::Window::BUTTON3_MASK,
                         [["text/uri-list", 0, 0]],
                         Gdk::DragContext::ACTION_COPY |
                           Gdk::DragContext::ACTION_MOVE)
    signal_connect('drag_data_get') {|widget, context, selection_data, info, time|
      # Note: Ruby interpreter dumps core
      #       without selection_data fed ``deep'' clones.
      selection_data.set_uris @urilist.collect{|elm| elm.clone}

      destroy
      Gtk.main_quit
    }
    signal_connect('key_press_event') {|widget, event|
      case event.keyval
      when Gdk::Keyval::GDK_Escape, Gdk::Keyval::GDK_q
        destroy
        Gtk.main_quit
      end
    }
    signal_connect('delete_event') {
      destroy
      Gtk.main_quit
    }
    label = Gtk::Label.new('Drag from here')
    add label
    show_all
  end

  def register_files(argv)
    @urilist.concat argv.collect {|elm|
      begin
        str = 'file://' + URI.escape(File.expand_path(elm))
        # puts str
      rescue
        $stderr.puts $!
      end
    }
  end
end

mainWin = MainWin.new
mainWin.register_files(ARGV)
Gtk.main

