Remove copypasta and maintain our own fork
This commit is contained in:
parent
b55ba14585
commit
23004b960f
16 changed files with 685 additions and 40 deletions
3
.github/workflows/test.yml
vendored
3
.github/workflows/test.yml
vendored
|
|
@ -11,9 +11,6 @@ jobs:
|
|||
- uses: hecrj/setup-rust-action@v1
|
||||
with:
|
||||
rust-version: ${{ matrix.rust }}
|
||||
- name: Install xcb libraries
|
||||
if: matrix.os == 'ubuntu-latest'
|
||||
run: sudo apt-get install -y libxcb-shape0-dev libxcb-xfixes0-dev
|
||||
- uses: actions/checkout@master
|
||||
- name: Run tests
|
||||
run: cargo test --verbose
|
||||
|
|
|
|||
19
Cargo.toml
19
Cargo.toml
|
|
@ -13,7 +13,24 @@ categories = ["gui"]
|
|||
|
||||
[dependencies]
|
||||
raw-window-handle = "0.3"
|
||||
copypasta = "0.6"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
window_clipboard_windows = { version = "0.1", path = "./windows" }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
window_clipboard_macos = { version = "0.1", path = "./macos" }
|
||||
|
||||
[target.'cfg(all(unix, not(any(target_os="macos", target_os="android", target_os="emscripten"))))'.dependencies]
|
||||
window_clipboard_x11 = { version = "0.1", path = "./x11" }
|
||||
window_clipboard_wayland = { version = "0.1", path = "./wayland" }
|
||||
|
||||
[dev-dependencies]
|
||||
winit = "=0.20.0-alpha5"
|
||||
|
||||
[workspace]
|
||||
members = [
|
||||
"macos",
|
||||
"wayland",
|
||||
"windows",
|
||||
"x11",
|
||||
]
|
||||
|
|
|
|||
12
macos/Cargo.toml
Normal file
12
macos/Cargo.toml
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
[package]
|
||||
name = "window_clipboard_macos"
|
||||
version = "0.1.0"
|
||||
authors = ["Héctor Ramón Jiménez <hector0193@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
objc = "0.2"
|
||||
objc_id = "0.1"
|
||||
objc-foundation = "0.1"
|
||||
88
macos/src/lib.rs
Normal file
88
macos/src/lib.rs
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
// Copyright 2016 Avraham Weinstock
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use objc::runtime::{Class, Object};
|
||||
use objc_foundation::{INSArray, INSObject, INSString};
|
||||
use objc_foundation::{NSArray, NSDictionary, NSObject, NSString};
|
||||
use objc_id::{Id, Owned};
|
||||
use std::error::Error;
|
||||
use std::mem::transmute;
|
||||
|
||||
pub struct Clipboard {
|
||||
pasteboard: Id<Object>,
|
||||
}
|
||||
|
||||
// required to bring NSPasteboard into the path of the class-resolver
|
||||
#[link(name = "AppKit", kind = "framework")]
|
||||
extern "C" {}
|
||||
|
||||
impl Clipboard {
|
||||
pub fn new() -> Result<Clipboard, Box<dyn Error>> {
|
||||
let cls =
|
||||
Class::get("NSPasteboard").ok_or("Class::get(\"NSPasteboard\")")?;
|
||||
let pasteboard: *mut Object =
|
||||
unsafe { msg_send![cls, generalPasteboard] };
|
||||
if pasteboard.is_null() {
|
||||
return Err("NSPasteboard#generalPasteboard returned null".into());
|
||||
}
|
||||
let pasteboard: Id<Object> = unsafe { Id::from_ptr(pasteboard) };
|
||||
Ok(Clipboard { pasteboard })
|
||||
}
|
||||
|
||||
fn read(&self) -> Result<String, Box<dyn Error>> {
|
||||
let string_class: Id<NSObject> = {
|
||||
let cls: Id<Class> = unsafe { Id::from_ptr(class("NSString")) };
|
||||
unsafe { transmute(cls) }
|
||||
};
|
||||
let classes: Id<NSArray<NSObject, Owned>> =
|
||||
NSArray::from_vec(vec![string_class]);
|
||||
let options: Id<NSDictionary<NSObject, NSObject>> = NSDictionary::new();
|
||||
let string_array: Id<NSArray<NSString>> = unsafe {
|
||||
let obj: *mut NSArray<NSString> = msg_send![self.pasteboard, readObjectsForClasses:&*classes options:&*options];
|
||||
if obj.is_null() {
|
||||
return Err(
|
||||
"pasteboard#readObjectsForClasses:options: returned null"
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
Id::from_ptr(obj)
|
||||
};
|
||||
if string_array.count() == 0 {
|
||||
Err("pasteboard#readObjectsForClasses:options: returned empty"
|
||||
.into())
|
||||
} else {
|
||||
Ok(string_array[0].as_str().to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
fn write(&mut self, data: String) -> Result<(), Box<dyn Error>> {
|
||||
let string_array = NSArray::from_vec(vec![NSString::from_str(&data)]);
|
||||
let _: usize = unsafe { msg_send![self.pasteboard, clearContents] };
|
||||
let success: bool =
|
||||
unsafe { msg_send![self.pasteboard, writeObjects: string_array] };
|
||||
return if success {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("NSPasteboard#writeObjects: returned false".into())
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// this is a convenience function that both cocoa-rs and
|
||||
// glutin define, which seems to depend on the fact that
|
||||
// Option::None has the same representation as a null pointer
|
||||
#[inline]
|
||||
pub fn class(name: &str) -> *mut Class {
|
||||
unsafe { transmute(Class::get(name)) }
|
||||
}
|
||||
61
src/lib.rs
61
src/lib.rs
|
|
@ -1,16 +1,3 @@
|
|||
use raw_window_handle::{HasRawWindowHandle, RawWindowHandle};
|
||||
use std::cell::RefCell;
|
||||
use std::error::Error;
|
||||
|
||||
pub struct Clipboard {
|
||||
raw: RefCell<Box<dyn copypasta::ClipboardProvider>>,
|
||||
}
|
||||
|
||||
impl Clipboard {
|
||||
pub fn new<W: HasRawWindowHandle>(
|
||||
window: &W,
|
||||
) -> Result<Self, Box<dyn Error>> {
|
||||
let raw = match window.raw_window_handle() {
|
||||
#[cfg(all(
|
||||
unix,
|
||||
not(any(
|
||||
|
|
@ -19,35 +6,43 @@ impl Clipboard {
|
|||
target_os = "emscripten"
|
||||
))
|
||||
))]
|
||||
RawWindowHandle::Wayland(handle) => {
|
||||
assert!(!handle.display.is_null());
|
||||
#[path = "platform/linux.rs"]
|
||||
mod platform;
|
||||
|
||||
Box::new(unsafe {
|
||||
let (_, raw) = copypasta::wayland_clipboard::create_clipboards_from_external(
|
||||
handle.display as *mut _,
|
||||
);
|
||||
#[cfg(not(all(
|
||||
unix,
|
||||
not(any(
|
||||
target_os = "macos",
|
||||
target_os = "android",
|
||||
target_os = "emscripten"
|
||||
))
|
||||
)))]
|
||||
#[path = "platform/not_linux.rs"]
|
||||
mod platform;
|
||||
|
||||
raw
|
||||
}) as _
|
||||
use raw_window_handle::HasRawWindowHandle;
|
||||
use std::error::Error;
|
||||
|
||||
pub struct Clipboard {
|
||||
raw: Box<dyn ClipboardProvider>,
|
||||
}
|
||||
_ => Box::new(copypasta::ClipboardContext::new()?) as _,
|
||||
};
|
||||
|
||||
Ok(Clipboard {
|
||||
raw: RefCell::new(raw),
|
||||
})
|
||||
impl Clipboard {
|
||||
pub fn new<W: HasRawWindowHandle>(
|
||||
window: &W,
|
||||
) -> Result<Self, Box<dyn Error>> {
|
||||
let raw = platform::new_clipboard(window)?;
|
||||
|
||||
Ok(Clipboard { raw })
|
||||
}
|
||||
|
||||
pub fn read(&self) -> Result<String, Box<dyn Error>> {
|
||||
// TODO: Think about use of `RefCell`
|
||||
// Maybe we should make `read` mutable (?)
|
||||
self.raw.borrow_mut().get_contents()
|
||||
self.raw.read()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write(
|
||||
&mut self,
|
||||
contents: impl Into<String>,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
self.raw.borrow_mut().set_contents(contents.into())
|
||||
}
|
||||
pub trait ClipboardProvider {
|
||||
fn read(&self) -> Result<String, Box<dyn Error>>;
|
||||
}
|
||||
|
|
|
|||
36
src/platform/linux.rs
Normal file
36
src/platform/linux.rs
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
use crate::ClipboardProvider;
|
||||
|
||||
use raw_window_handle::{HasRawWindowHandle, RawWindowHandle};
|
||||
use std::error::Error;
|
||||
|
||||
pub use window_clipboard_wayland as wayland;
|
||||
pub use window_clipboard_x11 as x11;
|
||||
|
||||
pub fn new_clipboard<W: HasRawWindowHandle>(
|
||||
window: &W,
|
||||
) -> Result<Box<dyn ClipboardProvider>, Box<dyn Error>> {
|
||||
let clipboard = match window.raw_window_handle() {
|
||||
RawWindowHandle::Wayland(handle) => {
|
||||
assert!(!handle.display.is_null());
|
||||
|
||||
Box::new(unsafe {
|
||||
wayland::Clipboard::new(handle.display as *mut _)
|
||||
}) as _
|
||||
}
|
||||
_ => Box::new(x11::Clipboard::new()?) as _,
|
||||
};
|
||||
|
||||
Ok(clipboard)
|
||||
}
|
||||
|
||||
impl ClipboardProvider for wayland::Clipboard {
|
||||
fn read(&self) -> Result<String, Box<dyn Error>> {
|
||||
self.read()
|
||||
}
|
||||
}
|
||||
|
||||
impl ClipboardProvider for x11::Clipboard {
|
||||
fn read(&self) -> Result<String, Box<dyn Error>> {
|
||||
self.read()
|
||||
}
|
||||
}
|
||||
29
src/platform/not_linux.rs
Normal file
29
src/platform/not_linux.rs
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
use crate::ClipboardProvider;
|
||||
|
||||
pub fn new_clipboard<W: HasRawWindowHandle>(
|
||||
_window: &W,
|
||||
) -> Result<Box<dyn ClipboardProvider>, Box<dyn Error>> {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
Ok(Box::new(window_clipboard_windows::Clipboard::new()?))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
Ok(Box::new(window_clipboard_macos::Clipboard::new()?))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
impl ClipboardProvider for window_clipboard_windows::Clipboard {
|
||||
fn read(&self) -> Result<String, Box<dyn Error>> {
|
||||
self.read()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
impl ClipboardProvider for window_clipboard_macos::Clipboard {
|
||||
fn read(&self) -> Result<String, Box<dyn Error>> {
|
||||
self.read()
|
||||
}
|
||||
}
|
||||
10
wayland/Cargo.toml
Normal file
10
wayland/Cargo.toml
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
[package]
|
||||
name = "window_clipboard_wayland"
|
||||
version = "0.1.0"
|
||||
authors = ["Héctor Ramón Jiménez <hector0193@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
smithay-clipboard = "0.3.4"
|
||||
43
wayland/src/lib.rs
Normal file
43
wayland/src/lib.rs
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
// Copyright 2017 Avraham Weinstock
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use std::error::Error;
|
||||
use std::ffi::c_void;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use smithay_clipboard::WaylandClipboard;
|
||||
|
||||
pub struct Clipboard {
|
||||
context: Arc<Mutex<WaylandClipboard>>,
|
||||
}
|
||||
|
||||
impl Clipboard {
|
||||
pub unsafe fn new(display: *mut c_void) -> Clipboard {
|
||||
let context = Arc::new(Mutex::new(
|
||||
WaylandClipboard::new_from_external(display as *mut _),
|
||||
));
|
||||
|
||||
Clipboard { context }
|
||||
}
|
||||
|
||||
pub fn read(&self) -> Result<String, Box<dyn Error>> {
|
||||
Ok(self.context.lock().unwrap().load(None))
|
||||
}
|
||||
|
||||
pub fn write(&mut self, data: String) -> Result<(), Box<dyn Error>> {
|
||||
self.context.lock().unwrap().store(None, data);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
10
windows/Cargo.toml
Normal file
10
windows/Cargo.toml
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
[package]
|
||||
name = "window_clipboard_windows"
|
||||
version = "0.1.0"
|
||||
authors = ["Héctor Ramón Jiménez <hector0193@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
clipboard-win = "2.1"
|
||||
33
windows/src/lib.rs
Normal file
33
windows/src/lib.rs
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
// Copyright 2016 Avraham Weinstock
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use clipboard_win::{get_clipboard_string, set_clipboard_string};
|
||||
|
||||
use std::error::Error;
|
||||
|
||||
pub struct Clipboard;
|
||||
|
||||
impl Clipboard {
|
||||
pub fn new() -> Result<Self, Box<dyn Error>> {
|
||||
Ok(Clipboard)
|
||||
}
|
||||
|
||||
pub fn read(&self) -> Result<String, Box<dyn Error>> {
|
||||
Ok(get_clipboard_string()?)
|
||||
}
|
||||
|
||||
pub fn write(&mut self, data: String) -> Result<(), Box<dyn Error>> {
|
||||
Ok(set_clipboard_string(&data)?)
|
||||
}
|
||||
}
|
||||
10
x11/Cargo.toml
Normal file
10
x11/Cargo.toml
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
[package]
|
||||
name = "window_clipboard_x11"
|
||||
version = "0.1.0"
|
||||
authors = ["Héctor Ramón Jiménez <hector0193@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
xcb = { version = "0.9", features = ["thread"] }
|
||||
7
x11/LICENSE
Normal file
7
x11/LICENSE
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
Copyright (c) 2019 quininer@live.com, Héctor Ramón, window_clipboard_x11 contributors
|
||||
|
||||
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:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
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.
|
||||
272
x11/src/clipboard.rs
Normal file
272
x11/src/clipboard.rs
Normal file
|
|
@ -0,0 +1,272 @@
|
|||
use crate::error::Error;
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
use xcb::base::ConnError;
|
||||
use xcb::{Atom, Connection, Window};
|
||||
|
||||
const POLL_DURATION: std::time::Duration = Duration::from_micros(50);
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Atoms {
|
||||
pub primary: Atom,
|
||||
pub clipboard: Atom,
|
||||
pub property: Atom,
|
||||
pub targets: Atom,
|
||||
pub string: Atom,
|
||||
pub utf8_string: Atom,
|
||||
pub incr: Atom,
|
||||
}
|
||||
|
||||
/// X11 Clipboard
|
||||
pub struct Clipboard {
|
||||
pub getter: Context,
|
||||
}
|
||||
|
||||
pub struct Context {
|
||||
pub connection: Connection,
|
||||
pub screen: i32,
|
||||
pub window: Window,
|
||||
pub atoms: Atoms,
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn get_atom(connection: &Connection, name: &str) -> Result<Atom, Error> {
|
||||
xcb::intern_atom(connection, false, name)
|
||||
.get_reply()
|
||||
.map(|reply| reply.atom())
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
impl Context {
|
||||
pub fn new(displayname: Option<&str>) -> Result<Self, Error> {
|
||||
let (connection, screen) = Connection::connect(displayname)?;
|
||||
let window = connection.generate_id();
|
||||
|
||||
{
|
||||
let screen = connection
|
||||
.get_setup()
|
||||
.roots()
|
||||
.nth(screen as usize)
|
||||
.ok_or(Error::XcbConn(ConnError::ClosedInvalidScreen))?;
|
||||
xcb::create_window(
|
||||
&connection,
|
||||
xcb::COPY_FROM_PARENT as u8,
|
||||
window,
|
||||
screen.root(),
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
1,
|
||||
0,
|
||||
xcb::WINDOW_CLASS_INPUT_OUTPUT as u16,
|
||||
screen.root_visual(),
|
||||
&[(
|
||||
xcb::CW_EVENT_MASK,
|
||||
xcb::EVENT_MASK_STRUCTURE_NOTIFY
|
||||
| xcb::EVENT_MASK_PROPERTY_CHANGE,
|
||||
)],
|
||||
);
|
||||
connection.flush();
|
||||
}
|
||||
|
||||
macro_rules! intern_atom {
|
||||
( $name:expr ) => {
|
||||
get_atom(&connection, $name)?
|
||||
};
|
||||
}
|
||||
|
||||
let atoms = Atoms {
|
||||
primary: xcb::ATOM_PRIMARY,
|
||||
clipboard: intern_atom!("CLIPBOARD"),
|
||||
property: intern_atom!("THIS_CLIPBOARD_OUT"),
|
||||
targets: intern_atom!("TARGETS"),
|
||||
string: xcb::ATOM_STRING,
|
||||
utf8_string: intern_atom!("UTF8_STRING"),
|
||||
incr: intern_atom!("INCR"),
|
||||
};
|
||||
|
||||
Ok(Context {
|
||||
connection,
|
||||
screen,
|
||||
window,
|
||||
atoms,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Clipboard {
|
||||
/// Create Clipboard.
|
||||
pub fn new() -> Result<Self, Error> {
|
||||
let getter = Context::new(None)?;
|
||||
|
||||
Ok(Clipboard { getter })
|
||||
}
|
||||
|
||||
fn process_event<T>(
|
||||
&self,
|
||||
buff: &mut Vec<u8>,
|
||||
selection: Atom,
|
||||
target: Atom,
|
||||
property: Atom,
|
||||
timeout: T,
|
||||
) -> Result<(), Error>
|
||||
where
|
||||
T: Into<Option<Duration>>,
|
||||
{
|
||||
let mut is_incr = false;
|
||||
let timeout = timeout.into();
|
||||
let start_time = if timeout.is_some() {
|
||||
Some(Instant::now())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
loop {
|
||||
if timeout
|
||||
.into_iter()
|
||||
.zip(start_time)
|
||||
.next()
|
||||
.map(|(timeout, time)| (Instant::now() - time) >= timeout)
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return Err(Error::Timeout);
|
||||
}
|
||||
|
||||
let event = match self.getter.connection.poll_for_event() {
|
||||
Some(event) => event,
|
||||
None => {
|
||||
thread::park_timeout(POLL_DURATION);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let r = event.response_type();
|
||||
|
||||
match r & !0x80 {
|
||||
xcb::SELECTION_NOTIFY => {
|
||||
let event = unsafe {
|
||||
xcb::cast_event::<xcb::SelectionNotifyEvent>(&event)
|
||||
};
|
||||
if event.selection() != selection {
|
||||
continue;
|
||||
};
|
||||
|
||||
// Note that setting the property argument to None indicates that the
|
||||
// conversion requested could not be made.
|
||||
if event.property() == xcb::ATOM_NONE {
|
||||
break;
|
||||
}
|
||||
|
||||
let reply = xcb::get_property(
|
||||
&self.getter.connection,
|
||||
false,
|
||||
self.getter.window,
|
||||
event.property(),
|
||||
xcb::ATOM_ANY,
|
||||
buff.len() as u32,
|
||||
::std::u32::MAX, // FIXME reasonable buffer size
|
||||
)
|
||||
.get_reply()?;
|
||||
|
||||
if reply.type_() == self.getter.atoms.incr {
|
||||
if let Some(&size) = reply.value::<i32>().get(0) {
|
||||
buff.reserve(size as usize);
|
||||
}
|
||||
xcb::delete_property(
|
||||
&self.getter.connection,
|
||||
self.getter.window,
|
||||
property,
|
||||
);
|
||||
self.getter.connection.flush();
|
||||
is_incr = true;
|
||||
continue;
|
||||
} else if reply.type_() != target {
|
||||
return Err(Error::UnexpectedType(reply.type_()));
|
||||
}
|
||||
|
||||
buff.extend_from_slice(reply.value());
|
||||
break;
|
||||
}
|
||||
xcb::PROPERTY_NOTIFY if is_incr => {
|
||||
let event = unsafe {
|
||||
xcb::cast_event::<xcb::PropertyNotifyEvent>(&event)
|
||||
};
|
||||
if event.state() != xcb::PROPERTY_NEW_VALUE as u8 {
|
||||
continue;
|
||||
};
|
||||
|
||||
let length = xcb::get_property(
|
||||
&self.getter.connection,
|
||||
false,
|
||||
self.getter.window,
|
||||
property,
|
||||
xcb::ATOM_ANY,
|
||||
0,
|
||||
0,
|
||||
)
|
||||
.get_reply()
|
||||
.map(|reply| reply.bytes_after())?;
|
||||
|
||||
let reply = xcb::get_property(
|
||||
&self.getter.connection,
|
||||
true,
|
||||
self.getter.window,
|
||||
property,
|
||||
xcb::ATOM_ANY,
|
||||
0,
|
||||
length,
|
||||
)
|
||||
.get_reply()?;
|
||||
|
||||
if reply.type_() != target {
|
||||
continue;
|
||||
};
|
||||
|
||||
if reply.value_len() != 0 {
|
||||
buff.extend_from_slice(reply.value());
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// load value.
|
||||
pub fn load<T>(
|
||||
&self,
|
||||
selection: Atom,
|
||||
target: Atom,
|
||||
property: Atom,
|
||||
timeout: T,
|
||||
) -> Result<Vec<u8>, Error>
|
||||
where
|
||||
T: Into<Option<Duration>>,
|
||||
{
|
||||
let mut buff = Vec::new();
|
||||
let timeout = timeout.into();
|
||||
|
||||
xcb::convert_selection(
|
||||
&self.getter.connection,
|
||||
self.getter.window,
|
||||
selection,
|
||||
target,
|
||||
property,
|
||||
xcb::CURRENT_TIME, // FIXME ^
|
||||
// Clients should not use CurrentTime for the time argument of a ConvertSelection request.
|
||||
// Instead, they should use the timestamp of the event that caused the request to be made.
|
||||
);
|
||||
self.getter.connection.flush();
|
||||
|
||||
self.process_event(&mut buff, selection, target, property, timeout)?;
|
||||
xcb::delete_property(
|
||||
&self.getter.connection,
|
||||
self.getter.window,
|
||||
property,
|
||||
);
|
||||
self.getter.connection.flush();
|
||||
Ok(buff)
|
||||
}
|
||||
}
|
||||
63
x11/src/error.rs
Normal file
63
x11/src/error.rs
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
use xcb::Atom;
|
||||
use xcb::base::{ ConnError, GenericError };
|
||||
use std::fmt;
|
||||
use std::sync::mpsc::SendError;
|
||||
use std::error::Error as StdError;
|
||||
|
||||
#[must_use]
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
Set(SendError<Atom>),
|
||||
XcbConn(ConnError),
|
||||
XcbGeneric(GenericError),
|
||||
Lock,
|
||||
Timeout,
|
||||
Owner,
|
||||
UnexpectedType(Atom),
|
||||
|
||||
#[doc(hidden)]
|
||||
__Unknown
|
||||
}
|
||||
|
||||
impl fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
use self::Error::*;
|
||||
match self {
|
||||
Set(e) => write!(f, "XCB - couldn't set atom: {:?}", e),
|
||||
XcbConn(e) => write!(f, "XCB connection error: {:?}", e),
|
||||
XcbGeneric(e) => write!(f, "XCB generic error: {:?}", e),
|
||||
Lock => write!(f, "XCB: Lock is poisoned"),
|
||||
Timeout => write!(f, "Selection timed out"),
|
||||
Owner => write!(f, "Failed to set new owner of XCB selection"),
|
||||
UnexpectedType(target) => write!(f, "Unexpected Reply type: {}", target),
|
||||
__Unknown => unreachable!()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StdError for Error {
|
||||
fn source(&self) -> Option<&(dyn StdError + 'static)> {
|
||||
use self::Error::*;
|
||||
match self {
|
||||
Set(e) => Some(e),
|
||||
XcbConn(e) => Some(e),
|
||||
XcbGeneric(e) => Some(e),
|
||||
Lock | Timeout | Owner | UnexpectedType(_) => None,
|
||||
__Unknown => unreachable!()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! define_from {
|
||||
( $item:ident from $err:ty ) => {
|
||||
impl From<$err> for Error {
|
||||
fn from(err: $err) -> Error {
|
||||
Error::$item(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
define_from!(Set from SendError<Atom>);
|
||||
define_from!(XcbConn from ConnError);
|
||||
define_from!(XcbGeneric from GenericError);
|
||||
23
x11/src/lib.rs
Normal file
23
x11/src/lib.rs
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
mod clipboard;
|
||||
mod error;
|
||||
|
||||
pub use xcb::*;
|
||||
|
||||
use std::error::Error;
|
||||
|
||||
pub struct Clipboard(clipboard::Clipboard);
|
||||
|
||||
impl Clipboard {
|
||||
pub fn new() -> Result<Clipboard, Box<dyn Error>> {
|
||||
Ok(Clipboard(clipboard::Clipboard::new()?))
|
||||
}
|
||||
|
||||
pub fn read(&self) -> Result<String, Box<dyn Error>> {
|
||||
Ok(String::from_utf8(self.0.load(
|
||||
self.0.getter.atoms.clipboard,
|
||||
self.0.getter.atoms.utf8_string,
|
||||
self.0.getter.atoms.property,
|
||||
std::time::Duration::from_secs(3),
|
||||
)?)?)
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue