Skip to main content

cosmic_applet_avestruz/handlers/
pasting.rs

1// SPDX-License-Identifier: MIT
2
3//! Handlers for text pasted into what is being written that says where
4//! it was copied from.
5//!
6//! A browser that copies text from a page puts the page's address on the
7//! clipboard beside it, as a kind of its own that nothing takes unless it
8//! asks for it ([`SOURCES`]): the text itself says nothing of where it is
9//! from. So when text is pasted into a new note (see
10//! [`crate::handlers::media`], which is where Ctrl+V in the composer
11//! goes), the clipboard is asked for that too, and where there is one,
12//! whoever pasted is asked what they meant: the text as a passage of
13//! that page, marked; or the text alone, as it always was pasted.
14//! Nothing is written until that is answered.
15//!
16//! ```mermaid
17//! flowchart TD
18//!     paste["Ctrl+V, in a new note: text"] --> from{"Does the clipboard say which page it is from?"}
19//!     from -->|"no, or the text is an address itself"| plain["Pasted, as it is"]
20//!     from -->|"yes"| ask{"Asked: as a highlight?"}
21//!     ask -->|"Enter"| marked["Kept beside the text, as the passage the note is about"]
22//!     ask -->|"Backspace"| plain
23//!     ask -->|"Esc"| nothing["Nothing is pasted"]
24//!     marked --> out["Published as a highlight (kind 9802): the passage, the page, and the text as its comment"]
25//! ```
26//!
27//! A passage that is marked is not in the text: it shows over it, with
28//! the page it is from, and what is written is what is said of it. What
29//! goes out is then a highlight (NIP-84; see
30//! [`crate::nostr::compose::highlight`]), which a client that knows
31//! highlights shows as a note quoting the passage, and one that does not
32//! shows not at all. It is kept with the draft, and can be taken out
33//! again, which leaves a note of its own.
34//!
35//! What the browser says is the page as far as it tells: Firefox says
36//! only the site (`https://example.com`) unless it is set to say the
37//! whole address (`clipboard.copyFullSourceURL`, from Firefox 163). The
38//! address is shown in the question, and over the text after it.
39//!
40//! A reply or a quote is about a note, and is no highlight: text pasted
41//! into one is pasted as it is.
42
43use 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
58/// The kinds a browser says the address of the page something was copied
59/// from as: Firefox's, in UTF-16, and Chromium's.
60const SOURCES: [&str; 2] = ["text/x-moz-url-priv", "chromium/x-source-url"];
61
62/// How long the address of a page may be and still be taken for one.
63const MAX_SOURCE_CHARS: usize = 2_000;
64
65/// Where what is on the clipboard was copied from, as what copied it
66/// says: the address of a page.
67#[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
84/// The address `bytes` say something was copied from, if they say one:
85/// of a page on the web, and nothing else. They are text in UTF-16, as
86/// Firefox writes it, with or without the mark that says which end
87/// first, or in UTF-8; told apart by the zero bytes that an address in
88/// UTF-16 is half made of.
89fn 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
104/// Whether `text` is worth asking about: there is something in it, and
105/// it is not an address by itself, which is no passage of anything.
106fn 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    /// Text was pasted into the composer: ask the clipboard which page
113    /// it was copied from, if it says, before anything is written.
114    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    /// The clipboard said which page the text `text`, pasted into the
121    /// composer, was copied from: `from`; or said nothing. With a page,
122    /// and in a new note, it is asked whether the text is meant as a
123    /// highlight of it. With none, in a reply or a quote, or of text
124    /// that is no passage, it is pasted as it is.
125    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    /// What was pasted is meant as `meant`: kept as the passage the note
138    /// is about, in place of any it was about before; written where the
139    /// cursor is, as it is; or neither. The keyboard is in the text.
140    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    /// `said`, as Firefox writes text to the clipboard.
165    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        // Firefox: UTF-16, with or without the mark, and what ends it.
174        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        // Chromium: UTF-8.
177        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        // An address that is not all in one alphabet is one all the same.
180        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        // As it was written, not as it would be written out in full.
184        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        // Bytes that are no text.
206        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}