Skip to main content

inset_services/
keyboard_inserted_content.rs

1//! Flutter counterpart: `services/keyboard_inserted_content.dart`.
2
3/// A class representing rich content (such as a PNG image) inserted via the
4/// system input method.
5///
6/// The following data is represented in this class:
7///  - MIME Type
8///  - Bytes
9///  - URI
10#[derive(Clone, Debug, PartialEq, Eq, Hash)]
11pub struct KeyboardInsertedContent {
12    /// The mime type of the inserted content.
13    pub mime_type: String,
14    /// The URI (location) of the inserted content, usually a "content://" URI.
15    pub uri: String,
16    /// The bytedata of the inserted content.
17    pub data: Option<Vec<u8>>,
18}
19
20impl KeyboardInsertedContent {
21    /// Creates an object to represent content that is inserted from the virtual
22    /// keyboard.
23    ///
24    /// The mime type and URI will always be provided, but the bytedata may be null.
25    pub fn new(mime_type: impl Into<String>, uri: impl Into<String>) -> KeyboardInsertedContent {
26        KeyboardInsertedContent {
27            mime_type: mime_type.into(),
28            uri: uri.into(),
29            data: None,
30        }
31    }
32
33    /// Dart `KeyboardInsertedContent(data:)`.
34    pub fn data(mut self, data: Vec<u8>) -> KeyboardInsertedContent {
35        self.data = Some(data);
36        self
37    }
38
39    /// Convenience getter to check if bytedata is available for the inserted content.
40    pub fn has_data(&self) -> bool {
41        self.data.as_ref().is_some_and(|data| !data.is_empty())
42    }
43}
44
45impl std::fmt::Display for KeyboardInsertedContent {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        write!(
48            f,
49            "KeyboardInsertedContent({}, {}, {:?})",
50            self.mime_type, self.uri, self.data
51        )
52    }
53}
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    #[test]
60    fn equality_and_has_data() {
61        let empty = KeyboardInsertedContent::new("image/png", "content://item");
62        let with_bytes =
63            KeyboardInsertedContent::new("image/png", "content://item").data(vec![1, 2]);
64        assert_eq!(
65            empty,
66            KeyboardInsertedContent::new("image/png", "content://item")
67        );
68        assert_ne!(empty, with_bytes);
69        assert!(!empty.has_data());
70        assert!(with_bytes.has_data());
71        assert!(
72            !KeyboardInsertedContent::new("image/png", "content://item")
73                .data(Vec::new())
74                .has_data()
75        );
76    }
77}