zbus_macros/
lib.rs

1#![deny(rust_2018_idioms)]
2#![doc(
3    html_logo_url = "https://raw.githubusercontent.com/z-galaxy/zbus/9f7a90d2b594ddc48b7a5f39fda5e00cd56a7dfb/logo.png"
4)]
5#![doc = include_str!("../README.md")]
6#![doc(test(attr(
7    warn(unused),
8    deny(warnings),
9    allow(dead_code),
10    // W/o this, we seem to get some bogus warning about `extern crate zbus`.
11    allow(unused_extern_crates),
12)))]
13
14use proc_macro::TokenStream;
15use syn::{
16    parse_macro_input, punctuated::Punctuated, DeriveInput, ItemImpl, ItemTrait, Meta, Token,
17};
18
19mod error;
20mod iface;
21mod proxy;
22mod utils;
23
24/// Attribute macro for defining D-Bus proxies (using [`zbus::Proxy`] and
25/// [`zbus::blocking::Proxy`]).
26///
27/// The macro must be applied on a `trait T`. Two matching `impl T` will provide an asynchronous
28/// Proxy implementation, named `TraitNameProxy` and a blocking one, named `TraitNameProxyBlocking`.
29/// The proxy instances can be created with the associated `new()` or `builder()` methods. The
30/// former doesn't take any argument and uses the default service name and path. The later allows
31/// you to specify non-default proxy arguments.
32///
33/// The following attributes are supported:
34///
35/// * `interface` - the name of the D-Bus interface this proxy is for.
36///
37/// * `default_service` - the default service this proxy should connect to.
38///
39/// * `default_path` - The default object path the method calls will be sent on and signals will be
40///   sent for by the target service.
41///
42/// * `gen_async` - Whether or not to generate the asynchronous Proxy type.
43///
44/// * `gen_blocking` - Whether or not to generate the blocking Proxy type. If the `blocking-api`
45///   cargo feature is disabled, this attribute is ignored and blocking Proxy type is not generated.
46///
47/// * `async_name` - Specify the exact name of the asynchronous proxy type.
48///
49/// * `blocking_name` - Specify the exact name of the blocking proxy type.
50///
51/// * `assume_defaults` - whether to auto-generate values for `default_path` and `default_service`
52///   if none are specified (default: `false`). `proxy` generates a warning if neither this
53///   attribute nor one of the default values are specified. Please make sure to explicitly set
54///   either this attribute or the default values, according to your needs.
55///
56/// Each trait method will be expanded to call to the associated D-Bus remote interface.
57///
58/// Trait methods accept `proxy` attributes:
59///
60/// * `name` - override the D-Bus name (pascal case form by default)
61///
62/// * `property` - expose the method as a property. If the method takes an argument, it must be a
63///   setter, with a `set_` prefix. Otherwise, it's a getter. Additional sub-attributes exists to
64///   control specific property behaviors:
65///   * `emits_changed_signal` - specifies how property changes are signaled. Valid values are those
66///     documented in [DBus specifications][dbus_emits_changed_signal]:
67///     * `"true"` - (default) change signal is always emitted with the value included. This uses
68///       the default caching behavior of the proxy, and generates a listener method for the change
69///       signal.
70///     * `"invalidates"` - change signal is emitted, but the value is not included in the signal.
71///       This has the same behavior as `"true"`.
72///     * `"const"` - property never changes, thus no signal is ever emitted for it. This uses the
73///       default caching behavior of the proxy, but does not generate a listener method for the
74///       change signal.
75///     * `"false"` - change signal is not (guaranteed to be) emitted if the property changes. This
76///       disables property value caching, and does not generate a listener method for the change
77///       signal.
78///
79/// * `signal` - declare a signal just like a D-Bus method. Read the [Signals](#signals) section
80///   below for details.
81///
82/// * `no_reply` - declare a method call that does not wait for a reply.
83///
84/// * `no_autostart` - declare a method call that will not trigger the bus to automatically launch
85///   the destination service if it is not already running.
86///
87/// * `allow_interactive_auth` - declare a method call that is allowed to trigger an interactive
88///   prompt for authorization or confirmation from the receiver.
89///
90/// * `object` - methods that returns an [`ObjectPath`] can be annotated with the `object` attribute
91///   to specify the proxy object to be constructed from the returned [`ObjectPath`].
92///
93/// * `async_object` - if the assumptions made by `object` attribute about naming of the
94///   asynchronous proxy type, don't fit your bill, you can use this to specify its exact name.
95///
96/// * `blocking_object` - if the assumptions made by `object` attribute about naming of the blocking
97///   proxy type, don't fit your bill, you can use this to specify its exact name.
98///
99///   NB: Any doc comments provided shall be appended to the ones added by the macro.
100///
101/// # Signals
102///
103/// For each signal method declared, this macro will provide a method, named `receive_<method_name>`
104/// to create a [`zbus::SignalStream`] ([`zbus::blocking::SignalIterator`] for the blocking proxy)
105/// wrapper, named `<SignalName>Stream` (`<SignalName>Iterator` for the blocking proxy) that yield
106/// a [`zbus::message::Message`] wrapper, named `<SignalName>`. This wrapper provides type safe
107/// access to the signal arguments. It also implements `Deref<Target = Message>` to allow easy
108/// access to the underlying [`zbus::message::Message`].
109///
110/// For each property with `emits_changed_signal` set to `"true"` (default) or `"invalidates"`,
111/// this macro will provide a method named `receive_<property_name>_changed` that creates a
112/// [`zbus::proxy::PropertyStream`] for the property.
113///
114/// # Example
115///
116/// ```no_run
117/// # use std::error::Error;
118/// use zbus_macros::proxy;
119/// use zbus::{blocking::Connection, Result, fdo, zvariant::Value};
120/// use futures_util::stream::StreamExt;
121/// use async_io::block_on;
122///
123/// #[proxy(
124///     interface = "org.test.SomeIface",
125///     default_service = "org.test.SomeService",
126///     default_path = "/org/test/SomeObject"
127/// )]
128/// trait SomeIface {
129///     fn do_this(&self, with: &str, some: u32, arg: &Value<'_>) -> Result<bool>;
130///
131///     #[zbus(property)]
132///     fn a_property(&self) -> fdo::Result<String>;
133///
134///     #[zbus(property)]
135///     fn set_a_property(&self, a_property: &str) -> fdo::Result<()>;
136///
137///     #[zbus(signal)]
138///     fn some_signal(&self, arg1: &str, arg2: u32) -> fdo::Result<()>;
139///
140///     #[zbus(object = "SomeOtherIface", blocking_object = "SomeOtherInterfaceBlock")]
141///     // The method will return a `SomeOtherIfaceProxy` or `SomeOtherIfaceProxyBlock`, depending
142///     // on whether it is called on `SomeIfaceProxy` or `SomeIfaceProxyBlocking`, respectively.
143///     //
144///     // NB: We explicitly specified the exact name of the blocking proxy type. If we hadn't,
145///     // `SomeOtherIfaceProxyBlock` would have been assumed and expected. We could also specify
146///     // the specific name of the asynchronous proxy types, using the `async_object` attribute.
147///     fn some_method(&self, arg1: &str);
148/// }
149///
150/// #[proxy(
151///     interface = "org.test.SomeOtherIface",
152///     default_service = "org.test.SomeOtherService",
153///     blocking_name = "SomeOtherInterfaceBlock",
154/// )]
155/// trait SomeOtherIface {}
156///
157/// let connection = Connection::session()?;
158/// // Use `builder` to override the default arguments, `new` otherwise.
159/// let proxy = SomeIfaceProxyBlocking::builder(&connection)
160///                .destination("org.another.Service")?
161///                .cache_properties(zbus::proxy::CacheProperties::No)
162///                .build()?;
163/// let _ = proxy.do_this("foo", 32, &Value::new(true));
164/// let _ = proxy.set_a_property("val");
165///
166/// let signal = proxy.receive_some_signal()?.next().unwrap();
167/// let args = signal.args()?;
168/// println!("arg1: {}, arg2: {}", args.arg1(), args.arg2());
169///
170/// // Now the same again, but asynchronous.
171/// block_on(async move {
172///     let proxy = SomeIfaceProxy::builder(&connection.into())
173///                    .cache_properties(zbus::proxy::CacheProperties::No)
174///                    .build()
175///                    .await
176///                    .unwrap();
177///     let _ = proxy.do_this("foo", 32, &Value::new(true)).await;
178///     let _ = proxy.set_a_property("val").await;
179///
180///     let signal = proxy.receive_some_signal().await?.next().await.unwrap();
181///     let args = signal.args()?;
182///     println!("arg1: {}, arg2: {}", args.arg1(), args.arg2());
183///
184///     Ok::<(), zbus::Error>(())
185/// })?;
186///
187/// # Ok::<_, Box<dyn Error + Send + Sync>>(())
188/// ```
189///
190/// [`zbus_polkit`] is a good example of how to bind a real D-Bus API.
191///
192/// [`zbus_polkit`]: https://docs.rs/zbus_polkit/1.0.0/zbus_polkit/policykit1/index.html
193/// [`zbus::Proxy`]: https://docs.rs/zbus/latest/zbus/proxy/struct.Proxy.html
194/// [`zbus::message::Message`]: https://docs.rs/zbus/latest/zbus/message/struct.Message.html
195/// [`zbus::proxy::PropertyStream`]: https://docs.rs/zbus/latest/zbus/proxy/struct.PropertyStream.html
196/// [`zbus::blocking::Proxy`]: https://docs.rs/zbus/latest/zbus/blocking/proxy/struct.Proxy.html
197/// [`zbus::SignalStream`]: https://docs.rs/zbus/latest/zbus/proxy/struct.SignalStream.html
198/// [`zbus::blocking::SignalIterator`]: https://docs.rs/zbus/latest/zbus/blocking/proxy/struct.SignalIterator.html
199/// [`ObjectPath`]: https://docs.rs/zvariant/latest/zvariant/struct.ObjectPath.html
200/// [dbus_emits_changed_signal]: https://dbus.freedesktop.org/doc/dbus-specification.html#introspection-format
201#[proc_macro_attribute]
202pub fn proxy(attr: TokenStream, item: TokenStream) -> TokenStream {
203    let args = parse_macro_input!(attr with Punctuated<Meta, Token![,]>::parse_terminated);
204    let input = parse_macro_input!(item as ItemTrait);
205    proxy::expand(args, input)
206        .unwrap_or_else(|err| err.to_compile_error())
207        .into()
208}
209
210/// Attribute macro for implementing a D-Bus interface.
211///
212/// The macro must be applied on an `impl T`. All methods will be exported, either as methods,
213/// properties or signal depending on the item attributes. It will implement the [`Interface`] trait
214/// `for T` on your behalf, to handle the message dispatching and introspection support.
215///
216/// The trait accepts the `interface` attributes:
217///
218/// * `name` - the D-Bus interface name
219///
220/// * `spawn` - Controls the spawning of tasks for method calls. By default, `true`, allowing zbus
221///   to spawn a separate task for each method call. This default behavior can lead to methods being
222///   handled out of their received order, which might not always align with expected or desired
223///   behavior.
224///
225///   - **When True (Default):** Suitable for interfaces where method calls are independent of each
226///     other or can be processed asynchronously without strict ordering. In scenarios where a
227///     client must wait for a reply before making further dependent calls, this default behavior is
228///     appropriate.
229///
230///   - **When False:** Use this setting to ensure methods are handled in the order they are
231///     received, which is crucial for interfaces requiring sequential processing of method calls.
232///     However, care must be taken to avoid making D-Bus method calls from within your interface
233///     methods when this setting is false, as it may lead to deadlocks under certain conditions.
234///
235/// * `proxy` - If specified, a proxy type will also be generated for the interface. This attribute
236///   supports all the [`macro@proxy`]-specific sub-attributes (e.g `gen_async`). The common
237///   sub-attributes (e.g `name`) are automatically forwarded to the [`macro@proxy`] macro.
238///
239/// * `introspection_docs` - whether to include the documentation in the introspection data
240///   (Default: `true`). If your interface is well-known or well-documented, you may want to set
241///   this to `false` to reduce the the size of your binary and D-Bus traffic.
242///
243/// The methods accepts the `interface` attributes:
244///
245/// * `name` - override the D-Bus name (pascal case form of the method by default)
246///
247/// * `property` - expose the method as a property. If the method takes an argument, it must be a
248///   setter, with a `set_` prefix. Otherwise, it's a getter. If it may fail, a property method must
249///   return `zbus::fdo::Result`. An additional sub-attribute exists to control the emission of
250///   signals on changes to the property:
251///   * `emits_changed_signal` - specifies how property changes are signaled. Valid values are those
252///     documented in [DBus specifications][dbus_emits_changed_signal]:
253///     * `"true"` - (default) the change signal is always emitted when the property's setter is
254///       called. The value of the property is included in the signal.
255///     * `"invalidates"` - the change signal is emitted, but the value is not included in the
256///       signal.
257///     * `"const"` - the property never changes, thus no signal is ever emitted for it.
258///     * `"false"` - the change signal is not emitted if the property changes. If a property is
259///       write-only, the change signal will not be emitted in this interface.
260///
261/// * `signal` - the method is a "signal". It must be a method declaration (without body). Its code
262///   block will be expanded to emit the signal from the object path associated with the interface
263///   instance. Moreover, `interface` will also generate a trait named `<Interface>Signals` that
264///   provides all the signal methods but without the `SignalEmitter` argument. The macro implements
265///   this trait for two types, `zbus::object_server::InterfaceRef<Interface>` and
266///   `SignalEmitter<'_>`. The former is useful for emitting signals from outside the context of an
267///   interface method and the latter is useful for emitting signals from inside interface methods.
268///
269///   You can call a signal method from a an interface method, or from an [`ObjectServer::with`]
270///   function.
271///
272/// * `out_args` - When returning multiple values from a method, naming the out arguments become
273///   important. You can use `out_args` to specify their names.
274///
275/// * `proxy` - Use this to specify the [`macro@proxy`]-specific method sub-attributes (e.g
276///   `object`). The common sub-attributes (e.g `name`) are automatically forworded to the
277///   [`macro@proxy`] macro. Moreover, you can use `visibility` sub-attribute to specify the
278///   visibility of the generated proxy type(s).
279///
280///   In such case, your method must return a tuple containing
281///   your out arguments, in the same order as passed to `out_args`.
282///
283/// The `struct_return` attribute (from zbus 1.x) is no longer supported. If you want to return a
284/// single structure from a method, declare it to return a tuple containing either a named structure
285/// or a nested tuple.
286///
287/// Note: a `<property_name_in_snake_case>_changed` method is generated for each property: this
288/// method emits the "PropertiesChanged" signal for the associated property. The setter (if it
289/// exists) will automatically call this method. For instance, a property setter named `set_foo`
290/// will be called to set the property "Foo", and will emit the "PropertiesChanged" signal with the
291/// new value for "Foo". Other changes to the "Foo" property can be signaled manually with the
292/// generated `foo_changed` method. In addition, a `<property_name_in_snake_case>_invalidated`
293/// method is also generated that much like `_changed` method, emits a "PropertyChanged" signal
294/// but does not send over the new value of the property along with it. It is usually best to avoid
295/// using this since it will force all interested peers to fetch the new value and hence result in
296/// excess traffic on the bus.
297///
298/// The method arguments support the following `zbus` attributes:
299///
300/// * `object_server` - This marks the method argument to receive a reference to the
301///   [`ObjectServer`] this method was called by.
302/// * `connection` - This marks the method argument to receive a reference to the [`Connection`] on
303///   which the method call was received.
304/// * `header` - This marks the method argument to receive the message header associated with the
305///   D-Bus method call being handled. For property methods, this will be an `Option<Header<'_>>`,
306///   which will be set to `None` if the method is called for reasons other than to respond to an
307///   external property access.
308/// * `signal_emitter` - This marks the method argument to receive a [`SignalEmitter`] instance,
309///   which is needed for emitting signals the easy way.
310///
311/// # Example
312///
313/// ```
314/// # use std::error::Error;
315/// use zbus_macros::interface;
316/// use zbus::{ObjectServer, object_server::SignalEmitter, message::Header};
317///
318/// struct Example {
319///     _some_data: String,
320/// }
321///
322/// #[interface(name = "org.myservice.Example")]
323/// impl Example {
324///     // "Quit" method. A method may throw errors.
325///     async fn quit(
326///         &self,
327///         #[zbus(header)]
328///         hdr: Header<'_>,
329///         #[zbus(signal_emitter)]
330///         emitter: SignalEmitter<'_>,
331///         #[zbus(object_server)]
332///         _server: &ObjectServer,
333///     ) -> zbus::fdo::Result<()> {
334///         let path = hdr.path().unwrap();
335///         let msg = format!("You are leaving me on the {} path?", path);
336///         emitter.bye(&msg).await?;
337///
338///         // Do some asynchronous tasks before quitting..
339///
340///         Ok(())
341///     }
342///
343///     // "TheAnswer" property (note: the "name" attribute), with its associated getter.
344///     // A `the_answer_changed` method has also been generated to emit the
345///     // "PropertiesChanged" signal for this property.
346///     #[zbus(property, name = "TheAnswer")]
347///     fn answer(&self) -> u32 {
348///         2 * 3 * 7
349///     }
350///
351///     // "IFail" property with its associated getter.
352///     // An `i_fail_changed` method has also been generated to emit the
353///     // "PropertiesChanged" signal for this property.
354///     #[zbus(property)]
355///     fn i_fail(&self) -> zbus::fdo::Result<i32> {
356///         Err(zbus::fdo::Error::UnknownProperty("IFail".into()))
357///     }
358///
359///     // "Bye" signal (note: no implementation body).
360///     #[zbus(signal)]
361///     async fn bye(signal_emitter: &SignalEmitter<'_>, message: &str) -> zbus::Result<()>;
362///
363///     #[zbus(out_args("answer", "question"))]
364///     fn meaning_of_life(&self) -> zbus::fdo::Result<(i32, String)> {
365///         Ok((42, String::from("Meaning of life")))
366///     }
367/// }
368///
369/// # Ok::<_, Box<dyn Error + Send + Sync>>(())
370/// ```
371///
372/// See also [`ObjectServer`] documentation to learn how to export an interface over a `Connection`.
373///
374/// [`ObjectServer`]: https://docs.rs/zbus/latest/zbus/object_server/struct.ObjectServer.html
375/// [`ObjectServer::with`]: https://docs.rs/zbus/latest/zbus/object_server/struct.ObjectServer.html#method.with
376/// [`Connection`]: https://docs.rs/zbus/latest/zbus/connection/struct.Connection.html
377/// [`Connection::emit_signal()`]: https://docs.rs/zbus/latest/zbus/connection/struct.Connection.html#method.emit_signal
378/// [`SignalEmitter`]: https://docs.rs/zbus/latest/zbus/object_server/struct.SignalEmitter.html
379/// [`Interface`]: https://docs.rs/zbus/latest/zbus/object_server/trait.Interface.html
380/// [dbus_emits_changed_signal]: https://dbus.freedesktop.org/doc/dbus-specification.html#introspection-format
381#[proc_macro_attribute]
382pub fn interface(attr: TokenStream, item: TokenStream) -> TokenStream {
383    let args = parse_macro_input!(attr with Punctuated<Meta, Token![,]>::parse_terminated);
384    let input = parse_macro_input!(item as ItemImpl);
385    iface::expand(args, input)
386        .unwrap_or_else(|err| err.to_compile_error())
387        .into()
388}
389
390/// Derive macro for implementing [`zbus::DBusError`] trait.
391///
392/// This macro makes it easy to implement the [`zbus::DBusError`] trait for your custom error type
393/// (currently only enums are supported).
394///
395/// If a special variant marked with the `zbus` attribute is present, `From<zbus::Error>` is
396/// also implemented for your type. This variant can only have a single unnamed field of type
397/// [`zbus::Error`]. This implementation makes it possible for you to declare proxy methods to
398/// directly return this type, rather than [`zbus::Error`].
399///
400/// Each variant (except for the special `zbus` one) can optionally have a (named or unnamed)
401/// `String` field (which is used as the human-readable error description).
402///
403/// # Example
404///
405/// ```
406/// use zbus_macros::DBusError;
407///
408/// #[derive(DBusError, Debug)]
409/// #[zbus(prefix = "org.myservice.App")]
410/// enum Error {
411///     #[zbus(error)]
412///     ZBus(zbus::Error),
413///     FileNotFound(String),
414///     OutOfMemory,
415/// }
416/// ```
417///
418/// [`zbus::DBusError`]: https://docs.rs/zbus/latest/zbus/trait.DBusError.html
419/// [`zbus::Error`]: https://docs.rs/zbus/latest/zbus/enum.Error.html
420/// [`zvariant::Type`]: https://docs.rs/zvariant/latest/zvariant/trait.Type.html
421/// [`serde::Serialize`]: https://docs.rs/serde/1.0.132/serde/trait.Serialize.html
422#[proc_macro_derive(DBusError, attributes(zbus))]
423pub fn derive_dbus_error(input: TokenStream) -> TokenStream {
424    let input = parse_macro_input!(input as DeriveInput);
425    error::expand_derive(input)
426        .unwrap_or_else(|err| err.to_compile_error())
427        .into()
428}