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