1use proc_macro2::{Ident, Span, TokenStream};
2
3use quote::{format_ident, quote};
4
5use crate::{
6 protocol::{Interface, Protocol, Type},
7 util::{description_to_doc_attr, dotted_to_relname, is_keyword, snake_to_camel, to_doc_attr},
8 Side,
9};
10
11pub fn generate_server_objects(protocol: &Protocol) -> TokenStream {
12 protocolimpl Iterator
13 .interfaces
14 .iter()
15 .filter(|iface: &&Interface| iface.name != "wl_display" && iface.name != "wl_registry")
16 .map(generate_objects_for)
17 .collect()
18}
19
20fn generate_objects_for(interface: &Interface) -> TokenStream {
21 let mod_name = Ident::new(&interface.name, Span::call_site());
22 let mod_doc = interface.description.as_ref().map(description_to_doc_attr);
23 let iface_name = Ident::new(&snake_to_camel(&interface.name), Span::call_site());
24 let iface_const_name = format_ident!("{}_INTERFACE", interface.name.to_ascii_uppercase());
25
26 let enums = crate::common::generate_enums_for(interface);
27 let msg_constants = crate::common::gen_msg_constants(&interface.requests, &interface.events);
28
29 let requests = crate::common::gen_message_enum(
30 &format_ident!("Request"),
31 Side::Server,
32 true,
33 &interface.requests,
34 );
35 let events = crate::common::gen_message_enum(
36 &format_ident!("Event"),
37 Side::Server,
38 false,
39 &interface.events,
40 );
41
42 let parse_body = crate::common::gen_parse_body(interface, Side::Server);
43 let write_body = crate::common::gen_write_body(interface, Side::Server);
44 let methods = gen_methods(interface);
45
46 let event_ref = if interface.requests.is_empty() {
47 "This interface has no requests."
48 } else {
49 "See also the [Request] enum for this interface."
50 };
51 let docs = match &interface.description {
52 Some((short, long)) => format!("{}\n\n{}\n\n{}", short, long, event_ref),
53 None => format!("{}\n\n{}", interface.name, event_ref),
54 };
55 let doc_attr = to_doc_attr(&docs);
56
57 quote! {
58 #mod_doc
59 pub mod #mod_name {
60 use std::sync::Arc;
61 use std::os::unix::io::OwnedFd;
62
63 use super::wayland_server::{
64 backend::{
65 smallvec, ObjectData, ObjectId, InvalidId, WeakHandle,
66 protocol::{WEnum, Argument, Message, Interface, same_interface}
67 },
68 Resource, Dispatch, DisplayHandle, DispatchError, ResourceData, New, Weak,
69 };
70
71 #enums
72 #msg_constants
73 #requests
74 #events
75
76 #doc_attr
77 #[derive(Debug, Clone)]
78 pub struct #iface_name {
79 id: ObjectId,
80 version: u32,
81 data: Option<Arc<dyn std::any::Any + Send + Sync + 'static>>,
82 handle: WeakHandle,
83 }
84
85 impl std::cmp::PartialEq for #iface_name {
86 fn eq(&self, other: &#iface_name) -> bool {
87 self.id == other.id
88 }
89 }
90
91 impl std::cmp::Eq for #iface_name {}
92
93 impl PartialEq<Weak<#iface_name>> for #iface_name {
94 fn eq(&self, other: &Weak<#iface_name>) -> bool {
95 self.id == other.id()
96 }
97 }
98
99 impl std::borrow::Borrow<ObjectId> for #iface_name {
100 fn borrow(&self) -> &ObjectId {
101 &self.id
102 }
103 }
104
105 impl std::hash::Hash for #iface_name {
106 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
107 self.id.hash(state)
108 }
109 }
110
111 impl super::wayland_server::Resource for #iface_name {
112 type Request = Request;
113 type Event<'event> = Event<'event>;
114
115 #[inline]
116 fn interface() -> &'static Interface{
117 &super::#iface_const_name
118 }
119
120 #[inline]
121 fn id(&self) -> ObjectId {
122 self.id.clone()
123 }
124
125 #[inline]
126 fn version(&self) -> u32 {
127 self.version
128 }
129
130 #[inline]
131 fn data<U: 'static>(&self) -> Option<&U> {
132 self.data.as_ref().and_then(|arc| (&**arc).downcast_ref::<ResourceData<Self, U>>()).map(|data| &data.udata)
133 }
134
135 #[inline]
136 fn object_data(&self) -> Option<&Arc<dyn std::any::Any + Send + Sync>> {
137 self.data.as_ref()
138 }
139
140 fn handle(&self) -> &WeakHandle {
141 &self.handle
142 }
143
144 #[inline]
145 fn from_id(conn: &DisplayHandle, id: ObjectId) -> Result<Self, InvalidId> {
146 if !same_interface(id.interface(), Self::interface()) && !id.is_null(){
147 return Err(InvalidId)
148 }
149 let version = conn.object_info(id.clone()).map(|info| info.version).unwrap_or(0);
150 let data = conn.get_object_data(id.clone()).ok();
151 Ok(#iface_name { id, data, version, handle: conn.backend_handle().downgrade() })
152 }
153
154 fn send_event(&self, evt: Self::Event<'_>) -> Result<(), InvalidId> {
155 let handle = DisplayHandle::from(self.handle.upgrade().ok_or(InvalidId)?);
156 handle.send_event(self, evt)
157 }
158
159 fn parse_request(conn: &DisplayHandle, msg: Message<ObjectId, OwnedFd>) -> Result<(Self, Self::Request), DispatchError> {
160 #parse_body
161 }
162
163 fn write_event<'a>(&self, conn: &DisplayHandle, msg: Self::Event<'a>) -> Result<Message<ObjectId, std::os::unix::io::BorrowedFd<'a>>, InvalidId> {
164 #write_body
165 }
166
167 fn __set_object_data(&mut self, odata: std::sync::Arc<dyn std::any::Any + Send + Sync + 'static>) {
168 self.data = Some(odata);
169 }
170 }
171
172 impl #iface_name {
173 #methods
174 }
175 }
176 }
177}
178
179fn gen_methods(interface: &Interface) -> TokenStream {
180 interface
181 .events
182 .iter()
183 .map(|request| {
184 let method_name = format_ident!(
185 "{}{}",
186 if is_keyword(&request.name) { "_" } else { "" },
187 request.name
188 );
189 let enum_variant = Ident::new(&snake_to_camel(&request.name), Span::call_site());
190
191 let fn_args = request.args.iter().flat_map(|arg| {
192 let arg_name =
193 format_ident!("{}{}", if is_keyword(&arg.name) { "_" } else { "" }, arg.name);
194
195 let arg_type = if let Some(ref enu) = arg.enum_ {
196 let enum_type = dotted_to_relname(enu);
197 quote! { #enum_type }
198 } else {
199 match arg.typ {
200 Type::Uint => quote! { u32 },
201 Type::Int => quote! { i32 },
202 Type::Fixed => quote! { f64 },
203 Type::String => {
204 if arg.allow_null {
205 quote! { Option<String> }
206 } else {
207 quote! { String }
208 }
209 }
210 Type::Array => {
211 if arg.allow_null {
212 quote! { Option<Vec<u8>> }
213 } else {
214 quote! { Vec<u8> }
215 }
216 }
217 Type::Fd => quote! { ::std::os::unix::io::BorrowedFd<'_> },
218 Type::Object | Type::NewId => {
219 let iface = arg.interface.as_ref().unwrap();
220 let iface_mod = Ident::new(iface, Span::call_site());
221 let iface_type = Ident::new(&snake_to_camel(iface), Span::call_site());
222 if arg.allow_null {
223 quote! { Option<&super::#iface_mod::#iface_type> }
224 } else {
225 quote! { &super::#iface_mod::#iface_type }
226 }
227 }
228 Type::Destructor => panic!("An argument cannot have type \"destructor\"."),
229 }
230 };
231
232 Some(quote! {
233 #arg_name: #arg_type
234 })
235 });
236
237 let enum_args = request.args.iter().flat_map(|arg| {
238 let arg_name =
239 format_ident!("{}{}", if is_keyword(&arg.name) { "_" } else { "" }, arg.name);
240 if arg.enum_.is_some() {
241 Some(quote! { #arg_name: WEnum::Value(#arg_name) })
242 } else if arg.typ == Type::Object || arg.typ == Type::NewId {
243 if arg.allow_null {
244 Some(quote! { #arg_name: #arg_name.cloned() })
245 } else {
246 Some(quote! { #arg_name: #arg_name.clone() })
247 }
248 } else {
249 Some(quote! { #arg_name })
250 }
251 });
252
253 let doc_attr = request.description.as_ref().map(description_to_doc_attr);
254
255 quote! {
256 #doc_attr
257 #[allow(clippy::too_many_arguments)]
258 pub fn #method_name(&self, #(#fn_args),*) {
259 let _ = self.send_event(
260 Event::#enum_variant {
261 #(#enum_args),*
262 }
263 );
264 }
265 }
266 })
267 .collect()
268}
269
270#[cfg(test)]
271mod tests {
272 #[test]
273 fn server_gen() {
274 let protocol_file =
275 std::fs::File::open("./tests/scanner_assets/test-protocol.xml").unwrap();
276 let protocol_parsed = crate::parse::parse(protocol_file);
277 let generated: String = super::generate_server_objects(&protocol_parsed).to_string();
278 let generated = crate::format_rust_code(&generated);
279
280 let reference =
281 std::fs::read_to_string("./tests/scanner_assets/test-server-code.rs").unwrap();
282 let reference = crate::format_rust_code(&reference);
283
284 if reference != generated {
285 let diff = similar::TextDiff::from_lines(&reference, &generated);
286 print!("{}", diff.unified_diff().context_radius(10).header("reference", "generated"));
287 panic!("Generated does not match reference!")
288 }
289 }
290}
291