egui-winit: if clipboard fails to start, fall back to local clipboard

This commit is contained in:
Emil Ernerfeldt 2022-04-12 11:39:35 +02:00
parent d364dfac66
commit 08b208586a
3 changed files with 17 additions and 22 deletions

View file

@ -1,11 +1,12 @@
/// Handles interfacing either with the OS clipboard.
/// If the "clipboard" feature is off it will instead simulate the clipboard locally.
/// Handles interfacing with the OS clipboard.
///
/// If the "clipboard" feature is off, or we cannot connect to the OS clipboard,
/// then a fallback clipboard that just works works within the same app is used instead.
pub struct Clipboard {
#[cfg(feature = "arboard")]
arboard: Option<arboard::Clipboard>,
/// Fallback manual clipboard.
#[cfg(not(feature = "arboard"))]
clipboard: String,
}
@ -15,7 +16,6 @@ impl Default for Clipboard {
#[cfg(feature = "arboard")]
arboard: init_arboard(),
#[cfg(not(feature = "arboard"))]
clipboard: String::default(),
}
}
@ -25,18 +25,15 @@ impl Clipboard {
pub fn get(&mut self) -> Option<String> {
#[cfg(feature = "arboard")]
if let Some(clipboard) = &mut self.arboard {
match clipboard.get_text() {
return match clipboard.get_text() {
Ok(text) => Some(text),
Err(err) => {
tracing::error!("Paste error: {}", err);
None
}
}
} else {
None
};
}
#[cfg(not(feature = "arboard"))]
Some(self.clipboard.clone())
}
@ -46,14 +43,12 @@ impl Clipboard {
if let Err(err) = clipboard.set_text(text) {
tracing::error!("Copy/Cut error: {}", err);
}
return;
}
#[cfg(not(feature = "arboard"))]
{
self.clipboard = text;
}
}
}
#[cfg(feature = "arboard")]
fn init_arboard() -> Option<arboard::Clipboard> {

View file

@ -412,9 +412,10 @@ impl State {
self.egui_input.events.push(egui::Event::Copy);
} else if is_paste_command(self.egui_input.modifiers, keycode) {
if let Some(contents) = self.clipboard.get() {
self.egui_input
.events
.push(egui::Event::Paste(contents.replace("\r\n", "\n")));
let contents = contents.replace("\r\n", "\n");
if !contents.is_empty() {
self.egui_input.events.push(egui::Event::Paste(contents));
}
}
}
}

View file

@ -464,12 +464,11 @@ fn install_document_events(runner_container: &AppRunnerContainer) -> Result<(),
|event: web_sys::ClipboardEvent, mut runner_lock| {
if let Some(data) = event.clipboard_data() {
if let Ok(text) = data.get_data("text") {
runner_lock
.input
.raw
.events
.push(egui::Event::Paste(text.replace("\r\n", "\n")));
let text = text.replace("\r\n", "\n");
if !text.is_empty() {
runner_lock.input.raw.events.push(egui::Event::Paste(text));
runner_lock.needs_repaint.set_true();
}
event.stop_propagation();
event.prevent_default();
}