v / cmd / tools / modules / vshare / clipboard.v
69 lines · 64 sloc · 1.46 KB · e2e5cf8db56f3562c7baa735061690be936bdf3e
Raw
1module vshare
2
3import os
4import time
5
6struct ClipboardCommand {
7 executable string
8 command string
9}
10
11// copy_to_clipboard copies `text` to the first available OS clipboard command.
12pub fn copy_to_clipboard(text string) bool {
13 return copy_to_clipboard_with_commands(text, clipboard_commands())
14}
15
16fn copy_to_clipboard_with_commands(text string, commands []ClipboardCommand) bool {
17 if text.len == 0 || commands.len == 0 {
18 return false
19 }
20 temp_file := os.join_path(os.vtmp_dir(),
21 'vshare_clipboard_${os.getpid()}_${time.now().unix_micro()}.txt')
22 os.write_file(temp_file, text) or { return false }
23 defer {
24 os.rm(temp_file) or {}
25 }
26 for command in commands {
27 if !os.exists_in_system_path(command.executable) {
28 continue
29 }
30 cmd := command.command.replace('@FILE@', os.quoted_path(temp_file))
31 if os.execute(cmd).exit_code == 0 {
32 return true
33 }
34 }
35 return false
36}
37
38fn clipboard_commands() []ClipboardCommand {
39 $if windows {
40 return [
41 ClipboardCommand{
42 executable: 'clip.exe'
43 command: 'type @FILE@ | clip'
44 },
45 ]
46 } $else $if macos {
47 return [
48 ClipboardCommand{
49 executable: 'pbcopy'
50 command: 'pbcopy < @FILE@'
51 },
52 ]
53 } $else {
54 return [
55 ClipboardCommand{
56 executable: 'wl-copy'
57 command: 'wl-copy < @FILE@'
58 },
59 ClipboardCommand{
60 executable: 'xclip'
61 command: 'xclip -selection clipboard @FILE@'
62 },
63 ClipboardCommand{
64 executable: 'xsel'
65 command: 'xsel --clipboard --input < @FILE@'
66 },
67 ]
68 }
69}
70