use std::sync::Arc;
use super::{Tree, find_node_by_path, find_path_by_id};
use crate::{
app::events::{ClipboardContent, CopyEvent, KeyboardEvent, PasteEvent, is_synthetic_input},
core::NodeId,
node::{node::Node, node_kind::NodeKind},
};
pub trait ClipboardReader: Send + Sync {
fn read_text(&self) -> Option<String>;
fn read(&self) -> Option<ClipboardContent>;
fn read_markdown(&self, _text: &str) -> Option<String> {
None
}
}
pub trait ClipboardWriter: Send + Sync {
fn write_text(&self, text: &str) -> bool;
fn write_rich(&self, text: &str, _markdown: &str) -> bool {
self.write_text(text)
}
}
#[cfg(feature = "clipboard")]
#[cfg_attr(not(feature = "markdown"), allow(dead_code))]
struct CopiedRich {
plain: String,
markdown: String,
written: String,
}
#[cfg(feature = "clipboard")]
static COPIED_RICH: parking_lot::Mutex<Option<CopiedRich>> = parking_lot::Mutex::new(None);
#[cfg(feature = "clipboard")]
fn same_lines(a: &str, b: &str) -> bool {
a == b
|| a.replace(
"
", "
",
) == b.replace(
"
", "
",
)
}
#[cfg(all(feature = "clipboard", not(target_arch = "wasm32")))]
fn copied_markdown(text: &str) -> Option<String> {
let copied = COPIED_RICH.lock();
let copied = copied.as_ref()?;
same_lines(&copied.plain, text).then(|| copied.markdown.clone())
}
#[cfg(feature = "clipboard")]
pub(crate) fn copied_rich(clipboard_text: &str) -> Option<(String, String)> {
let copied = COPIED_RICH.lock();
let copied = copied.as_ref()?;
same_lines(&copied.written, clipboard_text).then(|| (copied.plain.clone(), copied.markdown.clone()))
}
#[cfg(feature = "clipboard")]
struct OsClipboard;
#[cfg(all(feature = "clipboard", not(target_arch = "wasm32")))]
impl ClipboardReader for OsClipboard {
fn read_text(&self) -> Option<String> {
let text = crate::clipboard::read_from_clipboard()?;
Some(copied_rich(&text).map_or(text, |(plain, _)| plain))
}
fn read(&self) -> Option<ClipboardContent> {
let content = crate::clipboard::read_clipboard()?;
match content.text_content().and_then(copied_rich) {
Some((plain, _)) => Some(content.with_text(plain)),
None => Some(content),
}
}
fn read_markdown(&self, text: &str) -> Option<String> {
copied_markdown(text)
}
}
#[cfg(all(feature = "clipboard", target_arch = "wasm32"))]
impl ClipboardReader for OsClipboard {
fn read_text(&self) -> Option<String> {
crate::clipboard::web::request_paste();
None
}
fn read(&self) -> Option<ClipboardContent> {
crate::clipboard::web::request_paste();
None
}
}
impl Tree {
pub fn paste(&mut self, content: ClipboardContent) -> bool {
self.rebuild_if_dirty();
let keyboard = paste_keyboard();
let handled = self.paste_content(|_| Some(content), &keyboard);
self.finish_paste(handled);
handled
}
pub fn paste_from_os_clipboard(&mut self, synthetic: bool) -> bool {
if synthetic || is_synthetic_input() {
return false;
}
self.rebuild_if_dirty();
let keyboard = paste_keyboard();
let handled = self.paste_from_reader(&keyboard);
self.finish_paste(handled);
handled
}
pub fn set_clipboard_reader(&mut self, reader: Option<Arc<dyn ClipboardReader>>) {
self.clipboard_reader = reader;
}
fn finish_paste(&mut self, handled: bool) {
if handled {
self.needs_redraw = true;
self.reset_text_input_caret_blink();
}
self.apply_reactive_updates_after_event();
}
pub fn set_clipboard_writer(&mut self, writer: Option<Arc<dyn ClipboardWriter>>) {
self.clipboard_writer = writer;
}
fn clipboard_writer(&self) -> Option<Arc<dyn ClipboardWriter>> {
self.clipboard_writer.clone().or_else(|| {
let app = self.root_ctx.as_ref().and_then(crate::app::ctx::Ctx::app_if_set)?;
app.shared.clipboard_writer.lock().clone()
})
}
fn clipboard_reader(&self) -> Option<Arc<dyn ClipboardReader>> {
self.clipboard_reader.clone().or_else(|| {
let app = self.root_ctx.as_ref().and_then(crate::app::ctx::Ctx::app_if_set)?;
app.shared.clipboard_reader.lock().clone()
})
}
pub(super) fn write_clipboard_text(&self, text: &str) -> bool {
match &self.clipboard_writer() {
Some(writer) => writer.write_text(text),
None => {
#[cfg(feature = "clipboard")]
COPIED_RICH.lock().take();
super::write_os_clipboard_text(text)
}
}
}
#[cfg(feature = "markdown")]
pub(super) fn write_clipboard_rich(&self, text: &str, markdown: &str) -> bool {
match &self.clipboard_writer() {
Some(writer) => writer.write_rich(text, markdown),
None => {
let rich = crate::components::RichText::from_markdown(markdown);
let formatted = !rich.spans.is_empty()
|| !rich.objects.is_empty()
|| rich
.paragraphs
.iter()
.any(|kind| *kind != crate::components::ParagraphKind::Body);
let written = if formatted { markdown } else { text };
let done = super::write_os_clipboard_text(written);
#[cfg(feature = "clipboard")]
{
*COPIED_RICH.lock() = done.then(|| CopiedRich {
plain: text.to_owned(),
markdown: markdown.to_owned(),
written: written.to_owned(),
});
}
done
}
}
}
pub(super) fn write_input_copy(&self, state: &crate::node::node_kind::TextInputState, text: &str) -> bool {
#[cfg(feature = "markdown")]
if let Some(markdown) = state.clipboard_markdown() {
return self.write_clipboard_rich(text, &markdown);
}
#[cfg(not(feature = "markdown"))]
let _ = state;
self.write_clipboard_text(text)
}
pub(super) fn paste_from_reader(&mut self, keyboard: &KeyboardEvent) -> bool {
let Some(reader) = self.clipboard_reader().or_else(os_clipboard) else {
return false;
};
self.paste_content(
|wants_everything| {
let content = if wants_everything {
reader.read()
} else {
reader.read_text().map(ClipboardContent::text)
}?;
let markdown = match (content.markdown_content(), content.text_content()) {
(None, Some(text)) => reader.read_markdown(text),
_ => None,
};
Some(match markdown {
Some(markdown) => content.with_markdown(markdown),
None => content,
})
},
keyboard,
)
}
fn paste_content(&mut self, read: impl FnOnce(bool) -> Option<ClipboardContent>, keyboard: &KeyboardEvent) -> bool {
let Some(root) = &self.root else {
return false;
};
let path = self
.focused_path
.clone()
.or_else(|| self.focused_node.and_then(|id| find_path_by_id(root, id)));
let Some(path) = path else {
return false;
};
let Some(input) = find_node_by_path(root, &path) else {
return false;
};
let NodeKind::TextInput { state, .. } = input.node_kind() else {
let chain = nodes_along_path(root, &path);
if chain.iter().all(|node| node.events.on_paste.is_empty()) {
return false;
}
let Some(content) = read(true) else {
return false;
};
let event = PasteEvent::new(Arc::new(content), input.node_id());
dispatch_paste(&chain, &event);
return true;
};
let state = state.clone();
let chain = nodes_along_path(root, &path);
let has_handlers = chain.iter().any(|node| !node.events.on_paste.is_empty());
let Some(content) = read(has_handlers) else {
return false;
};
let event = PasteEvent::new(Arc::new(content), input.node_id());
dispatch_paste(&chain, &event);
if event.default_prevented() {
return true;
}
let Some(text) = event.text() else {
return false;
};
#[cfg(feature = "markdown")]
if let Some(pasted) = state.paste_rich(text, event.markdown(), keyboard) {
return pasted;
}
state.insert(text, keyboard)
}
}
fn paste_keyboard() -> KeyboardEvent {
KeyboardEvent::new("Paste", "Paste", false, false, false, false, NodeId::UNASSIGNED)
}
#[cfg(feature = "clipboard")]
fn os_clipboard() -> Option<Arc<dyn ClipboardReader>> {
Some(Arc::new(OsClipboard))
}
#[cfg(not(feature = "clipboard"))]
fn os_clipboard() -> Option<Arc<dyn ClipboardReader>> {
None
}
pub(super) fn nodes_along_path<'a>(root: &'a Node, path: &[usize]) -> Vec<&'a Node> {
let mut chain = Vec::with_capacity(path.len() + 1);
let mut current = root;
chain.push(current);
for &index in path {
let Some(child) = current.children().get(index) else {
break;
};
chain.push(child);
current = child;
}
chain
}
pub(super) fn dispatch_copy(chain: &[&Node], event: &CopyEvent) {
for node in chain.iter().rev() {
let event = event.at(node.node_id());
for handler in &node.events.on_copy {
handler.call(&event);
if event.immediate_propagation_stopped() {
return;
}
}
if event.propagation_stopped() {
return;
}
}
}
fn dispatch_paste(chain: &[&Node], event: &PasteEvent) {
for node in chain.iter().rev() {
let event = event.at(node.node_id());
for handler in &node.events.on_paste {
handler.call(&event);
if event.immediate_propagation_stopped() {
return;
}
}
if event.propagation_stopped() {
return;
}
}
}