use std::borrow::Cow;
use crate::image::{Image, ImageSource};
use crate::platform::ClipboardService;
use crate::Ui;
pub const TEXT: &str = "text/plain";
pub const HTML: &str = "text/html";
pub const IMAGE: &str = "image";
pub const COMPONENTS: &str = "application/x-aylis-components+json";
pub const FILES: &str = "text/uri-list";
pub fn rgba(image: &Image) -> Option<(u32, u32, Cow<'_, [u8]>)> {
match image.source() {
ImageSource::Rgba { width, height, pixels } => Some((*width, *height, Cow::Borrowed(pixels))),
ImageSource::Bgra { width, height, pixels } => {
let mut out = pixels.clone();
out.chunks_exact_mut(4).for_each(|px| px.swap(0, 2));
Some((*width, *height, Cow::Owned(out)))
}
ImageSource::Rgba16 { width, height, pixels } => Some((*width, *height, Cow::Owned(crate::image::rgba16_to_rgba8(pixels)))),
ImageSource::Encoded(_) => None,
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ClipboardContent {
pub text: Option<String>,
pub html: Option<String>,
pub image: Option<Image>,
pub data: Vec<(String, Vec<u8>)>,
}
impl ClipboardContent {
pub fn text(text: impl Into<String>) -> Self {
Self { text: Some(text.into()), ..Default::default() }
}
pub fn image(image: Image) -> Self {
Self { image: Some(image), ..Default::default() }
}
pub fn with_text(mut self, text: impl Into<String>) -> Self {
self.text = Some(text.into());
self
}
pub fn with_html(mut self, html: impl Into<String>) -> Self {
self.html = Some(html.into());
self
}
pub fn with_image(mut self, image: Image) -> Self {
self.image = Some(image);
self
}
pub fn with_data(mut self, format: &str, bytes: impl Into<Vec<u8>>) -> Self {
self.data.retain(|(f, _)| f != format);
self.data.push((format.to_string(), bytes.into()));
self
}
pub fn get_data(&self, format: &str) -> Option<&[u8]> {
self.data.iter().find(|(f, _)| f == format).map(|(_, b)| b.as_slice())
}
pub fn has(&self, format: &str) -> bool {
match format {
TEXT => self.text.is_some(),
HTML => self.html.is_some(),
IMAGE => self.image.is_some(),
_ => self.get_data(format).is_some(),
}
}
pub fn is_empty(&self) -> bool {
self.text.is_none() && self.html.is_none() && self.image.is_none() && self.data.is_empty()
}
}
#[derive(Default)]
pub struct LocalClipboard {
content: ClipboardContent,
mark: Option<Mark>,
}
#[derive(PartialEq)]
enum Mark {
Sequence(u64),
Text(Option<String>),
}
fn mark(service: &mut dyn ClipboardService) -> Mark {
match service.sequence() {
Some(n) => Mark::Sequence(n),
None => Mark::Text(service.get_text()),
}
}
fn local(ui: &mut Ui) -> Option<&ClipboardContent> {
let services = ui.services_mut();
let valid = match services.clipboard.as_deref_mut() {
Some(service) => services.clipboard_local.mark.as_ref() == Some(&mark(service)),
None => true,
};
valid.then_some(&services.clipboard_local.content)
}
pub fn set(ui: &mut Ui, content: ClipboardContent) {
let services = ui.services_mut();
let mark = services.clipboard.as_deref_mut().map(|service| {
service.set_content(&content);
mark(service)
});
services.clipboard_local = LocalClipboard { content, mark };
}
pub fn set_text(ui: &mut Ui, text: &str) {
set(ui, ClipboardContent::text(text));
}
pub fn clear(ui: &mut Ui) {
set(ui, ClipboardContent::default());
}
pub fn text(ui: &mut Ui) -> Option<String> {
let native = ui.services_mut().clipboard.as_deref_mut().and_then(|s| s.get_text());
native.or_else(|| local(ui)?.text.clone()).filter(|t| !t.is_empty())
}
pub fn html(ui: &mut Ui) -> Option<String> {
let native = ui.services_mut().clipboard.as_deref_mut().and_then(|s| s.get_html());
native.or_else(|| local(ui)?.html.clone())
}
pub fn image(ui: &mut Ui) -> Option<Image> {
if let Some(image) = local(ui).and_then(|c| c.image.clone()) {
return Some(image);
}
ui.services_mut().clipboard.as_deref_mut().and_then(|s| s.get_image())
}
pub fn data(ui: &mut Ui, format: &str) -> Option<Vec<u8>> {
if let Some(bytes) = local(ui).and_then(|c| c.get_data(format)) {
return Some(bytes.to_vec());
}
ui.services_mut().clipboard.as_deref_mut().and_then(|s| s.get_data(format))
}
pub fn files(ui: &mut Ui) -> Vec<String> {
data(ui, FILES).map(|bytes| paths_from_uri_list(&String::from_utf8_lossy(&bytes))).unwrap_or_default()
}
pub fn set_files(ui: &mut Ui, paths: &[String]) {
set(ui, ClipboardContent::default().with_data(FILES, uri_list(paths)));
}
pub fn uri_list(paths: &[String]) -> String {
paths.iter().map(|p| file_uri(p)).collect::<Vec<_>>().join("\r\n")
}
pub fn file_uri(path: &str) -> String {
let path = path.replace('\\', "/");
let mut out = String::from("file://");
if !path.starts_with('/') {
out.push('/');
}
for b in path.bytes() {
if b.is_ascii_alphanumeric() || b"-._~/:".contains(&b) {
out.push(b as char);
} else {
out.push_str(&format!("%{b:02X}"));
}
}
out
}
pub fn paths_from_uri_list(text: &str) -> Vec<String> {
text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')).filter_map(path_of_uri).collect()
}
pub fn path_of_uri(uri: &str) -> Option<String> {
let rest = uri.strip_prefix("file://")?;
let rest = if rest.starts_with('/') { rest } else { &rest[rest.find('/')?..] };
let mut bytes = Vec::with_capacity(rest.len());
let raw = rest.as_bytes();
let mut i = 0;
while i < raw.len() {
if raw[i] == b'%' && i + 2 < raw.len() {
if let Ok(b) = u8::from_str_radix(&rest[i + 1..i + 3], 16) {
bytes.push(b);
i += 3;
continue;
}
}
bytes.push(raw[i]);
i += 1;
}
let path = String::from_utf8(bytes).ok()?;
let windows = path.len() > 2 && path.as_bytes()[0] == b'/' && path.as_bytes()[2] == b':' && path.as_bytes()[1].is_ascii_alphabetic();
Some(if windows { path[1..].replace('/', "\\") } else { path })
}
pub fn has(ui: &mut Ui, format: &str) -> bool {
if local(ui).is_some_and(|c| c.has(format)) {
return true;
}
let Some(service) = ui.services_mut().clipboard.as_deref_mut() else { return false };
match format {
TEXT => service.get_text().is_some_and(|t| !t.is_empty()),
_ => service.has(format),
}
}