clipboard-rs 0.3.2

Cross-platform clipboard API (text | image | rich text | html | files | monitoring changes) | 跨平台剪贴板 API(文本|图片|富文本|html|文件|监听变化) Windows,MacOS,Linux
Documentation
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
use crate::common::Result;
#[cfg(feature = "image")]
use crate::common::{RustImage, RustImageData};
use crate::{Clipboard, ClipboardContent, ClipboardHandler, ClipboardWatcher, ContentFormat};
use objc2::rc::Retained;
use objc2::AllocAnyThread;
use objc2::ClassType;
use objc2::{rc::autoreleasepool, runtime::ProtocolObject};
use objc2_app_kit::{
	NSImage, NSPasteboard, NSPasteboardItem, NSPasteboardType, NSPasteboardTypeFileURL,
	NSPasteboardTypeHTML, NSPasteboardTypePNG, NSPasteboardTypeRTF, NSPasteboardTypeString,
	NSPasteboardTypeTIFF,
};
use objc2_foundation::{NSArray, NSData, NSString, NSURL};
use std::ffi::c_void;
use std::sync::mpsc::{self, Receiver, Sender};
use std::time::Duration;
use std::vec;

pub struct ClipboardContext {
	pasteboard: Retained<NSPasteboard>,
}

pub struct ClipboardWatcherContext<T: ClipboardHandler> {
	pasteboard: Retained<NSPasteboard>,
	handlers: Vec<T>,
	stop_signal: Sender<()>,
	stop_receiver: Receiver<()>,
	running: bool,
}

unsafe impl<T: ClipboardHandler> Send for ClipboardWatcherContext<T> {}

impl<T: ClipboardHandler> ClipboardWatcherContext<T> {
	pub fn new() -> Result<Self> {
		let ns_pasteboard = NSPasteboard::generalPasteboard();
		let (tx, rx) = mpsc::channel();
		Ok(ClipboardWatcherContext {
			pasteboard: ns_pasteboard,
			handlers: Vec::new(),
			stop_signal: tx,
			stop_receiver: rx,
			running: false,
		})
	}
}

impl<T: ClipboardHandler> ClipboardWatcher<T> for ClipboardWatcherContext<T> {
	fn add_handler(&mut self, handler: T) -> &mut Self {
		self.handlers.push(handler);
		self
	}

	fn start_watch(&mut self) {
		if self.running {
			println!("already start watch!");
			return;
		}
		if self.handlers.is_empty() {
			println!("no handler, no need to start watch!");
			return;
		}
		self.running = true;
		let mut last_change_count = self.pasteboard.changeCount();
		loop {
			// if receive stop signal, break loop
			if self
				.stop_receiver
				.recv_timeout(Duration::from_millis(500))
				.is_ok()
			{
				break;
			}
			let change_count = self.pasteboard.changeCount();
			if last_change_count == 0 {
				last_change_count = change_count;
			} else if change_count != last_change_count {
				self.handlers
					.iter_mut()
					.for_each(|handler| handler.on_clipboard_change());
				last_change_count = change_count;
			}
		}
		self.running = false;
	}

	fn get_shutdown_channel(&self) -> WatcherShutdown {
		WatcherShutdown {
			stop_signal: self.stop_signal.clone(),
		}
	}
}

impl ClipboardContext {
	pub fn new() -> Result<ClipboardContext> {
		let ns_pasteboard = NSPasteboard::generalPasteboard();
		let clipboard_ctx = ClipboardContext {
			pasteboard: ns_pasteboard,
		};
		Ok(clipboard_ctx)
	}

	fn plain(&self, r#type: &NSPasteboardType) -> Result<String> {
		autoreleasepool(|_| {
			let contents = self
				.pasteboard
				.pasteboardItems()
				.ok_or("NSPasteboard#pasteboardItems errored")?;
			for item in contents {
				if let Some(string) = item.stringForType(r#type) {
					return Ok(string.to_string());
				}
			}
			Err("No string found".into())
		})
	}

	fn set_files(&self, files: &[String]) -> Result<()> {
		autoreleasepool(|_| {
			// Build NSArray<NSURL> and write via writeObjects for better compatibility
			let urls: Vec<Retained<NSURL>> = files
				.iter()
				.filter_map(|file_path| {
					// Normalize to local filesystem path, and verify it exists
					let local_path = if file_path.starts_with("file://") {
						file_path.trim_start_matches("file://").to_string()
					} else {
						file_path.clone()
					};
					if !std::path::Path::new(&local_path).exists() {
						return None;
					}
					let ns_path = NSString::from_str(&local_path);
					// NSURL::fileURLWithPath returns a retained NSURL
					let url = NSURL::fileURLWithPath(&ns_path);
					Some(url)
				})
				.collect();
			if urls.is_empty() {
				return Err("no valid files".into());
			}
			let write_objects = NSArray::from_retained_slice(
				&urls
					.iter()
					.map(|u| ProtocolObject::from_retained(u.clone()))
					.collect::<Vec<_>>(),
			);
			if !self.pasteboard.writeObjects(&write_objects) {
				return Err("writeObjects failed for files".into());
			}
			Ok(())
		})
	}

	// learn from https://github.com/zed-industries/zed/blob/79c1003b344ee513cf97ee8313c38c7c3f02c916/crates/gpui/src/platform/mac/platform.rs#L793
	fn write_to_clipboard(&self, data: &[ClipboardContent], with_clear: bool) -> Result<()> {
		if with_clear {
			self.pasteboard.clearContents();
		}
		autoreleasepool(|_| {
			// we create one NSPasteboardItem for all representations of the same content
			let item = NSPasteboardItem::new();
			let mut has_content_other_than_files = false;

			for d in data {
				match d {
					ClipboardContent::Text(text) => {
						item.setString_forType(&NSString::from_str(text), unsafe {
							NSPasteboardTypeString
						});
						has_content_other_than_files = true;
					}
					ClipboardContent::Rtf(rtf) => {
						let rtf_data = unsafe {
							NSData::dataWithBytes_length(rtf.as_ptr() as *const c_void, rtf.len())
						};
						item.setData_forType(&rtf_data, unsafe { NSPasteboardTypeRTF });
						has_content_other_than_files = true;
					}
					ClipboardContent::Html(html) => {
						item.setString_forType(&NSString::from_str(html), unsafe {
							NSPasteboardTypeHTML
						});
						has_content_other_than_files = true;
					}
					#[cfg(feature = "image")]
					ClipboardContent::Image(image) => {
						if let Ok(png_buffer) = image.to_png() {
							let bytes = png_buffer.get_bytes();
							let ns_data = unsafe {
								NSData::dataWithBytes_length(
									bytes.as_ptr() as *mut c_void,
									bytes.len(),
								)
							};
							item.setData_forType(&ns_data, unsafe { NSPasteboardTypePNG });
							has_content_other_than_files = true;
						};
					}
					ClipboardContent::Files(files) => {
						// Files are set seperately
						let _ = self.set_files(files);
					}
					ClipboardContent::Other(format, buffer) => {
						let ns_data = unsafe {
							NSData::dataWithBytes_length(
								buffer.as_ptr() as *mut c_void,
								buffer.len(),
							)
						};
						item.setData_forType(&ns_data, &NSString::from_str(format));
						has_content_other_than_files = true;
					}
				}
			}
			if has_content_other_than_files {
				let write_objects =
					NSArray::from_retained_slice(&[ProtocolObject::from_retained(item)]);
				if !self.pasteboard.writeObjects(&write_objects) {
					return Err("writeObjects failed");
				}
			}
			Ok(())
		})?;
		Ok(())
	}
}

unsafe impl Send for ClipboardContext {}

unsafe impl Sync for ClipboardContext {}

impl Clipboard for ClipboardContext {
	fn available_formats(&self) -> Result<Vec<String>> {
		let types = self
			.pasteboard
			.types()
			.ok_or("NSPasteboard#types errored")?;
		let res = types.iter().map(|t| t.to_string()).collect();
		Ok(res)
	}

	fn has(&self, format: ContentFormat) -> bool {
		match format {
			ContentFormat::Text => {
				let types = NSArray::arrayWithObject(unsafe { NSPasteboardTypeString });
				// https://developer.apple.com/documentation/appkit/nspasteboard/1526078-availabletypefromarray?language=objc
				// The first pasteboard type in types that is available on the pasteboard, or nil if the receiver does not contain any of the types in types.
				// self.clipboard.availableTypeFromArray(types)
				self.pasteboard.availableTypeFromArray(&types).is_some()
			}
			ContentFormat::Rtf => {
				let types = NSArray::arrayWithObject(unsafe { NSPasteboardTypeRTF });
				self.pasteboard.availableTypeFromArray(&types).is_some()
			}
			ContentFormat::Html => {
				// Currently only judge whether there is a public.html format
				let types = NSArray::arrayWithObject(unsafe { NSPasteboardTypeHTML });
				self.pasteboard.availableTypeFromArray(&types).is_some()
			}
			#[cfg(feature = "image")]
			ContentFormat::Image => {
				// Currently only judge whether there is a png format
				let types = NSArray::from_retained_slice(&[
					unsafe { NSPasteboardTypePNG }.to_owned(),
					unsafe { NSPasteboardTypeTIFF }.to_owned(),
				]);
				self.pasteboard.availableTypeFromArray(&types).is_some()
			}
			ContentFormat::Files => {
				let types = NSArray::arrayWithObject(unsafe { NSPasteboardTypeFileURL });
				self.pasteboard.availableTypeFromArray(&types).is_some()
			}
			ContentFormat::Other(format) => {
				let types = NSArray::from_retained_slice(&[NSString::from_str(&format)]);
				self.pasteboard.availableTypeFromArray(&types).is_some()
			}
		}
	}

	fn clear(&self) -> Result<()> {
		self.pasteboard.clearContents();
		Ok(())
	}

	fn get_buffer(&self, format: &str) -> Result<Vec<u8>> {
		if let Some(data) = self.pasteboard.dataForType(&NSString::from_str(format)) {
			return Ok(data.to_vec());
		}
		Err("no data".into())
	}

	fn get_text(&self) -> Result<String> {
		self.plain(unsafe { NSPasteboardTypeString })
	}

	fn get_rich_text(&self) -> Result<String> {
		self.plain(unsafe { NSPasteboardTypeRTF })
	}

	fn get_html(&self) -> Result<String> {
		self.plain(unsafe { NSPasteboardTypeHTML })
	}

	#[cfg(feature = "image")]
	fn get_image(&self) -> Result<RustImageData> {
		autoreleasepool(|_| {
			let png_data = self.pasteboard.dataForType(unsafe { NSPasteboardTypePNG });
			if let Some(data) = png_data {
				return RustImageData::from_bytes(&data.to_vec());
			};
			// if no png data, read NSImage;
			let ns_image = NSImage::initWithPasteboard(NSImage::alloc(), &self.pasteboard);
			if let Some(image) = ns_image {
				let tiff_data = image.TIFFRepresentation();
				if let Some(data) = tiff_data {
					return RustImageData::from_bytes(&data.to_vec());
				}
			};
			Err("no image data".into())
		})
	}

	fn get_files(&self) -> Result<Vec<String>> {
		autoreleasepool(|_| {
			let mut res = vec![];
			// 使用 readObjectsForClasses 读取 NSURL(文件 URL)
			// 相当于 Objective-C: [pasteboard readObjectsForClasses:@[[NSURL class]] options:nil]
			let classes = NSArray::arrayWithObject(NSURL::class());
			let objects = unsafe {
				self.pasteboard
					.readObjectsForClasses_options(&classes, None)
			};
			if let Some(objects) = objects {
				for any_obj in objects {
					// 尝试将返回对象视为 NSURL
					if let Ok(url) = any_obj.downcast::<NSURL>() {
						// 只接受文件 URL
						if url.isFileURL() {
							// 优先使用 path(去掉 file:// 前缀后的本地路径)
							if let Some(path) = url.path() {
								res.push(path.to_string());
							} else {
								// 兜底使用 absoluteString,再去掉前缀
								let abs = if let Some(s) = url.absoluteString() {
									s.to_string()
								} else {
									String::new()
								};
								let file_path = if abs.starts_with("file://") {
									abs.strip_prefix("file://").unwrap_or(&abs).to_string()
								} else {
									abs
								};
								res.push(file_path);
							}
						}
					}
				}
			}
			if res.is_empty() {
				return Err("no files".into());
			}
			Ok(res)
		})
	}

	fn get(&self, formats: &[ContentFormat]) -> Result<Vec<ClipboardContent>> {
		autoreleasepool(|_| {
			let contents = self
				.pasteboard
				.pasteboardItems()
				.ok_or("NSPasteboard#pasteboardItems errored")?;
			let mut results = Vec::new();
			for format in formats {
				for item in contents.iter() {
					match format {
						ContentFormat::Text => {
							if let Some(string) =
								item.stringForType(unsafe { NSPasteboardTypeString })
							{
								results.push(ClipboardContent::Text(string.to_string()));
								break;
							}
						}
						ContentFormat::Rtf => {
							if let Some(string) = item.stringForType(unsafe { NSPasteboardTypeRTF })
							{
								results.push(ClipboardContent::Rtf(string.to_string()));
								break;
							}
						}
						ContentFormat::Html => {
							if let Some(string) =
								item.stringForType(unsafe { NSPasteboardTypeHTML })
							{
								results.push(ClipboardContent::Html(string.to_string()));
								break;
							}
						}
						#[cfg(feature = "image")]
						ContentFormat::Image => {
							if let Ok(image) = self.get_image() {
								results.push(ClipboardContent::Image(image));
								break;
							}
						}
						ContentFormat::Files => {
							if let Ok(files) = self.get_files() {
								results.push(ClipboardContent::Files(files));
								break;
							}
						}
						ContentFormat::Other(format_name) => {
							if let Some(data) = item.dataForType(&NSString::from_str(format_name)) {
								results.push(ClipboardContent::Other(
									format_name.to_string(),
									data.to_vec(),
								));
								break;
							}
						}
					}
				}
			}
			Ok(results)
		})
	}

	fn set_buffer(&self, format: &str, buffer: Vec<u8>) -> Result<()> {
		self.write_to_clipboard(&[ClipboardContent::Other(format.to_owned(), buffer)], true)
	}

	fn set_text(&self, text: String) -> Result<()> {
		self.write_to_clipboard(&[ClipboardContent::Text(text)], true)
	}

	fn set_rich_text(&self, text: String) -> Result<()> {
		self.write_to_clipboard(&[ClipboardContent::Rtf(text)], true)
	}

	fn set_html(&self, html: String) -> Result<()> {
		self.write_to_clipboard(&[ClipboardContent::Html(html)], true)
	}

	#[cfg(feature = "image")]
	fn set_image(&self, image: RustImageData) -> Result<()> {
		self.write_to_clipboard(&[ClipboardContent::Image(image)], true)
	}

	fn set_files(&self, files: Vec<String>) -> Result<()> {
		if files.is_empty() {
			return Err("file list is empty".into());
		}
		let _ = self.clear();
		self.set_files(&files)
	}

	fn set(&self, contents: Vec<ClipboardContent>) -> Result<()> {
		if contents.is_empty() {
			return Err(
				"contents is empty, if you want to clear clipboard, please use clear method".into(),
			);
		}
		self.write_to_clipboard(&contents, true)
	}
}

pub struct WatcherShutdown {
	stop_signal: Sender<()>,
}

impl Drop for WatcherShutdown {
	fn drop(&mut self) {
		let _ = self.stop_signal.send(());
	}
}