Skip to main content

cosmic_applet_avestruz/handlers/
images.rs

1// SPDX-License-Identifier: MIT
2
3//! Image message handlers for Avestruz.
4//!
5//! A view that needs a picture asks the [`ImageStore`](crate::images::ImageStore),
6//! which sends the address here as a `LoadImage`. This is where it is decided
7//! whether to fetch it, and where the fetched picture comes back to.
8//!
9//! A picture is copied from here as well: a click on one with the right
10//! button puts it on the clipboard. What is kept of a picture is as many
11//! pixels as it is shown with, which may be far fewer than it has, so
12//! what is copied is the picture itself, fetched again from where it is.
13//!
14//! That takes a moment, and something copied is on its way somewhere
15//! else: the popup may be gone before the picture is here, and only what
16//! has the keyboard may put anything on the clipboard. So the clipboard
17//! is given the picture at once, as something that is still to arrive
18//! ([`CopiedPicture`]): what it is asked for when it is pasted, it waits
19//! for then.
20//!
21//! ```mermaid
22//! sequenceDiagram
23//!     actor person as Someone
24//!     participant model as AppModel
25//!     participant clipboard as The clipboard
26//!     participant web as Where the picture is
27//!     person->>model: a right click on a picture
28//!     model->>clipboard: a picture, yet to arrive, and its address as text
29//!     model->>web: fetch it
30//!     web-->>model: the picture: made a PNG, the way up it says it is
31//!     person->>clipboard: paste, somewhere else
32//!     clipboard-->>person: the picture, once it is here, or what was shown of it if it never came
33//! ```
34
35use std::borrow::Cow;
36use std::sync::{Arc, Condvar, Mutex, PoisonError};
37use std::time::Duration;
38
39use cosmic::iced::clipboard;
40use cosmic::iced::clipboard::mime::AsMimeTypes;
41use cosmic::prelude::*;
42
43use crate::images::{self, ImageRequest, ImageShape, ImageState, LoadedImage};
44use crate::messages::Message;
45use crate::state::AppModel;
46
47/// What a picture is on the clipboard as: what takes a picture from one
48/// anywhere.
49const PICTURE: &str = "image/png";
50
51/// What text is on the clipboard as.
52const TEXTS: [&str; 3] = ["text/plain;charset=utf-8", "UTF8_STRING", "text/plain"];
53
54/// How long a paste waits for a picture that is still on its way: a
55/// little longer than a fetch may take.
56const PASTE_WAITS: Duration = Duration::from_secs(25);
57
58/// What there is of a copied picture so far.
59#[derive(Default)]
60struct Arrived {
61    /// What was shown of it, as a PNG: what is pasted if the picture
62    /// itself never comes.
63    shown: Option<Vec<u8>>,
64    /// The picture itself, as a PNG, or that it could not be had. `None`
65    /// while it is on its way.
66    whole: Option<Result<Vec<u8>, ()>>,
67}
68
69/// A picture on the clipboard, which may be still on its way from where
70/// it is: as a PNG, to whatever takes pictures, and as its address, to
71/// whatever takes text.
72///
73/// It is handed to the clipboard before the picture is here, and asked
74/// for the picture when something is pasted: it waits then, until the
75/// picture has come or [`PASTE_WAITS`] is up.
76#[derive(Clone)]
77pub struct CopiedPicture {
78    url: String,
79    arrived: Arc<(Mutex<Arrived>, Condvar)>,
80}
81
82impl CopiedPicture {
83    /// The picture at `url`, none of it here yet.
84    pub fn new(url: String) -> Self {
85        Self { url, arrived: Arc::default() }
86    }
87
88    /// Note what has come of the picture, and tell whoever waits.
89    fn note(&self, change: impl FnOnce(&mut Arrived)) {
90        let (arrived, changed) = &*self.arrived;
91        change(&mut arrived.lock().unwrap_or_else(PoisonError::into_inner));
92        changed.notify_all();
93    }
94
95    /// Have the picture come: what `shown` shows of it first, which is at
96    /// hand, and then the picture itself, fetched from where it is.
97    pub async fn arrive(self, http: reqwest::Client, shown: Option<LoadedImage>) {
98        if let Some(shown) = shown {
99            let png = tokio::task::spawn_blocking(move || images::shown_as_png(&shown)).await;
100            if let Ok(Ok(png)) = png {
101                self.note(|arrived| arrived.shown = Some(png));
102            }
103        }
104        let whole = images::fetch_as_png(&http, &self.url).await;
105        if let Err(e) = &whole {
106            tracing::debug!("the picture copied could not be fetched again ({e}): {}", self.url);
107        }
108        self.note(|arrived| arrived.whole = Some(whole.map_err(|_| ())));
109    }
110
111    /// The picture, as a PNG: itself, once it has come, waited for as
112    /// long as `wait`; and what was shown of it, if it has not come by
113    /// then or could not be had.
114    fn png(&self, wait: Duration) -> Option<Vec<u8>> {
115        let (arrived, changed) = &*self.arrived;
116        let arrived = arrived.lock().unwrap_or_else(PoisonError::into_inner);
117        let (arrived, _) =
118            changed.wait_timeout_while(arrived, wait, |arrived| arrived.whole.is_none()).unwrap_or_else(PoisonError::into_inner);
119        match &arrived.whole {
120            Some(Ok(whole)) => Some(whole.clone()),
121            _ => arrived.shown.clone(),
122        }
123    }
124}
125
126impl AsMimeTypes for CopiedPicture {
127    fn available(&self) -> Cow<'static, [String]> {
128        std::iter::once(PICTURE).chain(TEXTS).map(str::to_string).collect()
129    }
130
131    fn as_bytes(&self, mime_type: &str) -> Option<Cow<'static, [u8]>> {
132        if mime_type == PICTURE {
133            self.png(PASTE_WAITS).map(Cow::Owned)
134        } else if TEXTS.contains(&mime_type) {
135            Some(Cow::Owned(self.url.clone().into_bytes()))
136        } else {
137            None
138        }
139    }
140}
141
142impl AppModel {
143    /// A view asked for a picture. Fetch it, unless it is here, failed, or
144    /// on its way already, or too many others are.
145    pub fn handle_load_image(&mut self, request: ImageRequest) -> Task<cosmic::Action<Message>> {
146        if !self.images.begin(&request) {
147            return Task::none();
148        }
149        let http = self.http.clone();
150        let scale = self.screen_scale();
151        Task::perform(
152            async move {
153                let result = images::fetch(http, request.clone(), scale).await;
154                (request, result)
155            },
156            |(request, result)| cosmic::Action::App(Message::ImageLoaded(request, result)),
157        )
158    }
159
160    /// A picture arrived, or didn't. Either way the views that wanted it
161    /// are built again, and the ones still waiting ask again.
162    pub fn handle_image_loaded(&mut self, request: ImageRequest, result: Result<LoadedImage, String>) {
163        if let Err(e) = &result {
164            // Dead links are ordinary on Nostr: not worth a banner.
165            tracing::debug!("picture not shown ({e}): {}", request.url);
166        }
167        self.images.finish(request, result);
168    }
169
170    /// A picture was clicked with the right button: put it on the
171    /// clipboard (see the [module](self)), and have it say so.
172    pub fn handle_copy_picture(&mut self, url: String) -> Task<cosmic::Action<Message>> {
173        let shown = match self.images.get(&url, ImageShape::Original) {
174            ImageState::Ready(loaded) => Some(loaded.clone()),
175            ImageState::Loading | ImageState::Failed => None,
176        };
177        let copied = CopiedPicture::new(url.clone());
178        let arriving = copied.clone().arrive(self.http.clone(), shown);
179        self.picture_copied = Some(url);
180        Task::batch([clipboard::write_data(copied), Task::future(arriving).discard()])
181    }
182}
183
184#[cfg(test)]
185mod tests {
186    use super::{CopiedPicture, PICTURE};
187    use cosmic::iced::clipboard::mime::AsMimeTypes;
188    use std::time::Duration;
189
190    const URL: &str = "https://cdn.example.com/picture.jpg";
191
192    #[test]
193    fn a_copied_picture_is_a_picture_to_what_takes_pictures_and_its_address_to_what_takes_text() {
194        let copied = CopiedPicture::new(URL.into());
195        let offered = copied.available();
196        assert_eq!(offered.first().map(String::as_str), Some(PICTURE));
197        for text in ["text/plain;charset=utf-8", "UTF8_STRING", "text/plain"] {
198            assert!(offered.iter().any(|kind| kind == text));
199            assert_eq!(copied.as_bytes(text).as_deref(), Some(URL.as_bytes()));
200        }
201        assert_eq!(copied.as_bytes("text/html"), None);
202    }
203
204    #[test]
205    fn a_paste_gets_the_picture_itself_once_it_has_come() {
206        let copied = CopiedPicture::new(URL.into());
207        copied.note(|arrived| arrived.shown = Some(b"what was shown".to_vec()));
208        // It comes while the paste waits for it.
209        let arriving = copied.clone();
210        let came = std::thread::spawn(move || {
211            std::thread::sleep(Duration::from_millis(50));
212            arriving.note(|arrived| arrived.whole = Some(Ok(b"the picture itself".to_vec())));
213        });
214        assert_eq!(copied.png(Duration::from_secs(10)).as_deref(), Some(&b"the picture itself"[..]));
215        came.join().unwrap();
216        // And is there at once from then on.
217        assert_eq!(copied.png(Duration::ZERO).as_deref(), Some(&b"the picture itself"[..]));
218    }
219
220    #[test]
221    fn a_paste_gets_what_was_shown_of_a_picture_that_does_not_come() {
222        let copied = CopiedPicture::new(URL.into());
223        assert_eq!(copied.png(Duration::ZERO), None, "nothing of it is here");
224        copied.note(|arrived| arrived.shown = Some(b"what was shown".to_vec()));
225        // Not here when the wait is up.
226        assert_eq!(copied.png(Duration::from_millis(20)).as_deref(), Some(&b"what was shown"[..]));
227        // It could not be had: that is known at once.
228        copied.note(|arrived| arrived.whole = Some(Err(())));
229        assert_eq!(copied.png(Duration::from_secs(10)).as_deref(), Some(&b"what was shown"[..]));
230    }
231}