1
1
use anyhow:: { anyhow, Result } ;
2
- #[ cfg( target_family = "unix" ) ]
3
- #[ cfg( not( target_os = "macos" ) ) ]
4
- use std:: ffi:: OsStr ;
5
2
use std:: io:: Write ;
3
+ use std:: path:: PathBuf ;
6
4
use std:: process:: { Command , Stdio } ;
5
+ use which:: which;
7
6
8
- fn execute_copy_command ( command : Command , text : & str ) -> Result < ( ) > {
9
- let mut command = command;
7
+ fn exec_copy_with_args (
8
+ command : & str ,
9
+ args : & [ & str ] ,
10
+ text : & str ,
11
+ ) -> Result < ( ) > {
12
+ let binary = which ( command)
13
+ . ok ( )
14
+ . unwrap_or_else ( || PathBuf :: from ( command) ) ;
10
15
11
- let mut process = command
16
+ let mut process = Command :: new ( binary)
17
+ . args ( args)
12
18
. stdin ( Stdio :: piped ( ) )
13
19
. stdout ( Stdio :: null ( ) )
14
20
. spawn ( )
@@ -28,47 +34,35 @@ fn execute_copy_command(command: Command, text: &str) -> Result<()> {
28
34
Ok ( ( ) )
29
35
}
30
36
31
- #[ cfg( all( target_family = "unix" , not( target_os = "macos" ) ) ) ]
32
- fn gen_command (
33
- path : impl AsRef < OsStr > ,
34
- xclip_syntax : bool ,
35
- ) -> Command {
36
- let mut c = Command :: new ( path) ;
37
- if xclip_syntax {
38
- c. arg ( "-selection" ) ;
39
- c. arg ( "clipboard" ) ;
40
- } else {
41
- c. arg ( "--clipboard" ) ;
42
- }
43
- c
37
+ fn exec_copy ( command : & str , text : & str ) -> Result < ( ) > {
38
+ exec_copy_with_args ( command, & [ ] , text)
44
39
}
45
40
46
41
#[ cfg( all( target_family = "unix" , not( target_os = "macos" ) ) ) ]
47
- pub fn copy_string ( string : & str ) -> Result < ( ) > {
48
- use std:: path:: PathBuf ;
49
- use which:: which;
50
- let ( path, xclip_syntax) = which ( "xclip" ) . ok ( ) . map_or_else (
51
- || {
52
- (
53
- which ( "xsel" )
54
- . ok ( )
55
- . unwrap_or_else ( || PathBuf :: from ( "xsel" ) ) ,
56
- false ,
57
- )
58
- } ,
59
- |path| ( path, true ) ,
60
- ) ;
42
+ pub fn copy_string ( text : & str ) -> Result < ( ) > {
43
+ if std:: env:: var ( "WAYLAND_DISPLAY" ) . is_ok ( ) {
44
+ return exec_copy ( "wl-copy" , text) ;
45
+ }
61
46
62
- let cmd = gen_command ( path, xclip_syntax) ;
63
- execute_copy_command ( cmd, string)
47
+ if exec_copy_with_args (
48
+ "xclip" ,
49
+ & [ "-selection" , "clipboard" ] ,
50
+ text,
51
+ )
52
+ . is_err ( )
53
+ {
54
+ return exec_copy_with_args ( "xsel" , & [ "--clipboard" ] , text) ;
55
+ }
56
+
57
+ Ok ( ( ) )
64
58
}
65
59
66
60
#[ cfg( target_os = "macos" ) ]
67
- pub fn copy_string ( string : & str ) -> Result < ( ) > {
68
- execute_copy_command ( Command :: new ( "pbcopy" ) , string )
61
+ pub fn copy_string ( text : & str ) -> Result < ( ) > {
62
+ exec_copy ( "pbcopy" , text )
69
63
}
70
64
71
65
#[ cfg( windows) ]
72
- pub fn copy_string ( string : & str ) -> Result < ( ) > {
73
- execute_copy_command ( Command :: new ( "clip" ) , string )
66
+ pub fn copy_string ( text : & str ) -> Result < ( ) > {
67
+ exec_copy ( "clip" , text )
74
68
}
0 commit comments