Module: Clipboard::Utils

Extended by:
Utils
Included in:
Utils
Defined in:
lib/clipboard/utils.rb

Instance Method Summary collapse

Instance Method Details

#autodetect_implementationObject

Find out which implementation is best to use



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/clipboard/utils.rb', line 13

def autodetect_implementation
  os = case RbConfig::CONFIG['host_os']
  when /mac|darwin/        then :Mac
  when /linux|bsd/         then :Linux
  when /mswin|mingw/       then :Windows
  when /cygwin/            then :Cygwin
  else
    raise ClipboardLoadError, "clipboard: Could not find suitable implementation for OS(#{ RbConfig::CONFIG['host_os'] })"
  end

  # Running additional check to detect if running in Microsoft WSL or Wayland
  if os == :Linux
    require "etc"
    if Etc.uname[:release] =~ /Microsoft/
      os = :Wsl
    # Only choose Wayland implementation if wl-copy is found, since xclip / xsel *might* work
    elsif ENV["XDG_SESSION_TYPE"] == "wayland" && executable_installed?("wl-copy")
      os = :LinuxWayland
    end
  end

  os
end

#executable_installed?(cmd) ⇒ Boolean

Check if a necessary command is available

Returns:

  • (Boolean)


38
39
40
41
42
# File 'lib/clipboard/utils.rb', line 38

def executable_installed?(cmd)
  ENV['PATH'].split(::File::PATH_SEPARATOR).any? do |path|
    ::File.executable?(::File.join(path, cmd))
  end
end

#popen(cmd, data, read_output_stream = false) ⇒ Object

Utility to call external command

  • pure .popen2 becomes messy with xsel when not reading the output stream

  • xclip doesn’t like to have output stream read



47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/clipboard/utils.rb', line 47

def popen(cmd, data, read_output_stream = false)
  Open3.popen2(cmd) { |input, output, waiter_thread|
    output_thread = Thread.new { output.read } if read_output_stream

    begin
      input.write data
    rescue Errno::EPIPE
    end

    input.close
    output_thread.value if read_output_stream
    waiter_thread.value
  }
end