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 protocol
13 .interfaces
14 .iter()
15 .filter(|iface| 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 #[inline]
87 fn eq(&self, other: &#iface_name) -> bool {
88 self.id == other.id
89 }
90 }
91
92 impl std::cmp::Eq for #iface_name {}
93
94 impl PartialEq<Weak<#iface_name>> for #iface_name {
95 #[inline]
96 fn eq(&self, other: &Weak<#iface_name>) -> bool {
97 self.id == other.id()
98 }
99 }
100
101 impl std::borrow::Borrow<ObjectId> for #iface_name {
102 #[inline]
103 fn borrow(&self) -> &ObjectId {
104 &self.id
105 }
106 }
107
108 impl std::hash::Hash for #iface_name {
109 #[inline]
110 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
111 self.id.hash(state)
112 }
113 }
114
115 impl super::wayland_server::Resource for #iface_name {
116 type Request = Request;
117 type Event<'event> = Event<'event>;
118
119 #[inline]
120 fn interface() -> &'static Interface{
121 &super::#iface_const_name
122 }
123
124 #[inline]
125 fn id(&self) -> ObjectId {
126 self.id.clone()
127 }
128
129 #[inline]
130 fn version(&self) -> u32 {
131 self.version
132 }
133
134 #[inline]
135 fn data<U: 'static>(&self) -> Option<&U> {
136 self.data.as_ref().and_then(|arc| (&**arc).downcast_ref::<ResourceData<Self, U>>()).map(|data| &data.udata)
137 }
138
139 #[inline]
140 fn object_data(&self) -> Option<&Arc<dyn std::any::Any + Send + Sync>> {
141 self.data.as_ref()
142 }
143
144 fn handle(&self) -> &WeakHandle {
145 &self.handle
146 }
147
148 #[inline]
149 fn from_id(conn: &DisplayHandle, id: ObjectId) -> Result<Self, InvalidId> {
150 if !same_interface(id.interface(), Self::interface()) && !id.is_null(){
151 return Err(InvalidId)
152 }
153 let version = conn.object_info(id.clone()).map(|info| info.version).unwrap_or(0);
154 let data = conn.get_object_data(id.clone()).ok();
155 Ok(#iface_name { id, data, version, handle: conn.backend_handle().downgrade() })
156 }
157
158 fn send_event(&self, evt: Self::Event<'_>) -> Result<(), InvalidId> {
159 let handle = DisplayHandle::from(self.handle.upgrade().ok_or(InvalidId)?);
160 handle.send_event(self, evt)
161 }
162
163 fn parse_request(conn: &DisplayHandle, msg: Message<ObjectId, OwnedFd>) -> Result<(Self, Self::Request), DispatchError> {
164 #parse_body
165 }
166
167 fn write_event<'a>(&self, conn: &DisplayHandle, msg: Self::Event<'a>) -> Result<Message<ObjectId, std::os::unix::io::BorrowedFd<'a>>, InvalidId> {
168 #write_body
169 }
170
171 fn __set_object_data(&mut self, odata: std::sync::Arc<dyn std::any::Any + Send + Sync + 'static>) {
172 self.data = Some(odata);
173 }
174 }
175
176 impl #iface_name {
177 #methods
178 }
179 }
180 }
181}
182
183fn gen_methods(interface: &Interface) -> TokenStream {
184 interface
185 .events
186 .iter()
187 .map(|request| {
188 let method_name = format_ident!(
189 "{}{}",
190 if is_keyword(&request.name) { "_" } else { "" },
191 request.name
192 );
193 let enum_variant = Ident::new(&snake_to_camel(&request.name), Span::call_site());
194
195 let fn_args = request.args.iter().flat_map(|arg| {
196 let arg_name =
197 format_ident!("{}{}", if is_keyword(&arg.name) { "_" } else { "" }, arg.name);
198
199 let arg_type = if let Some(ref enu) = arg.enum_ {
200 let enum_type = dotted_to_relname(enu);
201 quote! { #enum_type }
202 } else {
203 match arg.typ {
204 Type::Uint => quote! { u32 },
205 Type::Int => quote! { i32 },
206 Type::Fixed => quote! { f64 },
207 Type::String => {
208 if arg.allow_null {
209 quote! { Option<String> }
210 } else {
211 quote! { String }
212 }
213 }
214 Type::Array => {
215 if arg.allow_null {
216 quote! { Option<Vec<u8>> }
217 } else {
218 quote! { Vec<u8> }
219 }
220 }
221 Type::Fd => quote! { ::std::os::unix::io::BorrowedFd<'_> },
222 Type::Object | Type::NewId => {
223 let iface = arg.interface.as_ref().unwrap();
224 let iface_mod = Ident::new(iface, Span::call_site());
225 let iface_type = Ident::new(&snake_to_camel(iface), Span::call_site());
226 if arg.allow_null {
227 quote! { Option<&super::#iface_mod::#iface_type> }
228 } else {
229 quote! { &super::#iface_mod::#iface_type }
230 }
231 }
232 Type::Destructor => panic!("An argument cannot have type \"destructor\"."),
233 }
234 };
235
236 Some(quote! {
237 #arg_name: #arg_type
238 })
239 });
240
241 let enum_args = request.args.iter().flat_map(|arg| {
242 let arg_name =
243 format_ident!("{}{}", if is_keyword(&arg.name) { "_" } else { "" }, arg.name);
244 if arg.enum_.is_some() {
245 Some(quote! { #arg_name: WEnum::Value(#arg_name) })
246 } else if arg.typ == Type::Object || arg.typ == Type::NewId {
247 if arg.allow_null {
248 Some(quote! { #arg_name: #arg_name.cloned() })
249 } else {
250 Some(quote! { #arg_name: #arg_name.clone() })
251 }
252 } else {
253 Some(quote! { #arg_name })
254 }
255 });
256
257 let doc_attr = request.description.as_ref().map(description_to_doc_attr);
258
259 quote! {
260 #doc_attr
261 #[allow(clippy::too_many_arguments)]
262 pub fn #method_name(&self, #(#fn_args),*) {
263 let _ = self.send_event(
264 Event::#enum_variant {
265 #(#enum_args),*
266 }
267 );
268 }
269 }
270 })
271 .collect()
272}
273
274#[cfg(test)]
275mod tests {
276 #[test]
277 fn server_gen() {
278 let protocol_file =
279 std::fs::File::open("./tests/scanner_assets/test-protocol.xml").unwrap();
280 let protocol_parsed = crate::parse::parse(protocol_file);
281 let generated: String = super::generate_server_objects(&protocol_parsed).to_string();
282 let generated = crate::format_rust_code(&generated);
283
284 let reference =
285 std::fs::read_to_string("./tests/scanner_assets/test-server-code.rs").unwrap();
286 let reference = crate::format_rust_code(&reference);
287
288 if reference != generated {
289 let diff = similar::TextDiff::from_lines(&reference, &generated);
290 print!("{}", diff.unified_diff().context_radius(10).header("reference", "generated"));
291 panic!("Generated does not match reference!")
292 }
293 }
294}