Skip to main content

ferroui_base/input/
async_data_transfer_item_extensions.rs

1use super::platform::ClipboardError;
2use super::{DataFormat, DataFormatOf, IAsyncDataTransferItem, LocalBoxFuture};
3use crate::media::imaging::Bitmap;
4use crate::platform::storage::IStorageItem;
5use std::rc::Rc;
6
7/// Contains extension methods for [`IAsyncDataTransferItem`].
8pub trait AsyncDataTransferItemExtensions: IAsyncDataTransferItem {
9    /// Gets whether the item supports a specific format.
10    fn contains(&self, format: &DataFormat) -> bool {
11        self.formats().iter().any(|candidate| candidate == format)
12    }
13
14    /// Gets whether the item supports a specific format, or the failure of
15    /// the platform that provides the formats of the item.
16    fn try_contains(&self, format: &DataFormat) -> Result<bool, ClipboardError> {
17        Ok(self.try_formats()?.iter().any(|candidate| candidate == format))
18    }
19
20    /// Tries to get a value for a given format from the item. The future
21    /// resolves to `None` if the format is not supported, and to an error
22    /// if the platform providing the value fails.
23    fn try_get_value_async<T: Clone + 'static>(
24        &self,
25        format: &DataFormatOf<T>,
26    ) -> LocalBoxFuture<Result<Option<T>, ClipboardError>> {
27        let raw = self.try_get_raw_async(format);
28        Box::pin(async move { Ok(raw.await?.and_then(|value| value.downcast_ref::<T>().cloned())) })
29    }
30
31    /// Returns a text, if available, from the item.
32    fn try_get_text_async(&self) -> LocalBoxFuture<Result<Option<String>, ClipboardError>> {
33        self.try_get_value_async(&DataFormat::text())
34    }
35
36    /// Returns a bitmap, if available, from the item.
37    fn try_get_bitmap_async(&self) -> LocalBoxFuture<Result<Option<Rc<Bitmap>>, ClipboardError>> {
38        self.try_get_value_async(&DataFormat::bitmap())
39    }
40
41    /// Returns a file (or folder), if available, from the item.
42    ///
43    /// See [`DataFormat::file`].
44    fn try_get_file_async(&self) -> LocalBoxFuture<Result<Option<Rc<dyn IStorageItem>>, ClipboardError>> {
45        self.try_get_value_async(&DataFormat::file())
46    }
47}
48
49impl<I: IAsyncDataTransferItem + ?Sized> AsyncDataTransferItemExtensions for I {}