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