###################################
#
# clipboard.rb
# Programmed by  nyasu <nyasu@osk.3web.ne.jp>
# Copyright 2000-2001 Nishikawa,Yasuhiro
#
# More information at http://www.threeweb.ad.jp/~nyasu/software/vrproject.html
# (in Japanese)
#
###################################

vr_DIR="vr/" unless vr_DIR
require vr_DIR+'sysmod'
require 'Win32API'

class Clipboard
  GetClipboardData = Win32API.new('user32','GetClipboardData','I','L')
  SetClipboardData = Win32API.new('user32','SetClipboardData','IL','L')
  EnumClipboardFormats = Win32API.new('user32','EnumClipboardFormats','I','I')
  OpenClipboard = Win32API.new('user32','OpenClipboard','L','I')
  CloseClipboard = Win32API.new('user32','CloseClipboard','V','I')
  EmptyClipboard = Win32API.new('user32','EmptyClipboard','V','I')

  CF_TEXT = 1
#

  def self.open(*args)
    r = self.new(*args)
    if iterator?
      yield r
      r.close
    else
      return r
    end
  end

  def initialize(hwnd)
    @hwnd = hwnd
    @opened = (OpenClipboard.call(hwnd)!=0)
    raise "fail to open clipboard" unless @opened
  end

  def close
    @opened = (CloseClipboard.call() == 0)
  end

  def getData(uformat)
    raise "Clipboard not opened" unless @opened
    gmem = GetClipboardData.call(uformat.to_i)
    raise "GetData failed" if gmem==0
    GMEM::Get(gmem) if gmem!=0
  end

  def setData(uformat,data)
    raise "Clipboard not opened" unless @opened
    EmptyClipboard.call
    gmem = GMEM::AllocStr(66,data)
    SetClipboardData.call(uformat,gmem)
#    GMEM::Free(gmem)
  end

  def getText
    r=getData(CF_TEXT)
    r.split("\0",0)[0]
  end

  def setText(str)
    setData CF_TEXT,str.to_s
  end

  def enum_formats
    r=0
    while true do
      r=EnumClipboardFormats.call(r)
      break if r==0
      yield r 
    end
  end
end


