Giter Site home page Giter Site logo

churchtao / clipboard-rs Goto Github PK

View Code? Open in Web Editor NEW
21.0 2.0 3.0 369 KB

Cross-platform clipboard API (text | image | rich text | html | files | monitoring changes) | 跨平台剪贴板 API(文本|图片|富文本|html|文件|监听变化) Windows,MacOS,Linux

Home Page: https://docs.rs/clipboard-rs

License: MIT License

Rust 100.00%
clipboard cross-platform rust electron tauri

clipboard-rs's Introduction

clipboard-rs

Latest version Documentation GitHub Actions Workflow Status MSRV GitHub License

clipboard-rs is a cross-platform library written in Rust for getting and setting the system-level clipboard content. It supports Linux, Windows, and MacOS.

简体中文

Function Support

  • Plain text
  • Html
  • Rich text
  • Image (In PNG format)
  • File (In file-uri-list format)
  • Any type (by specifying the type identifier) can be obtained through the available_formats method

Development Plan

  • MacOS Support
  • Linux Support (x11)
  • Windows Support

Usage

Add the following content to your Cargo.toml:

[dependencies]
clipboard-rs = "0.1.7"

Examples

All Usage Examples

Examples

Simple Read and Write

use clipboard_rs::{Clipboard, ClipboardContext, ContentFormat};

fn main() {
	let ctx = ClipboardContext::new().unwrap();
	let types = ctx.available_formats().unwrap();
	println!("{:?}", types);

	let has_rtf = ctx.has(ContentFormat::Rtf);
	println!("has_rtf={}", has_rtf);

	let rtf = ctx.get_rich_text().unwrap_or("".to_string());

	println!("rtf={}", rtf);

	let has_html = ctx.has(ContentFormat::Html);
	println!("has_html={}", has_html);

	let html = ctx.get_html().unwrap_or("".to_string());

	println!("html={}", html);

	let content = ctx.get_text().unwrap_or("".to_string());

	println!("txt={}", content);
}

Reading Images

use clipboard_rs::{common::RustImage, Clipboard, ClipboardContext};

const TMP_PATH: &str = "/tmp/";

fn main() {
	let ctx = ClipboardContext::new().unwrap();
	let types = ctx.available_formats().unwrap();
	println!("{:?}", types);

	let img = ctx.get_image();

	match img {
		Ok(img) => {
			img.save_to_path(format!("{}test.png", TMP_PATH).as_str())
				.unwrap();

			let resize_img = img.thumbnail(300, 300).unwrap();

			resize_img
				.save_to_path(format!("{}test_thumbnail.png", TMP_PATH).as_str())
				.unwrap();
		}
		Err(err) => {
			println!("err={}", err);
		}
	}
}

Reading Any Format

use clipboard_rs::{Clipboard, ClipboardContext};

fn main() {
    let ctx = ClipboardContext::new().unwrap();
    let types = ctx.available_formats().unwrap();
    println!("{:?}", types);

    let buffer = ctx.get_buffer("public.html").unwrap();

    let string = String::from_utf8(buffer).unwrap();

    println!("{}", string);
}

Listening to Clipboard Changes

use clipboard_rs::{
	Clipboard, ClipboardContext, ClipboardHandler, ClipboardWatcher, ClipboardWatcherContext,
};
use std::{thread, time::Duration};

struct Manager {
	ctx: ClipboardContext,
}

impl Manager {
	pub fn new() -> Self {
		let ctx = ClipboardContext::new().unwrap();
		Manager { ctx }
	}
}

impl ClipboardHandler for Manager {
	fn on_clipboard_change(&mut self) {
		println!(
			"on_clipboard_change, txt = {}",
			self.ctx.get_text().unwrap()
		);
	}
}

fn main() {
	let manager = Manager::new();

	let mut watcher = ClipboardWatcherContext::new().unwrap();

	let watcher_shutdown = watcher.add_handler(manager).get_shutdown_channel();

	thread::spawn(move || {
		thread::sleep(Duration::from_secs(5));
		println!("stop watch!");
		watcher_shutdown.stop();
	});

	println!("start watch!");
	watcher.start_watch();
}

Contributing

You are welcome to submit PRs and issues and contribute your code or ideas to the project. Due to my limited level, the library may also have bugs. You are welcome to point them out and I will modify them as soon as possible.

Thanks

License

This project is licensed under the MIT License. See the LICENSE file for details.

clipboard-rs's People

Contributors

churchtao avatar huakunshen avatar getreu avatar

Stargazers

陈磊 avatar zhongxiaotian avatar Chris Raethke avatar Jerry avatar 晓文 avatar qnnp avatar Scc avatar Qingmu avatar Icemic avatar Andy Gayton avatar Ricky avatar ahnan avatar  avatar  avatar  avatar xi4f3i avatar Null avatar Murat avatar  avatar  avatar Brandon A. Cardiel avatar

Watchers

 avatar Brandon A. Cardiel avatar

clipboard-rs's Issues

Abnormal exit

thread '' panicked at C:\Users\Administrator.cargo\registry\src\github.com-1ecc6299db9ec823\clipboard-rs-0.1.2\src\platform\win.rs:72:60:
Open clipboard: OSError(5)
note: run with RUST_BACKTRACE=1 environment variable to display a backtrace

Recurrence method : When copying text in windows Terminal

`set_html()` doesn't update text.

The problem | 问题描述

Original issue CrossCopy/tauri-plugin-clipboard#28

let ctx = ClipboardContext::new().unwrap();

ctx.set_html("<h1>hello</h1>".to_string()).unwrap();
let txt = ctx.get_text().unwrap();
println!("txt: {:?}", txt);
let html = ctx.get_html().unwrap();
println!("html: {:?}", html);

Output:

txt: ""
html: "<h1>hello</h1>"

Expected Behaviour

get_text() should return some text after set_html().

If I run both set_text() and set_html(), the later command will overwrite the first.

Release version | 版本

0.1.6

Operating system | 操作系统

Mac 14.4.1 + Win11

Logs | 日志

No response

Bug: Cannot read clipboard image on MacOS for screenshots taken by certain apps

The problem | 问题描述

Issue first mentioned in CrossCopy/tauri-plugin-clipboard#21 by @Tester-957

Screenshots taken with Feishu/Lark can neither be detected nor read by clipboard-rs, while regular screenshots and screenshots taken by other apps like WeChat could be detected.

By running the sample code we can see that ctx.get_image() doesn't return Err, but the resulting image has a size of (0, 0)

Release version | 版本

0.1.5

Operating system | 操作系统

MacOS

Logs | 日志

No response

关于`ClipboardWatcherContext.start_watch()`方法的一点疑问。

作者你好,由于start_watch()会阻塞当前线程,因此我将它放进新的线程中执行,结果无法监听到剪贴板的内容了,且同时无法shutdown。以下是我的代码:

use clipboard_rs::{Clipboard, ClipboardContext, ClipboardWatcher, ClipboardWatcherContext};
use std::{
    sync::{Arc, Mutex},
    thread,
    time::Duration,
};
struct ClipboardManager {
    ctx: Arc<Mutex<ClipboardContext>>,
    watcher: Arc<Mutex<ClipboardWatcherContext>>,
}

impl ClipboardManager {
    fn new() -> Self {
        ClipboardManager {
            ctx: Arc::new(Mutex::new(ClipboardContext::new().unwrap())),
            watcher: Arc::new(Mutex::new(ClipboardWatcherContext::new().unwrap())),
        }
    }
}

fn main() {
    let manager = ClipboardManager::new();

    let ctx = Arc::clone(&manager.ctx);
    let watcher = Arc::clone(&manager.watcher);
    let start_handle = thread::spawn(move || {
        let mut watcher = watcher.lock().unwrap();
        watcher.add_handler(Box::new(move || {
            let content = ctx.lock().unwrap().get_text().unwrap();
            println!("read:{}", content);
        }));

        println!("start watch!");
        watcher.start_watch();
    });

    let watcher = Arc::clone(&manager.watcher);
    let watcher_shutdown = watcher.lock().unwrap().get_shutdown_channel();
    let stop_handle = thread::spawn(move || {
        thread::sleep(Duration::from_secs(10));
        println!("stop watch!");
        watcher_shutdown.stop();
    });

    println!("main");
    stop_handle.join().unwrap();
    start_handle.join().unwrap();
}

还请作者帮忙看下是不是我的写法有问题,我又应该怎么去声明一个全局的watcher让它能够在任何地方都能够监听到剪贴板的内容和随时进行shutdown操作。

当写入html时,在Windows上长度似乎是有限制的,并且会被自动截断。截断的长度不固定

The problem | 问题描述

这是在另一个项目中提交的讨论:CrossCopy/tauri-plugin-clipboard#29
🐛因为内容是从剪切板中读取出来的HTML,使用API原样写入时遇到这个限制。通过系统快捷键写入的html没有这个限制。
🤖我不确定这是否是Windows的限制还是BUG ~

Release version | 版本

0.1.6

Operating system | 操作系统

Windows 11

Logs | 日志

Length (original): 132205
Length: 205

ClipboardContext 能否实现 Clone / Copy ?

The feature request | 需求描述

尝试将 ClipboardContext 进行保存到对应的状态对象中( 比如 tauri 提供 manage 存储 state )

move occurs because value has type ClipboardContext, which does not implement the Copy trait Help: consider borrowing here

Proposed solution | 解决方案

None

Does the get_image Method Support Windows?

Hello,

I'm experiencing an issue with the clipboard_rs crate on Windows 10, where I'm unable to retrieve an image from the clipboard using the provided example code. Despite having used the clipboard image tool to copy an image to the clipboard, the result returned by get_image is an empty image.

Here is the code snippet I'm using:

use clipboard_rs::{common::RustImage, Clipboard, ClipboardContext};
let ctx = ClipboardContext::new().unwrap();
let img = ctx.get_image().unwrap();

`get_files` Segmentation Fault when there is no files on clipboard

The problem | 问题描述

https://github.com/ChurchTao/clipboard-rs/blob/master/examples/files.rs

get_files gives me segmentation fault when there is no file on clipboard

let files = ctx.get_files().unwrap_or(vec![]);

Release version | 版本

0.1.3

Operating system | 操作系统

MacOS 14.4 (Arm)

Logs | 日志

["public.utf8-plain-text", "NSStringPboardType", "org.chromium.source-url"]
has_files=false
[1]    91105 segmentation fault  cargo run --bin read_files

Bug: No transparent background for clipboard image read on Windows

The problem | 问题描述

After copying image from apps like Microsoft paint or PowerPoint, pasting the image elsewhere should give a transparent background.

The pasted image should be like the one on the right, while image returned from clipboard-rs gives the one on the left (white background).

Release version | 版本

0.1.5

Operating system | 操作系统

Win11

Logs | 日志

No response

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.