Module: Clipboard::Windows

Extended by:
Windows
Included in:
Windows
Defined in:
lib/clipboard/windows.rb

Defined Under Namespace

Modules: Kernel32, User32

Constant Summary collapse

CF_TEXT =
1
CF_UNICODETEXT =
13
GMEM_MOVEABLE =
2

Instance Method Summary collapse

Instance Method Details

#clearObject



71
72
73
74
75
76
77
# File 'lib/clipboard/windows.rb', line 71

def clear
  if 0 != User32.open( 0 )
    User32.empty( )
    User32.close( )
  end
  paste
end

#copy(data_to_copy) ⇒ Object



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/clipboard/windows.rb', line 79

def copy(data_to_copy)
  if RubyVersion >= 1.9 && 0 != User32.open( 0 )
    User32.empty( )
    data = data_to_copy.encode("UTF-16LE") # TODO catch bad encodings
    data << 0 << 0
    handler = Kernel32.alloc( GMEM_MOVEABLE, data.bytesize )
    pointer_to_data = Kernel32.lock( handler )
    pointer_to_data.put_bytes( 0, data, 0, data.bytesize )
    Kernel32.unlock( handler )
    User32.set( CF_UNICODETEXT, handler )
    User32.close( )
  else # don't touch anything
    Open3.popen3( 'clip' ){ |input,_,_| input << data_to_copy } # depends on clip (available by default since Vista)
  end
  paste
end

#paste(_ = nil) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/clipboard/windows.rb', line 42

def paste(_ = nil)
  ret = ""
    if 0 != User32.open( 0 )
      hclip = User32.get( CF_UNICODETEXT )
      if hclip && 0 != hclip
        pointer_to_data = Kernel32.lock( hclip )
        data = ""
        # Windows Unicode is ended by to null bytes, so get the whole string
        current_byte = 0
        until data.size >= 2 && data[-1].ord == 0 && data[-2].ord == 0
          data << pointer_to_data.get_bytes( current_byte, 1 )
          current_byte += 1
        end
        if RubyVersion >= 1.9
          ret = data.chop.force_encoding("UTF-16LE").encode(Encoding.default_external) # TODO catch bad encodings
        else # 1.8: fallback to simple CP850 encoding
          require 'iconv'
          utf8 = Iconv.iconv( "UTF-8", "UTF-16LE", data.chop)[0]
          ret = Iconv.iconv( "CP850", "UTF-8", utf8)[0]
        end
      if data && 0 != data
        Kernel32.unlock( hclip )
      end
    end
    User32.close( )
  end
  ret || ""
end