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