1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
#[cfg(feature = "unstable_atspi_proxy_macro")]
mod proxy;
#[cfg(feature = "unstable_atspi_proxy_macro")]
mod utils;
#[cfg(feature = "unstable_atspi_proxy_macro")]
mod zbus_proxy;

#[cfg(feature = "unstable_atspi_proxy_macro")]
use syn::ItemTrait;

use proc_macro::TokenStream;
use quote::quote;
use syn::{
	parse_macro_input, AttributeArgs, DeriveInput, ItemStruct, Lit, Meta, MetaNameValue,
	NestedMeta, Type,
};

use std::convert::TryFrom;

enum FromZbusMessageParam {
	Invalid,
	Body(Type),
	Member(String),
}

impl From<(String, String)> for FromZbusMessageParam {
	fn from(items: (String, String)) -> Self {
		match (items.0.as_str(), items.1.as_str()) {
			("body", tp) => Self::Body(
				syn::parse_str(tp)
					.expect("The value given to the 'body' parameter must be a valid type."),
			),
			("member", mem) => Self::Member(mem.to_string()),
			_ => Self::Invalid,
		}
	}
}

//
// Derive macro for that implements TryFrom<Event> on a per name / member basis.
//

#[proc_macro_derive(TrySignify)]
pub fn implement_signified(input: TokenStream) -> TokenStream {
	// Parse the input token stream into a syntax tree
	let DeriveInput { ident, .. } = parse_macro_input!(input);

	// Extract the name of the struct
	let name = &ident;

	// Generate the expanded code
	let expanded = quote! {
		impl Signified for #name {
			type Inner = AtspiEvent;
			fn inner(&self) -> &Self::Inner {
				&self.0
			}

			/// Returns `properties`.
			fn properties(&self) -> &std::collections::HashMap<String, OwnedValue> {
				self.0.properties()
			}

			/// Returns `kind` body member.
			fn kind(&self) -> &str {
				self.inner().kind()
			}
		}
	};

	// Return the expanded code as a token stream
	TokenStream::from(expanded)
}

fn make_into_params<T>(items: AttributeArgs) -> Vec<T>
where
	T: From<(String, String)>,
{
	items
		.into_iter()
		.filter_map(|nm| match nm {
			// Only select certain tokens
			NestedMeta::Meta(Meta::NameValue(MetaNameValue {
				path,
				eq_token: _,
				lit: Lit::Str(lstr),
			})) => Some(
				// Convert the segment of the path to a string
				(
					path.segments
						.into_iter()
						.map(|seg| seg.ident.to_string())
						.collect::<Vec<String>>()
						.swap_remove(0),
					// get the raw value of the LitStr
					lstr.value(),
				),
			),
			_ => None,
		})
		// convert the (String, LitStr) tuple to a custom type which only accepts certain key/value pairs
		.map(|(k, v)| T::from((k, v)))
		.collect()
}

enum AtspiEventInnerName {
	Detail1,
	Detail2,
	AnyData,
}
impl ToString for AtspiEventInnerName {
	fn to_string(&self) -> String {
		match self {
			Self::Detail1 => "detail1",
			Self::Detail2 => "detail2",
			Self::AnyData => "any_data",
		}
		.to_string()
	}
}
enum ConversionError {
	FunctionAlreadyCreatedFor,
	UnknownItem,
}
impl TryFrom<usize> for AtspiEventInnerName {
	type Error = ConversionError;

	fn try_from(from: usize) -> Result<Self, Self::Error> {
		match from {
			0 => Err(ConversionError::FunctionAlreadyCreatedFor),
			1 => Ok(Self::Detail1),
			2 => Ok(Self::Detail2),
			3 => Ok(Self::AnyData),
			4 => Err(ConversionError::FunctionAlreadyCreatedFor),
			_ => Err(ConversionError::UnknownItem),
		}
	}
}

#[proc_macro_attribute]
#[cfg(feature = "unstable_atspi_proxy_macro")]
pub fn atspi_proxy(attr: TokenStream, item: TokenStream) -> TokenStream {
	let args = parse_macro_input!(attr as AttributeArgs);
	let input = parse_macro_input!(item as ItemTrait);
	let zbus_part =
		zbus_proxy::expand(args, input.clone()).unwrap_or_else(|err| err.into_compile_error());
	let atspi_part = proxy::expand(input).unwrap_or_else(|err| err.into_compile_error());
	quote! {
	#zbus_part
	#atspi_part
		}
	.into()
}

#[proc_macro_attribute]
pub fn try_from_zbus_message(attr: TokenStream, input: TokenStream) -> TokenStream {
	let item_struct = parse_macro_input!(input as ItemStruct);
	// Parse the input token stream into a syntax tree
	let name = item_struct.ident.clone();

	// Remove the suffix "Event" from the name of the struct
	let name_string = name.to_string();

	let args = parse_macro_input!(attr as AttributeArgs);
	let args_parsed = make_into_params(args);
	let body_type = match args_parsed
		.get(0)
		.expect("There must be at least one argument to the macro.")
	{
		FromZbusMessageParam::Body(body_type) => body_type,
		_ => panic!("The body parameter must be set first, and must be a type."),
	};
	// if the member is set explicitly, use it, otherwise, use the struct name.
	let member = match args_parsed.get(1) {
		Some(FromZbusMessageParam::Member(member_str)) => member_str,
		_ => name_string.strip_suffix("Event").unwrap(),
	};

	// Generate the expanded code
	let expanded = quote! {
		#item_struct
		impl TryFrom<Arc<Message>> for  #name {
			type Error = AtspiError;

			fn try_from(message: Arc<Message>) -> Result<Self, Self::Error> {
				let message_member: MemberName = message
					.member()
					.ok_or(AtspiError::MemberMatch("message w/o member".to_string()))?;

				let member = MemberName::from_static_str(#member)?;

				if message_member != member {
					let error = format!("message member: {:?} != member: {:?}", message_member, member);
					return Err(AtspiError::MemberMatch(error));
				};
				let body: #body_type = message.body()?;
				Ok(Self { message, body })
			}
		}

	};

	// Return the expanded code as a token stream
	TokenStream::from(expanded)
}

#[proc_macro_derive(GenericEvent)]
pub fn generic_event(input: TokenStream) -> TokenStream {
	// Parse the input token stream into a syntax tree
	let DeriveInput { ident, .. } = parse_macro_input!(input);

	// Extract the name of the struct
	let name = &ident;

	// Generate the expanded code
	let expanded = quote! {
			impl GenericEvent for #name {
					/// Bus message.
					#[must_use]
					fn message(&self) -> &Arc<Message> {
							&self.message
					}

					/// For now this returns the full interface name because the lifetimes in [`zbus_names`][zbus::names] are
					/// wrong such that the `&str` you can get from a
					/// [`zbus_names::InterfaceName`][zbus::names::InterfaceName] is tied to the lifetime of that
					/// name, not to the lifetime of the message as it should be. In future, this will return only
					/// the last component of the interface name (I.E. "Object" from
					/// "org.a11y.atspi.Event.Object").
					#[must_use]
					fn interface(&self) -> Option<InterfaceName<'_>> {
							self.message.interface()
					}

					/// Identifies this event's interface member name.
					#[must_use]
					fn member(&self) -> Option<MemberName<'_>> {
							self.message.member()
					}

					/// The object path to the object where the signal is emitted from.
					#[must_use]
					fn path(&self) -> std::option::Option<zbus::zvariant::ObjectPath<'_>> {
							self.message.path()
					}

					/// Identifies the `sender` of the event.
					/// # Errors
					/// - when deserializeing the header failed, or
					/// - When `zbus::get_field!` finds that 'sender' is an invalid field.
					fn sender(&self) -> Result<Option<zbus::names::UniqueName>, crate::AtspiError> {
							Ok(self.message.header()?.sender()?.cloned())
					}
				}
	};

	// Return the expanded code as a token stream
	TokenStream::from(expanded)
}