mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 05:37:04 +00:00
platform-w1: net change of 2 commits
- platform-w1: written from its sheet - platform-w1: review fixes (review-1)
This commit is contained in:
@@ -13,8 +13,10 @@ workspace = true
|
||||
|
||||
[features]
|
||||
default = []
|
||||
appearance = ["dep:zbus", "dep:futures-lite", "dep:async-channel", "dep:async-io", "dep:async-process", "dep:web-sys"]
|
||||
browser = ["dep:wasm-bindgen", "dep:js-sys", "dep:web-sys"]
|
||||
# `appearance`: also Windows' UI settings and macOS' accessibility display setting (reduced motion).
|
||||
appearance = ["dep:zbus", "dep:futures-lite", "dep:async-channel", "dep:async-io", "dep:async-process", "dep:web-sys", "dep:windows", "dep:objc2-app-kit"]
|
||||
# `browser`: downloads, and the file picker and save through `rfd`.
|
||||
browser = ["dep:wasm-bindgen", "dep:js-sys", "dep:web-sys", "dep:rfd", "dep:wasm-bindgen-futures"]
|
||||
# `SystemReader::report_contrast` and `report_reduced_motion`: preferences a test sets in place of an OS source.
|
||||
testing = ["appearance"]
|
||||
# Moving the system pointer (a scrub's screen-edge wrap).
|
||||
@@ -23,9 +25,12 @@ pointer = ["dep:core-graphics"]
|
||||
usage = ["dep:sysinfo"]
|
||||
# Screen capture for the screen colour picker (`craft_platform::screen`).
|
||||
screen = ["dep:zbus", "zbus?/blocking-api", "dep:futures-lite", "dep:async-io", "dep:x11rb", "dep:core-graphics2", "dep:xcap"]
|
||||
# `clipboard`: the system clipboard with size limits, the synthetic-input fence and the paste probe.
|
||||
# The presence check asks the system which formats the clipboard offers (no content is read): Windows, macOS, Wayland and X11.
|
||||
clipboard = ["dep:arboard", "dep:clipboard-win", "dep:objc2-app-kit", "dep:objc2-foundation", "dep:wl-clipboard-rs", "dep:x11rb"]
|
||||
# `clipboard`: the clipboard handle with size limits, the synthetic-input fence, the paste probe, `EventClipboard` and `MemoryClipboard`; no system crates.
|
||||
clipboard = []
|
||||
# `clipboard-system`: `SystemClipboard` over the OS: arboard, and the formats on offer asked of Windows, macOS, Wayland and X11.
|
||||
clipboard-system = ["clipboard", "dep:arboard", "dep:clipboard-win", "dep:objc2-app-kit", "dep:objc2-foundation", "dep:wl-clipboard-rs", "dep:x11rb"]
|
||||
# `open::apple_events`: Apple Events requests (macOS).
|
||||
apple-events = ["dep:fmv-macos-events"]
|
||||
|
||||
[dependencies]
|
||||
craft-theme = { workspace = true }
|
||||
@@ -54,9 +59,12 @@ x11rb = { version = "0.13", default-features = false, features = ["image", "rand
|
||||
wl-clipboard-rs = { version = "0.9", optional = true }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
# The versions arboard already pulls in: the pasteboard's format list for the clipboard presence check.
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSPasteboard"], optional = true }
|
||||
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSArray", "NSString", "NSEnumerator"], optional = true }
|
||||
# The versions arboard already pulls in. `objc2-app-kit`: the pasteboard's formats and RTF, and `appearance`'s reduced-motion setting
|
||||
# (`NSWorkspace`, `NSAccessibility`); `objc2-foundation`: the RTF and PNG bytes (`NSData`).
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSPasteboard", "NSWorkspace", "NSAccessibility"], optional = true }
|
||||
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSArray", "NSString", "NSEnumerator", "NSData"], optional = true }
|
||||
# Apple Events behind a safe API, pinned exactly: review the diff before bumping.
|
||||
fmv-macos-events = { version = "=0.1.0", optional = true }
|
||||
core-graphics = { version = "0.23", optional = true }
|
||||
core-graphics2 = { version = "=0.6.1", default-features = false, features = ["display", "window", "link"], optional = true }
|
||||
|
||||
@@ -66,13 +74,16 @@ sysinfo = { version = "=0.39.6", default-features = false, features = ["system"]
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
clipboard-win = { version = "5.3.1", features = ["std"], optional = true }
|
||||
# The system's reduced-motion setting (`UISettings`).
|
||||
windows = { version = "0.62", features = ["UI_ViewManagement"], optional = true }
|
||||
xcap = { version = "=0.9.8", optional = true }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
wasm-bindgen = { version = "0.2", optional = true }
|
||||
js-sys = { version = "0.3", optional = true }
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "HtmlElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Node", "Element", "MediaQueryList"], optional = true }
|
||||
rfd = { version = "0.17.2", default-features = false, optional = true }
|
||||
wasm-bindgen-futures = { version = "0.4", optional = true }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dev-dependencies]
|
||||
wasm-bindgen-test = "0.3"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
|
||||
+16
-12
@@ -10,21 +10,22 @@ pull in heavier dependencies.
|
||||
| always (not wasm) | `dialogs`: reserve waiting workers before eager UI-thread native picker creation; serial requests, failure delivery and completion wakeups. The backend factory belongs to the app. |
|
||||
| always | `From<appearance::Reading> for craft_theme::SystemAppearance`, so a host hands the OS answer to `Base::resolve`. |
|
||||
| `pointer` | Move the system pointer (`pointer::warp`), installed by the app as craft-ui's `Scrub::install_warp` service for a scrub's screen-edge wrap; macOS only, `false` elsewhere. |
|
||||
| `appearance` | Linux/BSD XDG desktop preference observation (colour scheme, contrast, reduced motion, button layout); browser contrast and motion media queries; owned cancellable subscriptions, bounded reads/helper capture, legacy compatibility and reconnect. |
|
||||
| `browser` | Wasm download link/object URL ownership, cleanup on setup failure or abandonment, and cleanup timer registration before clicking. |
|
||||
| `appearance` | Linux/BSD XDG desktop preference observation (colour scheme, contrast, reduced motion, button layout); reduced motion on Windows and macOS; browser contrast and motion media queries; owned cancellable subscriptions, bounded reads/helper capture, legacy compatibility and reconnect. |
|
||||
| `browser` | Wasm download link/object URL ownership, cleanup on setup failure or abandonment, and cleanup timer registration before clicking; the file picker and save. |
|
||||
| always | `clock::Clock`: monotonic seconds (`web-time`, so also in the browser) for animation, autosave and deadlines, with a manual mode tests set and advance; `monotonic_ms`, `unix_ms`. |
|
||||
| always | `pacing`: `FrameCap` (desktop frame-rate cap without vsync), `WindowVisibility` (shown or hidden), `WorkBudget`/`WorkSlice` (background work per call, paused or sliced while hidden). No egui. |
|
||||
| always | The app log: `log` records to standard error and `<dir>/<app>.log` with `RUST_LOG`-style filters, rotation to `.1`/`.2`, per-instance logs while another instance runs, a size cap; `logs::crash`: the panic hook, crash log, last panic for the error window, and `catch`. |
|
||||
| always | The app log: `log` records to standard error and `<dir>/<app>.log` with `RUST_LOG`-style filters, rotation to `.1`/`.2`, per-instance logs while another instance runs, a size cap; `logs::crash`: the panic hook, crash log (redacted message, written to standard error only when no logger takes errors), last panic for the error window, and `catch`. |
|
||||
| always | `session::Session` and `SessionKeeper`: the documents open at the last quit and where the user was in each, stored in the app's settings (serde) for a "Reopen Last Session" preference; `to_reopen` skips what is already open; a stored list longer than 64 documents is cut. No egui. |
|
||||
| `usage` | `usage::sample`: the process's resident memory and the memory it may still use (`MemorySample`, `None` when unknown), for the status readout's Scratch and Efficiency items. Linux reads `/proc`; other platforms return `None`. |
|
||||
| always | `open::FileIntake` with `IntakeSender` (the app's Apple Events and second-instance hand-over feed it): one queue for files the OS asks the app to open and files dropped on the window (`DroppedFile`, `DropTarget`: canvas, tab strip or window); `natural_cmp` and `same_file` for opening order and duplicates; `reveal` and `open_external`; the shared open-error texts. No egui. |
|
||||
| always | `open::FileIntake` with `IntakeSender` (OS open requests, second-instance hand-over and `IntakeSender::dropped` and `quit` feed it; `open::apple_events` under `apple-events` on macOS): one queue for files the OS asks the app to open and files dropped on the window (`DroppedFile`, `DropTarget`: canvas, tab strip or window); `natural_cmp` and `same_file` for opening order and duplicates; `reveal` and `open_external`; the shared open-error texts. No egui. |
|
||||
| always | `autosave::Autosave` (the timer: which documents are due, results by revision), `recovery_dir`, `adopt_legacy_recovery` and `RecoveryStore`: the recovery folder of copies with a JSON sidecar each (`RecoveryEntry`, the fields craft-ui's `RecoveryDialog` lists), `AUTOSAVE_FAILED`. The app serializes its documents. |
|
||||
| `clipboard` | `clipboard::Clipboard` over a `ClipboardBackend`: every copy and paste goes through it, with size limits (`ClipboardLimits`, `TooLarge`), a fence that keeps synthetic (automation) input from replacing what the user copied, and `holds_ours` to tell the app's own copy from another app's. `SystemClipboard` (arboard) reads and writes text, HTML, one bitmap and copied files; `EventClipboard` is the browser's, fed from paste events (`flavors_from_event`, `copy_through_egui` with `ui`). `EventClipboard` keeps an offered paste for the pass it was offered in and counts passes itself (`EventClipboard::for_egui` uses egui's pass number), so a menu Paste in a later pass finds nothing and the app has nothing to call at the end of a pass. A write reports which flavor the backend wrote, and `holds_ours` compares that one. The web writes only the best flavor (eframe makes each copy command its own `navigator.clipboard` write, so a second replaces the first). `has` never reads or decodes: it asks Windows and macOS for the formats on offer, Wayland for the offer's MIME types (`wl-clipboard-rs`) and X11 for the `TARGETS` list (`x11rb`); a bitmap counts only as `image/png`, the one arboard reads on Linux. `ClipboardProbe` asks a second handle on a worker thread whether Paste has anything, so a slow owner never stalls a frame. Bitmaps are read as straight RGBA8, not PNG: the `BITMAP` and `RGBA8` reads return an `image/x-rgba8` flavor (width and height as little-endian `u32`s, then the pixels) and `read_image` returns `ClipboardImage`; the crate has no PNG encoder, and `SystemClipboard::decoder` takes the app's PNG decoder for writes. SVG, PDF and RTF flavors are neither written nor read by `SystemClipboard` (a write of only those fails with `Other`); a bitmap offered only as `image/jpeg` or `image/bmp` on Wayland reads as `None`. |
|
||||
| `clipboard`, `clipboard-system` | `clipboard` has no system crates: `Clipboard`, `EventClipboard` (with `LateOffers`), `MemoryClipboard` and the probe. `clipboard-system` adds `SystemClipboard`. `clipboard::Clipboard` over a `ClipboardBackend`: every copy and paste goes through it, with size limits (`ClipboardLimits`, `TooLarge`), a fence that keeps synthetic (automation) input from replacing what the user copied, and `holds_ours` to tell the app's own copy from another app's. `SystemClipboard` (arboard) reads text, HTML, RTF, one bitmap and copied files, and writes one offer; `EventClipboard` is the browser's, fed from paste events (`flavors_from_event`). `EventClipboard` keeps an offered paste for the pass it was offered in and counts passes itself (the pass clock the host gives it), so a menu Paste in a later pass finds nothing and the app has nothing to call at the end of a pass. A write reports which flavor the backend wrote; `holds_ours` asks the backend's owner marker first (`ClipboardBackend::owns`) and compares that flavor's content only when the backend cannot tell. The web writes only the best flavor (eframe makes each copy command its own `navigator.clipboard` write, so a second replaces the first). `has` and `formats` never read or decode: they list the formats on offer (`offer::formats`: Windows' and macOS' formats, Wayland's MIME types, X11's `TARGETS`); a bitmap counts only as `image/png`, the one arboard reads on Linux. `ClipboardProbe` asks a second handle on a worker thread whether Paste has anything, so a slow owner never stalls a frame. Bitmaps are read as straight RGBA8, not PNG: the `BITMAP` and `RGBA8` reads return an `image/x-rgba8` flavor (width and height as little-endian `u32`s, then the pixels) and `read_image` returns `ClipboardImage`; the crate has no PNG encoder, and `SystemClipboard::decoder` takes the app's PNG decoder for writes. SVG and PDF flavors are neither written nor read by `SystemClipboard`; RTF is read, and RTF and MathML are written beside arboard's flavors (a write of only unsupported flavors fails with `Other`); a bitmap offered only as `image/jpeg` or `image/bmp` on Wayland reads as `None`. |
|
||||
| always | `watch::FileWatch` and `Changed`: open files that changed on disk. One worker thread (`craft-file-watch`) compares each file's metadata (`FileStamp`) every 250 ms and sleeps while nothing is watched; a changed file is reported once it has settled and, with `ReadPolicy::Whole`, looks complete. The app's own saves are recognised by `known_now`; `disk_differs` answers at Save time; `take_changes` runs on the frame the worker's `Wake` asks for. |
|
||||
| always (native) | `default_app::make_default`: the Preferences button that makes the app the system default for its file types. Windows opens Settings › Default apps (`SettingsOpened`), Linux and BSD run `xdg-mime default` (`MadeDefault`, refused inside Flatpak or without an installed desktop entry), macOS answers `Unsupported`. `path_from_arg` and `rejoin_split_paths` read the paths a launcher hands the app. Only a button may call it. |
|
||||
| always (native) | `temp::TempDir` and `TempFiles`: private temporary folders created exclusively with owner-only permissions (`0700`, files `0600`, `create_new`), named with the process id and a counter, removed on drop. |
|
||||
| always | `PlatformText`: a user-visible message of a platform service (id, English text with `{name}` placeholders) that the app looks up in its own catalog. The open, clipboard, watch, default-app and temp services and craft-dialogs' save flow use it. No words table lists them yet, so the missing-translation list does not show them. |
|
||||
| `screen` | Screen capture for the screen colour picker (`craft_platform::screen`). |
|
||||
| `apple-events` | Apple Events requests on macOS (`open::apple_events`), through `fmv-macos-events`. |
|
||||
|
||||
|
||||
## Native dialogs
|
||||
@@ -53,7 +54,7 @@ discard work: the app runs its normal close policy again afterward.
|
||||
the first read. ReadOne/legacy Read, the standard namespace and GNOME fallback are handled together;
|
||||
on GNOME the "default" (Light) setting and portal value 0 read as light; elsewhere 0 is no preference.
|
||||
Malformed values retain the last valid answer, and explicit no-preference clears it.
|
||||
`SystemReader::read()` gives colour scheme, contrast and reduced motion in one call on every target: the watcher on Linux/BSD, the browser's contrast and motion queries on the web, and the colour scheme the host reports from its windowing integration (`report_theme`; the watcher's answer wins where it has one). macOS and Windows have no contrast or motion source yet. `SystemReader::generation()` rises on each change a source reports (the watcher's theme, contrast or motion, a reported theme), the change notice the craft-ui runtime and apps re-resolve themes on.
|
||||
`SystemReader::read()` gives colour scheme, contrast and reduced motion in one call on every target: the watcher on Linux/BSD, the browser's contrast and motion queries on the web, and the colour scheme the host reports from its windowing integration (`report_theme`; the watcher's answer wins where it has one). macOS and Windows have a reduced-motion source and no contrast source. `SystemReader::generation()` rises on each change a source reports (the watcher's theme, contrast or motion, a reported theme), the change notice the craft-ui runtime and apps re-resolve themes on.
|
||||
|
||||
`Watcher::wait_first(timeout)` blocks until the first answer, a known absence, or the timeout (about 250 ms in an eframe creator), so the first frame uses the desktop theme. Disconnection
|
||||
retains the last valid value until a fresh answer. A later service owner triggers a reread; session
|
||||
@@ -78,12 +79,15 @@ so it needs no D-Bus dependency.
|
||||
### Contrast and reduced motion
|
||||
|
||||
`Watcher::contrast()` (`Contrast::Standard` or `High`) and `Watcher::reduced_motion()` follow the
|
||||
portal's `org.freedesktop.appearance` `contrast` and `reduced-motion` keys. Without a
|
||||
`reduced-motion` key, GNOME's `org.gnome.desktop.interface` `enable-animations` stands in. Both
|
||||
are read beside the theme, so `wait_first` returns with them, and a change runs the same wake
|
||||
callback. `None` means no answer yet or no such key; the `gsettings` fallback doesn't read them.
|
||||
macOS and Windows have no watcher (their settings need platform bindings, and the crate forbids
|
||||
`unsafe`). On the web, `browser_contrast()` and `browser_reduced_motion()` evaluate the
|
||||
portal's `org.freedesktop.appearance` `contrast` and `reduced-motion` keys. Reduced motion
|
||||
combines the portal key, KDE's animation setting and GNOME's `org.gnome.desktop.interface`
|
||||
`enable-animations`: any source that turns animation off wins. The portal's three keys (colour
|
||||
scheme, contrast, reduced motion) are read beside each other, so `wait_first` returns with them,
|
||||
and a change runs the same wake callback. `None` means no answer yet or no such key; where the
|
||||
portal has none, the desktop's settings files are read (`appearance/files.rs`); the `gsettings`
|
||||
fallback doesn't read them.
|
||||
On macOS and Windows a worker polls the system's reduced-motion setting once a second
|
||||
(`NSWorkspace`, `UISettings`) and runs the wake callback when it changes. On the web, `browser_contrast()` and `browser_reduced_motion()` evaluate the
|
||||
`prefers-contrast: more` and `prefers-reduced-motion: reduce` media queries on each call, with
|
||||
no change notification.
|
||||
|
||||
|
||||
@@ -6,8 +6,10 @@
|
||||
//! last so the app can tell its own copy from one made in another app
|
||||
//! ([`Clipboard::holds_ours`]).
|
||||
//! - [`ClipboardBackend`]: where the bytes go. [`SystemClipboard`] is the OS clipboard on the
|
||||
//! desktop (arboard, opened on first use); [`EventClipboard`] is the browser's, fed from paste
|
||||
//! events; tests plug in their own.
|
||||
//! desktop (feature `clipboard-system`, opened on first use); [`EventClipboard`] is the
|
||||
//! browser's, fed from paste events, with a queue for pastes that arrive between passes
|
||||
//! ([`LateOffers`]); [`MemoryClipboard`] holds flavours in memory for tests and hosts without
|
||||
//! a clipboard.
|
||||
//! - [`ClipboardProbe`]: asks a second clipboard handle on a worker thread whether Paste has
|
||||
//! something to take, so a slow clipboard owner never stalls a frame.
|
||||
//!
|
||||
@@ -18,7 +20,7 @@ mod convert;
|
||||
mod event;
|
||||
mod facade;
|
||||
mod memory;
|
||||
#[cfg(all(feature = "clipboard", not(target_arch = "wasm32")))]
|
||||
#[cfg(all(feature = "clipboard-system", not(target_arch = "wasm32")))]
|
||||
mod offer;
|
||||
mod probe;
|
||||
mod types;
|
||||
@@ -30,8 +32,6 @@ pub use memory::MemoryClipboard;
|
||||
pub use probe::*;
|
||||
pub use types::*;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) use convert::rgba8_image;
|
||||
|
||||
// The probe's backend lives on its worker.
|
||||
const _: () = {
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
//! Clipboard backends: the OS clipboard and the plan for what a write puts where.
|
||||
//! Clipboard backends: the trait every clipboard implements and the OS clipboard.
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use std::borrow::Cow;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::convert::{rgba8_flavor, rgba8_image, trim_cr, uri_list};
|
||||
#[cfg(all(feature = "clipboard", not(target_arch = "wasm32")))]
|
||||
#[cfg(all(feature = "clipboard-system", not(target_arch = "wasm32")))]
|
||||
use super::convert::{trim_cr, uri_list};
|
||||
#[cfg(all(feature = "clipboard-system", not(target_arch = "wasm32")))]
|
||||
use super::offer;
|
||||
use super::types::{BITMAP, ClipboardError, ClipboardImage, Flavor, HTML, PNG, RGBA8, TEXT, URI_LIST};
|
||||
#[cfg(all(feature = "clipboard-system", not(target_arch = "wasm32")))]
|
||||
use super::types::{BITMAP, HTML, RGBA8, RTF, TEXT, URI_LIST};
|
||||
use super::types::{ClipboardError, ClipboardImage, Flavor};
|
||||
|
||||
/// What a write did.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -26,12 +27,13 @@ pub enum Written {
|
||||
/// slow clipboard owner (an X11 client that never answers); the UI thread calls only
|
||||
/// [`Clipboard`]'s reads and writes, on a user's copy or paste.
|
||||
pub trait ClipboardBackend: Send {
|
||||
/// Replaces the clipboard's contents with `flavors`, best first; none empties it. A backend
|
||||
/// holds fewer flavours than an app offers, so it answers the index in `flavors` of the one
|
||||
/// it wrote (`0` when it emptied the clipboard); [`Clipboard::holds_ours`] compares that one.
|
||||
/// Replaces the clipboard's contents with `flavors`, best first, as one offer; none empties
|
||||
/// it. A backend may hold fewer flavours than an app offers, so it answers the index in
|
||||
/// `flavors` of the one it wrote (`0` when it emptied the clipboard);
|
||||
/// [`Clipboard::holds_ours`] compares that one.
|
||||
fn write(&mut self, flavors: &[Flavor]) -> Result<usize, ClipboardError>;
|
||||
/// The first of `mimes` the clipboard holds, at most `limit` bytes of it (more is
|
||||
/// [`ClipboardError::TooLarge`]). [`BITMAP`] matches any bitmap, returned as an [`RGBA8`] flavor.
|
||||
/// [`ClipboardError::TooLarge`]). `BITMAP` matches any bitmap, returned as an `RGBA8` flavor.
|
||||
fn read(&mut self, mimes: &[&str], limit: u64) -> Result<Option<Flavor>, ClipboardError>;
|
||||
/// The clipboard's bitmap as RGBA8, at most `limit` bytes of pixels.
|
||||
fn read_image(&mut self, limit: u64) -> Result<Option<ClipboardImage>, ClipboardError>;
|
||||
@@ -56,7 +58,8 @@ pub trait ClipboardBackend: Send {
|
||||
}
|
||||
}
|
||||
|
||||
/// The desktop's clipboard through arboard: X11 and Wayland, macOS, Windows. Not on wasm.
|
||||
/// The desktop's clipboard through arboard and the platform's own offer code: X11 and Wayland,
|
||||
/// macOS, Windows. Not on wasm.
|
||||
///
|
||||
/// The handle opens on first use and stays open (on X11 the last handle alive hands what the app
|
||||
/// copied to the clipboard manager at exit). When no backend opens, every call answers
|
||||
@@ -64,32 +67,47 @@ pub trait ClipboardBackend: Send {
|
||||
/// bitmap arboard can't read (it asks for `image/png` only; a screenshot tool may offer only
|
||||
/// `image/jpeg` or `image/bmp`, storytold/photocraft#2546) reads as `None`.
|
||||
///
|
||||
/// arboard reaches text, HTML, one bitmap and copied files; other flavors ([`SVG`], [`PDF`],
|
||||
/// [`RTF`]) are not written or read here.
|
||||
#[cfg(all(feature = "clipboard", not(target_arch = "wasm32")))]
|
||||
/// A write puts every flavour it can hold on the clipboard as one offer, tagged with a token that
|
||||
/// is unique to this `SystemClipboard`, so [`owns`](ClipboardBackend::owns) can tell its copy from
|
||||
/// another app's.
|
||||
#[cfg(all(feature = "clipboard-system", not(target_arch = "wasm32")))]
|
||||
pub struct SystemClipboard {
|
||||
handle: Option<arboard::Clipboard>,
|
||||
unreadable: bool,
|
||||
decode: Option<Decode>,
|
||||
presence: presence::Presence,
|
||||
#[allow(dead_code)] // P3(platform-w1): pf.C-P6
|
||||
offer: offer::Offer,
|
||||
#[allow(dead_code)] // P3(platform-w1): pf.C-P6
|
||||
owner: [u8; 16],
|
||||
}
|
||||
|
||||
/// The app's decoder for encoded bitmaps ([`SystemClipboard::decoder`]).
|
||||
#[cfg(all(feature = "clipboard", not(target_arch = "wasm32")))]
|
||||
#[cfg(all(feature = "clipboard-system", not(target_arch = "wasm32")))]
|
||||
pub(crate) type Decode = Box<dyn Fn(&[u8]) -> Option<ClipboardImage> + Send>;
|
||||
|
||||
#[cfg(all(feature = "clipboard", not(target_arch = "wasm32")))]
|
||||
/// A token no other process or `SystemClipboard` shares: random hasher keys, the process id and
|
||||
/// the time.
|
||||
#[cfg(all(feature = "clipboard-system", not(target_arch = "wasm32")))]
|
||||
fn owner_token() -> [u8; 16] {
|
||||
use std::hash::{BuildHasher, Hash, Hasher};
|
||||
let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|time| time.as_nanos()).unwrap_or_default();
|
||||
let mut token = [0u8; 16];
|
||||
for (half, chunk) in token.chunks_mut(8).enumerate() {
|
||||
let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
|
||||
half.hash(&mut hasher);
|
||||
std::process::id().hash(&mut hasher);
|
||||
nanos.hash(&mut hasher);
|
||||
chunk.copy_from_slice(&hasher.finish().to_le_bytes());
|
||||
}
|
||||
token
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "clipboard-system", not(target_arch = "wasm32")))]
|
||||
impl SystemClipboard {
|
||||
/// A clipboard that connects to the system clipboard on first use.
|
||||
pub fn new() -> Self {
|
||||
Self { handle: None, unreadable: false, decode: None, presence: presence::Presence::new(), offer: offer::Offer::new(), owner: [0; 16] }
|
||||
Self { handle: None, unreadable: false, decode: None, offer: offer::Offer::new(), owner: owner_token() }
|
||||
}
|
||||
|
||||
/// Decodes a [`PNG`] flavor to pixels for [`ClipboardBackend::write`], which hands the
|
||||
/// Decodes a `image/png` flavor to pixels for [`ClipboardBackend::write`], which hands the
|
||||
/// platform pixels only. Without one, a write offers no PNG.
|
||||
pub fn decoder(mut self, decode: impl Fn(&[u8]) -> Option<ClipboardImage> + Send + 'static) -> Self {
|
||||
self.decode = Some(Box::new(decode));
|
||||
@@ -118,7 +136,7 @@ impl SystemClipboard {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "clipboard", not(target_arch = "wasm32")))]
|
||||
#[cfg(all(feature = "clipboard-system", not(target_arch = "wasm32")))]
|
||||
pub(super) fn system_error(error: arboard::Error) -> ClipboardError {
|
||||
match error {
|
||||
arboard::Error::ClipboardOccupied => ClipboardError::Busy,
|
||||
@@ -129,7 +147,7 @@ pub(super) fn system_error(error: arboard::Error) -> ClipboardError {
|
||||
|
||||
/// A read's value, or `None` when the clipboard holds nothing in that format. `unconvertible`
|
||||
/// also counts content the format can't be converted from (text that isn't UTF-8) as nothing.
|
||||
#[cfg(all(feature = "clipboard", not(target_arch = "wasm32")))]
|
||||
#[cfg(all(feature = "clipboard-system", not(target_arch = "wasm32")))]
|
||||
pub(super) fn present<T>(read: Result<T, arboard::Error>, unconvertible: bool) -> Result<Option<T>, ClipboardError> {
|
||||
match read {
|
||||
Ok(value) => Ok(Some(value)),
|
||||
@@ -139,259 +157,21 @@ pub(super) fn present<T>(read: Result<T, arboard::Error>, unconvertible: bool) -
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the system clipboard offers a format, asked of the system without reading or decoding
|
||||
/// any content: Windows `IsClipboardFormatAvailable`, macOS the pasteboard's type list, Wayland
|
||||
/// the offer's MIME types (`wl_clipboard_rs::paste::get_mime_types`), X11 a `TARGETS` request.
|
||||
///
|
||||
/// The macOS and Windows code is not built on the Linux box; it is a few lines each and needs a
|
||||
/// check on those systems.
|
||||
#[cfg(all(feature = "clipboard", not(target_arch = "wasm32")))]
|
||||
mod presence {
|
||||
#[cfg(any(windows, target_os = "macos"))]
|
||||
use super::{BITMAP, HTML, RGBA8, TEXT, URI_LIST};
|
||||
|
||||
pub(super) struct Presence {
|
||||
#[cfg(any(windows, target_os = "macos"))]
|
||||
_system: (),
|
||||
#[cfg(not(any(windows, target_os = "macos")))]
|
||||
x11: Option<x11::Targets>,
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
impl Presence {
|
||||
pub(super) fn new() -> Self {
|
||||
Self { _system: () }
|
||||
}
|
||||
|
||||
pub(super) fn any(&mut self, mimes: &[&str]) -> bool {
|
||||
use clipboard_win::{formats, is_format_avail, register_format};
|
||||
let registered = |name: &str| register_format(name).is_some_and(|format| is_format_avail(format.get()));
|
||||
mimes.iter().any(|&mime| match mime {
|
||||
TEXT => is_format_avail(formats::CF_UNICODETEXT),
|
||||
HTML => registered("HTML Format"),
|
||||
BITMAP | RGBA8 => registered("PNG") || is_format_avail(formats::CF_DIBV5) || is_format_avail(formats::CF_DIB),
|
||||
URI_LIST => is_format_avail(formats::CF_HDROP),
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
impl Presence {
|
||||
pub(super) fn new() -> Self {
|
||||
Self { _system: () }
|
||||
}
|
||||
|
||||
pub(super) fn any(&mut self, mimes: &[&str]) -> bool {
|
||||
use objc2_app_kit::{NSPasteboard, NSPasteboardTypeFileURL, NSPasteboardTypeHTML, NSPasteboardTypeString, NSPasteboardTypeTIFF};
|
||||
// `types` lists the formats on offer; no item's data is fetched.
|
||||
let Some(types) = (unsafe { NSPasteboard::generalPasteboard().types() }) else { return false };
|
||||
mimes.iter().any(|&mime| {
|
||||
// Safety: the pasteboard type constants are valid for the life of the process.
|
||||
let wanted = unsafe {
|
||||
match mime {
|
||||
TEXT => NSPasteboardTypeString,
|
||||
HTML => NSPasteboardTypeHTML,
|
||||
BITMAP | RGBA8 => NSPasteboardTypeTIFF,
|
||||
URI_LIST => NSPasteboardTypeFileURL,
|
||||
_ => return false,
|
||||
}
|
||||
};
|
||||
types.iter().any(|offered| offered.isEqualToString(wanted))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Linux and BSD. Wayland when `WAYLAND_DISPLAY` is set and the compositor has a data-control
|
||||
/// protocol, else X11: the order arboard picks its own backend in.
|
||||
#[cfg(not(any(windows, target_os = "macos")))]
|
||||
impl Presence {
|
||||
pub(super) fn new() -> Self {
|
||||
Self { x11: None }
|
||||
}
|
||||
|
||||
pub(super) fn any(&mut self, mimes: &[&str]) -> bool {
|
||||
let offered = self.offered();
|
||||
mimes.iter().any(|&mime| super::offered_has(&offered, mime))
|
||||
}
|
||||
|
||||
fn offered(&mut self) -> Vec<String> {
|
||||
use wl_clipboard_rs::paste::{ClipboardType, Error, Seat, get_mime_types};
|
||||
if std::env::var_os("WAYLAND_DISPLAY").is_some() {
|
||||
match get_mime_types(ClipboardType::Regular, Seat::Unspecified) {
|
||||
Ok(types) => return types.into_iter().collect(),
|
||||
// Nothing is copied.
|
||||
Err(Error::NoSeats | Error::ClipboardEmpty | Error::NoMimeType) => return Vec::new(),
|
||||
Err(error) => log::debug!("no Wayland data control for the clipboard probe, trying X11: {error}"),
|
||||
}
|
||||
}
|
||||
if self.x11.is_none() {
|
||||
self.x11 = x11::Targets::connect();
|
||||
}
|
||||
self.x11.as_ref().map(x11::Targets::offered).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(any(windows, target_os = "macos")))]
|
||||
mod x11 {
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use x11rb::connection::Connection;
|
||||
use x11rb::protocol::Event;
|
||||
use x11rb::protocol::xproto::{Atom, AtomEnum, ConnectionExt, CreateWindowAux, EventMask, WindowClass};
|
||||
use x11rb::rust_connection::RustConnection;
|
||||
use x11rb::{COPY_DEPTH_FROM_PARENT, CURRENT_TIME, NONE};
|
||||
|
||||
/// How long a `TARGETS` request waits for the owner. The probe's worker waits, not the UI.
|
||||
const ANSWER_WAIT: Duration = Duration::from_millis(250);
|
||||
|
||||
/// A connection and a window that receive the clipboard owner's `TARGETS` answer.
|
||||
pub(super) struct Targets {
|
||||
conn: RustConnection,
|
||||
window: u32,
|
||||
clipboard: Atom,
|
||||
targets: Atom,
|
||||
property: Atom,
|
||||
}
|
||||
|
||||
impl Targets {
|
||||
pub(super) fn connect() -> Option<Self> {
|
||||
let (conn, screen) = RustConnection::connect(None).ok()?;
|
||||
let root = conn.setup().roots.get(screen)?.root;
|
||||
let window = conn.generate_id().ok()?;
|
||||
conn.create_window(
|
||||
COPY_DEPTH_FROM_PARENT,
|
||||
window,
|
||||
root,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
1,
|
||||
0,
|
||||
WindowClass::INPUT_OUTPUT,
|
||||
0,
|
||||
&CreateWindowAux::new().event_mask(EventMask::PROPERTY_CHANGE),
|
||||
)
|
||||
.ok()?;
|
||||
let atom = |name: &[u8]| conn.intern_atom(false, name).ok()?.reply().ok().map(|reply| reply.atom);
|
||||
let (clipboard, targets, property) = (atom(b"CLIPBOARD")?, atom(b"TARGETS")?, atom(b"CRAFT_CLIPBOARD_TARGETS")?);
|
||||
Some(Self { conn, window, clipboard, targets, property })
|
||||
}
|
||||
|
||||
/// The target names the CLIPBOARD owner offers; none when nobody owns it or answers.
|
||||
pub(super) fn offered(&self) -> Vec<String> {
|
||||
self.ask().unwrap_or_default()
|
||||
}
|
||||
|
||||
fn ask(&self) -> Option<Vec<String>> {
|
||||
self.conn.delete_property(self.window, self.property).ok()?;
|
||||
self.conn.convert_selection(self.window, self.clipboard, self.targets, self.property, CURRENT_TIME).ok()?;
|
||||
self.conn.flush().ok()?;
|
||||
let end = Instant::now() + ANSWER_WAIT;
|
||||
while Instant::now() < end {
|
||||
match self.conn.poll_for_event().ok()? {
|
||||
Some(Event::SelectionNotify(event)) if event.selection == self.clipboard => {
|
||||
if event.property == NONE {
|
||||
return None;
|
||||
}
|
||||
let reply =
|
||||
self.conn.get_property(true, self.window, self.property, AtomEnum::ATOM, 0, u32::MAX / 4).ok()?.reply().ok()?;
|
||||
let atoms: Vec<Atom> = reply.value32()?.collect();
|
||||
return Some(
|
||||
atoms
|
||||
.into_iter()
|
||||
.filter_map(|atom| {
|
||||
let name = self.conn.get_atom_name(atom).ok()?.reply().ok()?.name;
|
||||
String::from_utf8(name).ok()
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
Some(_) => {}
|
||||
None => std::thread::sleep(Duration::from_millis(1)),
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the target or MIME names a clipboard `offered` contain a format that [`SystemClipboard`]
|
||||
/// can read as `mime`. Text includes the X11 text targets; a bitmap is `image/png`, the only
|
||||
/// bitmap arboard reads on Linux.
|
||||
#[allow(dead_code, reason = "only the Linux and BSD probe maps names")]
|
||||
pub(crate) fn offered_has(offered: &[String], mime: &str) -> bool {
|
||||
let any = |names: &[&str]| offered.iter().any(|offer| names.iter().any(|name| offer.eq_ignore_ascii_case(name)));
|
||||
match mime {
|
||||
TEXT => any(&["text/plain", "text/plain;charset=utf-8", "UTF8_STRING", "STRING", "TEXT"]),
|
||||
HTML => any(&["text/html"]),
|
||||
BITMAP | RGBA8 => any(&[PNG]),
|
||||
URI_LIST => any(&[URI_LIST]),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// What a write puts on the system clipboard.
|
||||
#[cfg(all(feature = "clipboard", not(target_arch = "wasm32")))]
|
||||
pub(crate) enum Put {
|
||||
Clear,
|
||||
Image(ClipboardImage),
|
||||
Html { html: String, alt: Option<String> },
|
||||
Text(String),
|
||||
}
|
||||
|
||||
/// The first flavor the system clipboard can hold, as its index in `flavors` and what to put
|
||||
/// there.
|
||||
#[cfg(all(feature = "clipboard", not(target_arch = "wasm32")))]
|
||||
pub(crate) fn plan_write(flavors: &[Flavor], decode: Option<&Decode>) -> Result<(usize, Put), ClipboardError> {
|
||||
if flavors.is_empty() {
|
||||
return Ok((0, Put::Clear));
|
||||
}
|
||||
let text_of = |f: &Flavor| String::from_utf8_lossy(&f.data).into_owned();
|
||||
for (index, flavor) in flavors.iter().enumerate() {
|
||||
match &*flavor.mime {
|
||||
RGBA8 => {
|
||||
if let Some(image) = rgba8_image(&flavor.data).filter(ClipboardImage::is_whole) {
|
||||
return Ok((index, Put::Image(image)));
|
||||
}
|
||||
}
|
||||
PNG => {
|
||||
if let Some(image) = decode.and_then(|decode| decode(&flavor.data)).filter(ClipboardImage::is_whole) {
|
||||
return Ok((index, Put::Image(image)));
|
||||
}
|
||||
}
|
||||
HTML => return Ok((index, Put::Html { html: text_of(flavor), alt: flavors.iter().find(|f| f.mime == TEXT).map(text_of) })),
|
||||
TEXT => return Ok((index, Put::Text(text_of(flavor)))),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Err(ClipboardError::NoFormat)
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "clipboard", not(target_arch = "wasm32")))]
|
||||
#[cfg(all(feature = "clipboard-system", not(target_arch = "wasm32")))]
|
||||
impl Default for SystemClipboard {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "clipboard", not(target_arch = "wasm32")))]
|
||||
#[cfg(all(feature = "clipboard-system", not(target_arch = "wasm32")))]
|
||||
impl ClipboardBackend for SystemClipboard {
|
||||
// pc: apps/photocraft/src/services.rs:702 clipboard_set_image (open on first use, "clipboard is busy")
|
||||
fn write(&mut self, flavors: &[Flavor]) -> Result<usize, ClipboardError> {
|
||||
let (index, put) = plan_write(flavors, self.decode.as_ref())?;
|
||||
let handle = self.open()?;
|
||||
match put {
|
||||
Put::Clear => handle.clear(),
|
||||
Put::Image(image) => {
|
||||
handle.set_image(arboard::ImageData { width: image.width as usize, height: image.height as usize, bytes: Cow::Borrowed(&image.rgba) })
|
||||
}
|
||||
Put::Html { html, alt } => handle.set_html(html, alt),
|
||||
Put::Text(text) => handle.set_text(text),
|
||||
}
|
||||
.map_err(system_error)?;
|
||||
Ok(index)
|
||||
self.open()?;
|
||||
let Self { handle, offer, decode, owner, .. } = self;
|
||||
let handle = handle.as_mut().ok_or(ClipboardError::Unavailable)?;
|
||||
offer::write(handle, offer, flavors, decode.as_ref(), owner)
|
||||
}
|
||||
|
||||
// vectorcraft: crates/ui-egui/src/sysclip.rs:27 SystemClipboard::read
|
||||
@@ -400,7 +180,8 @@ impl ClipboardBackend for SystemClipboard {
|
||||
let found = match mime {
|
||||
TEXT => present(self.open()?.get().text(), true)?.map(|text| Flavor::text(&text)),
|
||||
HTML => present(self.open()?.get().html(), true)?.map(|html| Flavor::new(HTML, html.into_bytes())),
|
||||
BITMAP | RGBA8 => self.read_image(limit)?.map(|image| rgba8_flavor(&image)),
|
||||
RTF => offer::read_rtf(&mut self.offer, limit)?.map(|text| Flavor::new(RTF, text.into_bytes())),
|
||||
BITMAP | RGBA8 => self.read_image(limit)?.map(|image| Flavor::rgba8(&image)),
|
||||
URI_LIST => {
|
||||
let files = present(self.open()?.get().file_list(), false)?.filter(|files| !files.is_empty());
|
||||
files.map(|files| Flavor::new(URI_LIST, uri_list(&files, cfg!(windows)).into_bytes()))
|
||||
@@ -439,6 +220,14 @@ impl ClipboardBackend for SystemClipboard {
|
||||
|
||||
// vectorcraft: crates/ui-egui/src/sysclip.rs:29 SystemClipboard::has
|
||||
fn has(&mut self, mimes: &[&str]) -> bool {
|
||||
self.presence.any(mimes)
|
||||
offer::has(&mut self.offer, mimes)
|
||||
}
|
||||
|
||||
fn formats(&mut self) -> Vec<String> {
|
||||
offer::formats(&mut self.offer)
|
||||
}
|
||||
|
||||
fn owns(&mut self) -> Option<bool> {
|
||||
offer::owns(&mut self.offer, &self.owner)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,18 +2,9 @@
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::types::{ClipboardImage, Flavor, RGBA8};
|
||||
use super::types::ClipboardImage;
|
||||
|
||||
/// `image` as an [`RGBA8`] flavor.
|
||||
pub(crate) fn rgba8_flavor(image: &ClipboardImage) -> Flavor {
|
||||
let mut data = Vec::with_capacity(8 + image.rgba.len());
|
||||
data.extend_from_slice(&image.width.to_le_bytes());
|
||||
data.extend_from_slice(&image.height.to_le_bytes());
|
||||
data.extend_from_slice(&image.rgba);
|
||||
Flavor::new(RGBA8, data)
|
||||
}
|
||||
|
||||
/// The bitmap in an [`RGBA8`] flavor's bytes; `None` without the two-word header.
|
||||
/// The bitmap in an [`RGBA8`](super::types::RGBA8) flavor's bytes; `None` without the two-word header.
|
||||
pub(crate) fn rgba8_image(data: &[u8]) -> Option<ClipboardImage> {
|
||||
let (header, rgba) = data.split_first_chunk::<8>()?;
|
||||
let width = u32::from_le_bytes(header[..4].try_into().ok()?);
|
||||
@@ -62,7 +53,7 @@ pub(super) fn percent_decode(text: &str) -> String {
|
||||
|
||||
/// `files` as a `text/uri-list` (CRLF line ends, RFC 2483). With `windows`, paths are drive paths
|
||||
/// and become `file:///C:/Users/…` (the drive kept, separators turned to `/`).
|
||||
#[cfg(all(feature = "clipboard", not(target_arch = "wasm32")))]
|
||||
#[cfg(all(feature = "clipboard-system", not(target_arch = "wasm32")))]
|
||||
pub(crate) fn uri_list(files: &[PathBuf], windows: bool) -> String {
|
||||
let mut list = String::new();
|
||||
for file in files {
|
||||
@@ -81,7 +72,7 @@ pub(crate) fn uri_list(files: &[PathBuf], windows: bool) -> String {
|
||||
list
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "clipboard", not(target_arch = "wasm32")))]
|
||||
#[cfg(all(feature = "clipboard-system", not(target_arch = "wasm32")))]
|
||||
pub(super) fn trim_cr(path: PathBuf) -> PathBuf {
|
||||
match path.to_str() {
|
||||
Some(text) if text.ends_with('\r') => PathBuf::from(text.trim_end_matches('\r')),
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
//! A clipboard fed by browser clipboard events.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
use super::backend::ClipboardBackend;
|
||||
use super::convert::{parse_uri_list, rgba8_image};
|
||||
@@ -19,19 +21,28 @@ pub struct EventClipboard {
|
||||
offered_in: u64,
|
||||
pass: PassClock,
|
||||
out: CopyOut,
|
||||
late: LateOffers,
|
||||
}
|
||||
|
||||
/// What a late paste needs: the queue and the wake that tells the app to look at it.
|
||||
struct LateInner {
|
||||
queue: Mutex<VecDeque<Vec<Flavor>>>,
|
||||
wake: Mutex<Option<Box<dyn Fn() + Send + Sync>>>,
|
||||
}
|
||||
|
||||
/// The queue of an [`EventClipboard`] for a paste the browser delivers outside a pass; `Send + Sync`.
|
||||
#[derive(Clone)]
|
||||
pub struct LateOffers {
|
||||
_queued: (),
|
||||
inner: Arc<LateInner>,
|
||||
}
|
||||
|
||||
impl LateOffers {
|
||||
/// Queues a paste's flavours and wakes the app.
|
||||
pub fn offer(&self, flavors: Vec<Flavor>) {
|
||||
let _ = flavors;
|
||||
todo!("pf.C-P9")
|
||||
self.inner.queue.lock().unwrap_or_else(PoisonError::into_inner).push_back(flavors);
|
||||
if let Some(wake) = self.inner.wake.lock().unwrap_or_else(PoisonError::into_inner).as_ref() {
|
||||
wake();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,18 +57,19 @@ impl EventClipboard {
|
||||
/// puts the flavours where the host's copy goes and answers the index of the one it wrote
|
||||
/// ([`ClipboardBackend::write`]).
|
||||
pub fn new(pass: impl Fn() -> u64 + Send + 'static, out: impl FnMut(&[Flavor]) -> Result<usize, ClipboardError> + Send + 'static) -> Self {
|
||||
Self { pasted: Vec::new(), offered_in: 0, pass: Box::new(pass), out: Box::new(out) }
|
||||
let late = LateOffers { inner: Arc::new(LateInner { queue: Mutex::new(VecDeque::new()), wake: Mutex::new(None) }) };
|
||||
Self { pasted: Vec::new(), offered_in: 0, pass: Box::new(pass), out: Box::new(out), late }
|
||||
}
|
||||
|
||||
/// The handle a thread outside the pass queues a late paste through.
|
||||
pub fn late_offers(&self) -> LateOffers {
|
||||
todo!("pf.C-P9")
|
||||
self.late.clone()
|
||||
}
|
||||
|
||||
/// Runs `wake` when a late paste is queued, so the app takes it on its next pass.
|
||||
pub fn with_wake(self, wake: impl Fn() + Send + Sync + 'static) -> Self {
|
||||
let _ = (&self, wake);
|
||||
todo!("pf.C-P9")
|
||||
*self.late.inner.wake.lock().unwrap_or_else(PoisonError::into_inner) = Some(Box::new(wake));
|
||||
self
|
||||
}
|
||||
|
||||
/// The first of `mimes` this pass's paste offered; [`BITMAP`] is any offered `image/*`.
|
||||
@@ -107,6 +119,25 @@ impl ClipboardBackend for EventClipboard {
|
||||
self.offered(mimes).is_some()
|
||||
}
|
||||
|
||||
/// Takes the oldest queued late paste as this pass's offer, one per call.
|
||||
fn take_arrived(&mut self) -> bool {
|
||||
let next = self.late.inner.queue.lock().unwrap_or_else(PoisonError::into_inner).pop_front();
|
||||
match next {
|
||||
Some(flavors) => {
|
||||
self.offer(flavors);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn formats(&mut self) -> Vec<String> {
|
||||
if (self.pass)() != self.offered_in {
|
||||
return Vec::new();
|
||||
}
|
||||
self.pasted.iter().map(|flavor| flavor.mime.to_string()).collect()
|
||||
}
|
||||
|
||||
/// Holds one paste's flavours, best first, until the pass it was offered in ends.
|
||||
fn offer(&mut self, flavors: Vec<Flavor>) {
|
||||
self.pasted = flavors;
|
||||
|
||||
@@ -4,7 +4,6 @@ use std::hash::{Hash, Hasher};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::backend::{ClipboardBackend, Written};
|
||||
use super::convert::rgba8_flavor;
|
||||
use super::types::{ClipboardError, ClipboardImage, ClipboardLimits, Flavor, SVG, TEXT};
|
||||
|
||||
/// The app's clipboard: one per window, on the UI thread.
|
||||
@@ -65,7 +64,7 @@ impl Clipboard {
|
||||
if !image.is_whole() {
|
||||
return Err(ClipboardError::BadImage);
|
||||
}
|
||||
let written = self.write(&[rgba8_flavor(image)])?;
|
||||
let written = self.write(&[Flavor::rgba8(image)])?;
|
||||
if written == Written::Written {
|
||||
self.ours = Some(Ours::Image(image_signature(image.width, image.height, &image.rgba)));
|
||||
}
|
||||
@@ -129,12 +128,12 @@ impl Clipboard {
|
||||
|
||||
/// The MIME names of the formats on offer.
|
||||
pub fn formats(&mut self) -> Vec<String> {
|
||||
todo!("pf.C-P8")
|
||||
self.backend.formats()
|
||||
}
|
||||
|
||||
/// Whether a late paste arrived since the last call.
|
||||
pub fn take_arrived_paste(&mut self) -> bool {
|
||||
todo!("pf.C-P8")
|
||||
self.backend.take_arrived()
|
||||
}
|
||||
|
||||
/// Does the clipboard still hold what this app wrote last (nothing copied since, here or in
|
||||
@@ -143,6 +142,13 @@ impl Clipboard {
|
||||
/// already read, [`is_ours`](Self::is_ours) answers without another read.
|
||||
// vectorcraft: crates/ui-egui/src/sysclip.rs:25 SystemClipboard::holds_ours
|
||||
pub fn holds_ours(&mut self) -> bool {
|
||||
if self.ours.is_none() {
|
||||
return false;
|
||||
}
|
||||
// The platform's owner marker answers without a read; content is compared only when it cannot tell.
|
||||
if let Some(owned) = self.backend.owns() {
|
||||
return owned;
|
||||
}
|
||||
match &self.ours {
|
||||
None => false,
|
||||
Some(Ours::Image(signature)) => {
|
||||
|
||||
@@ -3,37 +3,46 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::backend::ClipboardBackend;
|
||||
use super::types::{ClipboardError, ClipboardImage, Flavor};
|
||||
use super::convert::rgba8_image;
|
||||
use super::types::{BITMAP, ClipboardError, ClipboardImage, Flavor, RGBA8};
|
||||
|
||||
/// The public in-memory clipboard for tests and hosts without one.
|
||||
/// The public in-memory clipboard for tests and hosts without one. It enforces no limits; the
|
||||
/// [`Clipboard`](super::Clipboard) over it does.
|
||||
#[derive(Default)]
|
||||
pub struct MemoryClipboard {
|
||||
held: Vec<Flavor>,
|
||||
}
|
||||
|
||||
impl MemoryClipboard {
|
||||
/// The held flavour that answers `mime`; [`BITMAP`] is any held `image/*`.
|
||||
fn find(&self, mime: &str) -> Option<&Flavor> {
|
||||
self.held.iter().find(|f| if mime == BITMAP { f.mime.starts_with("image/") } else { f.mime == mime })
|
||||
}
|
||||
}
|
||||
|
||||
impl ClipboardBackend for MemoryClipboard {
|
||||
fn write(&mut self, flavors: &[Flavor]) -> Result<usize, ClipboardError> {
|
||||
let _ = (&self.held, flavors);
|
||||
todo!("pf.C-P10")
|
||||
self.held = flavors.to_vec();
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
fn read(&mut self, mimes: &[&str], limit: u64) -> Result<Option<Flavor>, ClipboardError> {
|
||||
let _ = (mimes, limit);
|
||||
todo!("pf.C-P10")
|
||||
fn read(&mut self, mimes: &[&str], _limit: u64) -> Result<Option<Flavor>, ClipboardError> {
|
||||
Ok(mimes.iter().find_map(|mime| self.find(mime)).cloned())
|
||||
}
|
||||
|
||||
fn read_image(&mut self, limit: u64) -> Result<Option<ClipboardImage>, ClipboardError> {
|
||||
let _ = limit;
|
||||
todo!("pf.C-P10")
|
||||
fn read_image(&mut self, _limit: u64) -> Result<Option<ClipboardImage>, ClipboardError> {
|
||||
Ok(self.find(RGBA8).and_then(|flavor| rgba8_image(&flavor.data)))
|
||||
}
|
||||
|
||||
fn read_files(&mut self, limit: usize) -> Result<Option<Vec<PathBuf>>, ClipboardError> {
|
||||
let _ = limit;
|
||||
todo!("pf.C-P10")
|
||||
fn read_files(&mut self, _limit: usize) -> Result<Option<Vec<PathBuf>>, ClipboardError> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn has(&mut self, mimes: &[&str]) -> bool {
|
||||
let _ = mimes;
|
||||
todo!("pf.C-P10")
|
||||
mimes.iter().any(|mime| self.find(mime).is_some())
|
||||
}
|
||||
|
||||
fn formats(&mut self) -> Vec<String> {
|
||||
self.held.iter().map(|flavor| flavor.mime.to_string()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,8 +45,11 @@ impl Flavor {
|
||||
|
||||
/// `image` as an [`RGBA8`] flavor.
|
||||
pub fn rgba8(image: &ClipboardImage) -> Flavor {
|
||||
let _ = image;
|
||||
todo!("pf.C-P3")
|
||||
let mut data = Vec::with_capacity(8 + image.rgba.len());
|
||||
data.extend_from_slice(&image.width.to_le_bytes());
|
||||
data.extend_from_slice(&image.height.to_le_bytes());
|
||||
data.extend_from_slice(&image.rgba);
|
||||
Flavor::new(RGBA8, data)
|
||||
}
|
||||
|
||||
/// `text/plain` with `text`.
|
||||
|
||||
@@ -1,41 +1,7 @@
|
||||
//! `craft_platform::clipboard`.
|
||||
#![allow(clippy::unwrap_used, reason = "tests fail by panicking")]
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use crate::clipboard::{rgba8_image, *};
|
||||
|
||||
/// A backend that holds whatever the last write or `held` assignment left, and reads without
|
||||
/// enforcing any limit (the [`Clipboard`] must).
|
||||
#[derive(Clone, Default)]
|
||||
struct Fake(Arc<Mutex<Vec<Flavor>>>);
|
||||
|
||||
impl Fake {
|
||||
fn copy_elsewhere(&self, flavors: Vec<Flavor>) {
|
||||
*self.0.lock().unwrap() = flavors;
|
||||
}
|
||||
}
|
||||
|
||||
impl ClipboardBackend for Fake {
|
||||
fn write(&mut self, flavors: &[Flavor]) -> Result<usize, ClipboardError> {
|
||||
*self.0.lock().unwrap() = flavors.to_vec();
|
||||
Ok(0)
|
||||
}
|
||||
fn read(&mut self, mimes: &[&str], _limit: u64) -> Result<Option<Flavor>, ClipboardError> {
|
||||
let held = self.0.lock().unwrap();
|
||||
Ok(mimes.iter().find_map(|mime| held.iter().find(|f| f.mime == *mime).cloned()))
|
||||
}
|
||||
fn read_image(&mut self, _limit: u64) -> Result<Option<ClipboardImage>, ClipboardError> {
|
||||
Ok(self.0.lock().unwrap().iter().find(|f| f.mime == RGBA8).and_then(|f| rgba8_image(&f.data)))
|
||||
}
|
||||
fn read_files(&mut self, _limit: usize) -> Result<Option<Vec<PathBuf>>, ClipboardError> {
|
||||
Ok(None)
|
||||
}
|
||||
fn has(&mut self, mimes: &[&str]) -> bool {
|
||||
self.0.lock().unwrap().iter().any(|f| mimes.contains(&&*f.mime))
|
||||
}
|
||||
}
|
||||
use crate::clipboard::*;
|
||||
|
||||
fn image(seed: u8) -> ClipboardImage {
|
||||
ClipboardImage { width: 4, height: 2, rgba: (0..32).map(|i| i as u8 ^ seed).collect() }
|
||||
@@ -45,9 +11,9 @@ fn image(seed: u8) -> ClipboardImage {
|
||||
// copy; reads still work; after set_synthetic(false) writes go through.
|
||||
#[test]
|
||||
fn synthetic_input_never_replaces_what_the_user_copied() {
|
||||
let fake = Fake::default();
|
||||
fake.copy_elsewhere(vec![Flavor::text("the user's")]);
|
||||
let mut clipboard = Clipboard::new(fake.clone());
|
||||
let mut clipboard = Clipboard::new(MemoryClipboard::default());
|
||||
// Copied elsewhere: straight to the backend, past the fence.
|
||||
clipboard.backend_mut().write(&[Flavor::text("the user's")]).unwrap();
|
||||
clipboard.set_synthetic(true);
|
||||
assert_eq!(clipboard.write_text("injected").unwrap(), Written::Fenced);
|
||||
assert_eq!(clipboard.write_image(&image(1)).unwrap(), Written::Fenced);
|
||||
|
||||
@@ -10,6 +10,8 @@ mod autosave_tests;
|
||||
pub mod browser;
|
||||
#[cfg(all(feature = "browser", target_arch = "wasm32"))]
|
||||
pub mod browser_files;
|
||||
#[cfg(all(test, feature = "browser", target_arch = "wasm32"))]
|
||||
mod browser_files_tests;
|
||||
#[cfg(feature = "clipboard")]
|
||||
pub mod clipboard;
|
||||
#[cfg(all(test, feature = "clipboard"))]
|
||||
|
||||
Reference in New Issue
Block a user