Skip to content

Commit

Permalink
Use wayland clipboard
Browse files Browse the repository at this point in the history
  • Loading branch information
cshuaimin committed Nov 11, 2023
1 parent c0d2ff3 commit 0b20e54
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 7 deletions.
29 changes: 22 additions & 7 deletions src/clipboard.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,35 @@
use copypasta::{ClipboardContext, ClipboardProvider};
use std::error::Error;
use std::sync::OnceLock;

#[cfg(all(unix, not(target_os = "macos")))]
use copypasta::wayland_clipboard;
use copypasta::{ClipboardContext, ClipboardProvider};
use parking_lot::Mutex;
use raw_window_handle::{HasRawDisplayHandle, RawDisplayHandle, WaylandDisplayHandle};
use winit::event_loop::EventLoop;

use std::error::Error;
use crate::window::UserEvent;

type Result<T> = std::result::Result<T, Box<dyn Error + Send + Sync + 'static>>;

lazy_static! {
static ref CLIPBOARD_CONTEXT: Mutex<ClipboardContext> =
Mutex::new(ClipboardContext::new().unwrap());
static CLIPBOARD: OnceLock<Mutex<Box<dyn ClipboardProvider>>> = OnceLock::new();

pub fn init(event_loop: &EventLoop<UserEvent>) {
CLIPBOARD
.set(Mutex::new(match event_loop.raw_display_handle() {
#[cfg(all(unix, not(target_os = "macos",)))]
RawDisplayHandle::Wayland(WaylandDisplayHandle { display, .. }) => unsafe {
Box::new(wayland_clipboard::create_clipboards_from_external(display).1)
},
_ => Box::new(ClipboardContext::new().unwrap()),
}))
.ok();
}

pub fn get_contents() -> Result<String> {
CLIPBOARD_CONTEXT.lock().get_contents()
CLIPBOARD.get().unwrap().lock().get_contents()
}

pub fn set_contents(lines: String) -> Result<()> {
CLIPBOARD_CONTEXT.lock().set_contents(lines)
CLIPBOARD.get().unwrap().lock().set_contents(lines)
}
4 changes: 4 additions & 0 deletions src/window/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,8 @@ pub fn main_loop(
);
}));

crate::clipboard::init(&event_loop);

event_loop.run(move |e, window_target| {
match e {
Event::LoopExiting => {
Expand Down Expand Up @@ -309,6 +311,8 @@ pub fn main_loop(
let cmd_line_settings = SETTINGS.get::<CmdLineSettings>();
let mut window_wrapper = WinitWindowWrapper::new(window, initial_window_size);

crate::clipboard::init(&event_loop);

let mut update_loop = UpdateLoop::new(
cmd_line_settings.vsync,
cmd_line_settings.idle,
Expand Down

0 comments on commit 0b20e54

Please sign in to comment.