cosmic_applet_avestruz/handlers/
pasting.rs1use std::borrow::Cow;
44use std::sync::Arc;
45
46use cosmic::iced::clipboard;
47use cosmic::iced::clipboard::mime::AllowedMimeTypes;
48use cosmic::iced::widget::operation::focus;
49use cosmic::prelude::*;
50use cosmic::widget::text_editor::{Action, Edit};
51use nostr_sdk::prelude::Url;
52
53use crate::messages::Message;
54use crate::nostr::compose::{Highlighted, Target};
55use crate::state::{AppModel, PasteAs, Pasting};
56use crate::views::compose::COMPOSE_EDITOR_ID;
57
58const SOURCES: [&str; 2] = ["text/x-moz-url-priv", "chromium/x-source-url"];
61
62const MAX_SOURCE_CHARS: usize = 2_000;
64
65#[derive(Debug, Clone, PartialEq, Eq)]
68pub struct CopiedFrom(pub String);
69
70impl AllowedMimeTypes for CopiedFrom {
71 fn allowed() -> Cow<'static, [String]> {
72 SOURCES.iter().map(|kind| (*kind).to_string()).collect()
73 }
74}
75
76impl TryFrom<(Vec<u8>, String)> for CopiedFrom {
77 type Error = ();
78
79 fn try_from((bytes, _kind): (Vec<u8>, String)) -> Result<Self, Self::Error> {
80 copied_from(&bytes).map(Self).ok_or(())
81 }
82}
83
84fn copied_from(bytes: &[u8]) -> Option<String> {
90 let wide = bytes.len().is_multiple_of(2) && matches!(bytes, [0xff, 0xfe, ..] | [_, 0, ..]);
91 let said = if wide {
92 let units: Vec<u16> = bytes.as_chunks::<2>().0.iter().map(|pair| u16::from_le_bytes(*pair)).collect();
93 String::from_utf16(&units).ok()?
94 } else {
95 String::from_utf8(bytes.to_vec()).ok()?
96 };
97 let address = said.trim_start_matches('\u{feff}').trim_matches(|c: char| c.is_whitespace() || c == '\0');
98 let page = Url::parse(address).ok()?;
99 let on_the_web = matches!(page.scheme(), "http" | "https") && page.host_str().is_some();
100 let plain = address.chars().count() <= MAX_SOURCE_CHARS && !address.chars().any(char::is_whitespace);
101 (on_the_web && plain).then(|| address.to_string())
102}
103
104fn quotes_something(text: &str) -> bool {
107 let said = text.trim();
108 !said.is_empty() && (said.contains(char::is_whitespace) || Url::parse(said).is_err())
109}
110
111impl AppModel {
112 pub(crate) fn paste_text(&self, text: String) -> Task<cosmic::Action<Message>> {
115 clipboard::read_data::<CopiedFrom>().map(move |from| {
116 cosmic::Action::App(Message::ComposePastedText { text: text.clone(), from: from.map(|from| from.0) })
117 })
118 }
119
120 pub fn handle_compose_pasted_text(&mut self, text: String, from: Option<String>) -> Task<cosmic::Action<Message>> {
126 let Some(composer) = self.composer.as_mut().filter(|composer| !composer.publishing) else {
127 return Task::none();
128 };
129 let asks = composer.target == Target::Note && quotes_something(&text) && composer.preview.is_none() && !composer.leaving;
130 match from.filter(|_| asks) {
131 Some(source) => composer.pasting = Some(Pasting { text, source }),
132 None => self.handle_compose_edited(Action::Edit(Edit::Paste(Arc::new(text)))),
133 }
134 Task::none()
135 }
136
137 pub fn handle_paste_as(&mut self, meant: PasteAs) -> Task<cosmic::Action<Message>> {
141 let Some(composer) = self.composer.as_mut() else {
142 return Task::none();
143 };
144 let Some(Pasting { text, source }) = composer.pasting.take() else {
145 return Task::none();
146 };
147 match meant {
148 PasteAs::Highlight => {
149 composer.highlight = Some(Highlighted { passage: text.trim().to_string(), source });
150 composer.error = None;
151 }
152 PasteAs::Text => self.handle_compose_edited(Action::Edit(Edit::Paste(Arc::new(text)))),
153 PasteAs::Nothing => {}
154 }
155 focus(COMPOSE_EDITOR_ID.clone())
156 }
157}
158
159#[cfg(test)]
160mod tests {
161 use super::{CopiedFrom, copied_from, quotes_something};
162 use cosmic::iced::clipboard::mime::AllowedMimeTypes;
163
164 fn wide(said: &str) -> Vec<u8> {
166 said.encode_utf16().flat_map(u16::to_le_bytes).collect()
167 }
168
169 #[test]
170 fn the_page_something_was_copied_from_is_read_as_browsers_write_it() {
171 assert_eq!(CopiedFrom::allowed().to_vec(), ["text/x-moz-url-priv", "chromium/x-source-url"]);
172 let page = "https://example.com/a/page?of=its&own#part";
173 assert_eq!(copied_from(&wide(page)).as_deref(), Some(page));
175 assert_eq!(copied_from(&wide(&format!("\u{feff}{page}\0"))).as_deref(), Some(page));
176 assert_eq!(copied_from(page.as_bytes()).as_deref(), Some(page));
178 assert_eq!(copied_from(format!("{page}\n").as_bytes()).as_deref(), Some(page));
179 let named = "https://exämple.com/straße";
181 assert_eq!(copied_from(&wide(named)).as_deref(), Some(named));
182 assert_eq!(copied_from(named.as_bytes()).as_deref(), Some(named));
183 assert_eq!(copied_from(&wide("https://example.com")).as_deref(), Some("https://example.com"));
185 }
186
187 #[test]
188 fn only_a_page_on_the_web_is_where_something_was_copied_from() {
189 for other in [
190 "",
191 "about:reader?url=https://example.com",
192 "file:///home/ana/notes.html",
193 "moz-extension://0a1b/page.html",
194 "javascript:alert(1)",
195 "example.com/page",
196 "https://",
197 "https://example.com/a page",
198 "https://example.com/a\nhttps://example.com/b",
199 ] {
200 assert_eq!(copied_from(&wide(other)), None, "{other}");
201 assert_eq!(copied_from(other.as_bytes()), None, "{other}");
202 }
203 let long = format!("https://example.com/{}", "a".repeat(2_000));
204 assert_eq!(copied_from(&wide(&long)), None);
205 assert_eq!(copied_from(&[0xff, 0xfe, 0x00, 0xd8]), None);
207 assert_eq!(copied_from(&[0xc3, 0x28, 0x41]), None);
208 }
209
210 #[test]
211 fn text_that_is_an_address_by_itself_quotes_nothing() {
212 assert!(quotes_something("This must be the place"));
213 assert!(quotes_something("place"));
214 assert!(quotes_something("see https://example.com/a"));
215 assert!(!quotes_something("https://example.com/a"));
216 assert!(!quotes_something(" https://example.com/a\n"));
217 assert!(!quotes_something(" \n"));
218 }
219}