cosmic_applet_avestruz/handlers/
images.rs1use 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
47const PICTURE: &str = "image/png";
50
51const TEXTS: [&str; 3] = ["text/plain;charset=utf-8", "UTF8_STRING", "text/plain"];
53
54const PASTE_WAITS: Duration = Duration::from_secs(25);
57
58#[derive(Default)]
60struct Arrived {
61 shown: Option<Vec<u8>>,
64 whole: Option<Result<Vec<u8>, ()>>,
67}
68
69#[derive(Clone)]
77pub struct CopiedPicture {
78 url: String,
79 arrived: Arc<(Mutex<Arrived>, Condvar)>,
80}
81
82impl CopiedPicture {
83 pub fn new(url: String) -> Self {
85 Self { url, arrived: Arc::default() }
86 }
87
88 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 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 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 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 pub fn handle_image_loaded(&mut self, request: ImageRequest, result: Result<LoadedImage, String>) {
163 if let Err(e) = &result {
164 tracing::debug!("picture not shown ({e}): {}", request.url);
166 }
167 self.images.finish(request, result);
168 }
169
170 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 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 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 assert_eq!(copied.png(Duration::from_millis(20)).as_deref(), Some(&b"what was shown"[..]));
227 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}