1 use std::fmt::{Display, Formatter, Result as FmtResult};
2 use std::str::FromStr;
3 
4 /// Application property to copy to clipboard.
5 #[derive(Clone, Copy, Debug, PartialEq)]
6 pub enum Selection {
7 	/// Selected row of the keys table.
8 	TableRow(usize),
9 	/// Exported key.
10 	Key,
11 	/// ID of the selected key.
12 	KeyId,
13 	/// Fingerprint of the selected key.
14 	KeyFingerprint,
15 	/// User ID of the selected key.
16 	KeyUserId,
17 }
18 
19 impl Display for Selection {
fmt(&self, f: &mut Formatter<'_>) -> FmtResult20 	fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
21 		write!(
22 			f,
23 			"{}",
24 			match self {
25 				Self::TableRow(i) => format!("table row ({})", i),
26 				Self::Key => String::from("exported key"),
27 				Self::KeyId => String::from("key ID"),
28 				Self::KeyFingerprint => String::from("key fingerprint"),
29 				Self::KeyUserId => String::from("user ID"),
30 			}
31 		)
32 	}
33 }
34 
35 impl FromStr for Selection {
36 	type Err = String;
from_str(s: &str) -> Result<Self, Self::Err>37 	fn from_str(s: &str) -> Result<Self, Self::Err> {
38 		match s {
39 			"row1" | "1" => Ok(Self::TableRow(1)),
40 			"row2" | "2" => Ok(Self::TableRow(2)),
41 			"key" => Ok(Self::Key),
42 			"key_id" | "id" => Ok(Self::KeyId),
43 			"key_fingerprint" | "key_fpr" | "fingerprint" | "fpr" => {
44 				Ok(Self::KeyFingerprint)
45 			}
46 			"key_user_id" | "user" | "user_id" => Ok(Self::KeyUserId),
47 			_ => Err(String::from("could not parse the type")),
48 		}
49 	}
50 }
51 
52 #[cfg(test)]
53 mod tests {
54 	use super::*;
55 	use pretty_assertions::assert_eq;
56 	#[test]
test_app_clipboard()57 	fn test_app_clipboard() {
58 		let copy_type = Selection::from_str("row1").unwrap();
59 		assert_eq!(Selection::TableRow(1), copy_type);
60 		assert_eq!(String::from("table row (1)"), copy_type.to_string());
61 		let copy_type = Selection::from_str("key").unwrap();
62 		assert_eq!(Selection::Key, copy_type);
63 		assert_eq!(String::from("exported key"), copy_type.to_string());
64 		let copy_type = Selection::from_str("key_id").unwrap();
65 		assert_eq!(Selection::KeyId, copy_type);
66 		assert_eq!(String::from("key ID"), copy_type.to_string());
67 		let copy_type = Selection::from_str("key_fingerprint").unwrap();
68 		assert_eq!(Selection::KeyFingerprint, copy_type);
69 		assert_eq!(String::from("key fingerprint"), copy_type.to_string());
70 		let copy_type = Selection::from_str("key_user_id").unwrap();
71 		assert_eq!(Selection::KeyUserId, copy_type);
72 		assert_eq!(String::from("user ID"), copy_type.to_string());
73 	}
74 }
75