mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-12-04 21:13:13 -05:00
Merge pull request #8821 from storytold/fix/pdfcraft-0231-wayland-clipboard
Restore clipboard transfers in Wayland Flatpak sessions
This commit is contained in:
3 files changed
+180
-3
No files matched your search
@@ -645,6 +645,13 @@ fn app_creator<'a>(
|
||||
#[cfg(target_os = "macos")]
|
||||
let apple_events_poll = apple_events.connect(intake.sender(), &cc.egui_ctx);
|
||||
let mut app = PdfCraftApp::with_intake(&cc.egui_ctx, intake);
|
||||
#[cfg(target_os = "linux")]
|
||||
if let Some(window) = cc.winit_window() {
|
||||
use raw_window_handle::{HasDisplayHandle as _, RawDisplayHandle};
|
||||
if window.display_handle().is_ok_and(|h| matches!(h.as_raw(), RawDisplayHandle::Wayland(_))) {
|
||||
app.use_wayland_clipboard(&cc.egui_ctx);
|
||||
}
|
||||
}
|
||||
let exit_watch = nightly_watch.clone();
|
||||
app.at_exit = Some(Box::new(move || nightly_session::finish_once(&exit_watch, true)));
|
||||
#[cfg(target_os = "macos")]
|
||||
|
||||
@@ -2,6 +2,9 @@ use craft::host::queue::Priority;
|
||||
// PLAN: needs the `platform-clipboard` feature on the `craft` dependency in crates/ui-egui/Cargo.toml (owner: pdf-hub-w1); `craft::platform::clipboard` exists only with it
|
||||
use craft::platform::clipboard::{ClipboardImage, Flavor, HTML, RGBA8, TEXT};
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod wayland;
|
||||
|
||||
use super::{CommentClip, DocId, DocView, DocumentCopyJob, PdfCraftApp, QuickTool, comments};
|
||||
|
||||
/// The browser's clipboard: a page can't read it outside a paste event, so pastes arrive as events
|
||||
@@ -60,6 +63,12 @@ fn color_image(image: &ClipboardImage) -> Option<egui::ColorImage> {
|
||||
}
|
||||
|
||||
impl PdfCraftApp {
|
||||
/// Use the window's selection seat for regular clipboard transfers under Wayland.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn use_wayland_clipboard(&mut self, ctx: &egui::Context) {
|
||||
self.clipboard = wayland::clipboard(ctx);
|
||||
}
|
||||
|
||||
/// Whether text and images may be copied out of document `id`; says why not when they may
|
||||
/// not. Reading aloud and accessibility tools don't ask (assistive technology may read
|
||||
/// anything, §7.6.4.2).
|
||||
@@ -204,9 +213,11 @@ impl PdfCraftApp {
|
||||
rgba.extend(img.pixels.iter().flat_map(egui::Color32::to_srgba_unmultiplied));
|
||||
Some(ClipboardImage { width, height, rgba })
|
||||
});
|
||||
let text = delivered_text
|
||||
.or_else(|| if self.clipboard.has(&[TEXT]) { self.clipboard.read_text().ok().flatten().filter(|t| !t.is_empty()) } else { None });
|
||||
let image = delivered_image.or_else(|| self.clipboard.read_image().ok().flatten());
|
||||
let received = delivered_text.is_some() || delivered_image.is_some();
|
||||
let text = delivered_text.or_else(|| {
|
||||
if !received && self.clipboard.has(&[TEXT]) { self.clipboard.read_text().ok().flatten().filter(|t| !t.is_empty()) } else { None }
|
||||
});
|
||||
let image = delivered_image.or_else(|| if received { None } else { self.clipboard.read_image().ok().flatten() });
|
||||
if self.quick_tool == QuickTool::EditText && self.object_clipboard.is_some() && self.pastes_objects(text.as_deref(), image.as_ref()) {
|
||||
self.paste_objects(ctx, i);
|
||||
return;
|
||||
@@ -504,6 +515,17 @@ mod review_tests {
|
||||
assert_eq!(app.last_copied_image.as_ref().unwrap().2, vec![0, 255, 0, 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delivered_text_does_not_paste_an_unrelated_native_image() {
|
||||
let (mut app, _) = app_with_clipboard();
|
||||
let image = ClipboardImage { width: 1, height: 1, rgba: vec![0, 255, 0, 255] };
|
||||
app.clipboard.offer_paste(vec![Flavor::rgba8(&image)]);
|
||||
let mut pasted = craft::ui::runtime::commands::ClipContent::default();
|
||||
pasted.text = Some("from the focused seat".into());
|
||||
app.paste_from_clipboard_at(&egui::Context::default(), 0, Some(&pasted), None);
|
||||
assert!(app.session.get(app.views[0].id).unwrap().page_images(0).is_empty());
|
||||
}
|
||||
|
||||
/// The clipboard holds one paste at a time: an image offered with text pastes, with the
|
||||
/// pasted pixels kept as the app's cache, whichever event came first.
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
//! The focused Wayland seat owns regular Copy and Paste. Access to the compositor's
|
||||
//! separate data-control protocol (used for richer offers) is optional in a sandbox.
|
||||
use craft::platform::clipboard::{Clipboard, ClipboardBackend, ClipboardError, ClipboardImage, EventClipboard, Flavor, RGBA8, SystemClipboard, TEXT};
|
||||
use std::path::PathBuf;
|
||||
|
||||
struct WaylandClipboard {
|
||||
window: EventClipboard,
|
||||
direct: SystemClipboard,
|
||||
direct_write: bool,
|
||||
sandboxed: bool,
|
||||
}
|
||||
|
||||
pub(super) fn clipboard(ctx: &egui::Context) -> Clipboard {
|
||||
backend(ctx, std::path::Path::new("/.flatpak-info").is_file())
|
||||
}
|
||||
|
||||
fn backend(ctx: &egui::Context, sandboxed: bool) -> Clipboard {
|
||||
let pass = ctx.clone();
|
||||
let output = ctx.clone();
|
||||
let window = EventClipboard::new(
|
||||
move || pass.cumulative_pass_nr(),
|
||||
move |flavors| {
|
||||
if flavors.is_empty() {
|
||||
output.copy_text(String::new());
|
||||
return Ok(0);
|
||||
}
|
||||
for (index, flavor) in flavors.iter().enumerate() {
|
||||
if flavor.mime == TEXT
|
||||
&& let Ok(text) = std::str::from_utf8(&flavor.data)
|
||||
{
|
||||
output.copy_text(text.to_owned());
|
||||
return Ok(index);
|
||||
}
|
||||
if flavor.mime == RGBA8
|
||||
&& let Some(image) = flavor.rgba8_image().as_ref().and_then(super::color_image)
|
||||
{
|
||||
output.copy_image(image);
|
||||
return Ok(index);
|
||||
}
|
||||
}
|
||||
Err(ClipboardError::NoFormat)
|
||||
},
|
||||
);
|
||||
Clipboard::new(WaylandClipboard { window, direct: SystemClipboard::new(), direct_write: false, sandboxed })
|
||||
}
|
||||
|
||||
impl WaylandClipboard {
|
||||
// An event belongs to this user's paste. Reading a second connection could
|
||||
// substitute a different application's older clipboard item.
|
||||
fn reader(&mut self) -> &mut dyn ClipboardBackend {
|
||||
if self.window.formats().is_empty() { &mut self.direct } else { &mut self.window }
|
||||
}
|
||||
}
|
||||
|
||||
impl ClipboardBackend for WaylandClipboard {
|
||||
fn write(&mut self, flavors: &[Flavor]) -> Result<usize, ClipboardError> {
|
||||
// Keep a rich offer where the compositor grants data-control. The ordinary
|
||||
// text/image alternative always travels through the focused window if denied.
|
||||
let rich = flavors.iter().any(|f| f.mime != TEXT && f.mime != RGBA8);
|
||||
if rich
|
||||
&& !self.sandboxed
|
||||
&& let Ok(index) = self.direct.write(flavors)
|
||||
{
|
||||
self.direct_write = true;
|
||||
return Ok(index);
|
||||
}
|
||||
let index = self.window.write(flavors)?;
|
||||
self.direct_write = false;
|
||||
Ok(index)
|
||||
}
|
||||
|
||||
fn read(&mut self, mimes: &[&str], limit: u64) -> Result<Option<Flavor>, ClipboardError> {
|
||||
self.reader().read(mimes, limit)
|
||||
}
|
||||
|
||||
fn read_image(&mut self, limit: u64) -> Result<Option<ClipboardImage>, ClipboardError> {
|
||||
self.reader().read_image(limit)
|
||||
}
|
||||
|
||||
fn read_files(&mut self, limit: usize) -> Result<Option<Vec<PathBuf>>, ClipboardError> {
|
||||
self.reader().read_files(limit)
|
||||
}
|
||||
|
||||
fn has(&mut self, mimes: &[&str]) -> bool {
|
||||
self.reader().has(mimes)
|
||||
}
|
||||
|
||||
fn offer(&mut self, flavors: Vec<Flavor>) {
|
||||
self.window.offer(flavors);
|
||||
}
|
||||
|
||||
fn formats(&mut self) -> Vec<String> {
|
||||
self.reader().formats()
|
||||
}
|
||||
|
||||
fn owns(&mut self) -> Option<bool> {
|
||||
if self.direct_write { self.direct.owns() } else { None }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn flatpak_selection_uses_the_window_and_reads_the_paste_offer() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut clipboard = backend(&ctx, true);
|
||||
let _ = clipboard.write(&[Flavor::new(super::super::HTML, b"<b>Sel</b>".to_vec()), Flavor::text("Sel")]).unwrap();
|
||||
assert!(ctx.output(|out| out.commands.iter().any(|c| matches!(c, egui::OutputCommand::CopyText(s) if s == "Sel"))));
|
||||
clipboard.offer_paste(vec![Flavor::text("from another app")]);
|
||||
assert_eq!(clipboard.read_text().unwrap().as_deref(), Some("from another app"));
|
||||
assert!(clipboard.read_image().unwrap().is_none());
|
||||
clipboard.set_synthetic(true);
|
||||
let _ = clipboard.write_text("injected").unwrap();
|
||||
assert!(ctx.output(|out| !out.commands.iter().any(|c| matches!(c, egui::OutputCommand::CopyText(s) if s == "injected"))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn window_image_offers_keep_the_pixels_and_respect_read_limits() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut clipboard = backend(&ctx, true);
|
||||
let image = ClipboardImage { width: 2, height: 1, rgba: vec![255, 0, 0, 255, 0, 0, 255, 255] };
|
||||
let _ = clipboard.write_image(&image).unwrap();
|
||||
assert!(ctx.output(|out| out.commands.iter().any(|c| matches!(c, egui::OutputCommand::CopyImage(v) if v.size == [2, 1]))));
|
||||
let backend = clipboard.backend_mut();
|
||||
backend.offer(vec![Flavor::rgba8(&image)]);
|
||||
assert!(backend.has(&[RGBA8]));
|
||||
assert!(!backend.has(&[TEXT]));
|
||||
assert_eq!(backend.formats(), [RGBA8]);
|
||||
assert!(matches!(backend.read_image(4), Err(ClipboardError::TooLarge { limit: 4 })));
|
||||
assert_eq!(backend.read_image(8).unwrap(), Some(image));
|
||||
assert!(backend.read_files(1).unwrap().is_none());
|
||||
assert_eq!(backend.owns(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_window_offers_preserve_the_clipboard_until_a_valid_copy_or_clear() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut clipboard = backend(&ctx, true);
|
||||
let backend = clipboard.backend_mut();
|
||||
assert!(matches!(backend.write(&[Flavor::new(TEXT, vec![0xff]), Flavor::new(RGBA8, vec![0])]), Err(ClipboardError::NoFormat)));
|
||||
assert!(ctx.output(|out| out.commands.is_empty()));
|
||||
assert_eq!(backend.write(&[Flavor::new("application/x-unsupported", vec![1]), Flavor::text("fallback")]).unwrap(), 1);
|
||||
assert_eq!(backend.write(&[]).unwrap(), 0);
|
||||
assert!(ctx.output(|out| matches!(out.commands.last(), Some(egui::OutputCommand::CopyText(s)) if s.is_empty())));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user