├── .gitignore ├── rustfmt.toml ├── x11 ├── Cargo.toml ├── src │ ├── error.rs │ └── lib.rs └── LICENSE ├── wayland ├── Cargo.toml ├── src │ └── lib.rs └── LICENSE ├── src ├── platform │ ├── macos.rs │ ├── windows.rs │ ├── dummy.rs │ ├── ios.rs │ ├── android.rs │ └── linux.rs └── lib.rs ├── .github └── workflows │ └── test.yml ├── README.md ├── macos ├── Cargo.toml ├── src │ └── lib.rs └── LICENSE ├── examples ├── read.rs ├── write.rs └── big_file.rs ├── LICENSE └── Cargo.toml /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | max_width=80 2 | wrap_comments=true 3 | merge_imports=true 4 | -------------------------------------------------------------------------------- /x11/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "clipboard_x11" 3 | version = "0.4.3" 4 | authors = ["Héctor Ramón Jiménez "] 5 | edition = "2018" 6 | description = "A library to obtain access to the X11 clipboard" 7 | license = "MIT" 8 | repository = "https://github.com/hecrj/window_clipboard" 9 | documentation = "https://docs.rs/clipboard_x11" 10 | keywords = ["clipboard", "x11"] 11 | 12 | [dependencies] 13 | x11rb = "0.13" 14 | thiserror = "2.0" 15 | -------------------------------------------------------------------------------- /wayland/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "clipboard_wayland" 3 | version = "0.2.2" 4 | authors = ["Héctor Ramón Jiménez "] 5 | edition = "2018" 6 | description = "A library to obtain access to the clipboard of a Wayland window" 7 | license = "Apache-2.0" 8 | repository = "https://github.com/hecrj/window_clipboard" 9 | documentation = "https://docs.rs/clipboard_wayland" 10 | keywords = ["clipboard", "wayland"] 11 | 12 | [dependencies] 13 | smithay-clipboard = "0.7" 14 | -------------------------------------------------------------------------------- /src/platform/macos.rs: -------------------------------------------------------------------------------- 1 | use crate::ClipboardProvider; 2 | 3 | use raw_window_handle::HasDisplayHandle; 4 | use std::error::Error; 5 | 6 | pub fn connect( 7 | _window: &W, 8 | ) -> Result, Box> { 9 | Ok(Box::new(clipboard_macos::Clipboard::new()?)) 10 | } 11 | 12 | impl ClipboardProvider for clipboard_macos::Clipboard { 13 | fn read(&self) -> Result> { 14 | self.read() 15 | } 16 | 17 | fn write(&mut self, contents: String) -> Result<(), Box> { 18 | self.write(contents) 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | on: [push, pull_request] 3 | jobs: 4 | all: 5 | runs-on: ${{ matrix.os }} 6 | strategy: 7 | matrix: 8 | os: [ubuntu-latest, windows-latest, macOS-latest] 9 | rust: [stable, beta] 10 | steps: 11 | - uses: hecrj/setup-rust-action@v1 12 | with: 13 | rust-version: ${{ matrix.rust }} 14 | - uses: actions/checkout@master 15 | - name: Run tests 16 | run: cargo test --verbose 17 | - name: Add Wasm target 18 | run: rustup target add wasm32-unknown-unknown 19 | - name: Run tests on Wasm 20 | run: cargo build --verbose --target wasm32-unknown-unknown 21 | -------------------------------------------------------------------------------- /src/platform/windows.rs: -------------------------------------------------------------------------------- 1 | use crate::ClipboardProvider; 2 | 3 | use clipboard_win::{get_clipboard_string, set_clipboard_string}; 4 | use raw_window_handle::HasDisplayHandle; 5 | 6 | use std::error::Error; 7 | 8 | pub fn connect( 9 | _window: &W, 10 | ) -> Result, Box> { 11 | Ok(Box::new(Clipboard)) 12 | } 13 | 14 | pub struct Clipboard; 15 | 16 | impl ClipboardProvider for Clipboard { 17 | fn read(&self) -> Result> { 18 | Ok(get_clipboard_string()?) 19 | } 20 | 21 | fn write(&mut self, contents: String) -> Result<(), Box> { 22 | Ok(set_clipboard_string(&contents)?) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # window_clipboard 2 | [![Documentation](https://docs.rs/window_clipboard/badge.svg)][documentation] 3 | [![Crates.io](https://img.shields.io/crates/v/window_clipboard.svg)](https://crates.io/crates/window_clipboard) 4 | [![Test Status](https://img.shields.io/github/actions/workflow/status/hecrj/window_clipboard/test.yml?branch=master&event=push&label=test)](https://github.com/hecrj/window_clipboard/actions) 5 | [![License](https://img.shields.io/crates/l/window_clipboard.svg)](https://github.com/hecrj/window_clipboard/blob/master/LICENSE) 6 | 7 | A library to obtain clipboard access from a `raw-window-handle`. 8 | 9 | __Very experimental, use at your own risk!__ 10 | 11 | [documentation]: https://docs.rs/window_clipboard 12 | -------------------------------------------------------------------------------- /src/platform/dummy.rs: -------------------------------------------------------------------------------- 1 | use crate::ClipboardProvider; 2 | 3 | use raw_window_handle::HasDisplayHandle; 4 | 5 | struct Dummy; 6 | 7 | pub fn connect( 8 | _window: &W, 9 | ) -> Result, Box> { 10 | Ok(Box::new(Dummy)) 11 | } 12 | 13 | impl ClipboardProvider for Dummy { 14 | fn read(&self) -> Result> { 15 | Err(Box::new(Error::Unimplemented)) 16 | } 17 | 18 | fn write( 19 | &mut self, 20 | _contents: String, 21 | ) -> Result<(), Box> { 22 | Err(Box::new(Error::Unimplemented)) 23 | } 24 | } 25 | 26 | #[derive(Debug, Clone, Copy, thiserror::Error)] 27 | enum Error { 28 | #[error("unimplemented")] 29 | Unimplemented, 30 | } 31 | -------------------------------------------------------------------------------- /macos/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "clipboard_macos" 3 | version = "0.1.1" 4 | authors = ["Héctor Ramón Jiménez "] 5 | edition = "2018" 6 | description = "A library to obtain access to the macOS clipboard" 7 | license = "Apache-2.0" 8 | repository = "https://github.com/hecrj/window_clipboard" 9 | documentation = "https://docs.rs/clipboard_macos" 10 | keywords = ["clipboard", "macos"] 11 | 12 | [package.metadata.docs.rs] 13 | default-target = "x86_64-apple-darwin" 14 | 15 | [dependencies] 16 | objc2 = "0.5.1" 17 | objc2-foundation = { version = "0.2.0", default-features = false, features = [ 18 | "std", 19 | "NSArray", 20 | "NSString", 21 | "NSURL", 22 | ] } 23 | objc2-app-kit = { version = "0.2.0", default-features = false, features = [ 24 | "std", 25 | "NSPasteboard", 26 | ] } 27 | -------------------------------------------------------------------------------- /x11/src/error.rs: -------------------------------------------------------------------------------- 1 | use x11rb::errors::{ConnectError, ConnectionError, ReplyError}; 2 | use x11rb::protocol::xproto::Atom; 3 | 4 | use std::sync::mpsc; 5 | 6 | #[must_use] 7 | #[derive(Debug, thiserror::Error)] 8 | pub enum Error { 9 | #[error("connection failed: {0}")] 10 | ConnectionFailed(#[from] ConnectError), 11 | #[error("connection errored: {0}")] 12 | ConnectionErrored(#[from] ConnectionError), 13 | #[error("reply failed: {0}")] 14 | ReplyError(#[from] ReplyError), 15 | #[error("timeout")] 16 | Timeout, 17 | #[error("unexpected type: {0}")] 18 | UnexpectedType(Atom), 19 | #[error("invalid utf8 string: {0}")] 20 | InvalidUtf8(std::string::FromUtf8Error), 21 | #[error("deadlock")] 22 | SelectionLocked, 23 | #[error("invalid selection owner")] 24 | InvalidOwner, 25 | #[error("worker communication error")] 26 | SendError(#[from] mpsc::SendError), 27 | } 28 | -------------------------------------------------------------------------------- /examples/read.rs: -------------------------------------------------------------------------------- 1 | use window_clipboard::Clipboard; 2 | use winit::{ 3 | error::EventLoopError, 4 | event::{Event, WindowEvent}, 5 | event_loop::EventLoop, 6 | window::WindowBuilder, 7 | }; 8 | 9 | fn main() -> Result<(), EventLoopError> { 10 | let event_loop = EventLoop::new().unwrap(); 11 | 12 | let window = WindowBuilder::new() 13 | .with_title("A fantastic window!") 14 | .build(&event_loop) 15 | .unwrap(); 16 | 17 | let clipboard = 18 | unsafe { Clipboard::connect(&window) }.expect("Connect to clipboard"); 19 | 20 | event_loop.run(move |event, elwt| match event { 21 | Event::AboutToWait => { 22 | println!("{:?}", clipboard.read()); 23 | } 24 | Event::WindowEvent { 25 | event: WindowEvent::CloseRequested, 26 | window_id, 27 | } if window_id == window.id() => elwt.exit(), 28 | _ => {} 29 | }) 30 | } 31 | -------------------------------------------------------------------------------- /examples/write.rs: -------------------------------------------------------------------------------- 1 | use window_clipboard::Clipboard; 2 | use winit::{ 3 | error::EventLoopError, 4 | event::{Event, WindowEvent}, 5 | event_loop::EventLoop, 6 | window::WindowBuilder, 7 | }; 8 | 9 | fn main() -> Result<(), EventLoopError> { 10 | let event_loop = EventLoop::new().unwrap(); 11 | 12 | let window = WindowBuilder::new() 13 | .with_title("A fantastic window!") 14 | .build(&event_loop) 15 | .unwrap(); 16 | 17 | let mut clipboard = 18 | unsafe { Clipboard::connect(&window) }.expect("Connect to clipboard"); 19 | 20 | clipboard 21 | .write(String::from("Hello, world!")) 22 | .expect("Write to clipboard"); 23 | 24 | event_loop.run(move |event, elwt| match event { 25 | Event::WindowEvent { 26 | event: WindowEvent::CloseRequested, 27 | window_id, 28 | } if window_id == window.id() => elwt.exit(), 29 | _ => {} 30 | }) 31 | } 32 | -------------------------------------------------------------------------------- /x11/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2019 quininer@live.com, Héctor Ramón, window_clipboard_x11 contributors 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2019 Héctor Ramón, window_clipboard contributors 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of 4 | this software and associated documentation files (the "Software"), to deal in 5 | the Software without restriction, including without limitation the rights to 6 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software is furnished to do so, 8 | subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 15 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 16 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 17 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 18 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 19 | -------------------------------------------------------------------------------- /src/platform/ios.rs: -------------------------------------------------------------------------------- 1 | use crate::ClipboardProvider; 2 | 3 | use raw_window_handle::HasDisplayHandle; 4 | use std::error::Error; 5 | 6 | pub fn connect( 7 | _window: &W, 8 | ) -> Result, Box> { 9 | Ok(Box::new(Clipboard::new()?)) 10 | } 11 | 12 | pub struct Clipboard; 13 | 14 | impl Clipboard { 15 | pub fn new() -> Result> { 16 | Ok(Self) 17 | } 18 | } 19 | 20 | #[derive(Debug)] 21 | #[allow(non_camel_case_types)] 22 | pub enum iOSClipboardError { 23 | Unimplemented, 24 | } 25 | 26 | impl std::fmt::Display for iOSClipboardError { 27 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 28 | write!(f, "Unimplemented") 29 | } 30 | } 31 | 32 | impl Error for iOSClipboardError {} 33 | 34 | impl ClipboardProvider for Clipboard { 35 | fn read(&self) -> Result> { 36 | Err(Box::new(iOSClipboardError::Unimplemented)) 37 | } 38 | 39 | fn write(&mut self, contents: String) -> Result<(), Box> { 40 | Err(Box::new(iOSClipboardError::Unimplemented)) 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/platform/android.rs: -------------------------------------------------------------------------------- 1 | use crate::ClipboardProvider; 2 | 3 | use raw_window_handle::HasDisplayHandle; 4 | use std::error::Error; 5 | 6 | pub fn connect( 7 | _window: &W, 8 | ) -> Result, Box> { 9 | Ok(Box::new(Clipboard::new()?)) 10 | } 11 | 12 | pub struct Clipboard; 13 | 14 | impl Clipboard { 15 | pub fn new() -> Result> { 16 | Ok(Self) 17 | } 18 | } 19 | 20 | #[derive(Debug)] 21 | #[allow(non_camel_case_types)] 22 | pub enum AndroidClipboardError { 23 | Unimplemented, 24 | } 25 | 26 | impl std::fmt::Display for AndroidClipboardError { 27 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 28 | write!(f, "Unimplemented") 29 | } 30 | } 31 | 32 | impl Error for AndroidClipboardError {} 33 | 34 | impl ClipboardProvider for Clipboard { 35 | fn read(&self) -> Result> { 36 | Err(Box::new(AndroidClipboardError::Unimplemented)) 37 | } 38 | 39 | fn write(&mut self, contents: String) -> Result<(), Box> { 40 | Err(Box::new(AndroidClipboardError::Unimplemented)) 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "window_clipboard" 3 | version = "0.5.1" 4 | authors = ["Héctor Ramón Jiménez "] 5 | edition = "2021" 6 | description = "A library to obtain clipboard access from a `raw-window-handle`" 7 | license = "MIT" 8 | repository = "https://github.com/hecrj/window_clipboard" 9 | documentation = "https://docs.rs/window_clipboard" 10 | readme = "README.md" 11 | keywords = ["clipboard", "window", "ui", "gui", "raw-window-handle"] 12 | categories = ["gui"] 13 | 14 | [features] 15 | default = ["x11", "wayland"] 16 | x11 = ["clipboard_x11"] 17 | wayland = ["clipboard_wayland"] 18 | 19 | [dependencies] 20 | raw-window-handle = { version = "0.6", features = ["std"] } 21 | thiserror = "2.0" 22 | 23 | [target.'cfg(windows)'.dependencies] 24 | clipboard-win = { version = "5.0", features = ["std"] } 25 | 26 | [target.'cfg(target_os = "macos")'.dependencies] 27 | clipboard_macos = { version = "0.1", path = "./macos" } 28 | 29 | [target.'cfg(all(unix, not(any(target_os="macos", target_os="android", target_os="emscripten", target_os="ios", target_os="redox"))))'.dependencies] 30 | clipboard_x11 = { version = "0.4.2", path = "./x11", optional = true } 31 | clipboard_wayland = { version = "0.2.2", path = "./wayland", optional = true } 32 | 33 | [dev-dependencies] 34 | rand = "0.8" 35 | winit = "0.29" 36 | 37 | [workspace] 38 | members = [ 39 | "macos", 40 | "wayland", 41 | "x11", 42 | ] 43 | -------------------------------------------------------------------------------- /wayland/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 Avraham Weinstock 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use std::error::Error; 16 | use std::ffi::c_void; 17 | use std::sync::{Arc, Mutex}; 18 | 19 | pub struct Clipboard { 20 | context: Arc>, 21 | } 22 | 23 | impl Clipboard { 24 | pub unsafe fn connect(display: *mut c_void) -> Clipboard { 25 | let context = Arc::new(Mutex::new(smithay_clipboard::Clipboard::new( 26 | display as *mut _, 27 | ))); 28 | 29 | Clipboard { context } 30 | } 31 | 32 | pub fn read(&self) -> Result> { 33 | Ok(self.context.lock().unwrap().load()?) 34 | } 35 | 36 | pub fn read_primary(&self) -> Result> { 37 | Ok(self.context.lock().unwrap().load_primary()?) 38 | } 39 | 40 | pub fn write(&mut self, data: String) -> Result<(), Box> { 41 | self.context.lock().unwrap().store(data); 42 | 43 | Ok(()) 44 | } 45 | 46 | pub fn write_primary(&mut self, data: String) -> Result<(), Box> { 47 | self.context.lock().unwrap().store_primary(data); 48 | 49 | Ok(()) 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /examples/big_file.rs: -------------------------------------------------------------------------------- 1 | use rand::distributions::{Alphanumeric, Distribution}; 2 | use window_clipboard::Clipboard; 3 | use winit::{ 4 | error::EventLoopError, 5 | event::{ElementState, Event, KeyEvent, WindowEvent}, 6 | event_loop::EventLoop, 7 | keyboard::Key, 8 | window::WindowBuilder, 9 | }; 10 | 11 | fn main() -> Result<(), EventLoopError> { 12 | let mut rng = rand::thread_rng(); 13 | 14 | let data: String = Alphanumeric 15 | .sample_iter(&mut rng) 16 | .take(10_000_000) 17 | .map(char::from) 18 | .collect(); 19 | 20 | let event_loop = EventLoop::new().unwrap(); 21 | 22 | let window = WindowBuilder::new() 23 | .with_title("Press G to start the test!") 24 | .build(&event_loop) 25 | .unwrap(); 26 | 27 | let mut clipboard = 28 | unsafe { Clipboard::connect(&window) }.expect("Connect to clipboard"); 29 | 30 | clipboard.write(data.clone()).unwrap(); 31 | 32 | event_loop.run(move |event, elwt| match event { 33 | Event::WindowEvent { 34 | event: 35 | WindowEvent::KeyboardInput { 36 | event: 37 | KeyEvent { 38 | logical_key: Key::Character(c), 39 | state: ElementState::Released, 40 | .. 41 | }, 42 | .. 43 | }, 44 | .. 45 | } if c == "G" => { 46 | let new_data = clipboard.read().expect("Read data"); 47 | assert_eq!(data, new_data, "Data is equal"); 48 | println!("Data copied successfully!"); 49 | } 50 | Event::WindowEvent { 51 | event: WindowEvent::CloseRequested, 52 | window_id, 53 | } if window_id == window.id() => elwt.exit(), 54 | _ => {} 55 | }) 56 | } 57 | -------------------------------------------------------------------------------- /src/platform/linux.rs: -------------------------------------------------------------------------------- 1 | use crate::ClipboardProvider; 2 | 3 | use raw_window_handle::{HasDisplayHandle, RawDisplayHandle}; 4 | use std::error::Error; 5 | 6 | #[cfg(feature = "wayland")] 7 | pub use clipboard_wayland as wayland; 8 | #[cfg(feature = "x11")] 9 | pub use clipboard_x11 as x11; 10 | 11 | #[derive(Debug)] 12 | struct LinuxClipboardError; 13 | 14 | impl std::fmt::Display for LinuxClipboardError { 15 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 16 | f.write_str("This window server's clipboard feature is not enabled") 17 | } 18 | } 19 | 20 | impl Error for LinuxClipboardError {} 21 | 22 | pub unsafe fn connect( 23 | window: &W, 24 | ) -> Result, Box> { 25 | let clipboard = match window.display_handle()?.as_raw() { 26 | #[cfg(feature = "wayland")] 27 | RawDisplayHandle::Wayland(handle) => { 28 | Box::new(wayland::Clipboard::connect(handle.display.as_ptr())) as _ 29 | } 30 | #[cfg(feature = "x11")] 31 | RawDisplayHandle::Xlib(_) | RawDisplayHandle::Xcb(_) => { 32 | Box::new(x11::Clipboard::connect()?) as _ 33 | } 34 | _ => Err(LinuxClipboardError)?, 35 | }; 36 | 37 | Ok(clipboard) 38 | } 39 | 40 | #[cfg(feature = "wayland")] 41 | impl ClipboardProvider for wayland::Clipboard { 42 | fn read(&self) -> Result> { 43 | self.read() 44 | } 45 | 46 | fn read_primary(&self) -> Option>> { 47 | Some(self.read_primary()) 48 | } 49 | 50 | fn write(&mut self, contents: String) -> Result<(), Box> { 51 | self.write(contents) 52 | } 53 | 54 | fn write_primary(&mut self, contents: String) -> Option>> { 55 | Some(self.write_primary(contents)) 56 | } 57 | } 58 | 59 | #[cfg(feature = "x11")] 60 | impl ClipboardProvider for x11::Clipboard { 61 | fn read(&self) -> Result> { 62 | self.read().map_err(Box::from) 63 | } 64 | 65 | fn read_primary(&self) -> Option>> { 66 | Some(self.read_primary().map_err(Box::from)) 67 | } 68 | 69 | fn write(&mut self, contents: String) -> Result<(), Box> { 70 | self.write(contents).map_err(Box::from) 71 | } 72 | 73 | fn write_primary(&mut self, contents: String) -> Option>> { 74 | Some(self.write_primary(contents).map_err(Box::from)) 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #[cfg(all( 2 | unix, 3 | not(any( 4 | target_os = "macos", 5 | target_os = "ios", 6 | target_os = "android", 7 | target_os = "emscripten", 8 | target_os = "redox" 9 | )) 10 | ))] 11 | #[path = "platform/linux.rs"] 12 | mod platform; 13 | 14 | #[cfg(target_os = "windows")] 15 | #[path = "platform/windows.rs"] 16 | mod platform; 17 | 18 | #[cfg(target_os = "macos")] 19 | #[path = "platform/macos.rs"] 20 | mod platform; 21 | 22 | #[cfg(target_os = "ios")] 23 | #[path = "platform/ios.rs"] 24 | mod platform; 25 | 26 | #[cfg(target_os = "android")] 27 | #[path = "platform/android.rs"] 28 | mod platform; 29 | 30 | #[cfg(not(any( 31 | all( 32 | unix, 33 | not(any( 34 | target_os = "macos", 35 | target_os = "ios", 36 | target_os = "android", 37 | target_os = "emscripten", 38 | target_os = "redox" 39 | )) 40 | ), 41 | target_os = "windows", 42 | target_os = "macos", 43 | target_os = "ios", 44 | target_os = "android" 45 | )))] 46 | #[path = "platform/dummy.rs"] 47 | mod platform; 48 | 49 | use raw_window_handle::HasDisplayHandle; 50 | use std::error::Error; 51 | 52 | pub struct Clipboard { 53 | raw: Box, 54 | } 55 | 56 | impl Clipboard { 57 | /// Safety: the display handle must be valid for the lifetime of `Clipboard` 58 | pub unsafe fn connect( 59 | window: &W, 60 | ) -> Result> { 61 | let raw = platform::connect(window)?; 62 | 63 | Ok(Clipboard { raw }) 64 | } 65 | 66 | pub fn read(&self) -> Result> { 67 | self.raw.read() 68 | } 69 | 70 | pub fn write(&mut self, contents: String) -> Result<(), Box> { 71 | self.raw.write(contents) 72 | } 73 | } 74 | 75 | impl Clipboard { 76 | pub fn read_primary(&self) -> Option>> { 77 | self.raw.read_primary() 78 | } 79 | 80 | pub fn write_primary(&mut self, contents: String) -> Option>> { 81 | self.raw.write_primary(contents) 82 | } 83 | } 84 | 85 | pub trait ClipboardProvider { 86 | fn read(&self) -> Result>; 87 | 88 | fn write(&mut self, contents: String) -> Result<(), Box>; 89 | 90 | fn read_primary(&self) -> Option>> { 91 | None 92 | } 93 | 94 | fn write_primary(&mut self, _contents: String) -> Option>> { 95 | None 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /macos/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Avraham Weinstock 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use objc2::rc::Id; 16 | use objc2::runtime::{AnyClass, AnyObject, ProtocolObject}; 17 | use objc2::{msg_send_id, ClassType}; 18 | use objc2_app_kit::NSPasteboard; 19 | use objc2_foundation::{NSArray, NSString}; 20 | use std::error::Error; 21 | use std::panic::{RefUnwindSafe, UnwindSafe}; 22 | 23 | pub struct Clipboard { 24 | pasteboard: Id, 25 | } 26 | 27 | unsafe impl Send for Clipboard {} 28 | unsafe impl Sync for Clipboard {} 29 | impl UnwindSafe for Clipboard {} 30 | impl RefUnwindSafe for Clipboard {} 31 | 32 | impl Clipboard { 33 | pub fn new() -> Result> { 34 | // Use `msg_send_id!` instead of `NSPasteboard::generalPasteboard()` 35 | // in the off case that it will return NULL (even though it's 36 | // documented not to). 37 | let pasteboard: Option> = 38 | unsafe { msg_send_id![NSPasteboard::class(), generalPasteboard] }; 39 | let pasteboard = 40 | pasteboard.ok_or("NSPasteboard#generalPasteboard returned null")?; 41 | Ok(Self { pasteboard }) 42 | } 43 | 44 | pub fn read(&self) -> Result> { 45 | // The NSPasteboard API is a bit weird, it requires you to pass 46 | // classes as objects, which `objc2_foundation::NSArray` was not really 47 | // made for - so we convert the class to an `AnyObject` type instead. 48 | // 49 | // TODO: Use the NSPasteboard helper APIs (`stringForType`). 50 | let string_class = { 51 | let cls: *const AnyClass = NSString::class(); 52 | let cls = cls as *mut AnyObject; 53 | unsafe { Id::retain(cls).unwrap() } 54 | }; 55 | let classes = NSArray::from_vec(vec![string_class]); 56 | let string_array = unsafe { 57 | self.pasteboard 58 | .readObjectsForClasses_options(&classes, None) 59 | } 60 | .ok_or("pasteboard#readObjectsForClasses:options: returned null")?; 61 | 62 | let obj: *const AnyObject = string_array.first().ok_or( 63 | "pasteboard#readObjectsForClasses:options: returned empty", 64 | )?; 65 | // And this part is weird as well, since we now have to convert the object 66 | // into an NSString, which we know it to be since that's what we told 67 | // `readObjectsForClasses:options:`. 68 | let obj: *mut NSString = obj as _; 69 | Ok(unsafe { Id::retain(obj) }.unwrap().to_string()) 70 | } 71 | 72 | pub fn write(&mut self, data: String) -> Result<(), Box> { 73 | let string_array = NSArray::from_vec(vec![ProtocolObject::from_id( 74 | NSString::from_str(&data), 75 | )]); 76 | unsafe { self.pasteboard.clearContents() }; 77 | let success = unsafe { self.pasteboard.writeObjects(&string_array) }; 78 | if success { 79 | Ok(()) 80 | } else { 81 | Err("NSPasteboard#writeObjects: returned false".into()) 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /macos/LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /wayland/LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /x11/src/lib.rs: -------------------------------------------------------------------------------- 1 | #[forbid(unsafe_code)] 2 | mod error; 3 | 4 | pub use error::Error; 5 | 6 | use x11rb::connection::Connection as _; 7 | use x11rb::errors::ConnectError; 8 | use x11rb::protocol::xproto::{self, Atom, AtomEnum, EventMask, Window}; 9 | use x11rb::protocol::Event; 10 | use x11rb::rust_connection::RustConnection as Connection; 11 | use x11rb::wrapper::ConnectionExt; 12 | 13 | use std::collections::HashMap; 14 | use std::sync::{Arc, RwLock}; 15 | use std::thread; 16 | use std::time::{Duration, Instant}; 17 | 18 | const POLL_DURATION: std::time::Duration = Duration::from_micros(50); 19 | 20 | /// A connection to an X11 [`Clipboard`]. 21 | pub struct Clipboard { 22 | reader: Context, 23 | writer: Arc, 24 | selections: Arc)>>>, 25 | } 26 | 27 | impl Clipboard { 28 | /// Connect to the running X11 server and obtain a [`Clipboard`]. 29 | pub fn connect() -> Result { 30 | let reader = Context::new(None)?; 31 | let writer = Arc::new(Context::new(None)?); 32 | let selections = Arc::new(RwLock::new(HashMap::new())); 33 | 34 | let worker = Worker { 35 | context: Arc::clone(&writer), 36 | selections: Arc::clone(&selections), 37 | }; 38 | 39 | thread::spawn(move || worker.run()); 40 | 41 | Ok(Clipboard { 42 | reader, 43 | writer, 44 | selections, 45 | }) 46 | } 47 | 48 | fn read_selection(&self, selection: Atom) -> Result { 49 | Ok(String::from_utf8(self.load( 50 | selection, 51 | self.reader.atoms.utf8_string, 52 | self.reader.atoms.property, 53 | std::time::Duration::from_secs(3), 54 | )?) 55 | .map_err(Error::InvalidUtf8)?) 56 | } 57 | 58 | /// Read the current CLIPBOARD [`Clipboard`] value. 59 | pub fn read(&self) -> Result { 60 | self.read_selection(self.reader.atoms.clipboard) 61 | } 62 | 63 | 64 | /// Read the current PRIMARY [`Clipboard`] value. 65 | pub fn read_primary(&self) -> Result { 66 | self.read_selection(self.reader.atoms.primary) 67 | } 68 | 69 | fn write_selection(&mut self, selection: Atom, contents: String) -> Result<(), Error> { 70 | let target = self.writer.atoms.utf8_string; 71 | 72 | self.selections 73 | .write() 74 | .map_err(|_| Error::SelectionLocked)? 75 | .insert(selection, (target, contents.into())); 76 | 77 | let _ = xproto::set_selection_owner( 78 | &self.writer.connection, 79 | self.writer.window, 80 | selection, 81 | x11rb::CURRENT_TIME, 82 | )?; 83 | 84 | let _ = self.writer.connection.flush()?; 85 | 86 | let reply = 87 | xproto::get_selection_owner(&self.writer.connection, selection) 88 | .map_err(Into::into) 89 | .and_then(|cookie| cookie.reply())?; 90 | 91 | if reply.owner == self.writer.window { 92 | Ok(()) 93 | } else { 94 | Err(Error::InvalidOwner) 95 | } 96 | } 97 | 98 | /// Write a new value to the CLIPBOARD [`Clipboard`]. 99 | pub fn write(&mut self, contents: String) -> Result<(), Error> { 100 | let selection = self.writer.atoms.clipboard; 101 | self.write_selection(selection, contents) 102 | } 103 | 104 | /// Write a new value to the PRIMARY [`Clipboard`]. 105 | pub fn write_primary(&mut self, contents: String) -> Result<(), Error> { 106 | let selection = self.writer.atoms.primary; 107 | self.write_selection(selection, contents) 108 | } 109 | 110 | /// load value. 111 | fn load( 112 | &self, 113 | selection: Atom, 114 | target: Atom, 115 | property: Atom, 116 | timeout: impl Into>, 117 | ) -> Result, Error> { 118 | let mut buff = Vec::new(); 119 | let timeout = timeout.into(); 120 | 121 | let _ = xproto::convert_selection( 122 | &self.reader.connection, 123 | self.reader.window, 124 | selection, 125 | target, 126 | property, 127 | x11rb::CURRENT_TIME, // FIXME ^ 128 | // Clients should not use CurrentTime for the time argument of a ConvertSelection request. 129 | // Instead, they should use the timestamp of the event that caused the request to be made. 130 | )?; 131 | let _ = self.reader.connection.flush()?; 132 | 133 | self.process_event(&mut buff, selection, target, property, timeout)?; 134 | 135 | let _ = xproto::delete_property( 136 | &self.reader.connection, 137 | self.reader.window, 138 | property, 139 | )?; 140 | let _ = self.reader.connection.flush()?; 141 | 142 | Ok(buff) 143 | } 144 | 145 | fn process_event( 146 | &self, 147 | buff: &mut Vec, 148 | selection: Atom, 149 | target: Atom, 150 | property: Atom, 151 | timeout: T, 152 | ) -> Result<(), Error> 153 | where 154 | T: Into>, 155 | { 156 | let mut is_incr = false; 157 | let timeout = timeout.into(); 158 | let start_time = if timeout.is_some() { 159 | Some(Instant::now()) 160 | } else { 161 | None 162 | }; 163 | 164 | loop { 165 | if timeout 166 | .into_iter() 167 | .zip(start_time) 168 | .next() 169 | .map(|(timeout, time)| (Instant::now() - time) >= timeout) 170 | .unwrap_or(false) 171 | { 172 | return Err(Error::Timeout); 173 | } 174 | 175 | let event = match self.reader.connection.poll_for_event()? { 176 | Some(event) => event, 177 | None => { 178 | thread::park_timeout(POLL_DURATION); 179 | continue; 180 | } 181 | }; 182 | 183 | match event { 184 | Event::SelectionNotify(event) => { 185 | if event.selection != selection { 186 | continue; 187 | }; 188 | 189 | // Note that setting the property argument to None indicates that the 190 | // conversion requested could not be made. 191 | if event.property == AtomEnum::NONE.into() { 192 | break; 193 | } 194 | 195 | let reply = xproto::get_property( 196 | &self.reader.connection, 197 | false, 198 | self.reader.window, 199 | event.property, 200 | Atom::from(AtomEnum::ANY), 201 | buff.len() as u32, 202 | ::std::u32::MAX, // FIXME reasonable buffer size 203 | ) 204 | .map_err(Into::into) 205 | .and_then(|cookie| cookie.reply())?; 206 | 207 | if reply.type_ == self.reader.atoms.incr { 208 | if let Some(&size) = reply.value.get(0) { 209 | buff.reserve(size as usize); 210 | } 211 | 212 | let _ = xproto::delete_property( 213 | &self.reader.connection, 214 | self.reader.window, 215 | property, 216 | ); 217 | 218 | let _ = self.reader.connection.flush(); 219 | is_incr = true; 220 | 221 | continue; 222 | } else if reply.type_ != target { 223 | return Err(Error::UnexpectedType(reply.type_)); 224 | } 225 | 226 | buff.extend_from_slice(&reply.value); 227 | break; 228 | } 229 | Event::PropertyNotify(event) if is_incr => { 230 | if event.state != xproto::Property::NEW_VALUE { 231 | continue; 232 | }; 233 | 234 | let length = xproto::get_property( 235 | &self.reader.connection, 236 | false, 237 | self.reader.window, 238 | property, 239 | Atom::from(AtomEnum::ANY), 240 | 0, 241 | 0, 242 | ) 243 | .map_err(Into::into) 244 | .and_then(|cookie| cookie.reply())? 245 | .bytes_after; 246 | 247 | let reply = xproto::get_property( 248 | &self.reader.connection, 249 | true, 250 | self.reader.window, 251 | property, 252 | Atom::from(AtomEnum::ANY), 253 | 0, 254 | length, 255 | ) 256 | .map_err(Into::into) 257 | .and_then(|cookie| cookie.reply())?; 258 | 259 | if reply.type_ != target { 260 | continue; 261 | }; 262 | 263 | if reply.value_len != 0 { 264 | buff.extend_from_slice(&reply.value); 265 | } else { 266 | break; 267 | } 268 | } 269 | _ => {} 270 | } 271 | } 272 | 273 | Ok(()) 274 | } 275 | } 276 | 277 | pub struct Context { 278 | pub connection: Connection, 279 | pub screen: usize, 280 | pub window: Window, 281 | pub atoms: Atoms, 282 | } 283 | 284 | #[derive(Clone, Debug)] 285 | pub struct Atoms { 286 | pub primary: Atom, 287 | pub clipboard: Atom, 288 | pub property: Atom, 289 | pub targets: Atom, 290 | pub string: Atom, 291 | pub utf8_string: Atom, 292 | pub incr: Atom, 293 | } 294 | 295 | #[inline] 296 | fn get_atom(connection: &Connection, name: &str) -> Result { 297 | x11rb::protocol::xproto::intern_atom(connection, false, name.as_bytes()) 298 | .map_err(Into::into) 299 | .and_then(|cookie| cookie.reply()) 300 | .map(|reply| reply.atom) 301 | .map_err(Into::into) 302 | } 303 | 304 | impl Context { 305 | pub fn new(displayname: Option<&str>) -> Result { 306 | let (connection, screen) = Connection::connect(displayname)?; 307 | let window = connection.generate_id().map_err(|_| { 308 | Error::ConnectionFailed(ConnectError::InvalidScreen) 309 | })?; 310 | 311 | { 312 | let screen = 313 | connection.setup().roots.get(screen as usize).ok_or( 314 | Error::ConnectionFailed(ConnectError::InvalidScreen), 315 | )?; 316 | 317 | let _ = xproto::create_window( 318 | &connection, 319 | x11rb::COPY_DEPTH_FROM_PARENT, 320 | window, 321 | screen.root, 322 | 0, 323 | 0, 324 | 1, 325 | 1, 326 | 0, 327 | xproto::WindowClass::INPUT_OUTPUT, 328 | screen.root_visual, 329 | &xproto::CreateWindowAux::new().event_mask( 330 | xproto::EventMask::STRUCTURE_NOTIFY 331 | | xproto::EventMask::PROPERTY_CHANGE, 332 | ), 333 | )?; 334 | 335 | let _ = connection.flush()?; 336 | } 337 | 338 | let atoms = Atoms { 339 | primary: AtomEnum::PRIMARY.into(), 340 | clipboard: get_atom(&connection, "CLIPBOARD")?, 341 | property: get_atom(&connection, "THIS_CLIPBOARD_OUT")?, 342 | targets: get_atom(&connection, "TARGETS")?, 343 | string: AtomEnum::STRING.into(), 344 | utf8_string: get_atom(&connection, "UTF8_STRING")?, 345 | incr: get_atom(&connection, "INCR")?, 346 | }; 347 | 348 | Ok(Context { 349 | connection, 350 | screen, 351 | window, 352 | atoms, 353 | }) 354 | } 355 | } 356 | 357 | pub struct Worker { 358 | context: Arc, 359 | selections: Arc)>>>, 360 | } 361 | 362 | impl Worker { 363 | pub const INCR_CHUNK_SIZE: usize = 4000; 364 | 365 | pub fn run(self) { 366 | while let Ok(event) = self.context.connection.wait_for_event() { 367 | match event { 368 | Event::SelectionRequest(event) => { 369 | let selections = match self.selections.read().ok() { 370 | Some(selections) => selections, 371 | None => continue, 372 | }; 373 | 374 | let &(target, ref value) = 375 | match selections.get(&event.selection) { 376 | Some(key_value) => key_value, 377 | None => continue, 378 | }; 379 | 380 | if event.target == self.context.atoms.targets { 381 | let data = [self.context.atoms.targets, target]; 382 | 383 | self.context 384 | .connection 385 | .change_property32( 386 | xproto::PropMode::REPLACE, 387 | event.requestor, 388 | event.property, 389 | xproto::AtomEnum::ATOM, 390 | &data, 391 | ) 392 | .expect("Change property"); 393 | } else { 394 | let _ = self 395 | .context 396 | .connection 397 | .change_property8( 398 | xproto::PropMode::REPLACE, 399 | event.requestor, 400 | event.property, 401 | target, 402 | value, 403 | ) 404 | .expect("Change property"); 405 | } 406 | 407 | let _ = xproto::send_event( 408 | &self.context.connection, 409 | false, 410 | event.requestor, 411 | EventMask::NO_EVENT, 412 | xproto::SelectionNotifyEvent { 413 | response_type: 31, 414 | sequence: event.sequence, 415 | time: event.time, 416 | requestor: event.requestor, 417 | selection: event.selection, 418 | target: event.target, 419 | property: event.property, 420 | }, 421 | ) 422 | .expect("Send event"); 423 | 424 | let _ = self.context.connection.flush(); 425 | } 426 | Event::SelectionClear(event) => { 427 | if let Ok(mut write_setmap) = self.selections.write() { 428 | write_setmap.remove(&event.selection); 429 | } 430 | } 431 | _ => (), 432 | } 433 | } 434 | } 435 | } 436 | --------------------------------------------------------------------------------