cli_clipboard/
wayland_clipboard.rs

1/*
2Copyright 2019 Gregory Meyer
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8   http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17use crate::common::*;
18use crate::Result;
19use std::io::{self, Read};
20use 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/// ```
46pub struct WaylandClipboardContext {
47    supports_primary_selection: bool,
48}
49
50impl 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<WaylandClipboardContext> {
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<String> {
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
158fn read_into_string<R: Read>(reader: &mut R) -> io::Result<String> {
159    let mut contents = String::new();
160    reader.read_to_string(&mut contents)?;
161
162    Ok(contents)
163}
164
165#[cfg(test)]
166mod 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}