Coder Social home page Coder Social logo

churchtao / clipboard-rs Goto Github PK

View Code? Open in Web Editor NEW
37.0 2.0 7.0 449 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.11"

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

Contract

if you have any questions, you can contact me by email: [email protected]

Chinese users can also contact me by wechatNo: uniq_idx_church_lynn

License

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

clipboard-rs's People

Contributors

churchtao avatar getreu avatar huakunshen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

clipboard-rs's Issues

`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

`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: 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

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

如何获取复制内容的 app 来源

The feature request | 需求描述

大佬,您有没有推荐的方法能够在兼容各平台的情况下,获取复制内容的 app 来源啊!

Proposed solution | 解决方案

希望大佬能指点迷津,谢谢😁

关于`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操作。

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

当写入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

设置剪切板时图片失真,像素偏移

The problem | 问题描述

截图工具 pixpin

原图:
1721711358842
设置剪切板后:
1721711376563

使用ClipboardWatcherContext监听剪切板变化,然后将获取到的图片立刻set回去,此时图片失真

impl ClipboardHandler for Manager {
    fn on_clipboard_change(&mut self) {
        if self.ctx.has(ContentFormat::Text) {
            if let Ok(result) = self.ctx.get_text() {
                info!("复制了文字{}", result);
            }
        } else if self.ctx.has(ContentFormat::Image) {
            if let Ok(result) = self.ctx.get_image() {
                info!("复制了图片");
                let _ = self.ctx.set_image(result);
            }
        }
    }
}

Release version | 版本

0.1.9

Operating system | 操作系统

windows 11

Logs | 日志

None

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

如何触发富文本的复制

The feature request | 需求描述

大佬,怎么正确的触发富文本的复制啊,我这里一直都是 has_html 为 true,has_rich_text 为 false!

#[command]
async fn has_html(manager: State<'_, ClipboardManager>) -> Result<bool> {
    Ok(manager.has(ContentFormat::Html))
}

#[command]
async fn has_rich_text(manager: State<'_, ClipboardManager>) -> Result<bool> {
    Ok(manager.has(ContentFormat::Rtf))
}

Proposed solution | 解决方案

求解惑,谢谢大佬😁

linux 下 get_files()一直拿不到结果

The problem | 问题描述

我用的是国产化 uos 操作系统
当清掉剪贴板内容后,立马执行 get_files()获取剪贴板文件路径,有一定概率没有返回结果,这样会导致程序卡死,我看 process_event 的代码是有超时,但是没用到,这个可以加上吗,还是有其他的方式解决

Release version | 版本

1.7

Operating system | 操作系统

uos

Logs | 日志

No response

[bug] windows 系统 html 写入剪切板的问题

The problem | 问题描述

在 Windows 系统中,我发现一个奇怪的问题:当我先使用 write_files 复制一个文件时,粘贴操作是正常的;但随后如果我使用 write_html 复制 HTML 内容,粘贴时依然会是之前复制的文件!而在 MacOS 上,这个现象并不会出现。

#[command]
async fn write_files(manager: State<'_, ClipboardManager>, value: Vec<String>) -> Result<()> {
    manager.context.set_files(value).unwrap();

    Ok(())
}

#[command]
async fn write_html(
    manager: State<'_, ClipboardManager>,
    text: String,
    html: String,
) -> Result<()> {
    let contents = vec![ClipboardContent::Text(text), ClipboardContent::Html(html)];

    manager.context.set(contents).unwrap();

    Ok(())
}

Release version | 版本

0.1.7

Operating system | 操作系统

Windows 11

Logs | 日志

iShot_2024-07-21_15.18.47.1.mp4

如何计算图像的哈希值?

The feature request | 需求描述

大佬,我是 Rust 新手,现在正在处理 read_image 拿到的图像的哈希值计算,以便将哈希值作为文件名称,这样可以避免重复复制相同的图片。我尝试使用 img_hash 库,但在参数传递时总是出错。希望能得到您的帮助,谢谢!

Proposed solution | 解决方案

我主要就是想实现避免重复复制相同的图片,希望能得到您的帮助,提供一个实现思路,非常感谢!

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();

重新复制 HTML 时,部分软件粘贴失效

The problem | 问题描述

大佬,我在对 get_html() 获取到的内容,原封不动的调用 set_html(html),但是发现这样的话在 vscode、微信、谷歌浏览器(目前只发现这几个)粘贴都是失效的,但是其它同类型剪切板 app 重新复制粘贴是没有问题的!这个不知道是啥情况,还望大佬解惑😁

Release version | 版本

0.1.7

Operating system | 操作系统

MacOS M1 Pro Sonoma 14.4

Logs | 日志

No response

在微信选中文字就会触发 `on_clipboard_change`

The problem | 问题描述

大佬,忽然发现在微信上随便选几个字,但是不复制,仍然会触发 on_clipboard_change 事件,但是复制的内容又没发生变化,这是什么情况啊!🤨

iShot_2024-06-21_18.09.21.1.mp4

Release version | 版本

0.1.7

Operating system | 操作系统

MacOS M1 Pro Sonoma 14.4

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.