File: dbus_peer.rs

package info (click to toggle)
rust-gio 0.20.9-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,628 kB
  • sloc: makefile: 35; xml: 11
file content (223 lines) | stat: -rw-r--r-- 6,604 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
// Take a look at the license at the top of the repository in the LICENSE file.

#[cfg(unix)]
#[test]
fn test_gdbus_peer_connection() {
    use gio::{
        glib::{self, VariantTy},
        prelude::*,
        DBusConnection, DBusConnectionFlags, DBusNodeInfo, Socket,
    };
    use std::os::{fd::IntoRawFd, unix::net::UnixStream};

    const EXAMPLE_XML: &str = r#"
  <node>
    <interface name='com.github.gtk_rs'>
      <property type='i' name='Number' access='readwrite' />
      <method name='Hello'>
        <arg type='s' name='name' direction='in'/>
        <arg type='s' name='greet' direction='out'/>
      </method>
    </interface>
  </node>
"#;

    pub async fn spawn_server(fd: UnixStream) -> DBusConnection {
        let socket = unsafe { Socket::from_fd(fd.into_raw_fd()) }.unwrap();
        let socket_connection = socket.connection_factory_create_connection();

        let guid = gio::dbus_generate_guid();

        dbg!("server connecting");

        let connection = DBusConnection::new_future(
            &socket_connection,
            Some(&guid),
            DBusConnectionFlags::AUTHENTICATION_SERVER
                .union(DBusConnectionFlags::DELAY_MESSAGE_PROCESSING),
            None,
        )
        .await
        .unwrap();

        dbg!("server connected");

        let interface_info = DBusNodeInfo::for_xml(EXAMPLE_XML)
            .unwrap()
            .lookup_interface("com.github.gtk_rs")
            .unwrap();

        let _id = connection
            .register_object("/com/github/gtk_rs", &interface_info)
            .method_call(
                |_connection,
                 _sender,
                 _object_path,
                 _interface_name,
                 _method_name,
                 parameters,
                 invocation| {
                    dbg!(
                        "method_call",
                        _sender,
                        _object_path,
                        _interface_name,
                        _method_name,
                        &parameters,
                        &invocation
                    );

                    let name = parameters.child_get::<String>(0);
                    invocation.return_value(Some(&(format!("Hello {name}!"),).to_variant()));
                },
            )
            .property({
                |_connection, _sender, _object_path, _interface_name, _property_name| {
                    dbg!(
                        "get_property",
                        _sender,
                        _object_path,
                        _interface_name,
                        _property_name
                    );
                    assert_eq!(_property_name, "Number");
                    123.to_variant()
                }
            })
            .set_property({
                |_connection, _sender, _object_path, _interface_name, _property_name, _value| {
                    dbg!(
                        "set_property",
                        _sender,
                        _object_path,
                        _interface_name,
                        _property_name,
                        &_value
                    );
                    assert_eq!(_property_name, "Number");
                    assert_eq!(_value, 456.to_variant());
                    true
                }
            })
            .build()
            .unwrap();

        dbg!("server starts message processing");

        connection.start_message_processing();

        dbg!("server awaiting calls");

        connection
    }

    pub async fn spawn_client(fd: UnixStream) -> DBusConnection {
        let socket_client = unsafe { Socket::from_fd(fd.into_raw_fd()) }.unwrap();
        let socket_connection_client = socket_client.connection_factory_create_connection();

        dbg!("client connecting");

        let connection = DBusConnection::new_future(
            &socket_connection_client,
            None,
            DBusConnectionFlags::AUTHENTICATION_CLIENT,
            None,
        )
        .await
        .unwrap();

        dbg!("client connected");

        connection
    }

    let ctx = glib::MainContext::default();

    let (x, y) = std::os::unix::net::UnixStream::pair().unwrap();

    x.set_nonblocking(true).unwrap();
    y.set_nonblocking(true).unwrap();

    ctx.block_on(async move {
        let ctx = glib::MainContext::default();

        let server = ctx.spawn_local(spawn_server(x));
        let client = ctx.spawn_local(spawn_client(y));

        let server = server.await.unwrap();
        let client = client.await.unwrap();

        dbg!("calling method");

        let result = client
            .call_future(
                None,
                "/com/github/gtk_rs",
                "com.github.gtk_rs",
                "Hello",
                Some(&("World",).into()),
                Some(VariantTy::new("(s)").unwrap()),
                gio::DBusCallFlags::NONE,
                10000,
            )
            .await
            .unwrap();

        dbg!("method called");

        dbg!(&result);

        dbg!("getting property");

        let getresult = client
            .call_future(
                None,
                "/com/github/gtk_rs",
                "org.freedesktop.DBus.Properties",
                "Get",
                Some(&("com.github.gtk_rs", "Number").to_variant()),
                Some(VariantTy::new("(v)").unwrap()),
                gio::DBusCallFlags::NONE,
                10000,
            )
            .await
            .unwrap();

        assert_eq!(getresult, (123.to_variant(),).to_variant());

        dbg!("setting property");

        let setresult = client
            .call_future(
                None,
                "/com/github/gtk_rs",
                "org.freedesktop.DBus.Properties",
                "Set",
                Some(&("com.github.gtk_rs", "Number", 456.to_variant()).to_variant()),
                None,
                gio::DBusCallFlags::NONE,
                10000,
            )
            .await
            .unwrap();

        assert_eq!(setresult, ().to_variant());

        dbg!("closing client");
        client.close_future().await.unwrap();
        dbg!("closed client, closing server");
        server.close_future().await.unwrap();
        dbg!("closed server");

        drop(client);
        drop(server);

        assert_eq!(result.child_get::<String>(0), "Hello World!");

        glib::timeout_future_with_priority(
            glib::Priority::LOW,
            std::time::Duration::from_millis(50),
        )
        .await;
    });
}