├── .github └── workflows │ └── rust.yml ├── .gitignore ├── .mailmap ├── .travis.yml ├── Cargo.toml ├── LICENSE.apache2 ├── LICENSE.mit ├── README.md ├── appveyor.yml ├── examples ├── hello_world.rs └── primary_selection.rs └── src ├── common.rs ├── lib.rs ├── linux_clipboard.rs ├── macos_clipboard.rs ├── wayland_clipboard.rs ├── windows_clipboard.rs └── x11_clipboard.rs /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: 4 | push: 5 | branches: [ master, develop ] 6 | pull_request: 7 | branches: [ master, develop ] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | test: 14 | name: Test on ${{ matrix.os }} 15 | runs-on: ${{ matrix.os }} 16 | strategy: 17 | matrix: 18 | os: [ubuntu-latest, windows-latest, macOS-latest] 19 | 20 | steps: 21 | - uses: actions/checkout@v2 22 | - name: Setup xcb 23 | if: ${{ matrix.os == 'ubuntu-latest' }} 24 | run: sudo apt-get install libxcb-xfixes0-dev 25 | - name: Setup rust toolchain 26 | uses: actions-rs/toolchain@v1 27 | with: 28 | toolchain: stable 29 | components: rustfmt, clippy 30 | - name: Clippy 31 | run: cargo clippy 32 | - name: RustFmt 33 | run: cargo fmt -- --check 34 | - name: Run tests 35 | uses: GabrielBB/xvfb-action@v1.2 36 | with: 37 | run: cargo test --verbose -- --test-threads=1 38 | - name: Build 39 | run: cargo build 40 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | Cargo.lock 2 | target 3 | Session.vim 4 | -------------------------------------------------------------------------------- /.mailmap: -------------------------------------------------------------------------------- 1 | Allie Stephan 2 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | 3 | os: 4 | - linux 5 | - osx 6 | 7 | # TODO: figure out how to get headless X11 working 8 | script: | 9 | #!/bin/bash 10 | cargo build --verbose 11 | if [[ $TRAVIS_OS_NAME == 'linux' ]]; then 12 | cargo build --tests --verbose 13 | else 14 | cargo test --verbose 15 | fi 16 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cli-clipboard" 3 | version = "0.4.0" 4 | authors = ["Allie Stephan "] 5 | description = "cli-clipboard is a cross-platform library for getting and setting the contents of the OS-level clipboard." 6 | repository = "https://github.com/actuallyallie/cli-clipboard" 7 | license = "MIT / Apache-2.0" 8 | keywords = ["clipboard"] 9 | edition = "2018" 10 | readme = "README.md" 11 | 12 | [target.'cfg(windows)'.dependencies] 13 | clipboard-win = {version = "4.4", features=["std"]} 14 | 15 | [target.'cfg(target_os = "macos")'.dependencies] 16 | objc = "0.2" 17 | objc_id = "0.1" 18 | objc-foundation = "0.1" 19 | 20 | [target.'cfg(all(unix, not(any(target_os="macos", target_os="android", target_os="emscripten"))))'.dependencies] 21 | wl-clipboard-rs = "0.7" 22 | x11-clipboard = "0.7" 23 | -------------------------------------------------------------------------------- /LICENSE.apache2: -------------------------------------------------------------------------------- 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. -------------------------------------------------------------------------------- /LICENSE.mit: -------------------------------------------------------------------------------- 1 | Copyright (c) 2017 Avraham Weinstock 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CLI Clipboard 2 | 3 | ![Rust](https://github.com/TheKiteEatingTree/cli-clipboard/workflows/Rust/badge.svg) 4 | 5 | cli-clipboard is a fork of [rust-clipboard](https://github.com/aweinstock314/rust-clipboard) that adds wayland support for terminal and window-less applications via [wl-clipboard-rs](https://github.com/YaLTeR/wl-clipboard-rs). For terminal applications it supports copy and paste for both wayland and X11 linux environments, macOS and windows. 6 | 7 | On Linux it will first attempt to setup a Wayland clipboard provider. If that fails it will then fallback to the X11 clipboard provider. 8 | 9 | Note: On Linux, you'll need to have xorg-dev and libxcb-composite0-dev to compile. On Debian and Ubuntu you can install them with 10 | 11 | sudo apt install xorg-dev libxcb-composite0-dev 12 | 13 | ## Examples 14 | 15 | Using ClipboardContext to create a clipboard provider: 16 | 17 | ```rust 18 | use cli_clipboard::{ClipboardContext, ClipboardProvider}; 19 | 20 | let mut ctx = ClipboardContext::new().unwrap(); 21 | let the_string = "Hello, world!"; 22 | ctx.set_contents(the_string.to_owned()).unwrap(); 23 | assert_eq!(ctx.get_contents().unwrap(), the_string); 24 | ctx.clear(); 25 | // clearing the clipboard causes get_contents to return Err on macos and windows 26 | if cfg!(any(windows, target_os = "macos")) { 27 | if ctx.get_contents().is_ok() { 28 | panic!("Should be Err"); 29 | } 30 | } else { 31 | assert_eq!(ctx.get_contents(), ""); 32 | } 33 | ``` 34 | 35 | Using the helper functions: 36 | 37 | ```rust 38 | use cli_clipboard; 39 | 40 | let the_string = "Hello, world!"; 41 | cli_clipboard::set_contents(the_string.to_owned()).unwrap(); 42 | assert_eq!(cli_clipboard::get_contents().unwrap(), the_string); 43 | ``` 44 | 45 | ## API 46 | 47 | ### ClipboardProvider 48 | 49 | The `ClipboardProvider` trait has the following functions: 50 | 51 | ```rust 52 | fn new() -> anyhow::Result; 53 | fn get_contents(&mut self) -> anyhow::Result; 54 | fn set_contents(&mut self, String) -> anyhow::Result<()>; 55 | fn clear(&mut self) -> anhow::Result<()>; 56 | ``` 57 | 58 | ### ClipboardContext 59 | 60 | - `ClipboardContext` is a type alias for one of {`WindowsClipboardContext`, `OSXClipboardContext`, `LinuxClipboardContext`}, all of which implement `ClipboardProvider`. Which concrete type is chosen for `ClipboardContext` depends on the OS (via conditional compilation). 61 | - `WaylandClipboardContext` and `X11ClipboardContext` are also available but generally the correct one will be chosen by `LinuxClipboardContext`. 62 | 63 | ### Convenience Functions 64 | 65 | `get_contents` and `set_contents` are convenience functions that create a context for you and call the respective function on it. 66 | 67 | ## Alternatives 68 | 69 | 1. [arboard - very active rust-clipboard fork. Has at least some amount of wayland support](https://github.com/1Password/arboard) 70 | 1. [copypasta - rust-clipboard fork adding wayland support for windowed applications](https://github.com/alacritty/copypasta) 71 | 1. [The original rust-clipboard](https://github.com/aweinstock314/rust-clipboard) 72 | 73 | ## License 74 | 75 | `cli-clipboard` is dual-licensed under MIT and Apache2. 76 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | # Appveyor configuration template for Rust using rustup for Rust installation 2 | # https://github.com/starkat99/appveyor-rust 3 | 4 | ## Operating System (VM environment) ## 5 | 6 | # Rust needs at least Visual Studio 2013 Appveyor OS for MSVC targets. 7 | os: Visual Studio 2015 8 | 9 | ## Build Matrix ## 10 | 11 | # This configuration will setup a build for each channel & target combination (12 windows 12 | # combinations in all). 13 | # 14 | # There are 3 channels: stable, beta, and nightly. 15 | # 16 | # Alternatively, the full version may be specified for the channel to build using that specific 17 | # version (e.g. channel: 1.5.0) 18 | # 19 | # The values for target are the set of windows Rust build targets. Each value is of the form 20 | # 21 | # ARCH-pc-windows-TOOLCHAIN 22 | # 23 | # Where ARCH is the target architecture, either x86_64 or i686, and TOOLCHAIN is the linker 24 | # toolchain to use, either msvc or gnu. See https://www.rust-lang.org/downloads.html#win-foot for 25 | # a description of the toolchain differences. 26 | # See https://github.com/rust-lang-nursery/rustup.rs/#toolchain-specification for description of 27 | # toolchains and host triples. 28 | # 29 | # Comment out channel/target combos you do not wish to build in CI. 30 | # 31 | # You may use the `cargoflags` and `RUSTFLAGS` variables to set additional flags for cargo commands 32 | # and rustc, respectively. For instance, you can uncomment the cargoflags lines in the nightly 33 | # channels to enable unstable features when building for nightly. Or you could add additional 34 | # matrix entries to test different combinations of features. 35 | environment: 36 | matrix: 37 | 38 | ### MSVC Toolchains ### 39 | 40 | # Stable 64-bit MSVC 41 | - channel: stable 42 | target: x86_64-pc-windows-msvc 43 | # Stable 32-bit MSVC 44 | - channel: stable 45 | target: i686-pc-windows-msvc 46 | # Beta 64-bit MSVC 47 | - channel: beta 48 | target: x86_64-pc-windows-msvc 49 | # Beta 32-bit MSVC 50 | - channel: beta 51 | target: i686-pc-windows-msvc 52 | # Nightly 64-bit MSVC 53 | - channel: nightly 54 | target: x86_64-pc-windows-msvc 55 | #cargoflags: --features "unstable" 56 | # Nightly 32-bit MSVC 57 | - channel: nightly 58 | target: i686-pc-windows-msvc 59 | #cargoflags: --features "unstable" 60 | 61 | ### GNU Toolchains ### 62 | 63 | # Stable 64-bit GNU 64 | - channel: stable 65 | target: x86_64-pc-windows-gnu 66 | # Stable 32-bit GNU 67 | - channel: stable 68 | target: i686-pc-windows-gnu 69 | # Beta 64-bit GNU 70 | - channel: beta 71 | target: x86_64-pc-windows-gnu 72 | # Beta 32-bit GNU 73 | - channel: beta 74 | target: i686-pc-windows-gnu 75 | # Nightly 64-bit GNU 76 | - channel: nightly 77 | target: x86_64-pc-windows-gnu 78 | #cargoflags: --features "unstable" 79 | # Nightly 32-bit GNU 80 | - channel: nightly 81 | target: i686-pc-windows-gnu 82 | #cargoflags: --features "unstable" 83 | 84 | ### Allowed failures ### 85 | 86 | # See Appveyor documentation for specific details. In short, place any channel or targets you wish 87 | # to allow build failures on (usually nightly at least is a wise choice). This will prevent a build 88 | # or test failure in the matching channels/targets from failing the entire build. 89 | matrix: 90 | allow_failures: 91 | - channel: nightly 92 | 93 | # If you only care about stable channel build failures, uncomment the following line: 94 | #- channel: beta 95 | 96 | ## Install Script ## 97 | 98 | # This is the most important part of the Appveyor configuration. This installs the version of Rust 99 | # specified by the 'channel' and 'target' environment variables from the build matrix. This uses 100 | # rustup to install Rust. 101 | # 102 | # For simple configurations, instead of using the build matrix, you can simply set the 103 | # default-toolchain and default-host manually here. 104 | install: 105 | - appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe 106 | - rustup-init -yv --default-toolchain %channel% --default-host %target% 107 | - set PATH=%PATH%;%USERPROFILE%\.cargo\bin 108 | - rustc -vV 109 | - cargo -vV 110 | 111 | ## Build Script ## 112 | 113 | # 'cargo test' takes care of building for us, so disable Appveyor's build stage. This prevents 114 | # the "directory does not contain a project or solution file" error. 115 | build: false 116 | 117 | # Uses 'cargo test' to run tests and build. Alternatively, the project may call compiled programs 118 | #directly or perform other testing commands. Rust will automatically be placed in the PATH 119 | # environment variable. 120 | test_script: 121 | - cargo test --verbose %cargoflags% 122 | -------------------------------------------------------------------------------- /examples/hello_world.rs: -------------------------------------------------------------------------------- 1 | use cli_clipboard::{ClipboardContext, ClipboardProvider}; 2 | 3 | fn main() { 4 | let mut ctx = ClipboardContext::new().unwrap(); 5 | let the_string = "Hello, world!"; 6 | ctx.set_contents(the_string.to_owned()).unwrap(); 7 | } 8 | -------------------------------------------------------------------------------- /examples/primary_selection.rs: -------------------------------------------------------------------------------- 1 | extern crate cli_clipboard; 2 | 3 | #[cfg(target_os = "linux")] 4 | use cli_clipboard::x11_clipboard::{Primary, X11ClipboardContext}; 5 | #[cfg(target_os = "linux")] 6 | use cli_clipboard::ClipboardProvider; 7 | 8 | #[cfg(target_os = "linux")] 9 | fn main() { 10 | let mut ctx: X11ClipboardContext = X11ClipboardContext::new().unwrap(); 11 | 12 | let the_string = "Hello, world!"; 13 | 14 | ctx.set_contents(the_string.to_owned()).unwrap(); 15 | } 16 | 17 | #[cfg(not(target_os = "linux"))] 18 | fn main() { 19 | println!("Primary selection is only available under linux!"); 20 | } 21 | -------------------------------------------------------------------------------- /src/common.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2016 Avraham Weinstock 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | use crate::Result; 18 | 19 | /// Trait for clipboard access 20 | pub trait ClipboardProvider: Sized { 21 | /// Create a context with which to access the clipboard 22 | fn new() -> Result; 23 | /// Method to get the clipboard contents as a String 24 | fn get_contents(&mut self) -> Result; 25 | /// Method to set the clipboard contents as a String 26 | fn set_contents(&mut self, content: String) -> Result<()>; 27 | // TODO: come up with some platform-agnostic API for richer types 28 | // than just strings (c.f. issue #31) 29 | /// Method to clear the clipboard 30 | fn clear(&mut self) -> Result<()>; 31 | } 32 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2016 Avraham Weinstock 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | //! # CLI Clipboard 18 | //! 19 | //! cli-clipboard is a fork of 20 | //! [rust-clipboard](https://github.com/aweinstock314/rust-clipboard) that 21 | //! adds wayland support for terminal and window-less applications via 22 | //! [wl-clipboard-rs](https://github.com/YaLTeR/wl-clipboard-rs). For terminal 23 | //! applications it supports copy and paste for both wayland and X11 linux 24 | //! environments, macOS and windows. 25 | //! 26 | //! Also adds convenience functions for [get_contents](fn.get_contents.html) and 27 | //! [set_contents](fn.set_contents.html). 28 | //! 29 | //! On Linux it will first attempt to setup a Wayland clipboard provider. If that 30 | //! fails it will then fallback to the X11 clipboard provider. 31 | //! 32 | //! ## Examples 33 | //! 34 | //! Using ClipboardContext to create a clipboard provider: 35 | //! 36 | //! ``` 37 | //! use cli_clipboard::{ClipboardContext, ClipboardProvider}; 38 | //! 39 | //! let mut ctx = ClipboardContext::new().unwrap(); 40 | //! let the_string = "Hello, world!"; 41 | //! ctx.set_contents(the_string.to_owned()).unwrap(); 42 | //! assert_eq!(ctx.get_contents().unwrap(), the_string); 43 | //! ctx.clear(); 44 | //! // clearing the clipboard causes get_contents to return Err on macos and windows 45 | //! if cfg!(any(windows, target_os = "macos")) { 46 | //! if ctx.get_contents().is_ok() { 47 | //! panic!("Should be Err"); 48 | //! } 49 | //! } else { 50 | //! assert_eq!(ctx.get_contents().unwrap(), ""); 51 | //! } 52 | //! ``` 53 | //! 54 | //! Using the helper functions: 55 | //! 56 | //! ``` 57 | //! use cli_clipboard; 58 | //! 59 | //! let the_string = "Hello, world!"; 60 | //! cli_clipboard::set_contents(the_string.to_owned()).unwrap(); 61 | //! assert_eq!(cli_clipboard::get_contents().unwrap(), the_string); 62 | //! ``` 63 | 64 | #[cfg(all( 65 | unix, 66 | not(any(target_os = "macos", target_os = "android", target_os = "emscripten")) 67 | ))] 68 | extern crate x11_clipboard as x11_clipboard_crate; 69 | 70 | #[cfg(target_os = "macos")] 71 | #[macro_use] 72 | extern crate objc; 73 | 74 | type Result = std::result::Result>; 75 | 76 | mod common; 77 | pub use common::ClipboardProvider; 78 | 79 | #[cfg(all( 80 | unix, 81 | not(any(target_os = "macos", target_os = "android", target_os = "emscripten")) 82 | ))] 83 | pub mod wayland_clipboard; 84 | 85 | #[cfg(all( 86 | unix, 87 | not(any(target_os = "macos", target_os = "android", target_os = "emscripten")) 88 | ))] 89 | pub mod x11_clipboard; 90 | 91 | #[cfg(all( 92 | unix, 93 | not(any(target_os = "macos", target_os = "android", target_os = "emscripten")) 94 | ))] 95 | pub mod linux_clipboard; 96 | 97 | #[cfg(windows)] 98 | pub mod windows_clipboard; 99 | 100 | #[cfg(target_os = "macos")] 101 | pub mod macos_clipboard; 102 | 103 | #[cfg(all( 104 | unix, 105 | not(any(target_os = "macos", target_os = "android", target_os = "emscripten")) 106 | ))] 107 | pub type ClipboardContext = linux_clipboard::LinuxClipboardContext; 108 | 109 | #[cfg(windows)] 110 | pub type ClipboardContext = windows_clipboard::WindowsClipboardContext; 111 | 112 | #[cfg(target_os = "macos")] 113 | pub type ClipboardContext = macos_clipboard::MacOSClipboardContext; 114 | 115 | /// Get the current clipboard contents 116 | /// 117 | /// # Example 118 | /// ``` 119 | /// cli_clipboard::set_contents("testing".to_owned()).unwrap(); 120 | /// assert_eq!(cli_clipboard::get_contents().unwrap(), "testing"); 121 | /// ``` 122 | pub fn get_contents() -> Result { 123 | let mut ctx = ClipboardContext::new()?; 124 | ctx.get_contents() 125 | } 126 | 127 | /// Write a string to the clipboard 128 | /// 129 | /// This uses the platform default behavior for setting clipboard contents. 130 | /// Other users of the Wayland or X11 clipboard will only see the contents 131 | /// copied to the clipboard so long as the process copying to the 132 | /// clipboard exists. 133 | /// MacOS and Windows clipboard contents will stick around after your 134 | /// application exits. 135 | /// 136 | /// # Example 137 | /// ``` 138 | /// cli_clipboard::set_contents("testing".to_owned()).unwrap(); 139 | /// assert_eq!(cli_clipboard::get_contents().unwrap(), "testing"); 140 | /// ``` 141 | pub fn set_contents(data: String) -> Result<()> { 142 | let mut ctx = ClipboardContext::new()?; 143 | ctx.set_contents(data)?; 144 | Ok(()) 145 | } 146 | 147 | #[cfg(test)] 148 | mod tests { 149 | use super::*; 150 | 151 | #[test] 152 | fn test_clipboard() { 153 | let mut ctx = ClipboardContext::new().unwrap(); 154 | ctx.set_contents("some string".to_owned()).unwrap(); 155 | assert_eq!(ctx.get_contents().unwrap(), "some string"); 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /src/linux_clipboard.rs: -------------------------------------------------------------------------------- 1 | use crate::common::*; 2 | use crate::wayland_clipboard::WaylandClipboardContext; 3 | use crate::x11_clipboard::{Clipboard, X11ClipboardContext}; 4 | use crate::Result; 5 | 6 | enum LinuxContext { 7 | Wayland(WaylandClipboardContext), 8 | X11(X11ClipboardContext), 9 | } 10 | 11 | pub struct LinuxClipboardContext { 12 | context: LinuxContext, 13 | } 14 | 15 | impl ClipboardProvider for LinuxClipboardContext { 16 | fn new() -> Result { 17 | match WaylandClipboardContext::new() { 18 | Ok(context) => Ok(LinuxClipboardContext { 19 | context: LinuxContext::Wayland(context), 20 | }), 21 | Err(_) => match X11ClipboardContext::::new() { 22 | Ok(context) => Ok(LinuxClipboardContext { 23 | context: LinuxContext::X11(context), 24 | }), 25 | Err(err) => Err(err), 26 | }, 27 | } 28 | } 29 | 30 | fn get_contents(&mut self) -> Result { 31 | match &mut self.context { 32 | LinuxContext::Wayland(context) => context.get_contents(), 33 | LinuxContext::X11(context) => context.get_contents(), 34 | } 35 | } 36 | 37 | fn set_contents(&mut self, content: String) -> Result<()> { 38 | match &mut self.context { 39 | LinuxContext::Wayland(context) => context.set_contents(content), 40 | LinuxContext::X11(context) => context.set_contents(content), 41 | } 42 | } 43 | 44 | fn clear(&mut self) -> Result<()> { 45 | match &mut self.context { 46 | LinuxContext::Wayland(context) => context.clear(), 47 | LinuxContext::X11(context) => context.clear(), 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/macos_clipboard.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2016 Avraham Weinstock 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | use crate::common::*; 18 | use crate::Result; 19 | use objc::runtime::{Class, Object}; 20 | use objc_foundation::{INSArray, INSObject, INSString}; 21 | use objc_foundation::{NSArray, NSDictionary, NSObject, NSString}; 22 | use objc_id::{Id, Owned}; 23 | use std::mem::transmute; 24 | 25 | pub struct MacOSClipboardContext { 26 | pasteboard: Id, 27 | } 28 | 29 | // required to bring NSPasteboard into the path of the class-resolver 30 | #[link(name = "AppKit", kind = "framework")] 31 | extern "C" {} 32 | 33 | impl ClipboardProvider for MacOSClipboardContext { 34 | fn new() -> Result { 35 | let cls = Class::get("NSPasteboard").ok_or_else(|| "Class::get(\"NSPasteboard\")")?; 36 | let pasteboard: *mut Object = unsafe { msg_send![cls, generalPasteboard] }; 37 | if pasteboard.is_null() { 38 | return Err("NSPasteboard#generalPasteboard returned null".into()); 39 | } 40 | let pasteboard: Id = unsafe { Id::from_ptr(pasteboard) }; 41 | Ok(MacOSClipboardContext { pasteboard }) 42 | } 43 | 44 | fn get_contents(&mut self) -> Result { 45 | let string_class: Id = { 46 | let cls: Id = unsafe { Id::from_ptr(class("NSString")) }; 47 | unsafe { transmute(cls) } 48 | }; 49 | let classes: Id> = NSArray::from_vec(vec![string_class]); 50 | let options: Id> = NSDictionary::new(); 51 | let string_array: Id> = unsafe { 52 | let obj: *mut NSArray = 53 | msg_send![self.pasteboard, readObjectsForClasses:&*classes options:&*options]; 54 | if obj.is_null() { 55 | return Err("pasteboard#readObjectsForClasses:options: returned null".into()); 56 | } 57 | Id::from_ptr(obj) 58 | }; 59 | if string_array.count() == 0 { 60 | Err("pasteboard#readObjectsForClasses:options: returned empty".into()) 61 | } else { 62 | Ok(string_array[0].as_str().to_owned()) 63 | } 64 | } 65 | 66 | fn set_contents(&mut self, data: String) -> Result<()> { 67 | let string_array = NSArray::from_vec(vec![NSString::from_str(&data)]); 68 | let _: usize = unsafe { msg_send![self.pasteboard, clearContents] }; 69 | let success: bool = unsafe { msg_send![self.pasteboard, writeObjects: string_array] }; 70 | if success { 71 | Ok(()) 72 | } else { 73 | Err("NSPasteboard#writeObjects: returned false".into()) 74 | } 75 | } 76 | 77 | fn clear(&mut self) -> Result<()> { 78 | let _: usize = unsafe { msg_send![self.pasteboard, clearContents] }; 79 | Ok(()) 80 | } 81 | } 82 | 83 | // this is a convenience function that both cocoa-rs and 84 | // glutin define, which seems to depend on the fact that 85 | // Option::None has the same representation as a null pointer 86 | #[inline] 87 | pub fn class(name: &str) -> *mut Class { 88 | unsafe { transmute(Class::get(name)) } 89 | } 90 | -------------------------------------------------------------------------------- /src/wayland_clipboard.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2019 Gregory Meyer 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | use crate::common::*; 18 | use crate::Result; 19 | use std::io::{self, Read}; 20 | use wl_clipboard_rs::{ 21 | copy::{self, clear, Options, ServeRequests}, 22 | paste, utils, 23 | }; 24 | 25 | /// Interface to the clipboard for Wayland windowing systems. 26 | /// 27 | /// Other users of the Wayland clipboard will only see the contents 28 | /// copied to the clipboard so long as the process copying to the 29 | /// clipboard exists. If you need the contents of the clipboard to 30 | /// remain after your application shuts down, consider daemonizing the 31 | /// clipboard components of your application. 32 | /// 33 | /// `WaylandClipboardContext` automatically detects support for and 34 | /// uses the primary selection protocol. 35 | /// 36 | /// # Example 37 | /// 38 | /// ```noop 39 | /// use cli_clipboard::ClipboardProvider; 40 | /// let mut clipboard = cli_clipboard::wayland_clipboard::WaylandClipboardContext::new().unwrap(); 41 | /// clipboard.set_contents("foo bar baz".to_string()).unwrap(); 42 | /// let contents = clipboard.get_contents().unwrap(); 43 | /// 44 | /// assert_eq!(contents, "foo bar baz"); 45 | /// ``` 46 | pub struct WaylandClipboardContext { 47 | supports_primary_selection: bool, 48 | } 49 | 50 | impl ClipboardProvider for WaylandClipboardContext { 51 | /// Constructs a new `WaylandClipboardContext` that operates on all 52 | /// seats using the data-control clipboard protocol. This is 53 | /// intended for CLI applications that do not create Wayland 54 | /// windows. 55 | /// 56 | /// Attempts to detect whether the primary selection is supported. 57 | /// Assumes no primary selection support if no seats are available. 58 | /// In addition to returning Err on communication errors (such as 59 | /// when operating in an X11 environment), will also return Err if 60 | /// the compositor does not support the data-control protocol. 61 | fn new() -> Result { 62 | let supports_primary_selection = match utils::is_primary_selection_supported() { 63 | Ok(v) => v, 64 | Err(utils::PrimarySelectionCheckError::NoSeats) => false, 65 | Err(e) => return Err(e.into()), 66 | }; 67 | 68 | Ok(WaylandClipboardContext { 69 | supports_primary_selection, 70 | }) 71 | } 72 | 73 | /// Pastes from the Wayland clipboard. 74 | /// 75 | /// If the Wayland environment supported the primary selection when 76 | /// this context was constructed, first checks the primary 77 | /// selection. If pasting from the primary selection raises an 78 | /// error or the primary selection is unsupported, falls back to 79 | /// the regular clipboard. 80 | /// 81 | /// An empty clipboard is not considered an error, but the 82 | /// clipboard must indicate a text MIME type and the contained text 83 | /// must be valid UTF-8. 84 | fn get_contents(&mut self) -> Result { 85 | if self.supports_primary_selection { 86 | match paste::get_contents( 87 | paste::ClipboardType::Primary, 88 | paste::Seat::Unspecified, 89 | paste::MimeType::Text, 90 | ) { 91 | Ok((mut reader, _)) => { 92 | // this looks weird, but rustc won't let me do it 93 | // the natural way 94 | return Ok(read_into_string(&mut reader).map_err(Box::new)?); 95 | } 96 | Err(e) => match e { 97 | paste::Error::NoSeats 98 | | paste::Error::ClipboardEmpty 99 | | paste::Error::NoMimeType => return Ok("".to_string()), 100 | _ => (), 101 | }, 102 | } 103 | } 104 | 105 | let mut reader = match paste::get_contents( 106 | paste::ClipboardType::Regular, 107 | paste::Seat::Unspecified, 108 | paste::MimeType::Text, 109 | ) { 110 | Ok((reader, _)) => reader, 111 | Err( 112 | paste::Error::NoSeats | paste::Error::ClipboardEmpty | paste::Error::NoMimeType, 113 | ) => return Ok("".to_string()), 114 | Err(e) => return Err(e.into()), 115 | }; 116 | 117 | Ok(read_into_string(&mut reader).map_err(Box::new)?) 118 | } 119 | 120 | /// Copies to the Wayland clipboard. 121 | /// 122 | /// If the Wayland environment supported the primary selection when 123 | /// this context was constructed, this will copy to both the 124 | /// primary selection and the regular clipboard. Otherwise, only 125 | /// the regular clipboard will be pasted to. 126 | fn set_contents(&mut self, data: String) -> Result<()> { 127 | let mut options = Options::new(); 128 | 129 | options 130 | .seat(copy::Seat::All) 131 | .trim_newline(false) 132 | .foreground(false) 133 | .serve_requests(ServeRequests::Unlimited); 134 | 135 | if self.supports_primary_selection { 136 | options.clipboard(copy::ClipboardType::Both); 137 | } else { 138 | options.clipboard(copy::ClipboardType::Regular); 139 | } 140 | 141 | options 142 | .copy( 143 | copy::Source::Bytes(data.into_bytes().into()), 144 | copy::MimeType::Text, 145 | ) 146 | .map_err(Into::into) 147 | } 148 | 149 | fn clear(&mut self) -> Result<()> { 150 | if self.supports_primary_selection { 151 | clear(copy::ClipboardType::Both, copy::Seat::All).map_err(Into::into) 152 | } else { 153 | clear(copy::ClipboardType::Regular, copy::Seat::All).map_err(Into::into) 154 | } 155 | } 156 | } 157 | 158 | fn read_into_string(reader: &mut R) -> io::Result { 159 | let mut contents = String::new(); 160 | reader.read_to_string(&mut contents)?; 161 | 162 | Ok(contents) 163 | } 164 | 165 | #[cfg(test)] 166 | mod tests { 167 | use super::*; 168 | 169 | #[test] 170 | #[ignore] 171 | fn wayland_test() { 172 | let mut clipboard = 173 | WaylandClipboardContext::new().expect("couldn't create a Wayland clipboard"); 174 | 175 | clipboard 176 | .set_contents("foo bar baz".to_string()) 177 | .expect("couldn't set contents of Wayland clipboard"); 178 | 179 | assert_eq!( 180 | clipboard 181 | .get_contents() 182 | .expect("couldn't get contents of Wayland clipboard"), 183 | "foo bar baz" 184 | ); 185 | } 186 | } 187 | -------------------------------------------------------------------------------- /src/windows_clipboard.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2016 Avraham Weinstock 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | use clipboard_win::{empty, get_clipboard_string, set_clipboard_string, Clipboard}; 18 | 19 | use crate::common::ClipboardProvider; 20 | use crate::Result; 21 | 22 | pub struct WindowsClipboardContext; 23 | 24 | impl ClipboardProvider for WindowsClipboardContext { 25 | fn new() -> Result { 26 | Ok(WindowsClipboardContext) 27 | } 28 | 29 | fn get_contents(&mut self) -> Result { 30 | Ok(get_clipboard_string()?) 31 | } 32 | 33 | fn set_contents(&mut self, data: String) -> Result<()> { 34 | Ok(set_clipboard_string(&data)?) 35 | } 36 | 37 | fn clear(&mut self) -> Result<()> { 38 | let _clip = Clipboard::new_attempts(10)?; 39 | Ok(empty()?) 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/x11_clipboard.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017 Avraham Weinstock 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | use crate::common::*; 18 | use crate::Result; 19 | use std::marker::PhantomData; 20 | use std::time::Duration; 21 | use x11_clipboard_crate::Clipboard as X11Clipboard; 22 | use x11_clipboard_crate::{Atom, Atoms}; 23 | 24 | pub trait Selection { 25 | fn atom(atoms: &Atoms) -> Atom; 26 | } 27 | 28 | pub struct Primary; 29 | 30 | impl Selection for Primary { 31 | fn atom(atoms: &Atoms) -> Atom { 32 | atoms.primary 33 | } 34 | } 35 | 36 | pub struct Clipboard; 37 | 38 | impl Selection for Clipboard { 39 | fn atom(atoms: &Atoms) -> Atom { 40 | atoms.clipboard 41 | } 42 | } 43 | 44 | pub struct X11ClipboardContext(X11Clipboard, PhantomData) 45 | where 46 | S: Selection; 47 | 48 | impl ClipboardProvider for X11ClipboardContext 49 | where 50 | S: Selection, 51 | { 52 | fn new() -> Result> { 53 | Ok(X11ClipboardContext(X11Clipboard::new()?, PhantomData)) 54 | } 55 | 56 | fn get_contents(&mut self) -> Result { 57 | Ok(String::from_utf8(self.0.load( 58 | S::atom(&self.0.getter.atoms), 59 | self.0.getter.atoms.utf8_string, 60 | self.0.getter.atoms.property, 61 | Duration::from_secs(3), 62 | )?)?) 63 | } 64 | 65 | fn set_contents(&mut self, data: String) -> Result<()> { 66 | Ok(self.0.store( 67 | S::atom(&self.0.setter.atoms), 68 | self.0.setter.atoms.utf8_string, 69 | data, 70 | )?) 71 | } 72 | 73 | fn clear(&mut self) -> Result<()> { 74 | Ok(self.0.store( 75 | S::atom(&self.0.setter.atoms), 76 | self.0.setter.atoms.utf8_string, 77 | "".to_string(), 78 | )?) 79 | } 80 | } 81 | --------------------------------------------------------------------------------