forked from cjpais/Handy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclipboard.rs
More file actions
408 lines (352 loc) · 12.9 KB
/
clipboard.rs
File metadata and controls
408 lines (352 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
use crate::input::{self, EnigoState};
use crate::settings::{get_settings, ClipboardHandling, PasteMethod};
use enigo::Enigo;
use log::info;
use tauri::{AppHandle, Manager};
use tauri_plugin_clipboard_manager::ClipboardExt;
#[cfg(target_os = "linux")]
use crate::utils::is_wayland;
#[cfg(target_os = "linux")]
use std::process::Command;
/// Pastes text using the clipboard: saves current content, writes text, sends paste keystroke, restores clipboard.
fn paste_via_clipboard(
enigo: &mut Enigo,
text: &str,
app_handle: &AppHandle,
paste_method: &PasteMethod,
) -> Result<(), String> {
let clipboard = app_handle.clipboard();
let clipboard_content = clipboard.read_text().unwrap_or_default();
// Write text to clipboard first
clipboard
.write_text(text)
.map_err(|e| format!("Failed to write to clipboard: {}", e))?;
std::thread::sleep(std::time::Duration::from_millis(50));
// Send paste key combo
#[cfg(target_os = "linux")]
let key_combo_sent = try_send_key_combo_linux(paste_method)?;
#[cfg(not(target_os = "linux"))]
let key_combo_sent = false;
// Fall back to enigo if no native tool handled it
if !key_combo_sent {
match paste_method {
PasteMethod::CtrlV => input::send_paste_ctrl_v(enigo)?,
PasteMethod::CtrlShiftV => input::send_paste_ctrl_shift_v(enigo)?,
PasteMethod::ShiftInsert => input::send_paste_shift_insert(enigo)?,
_ => return Err("Invalid paste method for clipboard paste".into()),
}
}
std::thread::sleep(std::time::Duration::from_millis(50));
// Restore original clipboard content
clipboard
.write_text(&clipboard_content)
.map_err(|e| format!("Failed to restore clipboard: {}", e))?;
Ok(())
}
/// Attempts to send a key combination using Linux-native tools.
/// Returns `Ok(true)` if a native tool handled it, `Ok(false)` to fall back to enigo.
#[cfg(target_os = "linux")]
fn try_send_key_combo_linux(paste_method: &PasteMethod) -> Result<bool, String> {
if is_wayland() {
// Wayland: prefer wtype, then dotool, then ydotool
if is_wtype_available() {
info!("Using wtype for key combo");
send_key_combo_via_wtype(paste_method)?;
return Ok(true);
}
if is_dotool_available() {
info!("Using dotool for key combo");
send_key_combo_via_dotool(paste_method)?;
return Ok(true);
}
if is_ydotool_available() {
info!("Using ydotool for key combo");
send_key_combo_via_ydotool(paste_method)?;
return Ok(true);
}
} else {
// X11: prefer xdotool, then ydotool
if is_xdotool_available() {
info!("Using xdotool for key combo");
send_key_combo_via_xdotool(paste_method)?;
return Ok(true);
}
if is_ydotool_available() {
info!("Using ydotool for key combo");
send_key_combo_via_ydotool(paste_method)?;
return Ok(true);
}
}
Ok(false)
}
/// Attempts to type text directly using Linux-native tools.
/// Returns `Ok(true)` if a native tool handled it, `Ok(false)` to fall back to enigo.
#[cfg(target_os = "linux")]
fn try_direct_typing_linux(text: &str) -> Result<bool, String> {
if is_wayland() {
// Wayland: prefer wtype, then dotool, then ydotool
if is_wtype_available() {
info!("Using wtype for direct text input");
type_text_via_wtype(text)?;
return Ok(true);
}
if is_dotool_available() {
info!("Using dotool for direct text input");
type_text_via_dotool(text)?;
return Ok(true);
}
if is_ydotool_available() {
info!("Using ydotool for direct text input");
type_text_via_ydotool(text)?;
return Ok(true);
}
} else {
// X11: prefer xdotool, then ydotool
if is_xdotool_available() {
info!("Using xdotool for direct text input");
type_text_via_xdotool(text)?;
return Ok(true);
}
if is_ydotool_available() {
info!("Using ydotool for direct text input");
type_text_via_ydotool(text)?;
return Ok(true);
}
}
Ok(false)
}
/// Check if wtype is available (Wayland text input tool)
#[cfg(target_os = "linux")]
fn is_wtype_available() -> bool {
Command::new("which")
.arg("wtype")
.output()
.map(|output| output.status.success())
.unwrap_or(false)
}
/// Check if dotool is available (another Wayland text input tool)
#[cfg(target_os = "linux")]
fn is_dotool_available() -> bool {
Command::new("which")
.arg("dotool")
.output()
.map(|output| output.status.success())
.unwrap_or(false)
}
/// Check if ydotool is available (uinput-based, works on both Wayland and X11)
#[cfg(target_os = "linux")]
fn is_ydotool_available() -> bool {
Command::new("which")
.arg("ydotool")
.output()
.map(|output| output.status.success())
.unwrap_or(false)
}
#[cfg(target_os = "linux")]
fn is_xdotool_available() -> bool {
Command::new("which")
.arg("xdotool")
.output()
.map(|output| output.status.success())
.unwrap_or(false)
}
/// Type text directly via wtype on Wayland.
#[cfg(target_os = "linux")]
fn type_text_via_wtype(text: &str) -> Result<(), String> {
let output = Command::new("wtype")
.arg("--") // Protect against text starting with -
.arg(text)
.output()
.map_err(|e| format!("Failed to execute wtype: {}", e))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!("wtype failed: {}", stderr));
}
Ok(())
}
/// Type text directly via xdotool on X11.
#[cfg(target_os = "linux")]
fn type_text_via_xdotool(text: &str) -> Result<(), String> {
let output = Command::new("xdotool")
.arg("type")
.arg("--clearmodifiers")
.arg("--")
.arg(text)
.output()
.map_err(|e| format!("Failed to execute xdotool: {}", e))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!("xdotool failed: {}", stderr));
}
Ok(())
}
/// Type text directly via dotool (works on both Wayland and X11 via uinput).
#[cfg(target_os = "linux")]
fn type_text_via_dotool(text: &str) -> Result<(), String> {
use std::io::Write;
use std::process::Stdio;
let mut child = Command::new("dotool")
.stdin(Stdio::piped())
.spawn()
.map_err(|e| format!("Failed to spawn dotool: {}", e))?;
if let Some(mut stdin) = child.stdin.take() {
// dotool uses "type <text>" command
writeln!(stdin, "type {}", text)
.map_err(|e| format!("Failed to write to dotool stdin: {}", e))?;
}
let output = child
.wait_with_output()
.map_err(|e| format!("Failed to wait for dotool: {}", e))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!("dotool failed: {}", stderr));
}
Ok(())
}
/// Type text directly via ydotool (uinput-based, requires ydotoold daemon).
#[cfg(target_os = "linux")]
fn type_text_via_ydotool(text: &str) -> Result<(), String> {
let output = Command::new("ydotool")
.arg("type")
.arg("--")
.arg(text)
.output()
.map_err(|e| format!("Failed to execute ydotool: {}", e))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!("ydotool failed: {}", stderr));
}
Ok(())
}
/// Send a key combination (e.g., Ctrl+V) via wtype on Wayland.
#[cfg(target_os = "linux")]
fn send_key_combo_via_wtype(paste_method: &PasteMethod) -> Result<(), String> {
let args: Vec<&str> = match paste_method {
PasteMethod::CtrlV => vec!["-M", "ctrl", "-k", "v"],
PasteMethod::ShiftInsert => vec!["-M", "shift", "-k", "Insert"],
PasteMethod::CtrlShiftV => vec!["-M", "ctrl", "-M", "shift", "-k", "v"],
_ => return Err("Unsupported paste method".into()),
};
let output = Command::new("wtype")
.args(&args)
.output()
.map_err(|e| format!("Failed to execute wtype: {}", e))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!("wtype failed: {}", stderr));
}
Ok(())
}
/// Send a key combination (e.g., Ctrl+V) via dotool.
#[cfg(target_os = "linux")]
fn send_key_combo_via_dotool(paste_method: &PasteMethod) -> Result<(), String> {
let command;
match paste_method {
PasteMethod::CtrlV => command = "echo key ctrl+v | dotool",
PasteMethod::ShiftInsert => command = "echo key shift+insert | dotool",
PasteMethod::CtrlShiftV => command = "echo key ctrl+shift+v | dotool",
_ => return Err("Unsupported paste method".into()),
}
let output = Command::new("sh")
.arg("-c")
.arg(command)
.output()
.map_err(|e| format!("Failed to execute dotool: {}", e))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!("dotool failed: {}", stderr));
}
Ok(())
}
/// Send a key combination (e.g., Ctrl+V) via ydotool (requires ydotoold daemon).
#[cfg(target_os = "linux")]
fn send_key_combo_via_ydotool(paste_method: &PasteMethod) -> Result<(), String> {
// ydotool uses Linux input event keycodes with format <keycode>:<pressed>
// where pressed is 1 for down, 0 for up. Keycodes: ctrl=29, shift=42, v=47, insert=110
let args: Vec<&str> = match paste_method {
PasteMethod::CtrlV => vec!["key", "29:1", "47:1", "47:0", "29:0"],
PasteMethod::ShiftInsert => vec!["key", "42:1", "110:1", "110:0", "42:0"],
PasteMethod::CtrlShiftV => vec!["key", "29:1", "42:1", "47:1", "47:0", "42:0", "29:0"],
_ => return Err("Unsupported paste method".into()),
};
let output = Command::new("ydotool")
.args(&args)
.output()
.map_err(|e| format!("Failed to execute ydotool: {}", e))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!("ydotool failed: {}", stderr));
}
Ok(())
}
/// Send a key combination (e.g., Ctrl+V) via xdotool on X11.
#[cfg(target_os = "linux")]
fn send_key_combo_via_xdotool(paste_method: &PasteMethod) -> Result<(), String> {
let key_combo = match paste_method {
PasteMethod::CtrlV => "ctrl+v",
PasteMethod::CtrlShiftV => "ctrl+shift+v",
PasteMethod::ShiftInsert => "shift+Insert",
_ => return Err("Unsupported paste method".into()),
};
let output = Command::new("xdotool")
.arg("key")
.arg("--clearmodifiers")
.arg(key_combo)
.output()
.map_err(|e| format!("Failed to execute xdotool: {}", e))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!("xdotool failed: {}", stderr));
}
Ok(())
}
/// Types text directly by simulating individual key presses.
fn paste_direct(enigo: &mut Enigo, text: &str) -> Result<(), String> {
#[cfg(target_os = "linux")]
{
if try_direct_typing_linux(text)? {
return Ok(());
}
info!("Falling back to enigo for direct text input");
}
input::paste_text_direct(enigo, text)
}
pub fn paste(text: String, app_handle: AppHandle) -> Result<(), String> {
let settings = get_settings(&app_handle);
let paste_method = settings.paste_method;
// Append trailing space if setting is enabled
let text = if settings.append_trailing_space {
format!("{} ", text)
} else {
text
};
info!("Using paste method: {:?}", paste_method);
// Get the managed Enigo instance
let enigo_state = app_handle
.try_state::<EnigoState>()
.ok_or("Enigo state not initialized")?;
let mut enigo = enigo_state
.0
.lock()
.map_err(|e| format!("Failed to lock Enigo: {}", e))?;
// Perform the paste operation
match paste_method {
PasteMethod::None => {
info!("PasteMethod::None selected - skipping paste action");
}
PasteMethod::Direct => {
paste_direct(&mut enigo, &text)?;
}
PasteMethod::CtrlV | PasteMethod::CtrlShiftV | PasteMethod::ShiftInsert => {
paste_via_clipboard(&mut enigo, &text, &app_handle, &paste_method)?
}
}
// After pasting, optionally copy to clipboard based on settings
if settings.clipboard_handling == ClipboardHandling::CopyToClipboard {
let clipboard = app_handle.clipboard();
clipboard
.write_text(&text)
.map_err(|e| format!("Failed to copy to clipboard: {}", e))?;
}
Ok(())
}