1use zbus_names::BusName;
2
3use crate::{zvariant::ObjectPath, Connection, Error, Result};
4use std::convert::TryInto;
5
6/// A signal emission context.
7///
8/// For signal emission using the high-level API, you'll need instances of this type.
9///
10/// See [`crate::InterfaceRef::signal_context`] and [`crate::dbus_interface`]
11/// documentation for details and examples of this type in use.
12#[derive(Clone, Debug)]
13pub struct SignalContext<'s> {
14 conn: Connection,
15 path: ObjectPath<'s>,
16 destination: Option<BusName<'s>>,
17}
18
19impl<'s> SignalContext<'s> {
20 /// Create a new signal context for the given connection and object path.
21 pub fn new<P>(conn: &Connection, path: P) -> Result<Self>
22 where
23 P: TryInto<ObjectPath<'s>>,
24 P::Error: Into<Error>,
25 {
26 path.try_into()
27 .map(|p| Self {
28 conn: conn.clone(),
29 path: p,
30 destination: None,
31 })
32 .map_err(Into::into)
33 }
34
35 /// Create a new signal context for the given connection and object path.
36 pub fn from_parts(conn: Connection, path: ObjectPath<'s>) -> Self {
37 Self {
38 conn,
39 path,
40 destination: None,
41 }
42 }
43
44 /// Set the destination for the signal emission.
45 ///
46 /// Signals are typically broadcasted and thus don't have a destination. However, there are
47 /// cases where you need to unicast signals to specific peers. This method allows you to set the
48 /// destination for the signals emitted with this context.
49 pub fn set_destination(mut self, destination: BusName<'s>) -> Self {
50 self.destination = Some(destination);
51
52 self
53 }
54
55 /// Get a reference to the associated connection.
56 pub fn connection(&self) -> &Connection {
57 &self.conn
58 }
59
60 /// Get a reference to the associated object path.
61 pub fn path(&self) -> &ObjectPath<'s> {
62 &self.path
63 }
64
65 /// Get a reference to the associated destination (if any).
66 pub fn destination(&self) -> Option<&BusName<'s>> {
67 self.destination.as_ref()
68 }
69
70 /// Creates an owned clone of `self`.
71 pub fn to_owned(&self) -> SignalContext<'static> {
72 SignalContext {
73 conn: self.conn.clone(),
74 path: self.path.to_owned(),
75 destination: self.destination.as_ref().map(|d| d.to_owned()),
76 }
77 }
78
79 /// Creates an owned clone of `self`.
80 pub fn into_owned(self) -> SignalContext<'static> {
81 SignalContext {
82 conn: self.conn,
83 path: self.path.into_owned(),
84 destination: self.destination.map(|d| d.into_owned()),
85 }
86 }
87}
88