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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT

#[cfg(any(unix, feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(unix)))]
use crate::UnixFDList;
use crate::{
    AsyncInitable, AsyncResult, Cancellable, Credentials, DBusAuthObserver, DBusCallFlags,
    DBusCapabilityFlags, DBusConnectionFlags, DBusMessage, DBusSendMessageFlags, IOStream,
    Initable,
};
use glib::{
    prelude::*,
    signal::{connect_raw, SignalHandlerId},
    translate::*,
};
use std::{boxed::Box as Box_, fmt, mem, mem::transmute, pin::Pin, ptr};

glib::wrapper! {
    /// The [`DBusConnection`][crate::DBusConnection] type is used for D-Bus connections to remote
    /// peers such as a message buses. It is a low-level API that offers a
    /// lot of flexibility. For instance, it lets you establish a connection
    /// over any transport that can by represented as a [`IOStream`][crate::IOStream].
    ///
    /// This class is rarely used directly in D-Bus clients. If you are writing
    /// a D-Bus client, it is often easier to use the `g_bus_own_name()`,
    /// `g_bus_watch_name()` or [`DBusProxy::for_bus()`][crate::DBusProxy::for_bus()] APIs.
    ///
    /// As an exception to the usual GLib rule that a particular object must not
    /// be used by two threads at the same time, [`DBusConnection`][crate::DBusConnection]'s methods may be
    /// called from any thread. This is so that [`bus_get()`][crate::bus_get()] and [`bus_get_sync()`][crate::bus_get_sync()]
    /// can safely return the same [`DBusConnection`][crate::DBusConnection] when called from any thread.
    ///
    /// Most of the ways to obtain a [`DBusConnection`][crate::DBusConnection] automatically initialize it
    /// (i.e. connect to D-Bus): for instance, [`new()`][Self::new()] and
    /// [`bus_get()`][crate::bus_get()], and the synchronous versions of those methods, give you an
    /// initialized connection. Language bindings for GIO should use
    /// [`Initable::new()`][crate::Initable::new()] or [`AsyncInitable::new_async()`][crate::AsyncInitable::new_async()], which also initialize the
    /// connection.
    ///
    /// If you construct an uninitialized [`DBusConnection`][crate::DBusConnection], such as via
    /// [`glib::Object::new()`][crate::glib::Object::new()], you must initialize it via [`InitableExt::init()`][crate::prelude::InitableExt::init()] or
    /// [`AsyncInitableExt::init_async()`][crate::prelude::AsyncInitableExt::init_async()] before using its methods or properties.
    /// Calling methods or accessing properties on a [`DBusConnection`][crate::DBusConnection] that has not
    /// completed initialization successfully is considered to be invalid, and leads
    /// to undefined behaviour. In particular, if initialization fails with a
    /// [`glib::Error`][crate::glib::Error], the only valid thing you can do with that [`DBusConnection`][crate::DBusConnection] is to
    /// free it with `g_object_unref()`.
    ///
    /// ## An example D-Bus server # {`gdbus`-server}
    ///
    /// Here is an example for a D-Bus server:
    /// [gdbus-example-server.c](https://gitlab.gnome.org/GNOME/glib/-/blob/HEAD/gio/tests/gdbus-example-server.c)
    ///
    /// ## An example for exporting a subtree # {`gdbus`-subtree-server}
    ///
    /// Here is an example for exporting a subtree:
    /// [gdbus-example-subtree.c](https://gitlab.gnome.org/GNOME/glib/-/blob/HEAD/gio/tests/gdbus-example-subtree.c)
    ///
    /// ## An example for file descriptor passing # {`gdbus`-unix-fd-client}
    ///
    /// Here is an example for passing UNIX file descriptors:
    /// [gdbus-unix-fd-client.c](https://gitlab.gnome.org/GNOME/glib/-/blob/HEAD/gio/tests/gdbus-example-unix-fd-client.c)
    ///
    /// ## An example for exporting a GObject # {`gdbus`-export}
    ///
    /// Here is an example for exporting a [`glib::Object`][crate::glib::Object]:
    /// [gdbus-example-export.c](https://gitlab.gnome.org/GNOME/glib/-/blob/HEAD/gio/tests/gdbus-example-export.c)
    ///
    /// ## Properties
    ///
    ///
    /// #### `address`
    ///  A D-Bus address specifying potential endpoints that can be used
    /// when establishing the connection.
    ///
    /// Writeable | Construct Only
    ///
    ///
    /// #### `authentication-observer`
    ///  A [`DBusAuthObserver`][crate::DBusAuthObserver] object to assist in the authentication process or [`None`].
    ///
    /// Writeable | Construct Only
    ///
    ///
    /// #### `capabilities`
    ///  Flags from the [`DBusCapabilityFlags`][crate::DBusCapabilityFlags] enumeration
    /// representing connection features negotiated with the other peer.
    ///
    /// Readable
    ///
    ///
    /// #### `closed`
    ///  A boolean specifying whether the connection has been closed.
    ///
    /// Readable
    ///
    ///
    /// #### `exit-on-close`
    ///  A boolean specifying whether the process will be terminated (by
    /// calling `raise(SIGTERM)`) if the connection is closed by the
    /// remote peer.
    ///
    /// Note that [`DBusConnection`][crate::DBusConnection] objects returned by `g_bus_get_finish()`
    /// and [`bus_get_sync()`][crate::bus_get_sync()] will (usually) have this property set to [`true`].
    ///
    /// Readable | Writeable
    ///
    ///
    /// #### `flags`
    ///  Flags from the [`DBusConnectionFlags`][crate::DBusConnectionFlags] enumeration.
    ///
    /// Readable | Writeable | Construct Only
    ///
    ///
    /// #### `guid`
    ///  The GUID of the peer performing the role of server when
    /// authenticating.
    ///
    /// If you are constructing a [`DBusConnection`][crate::DBusConnection] and pass
    /// [`DBusConnectionFlags::AUTHENTICATION_SERVER`][crate::DBusConnectionFlags::AUTHENTICATION_SERVER] in the
    /// [`flags`][struct@crate::DBusConnection#flags] property then you **must** also set this
    /// property to a valid guid.
    ///
    /// If you are constructing a [`DBusConnection`][crate::DBusConnection] and pass
    /// [`DBusConnectionFlags::AUTHENTICATION_CLIENT`][crate::DBusConnectionFlags::AUTHENTICATION_CLIENT] in the
    /// [`flags`][struct@crate::DBusConnection#flags] property you will be able to read the GUID
    /// of the other peer here after the connection has been successfully
    /// initialized.
    ///
    /// Note that the
    /// [D-Bus specification](https://dbus.freedesktop.org/doc/dbus-specification.html`addresses`)
    /// uses the term ‘UUID’ to refer to this, whereas GLib consistently uses the
    /// term ‘GUID’ for historical reasons.
    ///
    /// Despite its name, the format of [`guid`][struct@crate::DBusConnection#guid] does not follow
    /// [RFC 4122](https://datatracker.ietf.org/doc/html/rfc4122) or the Microsoft
    /// GUID format.
    ///
    /// Readable | Writeable | Construct Only
    ///
    ///
    /// #### `stream`
    ///  The underlying [`IOStream`][crate::IOStream] used for I/O.
    ///
    /// If this is passed on construction and is a [`SocketConnection`][crate::SocketConnection],
    /// then the corresponding [`Socket`][crate::Socket] will be put into non-blocking mode.
    ///
    /// While the [`DBusConnection`][crate::DBusConnection] is active, it will interact with this
    /// stream from a worker thread, so it is not safe to interact with
    /// the stream directly.
    ///
    /// Readable | Writeable | Construct Only
    ///
    ///
    /// #### `unique-name`
    ///  The unique name as assigned by the message bus or [`None`] if the
    /// connection is not open or not a message bus connection.
    ///
    /// Readable
    ///
    /// ## Signals
    ///
    ///
    /// #### `closed`
    ///  Emitted when the connection is closed.
    ///
    /// The cause of this event can be
    ///
    /// - If [`DBusConnection::close()`][crate::DBusConnection::close()] is called. In this case
    ///  `remote_peer_vanished` is set to [`false`] and `error` is [`None`].
    ///
    /// - If the remote peer closes the connection. In this case
    ///  `remote_peer_vanished` is set to [`true`] and `error` is set.
    ///
    /// - If the remote peer sends invalid or malformed data. In this
    ///  case `remote_peer_vanished` is set to [`false`] and `error` is set.
    ///
    /// Upon receiving this signal, you should give up your reference to
    /// `connection`. You are guaranteed that this signal is emitted only
    /// once.
    ///
    ///
    ///
    /// # Implements
    ///
    /// [`trait@glib::ObjectExt`], [`AsyncInitableExt`][trait@crate::prelude::AsyncInitableExt], [`InitableExt`][trait@crate::prelude::InitableExt]
    #[doc(alias = "GDBusConnection")]
    pub struct DBusConnection(Object<ffi::GDBusConnection>) @implements AsyncInitable, Initable;

    match fn {
        type_ => || ffi::g_dbus_connection_get_type(),
    }
}

impl DBusConnection {
    /// Synchronously connects and sets up a D-Bus client connection for
    /// exchanging D-Bus messages with an endpoint specified by `address`
    /// which must be in the
    /// [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html`addresses`).
    ///
    /// This constructor can only be used to initiate client-side
    /// connections - use [`new_sync()`][Self::new_sync()] if you need to act
    /// as the server. In particular, `flags` cannot contain the
    /// [`DBusConnectionFlags::AUTHENTICATION_SERVER`][crate::DBusConnectionFlags::AUTHENTICATION_SERVER],
    /// [`DBusConnectionFlags::AUTHENTICATION_ALLOW_ANONYMOUS`][crate::DBusConnectionFlags::AUTHENTICATION_ALLOW_ANONYMOUS] or
    /// [`DBusConnectionFlags::AUTHENTICATION_REQUIRE_SAME_USER`][crate::DBusConnectionFlags::AUTHENTICATION_REQUIRE_SAME_USER] flags.
    ///
    /// This is a synchronous failable constructor. See
    /// [`for_address()`][Self::for_address()] for the asynchronous version.
    ///
    /// If `observer` is not [`None`] it may be used to control the
    /// authentication process.
    /// ## `address`
    /// a D-Bus address
    /// ## `flags`
    /// flags describing how to make the connection
    /// ## `observer`
    /// a [`DBusAuthObserver`][crate::DBusAuthObserver] or [`None`]
    /// ## `cancellable`
    /// a [`Cancellable`][crate::Cancellable] or [`None`]
    ///
    /// # Returns
    ///
    /// a [`DBusConnection`][crate::DBusConnection] or [`None`] if `error` is set.
    ///  Free with `g_object_unref()`.
    #[doc(alias = "g_dbus_connection_new_for_address_sync")]
    #[doc(alias = "new_for_address_sync")]
    pub fn for_address_sync(
        address: &str,
        flags: DBusConnectionFlags,
        observer: Option<&DBusAuthObserver>,
        cancellable: Option<&impl IsA<Cancellable>>,
    ) -> Result<DBusConnection, glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let ret = ffi::g_dbus_connection_new_for_address_sync(
                address.to_glib_none().0,
                flags.into_glib(),
                observer.to_glib_none().0,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                &mut error,
            );
            if error.is_null() {
                Ok(from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Synchronously sets up a D-Bus connection for exchanging D-Bus messages
    /// with the end represented by `stream`.
    ///
    /// If `stream` is a [`SocketConnection`][crate::SocketConnection], then the corresponding [`Socket`][crate::Socket]
    /// will be put into non-blocking mode.
    ///
    /// The D-Bus connection will interact with `stream` from a worker thread.
    /// As a result, the caller should not interact with `stream` after this
    /// method has been called, except by calling `g_object_unref()` on it.
    ///
    /// If `observer` is not [`None`] it may be used to control the
    /// authentication process.
    ///
    /// This is a synchronous failable constructor. See
    /// [`new()`][Self::new()] for the asynchronous version.
    /// ## `stream`
    /// a [`IOStream`][crate::IOStream]
    /// ## `guid`
    /// the GUID to use if authenticating as a server or [`None`]
    /// ## `flags`
    /// flags describing how to make the connection
    /// ## `observer`
    /// a [`DBusAuthObserver`][crate::DBusAuthObserver] or [`None`]
    /// ## `cancellable`
    /// a [`Cancellable`][crate::Cancellable] or [`None`]
    ///
    /// # Returns
    ///
    /// a [`DBusConnection`][crate::DBusConnection] or [`None`] if `error` is set.
    ///  Free with `g_object_unref()`.
    #[doc(alias = "g_dbus_connection_new_sync")]
    pub fn new_sync(
        stream: &impl IsA<IOStream>,
        guid: Option<&str>,
        flags: DBusConnectionFlags,
        observer: Option<&DBusAuthObserver>,
        cancellable: Option<&impl IsA<Cancellable>>,
    ) -> Result<DBusConnection, glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let ret = ffi::g_dbus_connection_new_sync(
                stream.as_ref().to_glib_none().0,
                guid.to_glib_none().0,
                flags.into_glib(),
                observer.to_glib_none().0,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                &mut error,
            );
            if error.is_null() {
                Ok(from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Asynchronously invokes the `method_name` method on the
    /// `interface_name` D-Bus interface on the remote object at
    /// `object_path` owned by `bus_name`.
    ///
    /// If `self` is closed then the operation will fail with
    /// [`IOErrorEnum::Closed`][crate::IOErrorEnum::Closed]. If `cancellable` is canceled, the operation will
    /// fail with [`IOErrorEnum::Cancelled`][crate::IOErrorEnum::Cancelled]. If `parameters` contains a value
    /// not compatible with the D-Bus protocol, the operation fails with
    /// [`IOErrorEnum::InvalidArgument`][crate::IOErrorEnum::InvalidArgument].
    ///
    /// If `reply_type` is non-[`None`] then the reply will be checked for having this type and an
    /// error will be raised if it does not match. Said another way, if you give a `reply_type`
    /// then any non-[`None`] return value will be of this type. Unless it’s
    /// `G_VARIANT_TYPE_UNIT`, the `reply_type` will be a tuple containing one or more
    /// values.
    ///
    /// If the `parameters` [`glib::Variant`][struct@crate::glib::Variant] is floating, it is consumed. This allows
    /// convenient 'inline' use of [`glib::Variant::new()`][crate::glib::Variant::new()], e.g.:
    ///
    ///
    /// **⚠️ The following code is in C ⚠️**
    ///
    /// ```C
    ///  g_dbus_connection_call (connection,
    ///                          "org.freedesktop.StringThings",
    ///                          "/org/freedesktop/StringThings",
    ///                          "org.freedesktop.StringThings",
    ///                          "TwoStrings",
    ///                          g_variant_new ("(ss)",
    ///                                         "Thing One",
    ///                                         "Thing Two"),
    ///                          NULL,
    ///                          G_DBUS_CALL_FLAGS_NONE,
    ///                          -1,
    ///                          NULL,
    ///                          (GAsyncReadyCallback) two_strings_done,
    ///                          NULL);
    /// ```
    ///
    /// This is an asynchronous method. When the operation is finished,
    /// `callback` will be invoked in the
    /// [thread-default main context][g-main-context-push-thread-default]
    /// of the thread you are calling this method from. You can then call
    /// `g_dbus_connection_call_finish()` to get the result of the operation.
    /// See [`call_sync()`][Self::call_sync()] for the synchronous version of this
    /// function.
    ///
    /// If `callback` is [`None`] then the D-Bus method call message will be sent with
    /// the [`DBusMessageFlags::NO_REPLY_EXPECTED`][crate::DBusMessageFlags::NO_REPLY_EXPECTED] flag set.
    /// ## `bus_name`
    /// a unique or well-known bus name or [`None`] if
    ///  `self` is not a message bus connection
    /// ## `object_path`
    /// path of remote object
    /// ## `interface_name`
    /// D-Bus interface to invoke method on
    /// ## `method_name`
    /// the name of the method to invoke
    /// ## `parameters`
    /// a [`glib::Variant`][struct@crate::glib::Variant] tuple with parameters for the method
    ///  or [`None`] if not passing parameters
    /// ## `reply_type`
    /// the expected type of the reply (which will be a
    ///  tuple), or [`None`]
    /// ## `flags`
    /// flags from the [`DBusCallFlags`][crate::DBusCallFlags] enumeration
    /// ## `timeout_msec`
    /// the timeout in milliseconds, -1 to use the default
    ///  timeout or `G_MAXINT` for no timeout
    /// ## `cancellable`
    /// a [`Cancellable`][crate::Cancellable] or [`None`]
    /// ## `callback`
    /// a `GAsyncReadyCallback` to call when the request
    ///  is satisfied or [`None`] if you don't care about the result of the
    ///  method invocation
    #[doc(alias = "g_dbus_connection_call")]
    pub fn call<P: FnOnce(Result<glib::Variant, glib::Error>) + 'static>(
        &self,
        bus_name: Option<&str>,
        object_path: &str,
        interface_name: &str,
        method_name: &str,
        parameters: Option<&glib::Variant>,
        reply_type: Option<&glib::VariantTy>,
        flags: DBusCallFlags,
        timeout_msec: i32,
        cancellable: Option<&impl IsA<Cancellable>>,
        callback: P,
    ) {
        let main_context = glib::MainContext::ref_thread_default();
        let is_main_context_owner = main_context.is_owner();
        let has_acquired_main_context = (!is_main_context_owner)
            .then(|| main_context.acquire().ok())
            .flatten();
        assert!(
            is_main_context_owner || has_acquired_main_context.is_some(),
            "Async operations only allowed if the thread is owning the MainContext"
        );

        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
        unsafe extern "C" fn call_trampoline<
            P: FnOnce(Result<glib::Variant, glib::Error>) + 'static,
        >(
            _source_object: *mut glib::gobject_ffi::GObject,
            res: *mut crate::ffi::GAsyncResult,
            user_data: glib::ffi::gpointer,
        ) {
            let mut error = ptr::null_mut();
            let ret = ffi::g_dbus_connection_call_finish(_source_object as *mut _, res, &mut error);
            let result = if error.is_null() {
                Ok(from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            };
            let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
                Box_::from_raw(user_data as *mut _);
            let callback: P = callback.into_inner();
            callback(result);
        }
        let callback = call_trampoline::<P>;
        unsafe {
            ffi::g_dbus_connection_call(
                self.to_glib_none().0,
                bus_name.to_glib_none().0,
                object_path.to_glib_none().0,
                interface_name.to_glib_none().0,
                method_name.to_glib_none().0,
                parameters.to_glib_none().0,
                reply_type.to_glib_none().0,
                flags.into_glib(),
                timeout_msec,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                Some(callback),
                Box_::into_raw(user_data) as *mut _,
            );
        }
    }

    pub fn call_future(
        &self,
        bus_name: Option<&str>,
        object_path: &str,
        interface_name: &str,
        method_name: &str,
        parameters: Option<&glib::Variant>,
        reply_type: Option<&glib::VariantTy>,
        flags: DBusCallFlags,
        timeout_msec: i32,
    ) -> Pin<Box_<dyn std::future::Future<Output = Result<glib::Variant, glib::Error>> + 'static>>
    {
        let bus_name = bus_name.map(ToOwned::to_owned);
        let object_path = String::from(object_path);
        let interface_name = String::from(interface_name);
        let method_name = String::from(method_name);
        let parameters = parameters.map(ToOwned::to_owned);
        let reply_type = reply_type.map(ToOwned::to_owned);
        Box_::pin(crate::GioFuture::new(
            self,
            move |obj, cancellable, send| {
                obj.call(
                    bus_name.as_ref().map(::std::borrow::Borrow::borrow),
                    &object_path,
                    &interface_name,
                    &method_name,
                    parameters.as_ref().map(::std::borrow::Borrow::borrow),
                    reply_type.as_ref().map(::std::borrow::Borrow::borrow),
                    flags,
                    timeout_msec,
                    Some(cancellable),
                    move |res| {
                        send.resolve(res);
                    },
                );
            },
        ))
    }

    /// Synchronously invokes the `method_name` method on the
    /// `interface_name` D-Bus interface on the remote object at
    /// `object_path` owned by `bus_name`.
    ///
    /// If `self` is closed then the operation will fail with
    /// [`IOErrorEnum::Closed`][crate::IOErrorEnum::Closed]. If `cancellable` is canceled, the
    /// operation will fail with [`IOErrorEnum::Cancelled`][crate::IOErrorEnum::Cancelled]. If `parameters`
    /// contains a value not compatible with the D-Bus protocol, the operation
    /// fails with [`IOErrorEnum::InvalidArgument`][crate::IOErrorEnum::InvalidArgument].
    ///
    /// If `reply_type` is non-[`None`] then the reply will be checked for having
    /// this type and an error will be raised if it does not match. Said
    /// another way, if you give a `reply_type` then any non-[`None`] return
    /// value will be of this type.
    ///
    /// If the `parameters` [`glib::Variant`][struct@crate::glib::Variant] is floating, it is consumed.
    /// This allows convenient 'inline' use of [`glib::Variant::new()`][crate::glib::Variant::new()], e.g.:
    ///
    ///
    /// **⚠️ The following code is in C ⚠️**
    ///
    /// ```C
    ///  g_dbus_connection_call_sync (connection,
    ///                               "org.freedesktop.StringThings",
    ///                               "/org/freedesktop/StringThings",
    ///                               "org.freedesktop.StringThings",
    ///                               "TwoStrings",
    ///                               g_variant_new ("(ss)",
    ///                                              "Thing One",
    ///                                              "Thing Two"),
    ///                               NULL,
    ///                               G_DBUS_CALL_FLAGS_NONE,
    ///                               -1,
    ///                               NULL,
    ///                               &error);
    /// ```
    ///
    /// The calling thread is blocked until a reply is received. See
    /// [`call()`][Self::call()] for the asynchronous version of
    /// this method.
    /// ## `bus_name`
    /// a unique or well-known bus name or [`None`] if
    ///  `self` is not a message bus connection
    /// ## `object_path`
    /// path of remote object
    /// ## `interface_name`
    /// D-Bus interface to invoke method on
    /// ## `method_name`
    /// the name of the method to invoke
    /// ## `parameters`
    /// a [`glib::Variant`][struct@crate::glib::Variant] tuple with parameters for the method
    ///  or [`None`] if not passing parameters
    /// ## `reply_type`
    /// the expected type of the reply, or [`None`]
    /// ## `flags`
    /// flags from the [`DBusCallFlags`][crate::DBusCallFlags] enumeration
    /// ## `timeout_msec`
    /// the timeout in milliseconds, -1 to use the default
    ///  timeout or `G_MAXINT` for no timeout
    /// ## `cancellable`
    /// a [`Cancellable`][crate::Cancellable] or [`None`]
    ///
    /// # Returns
    ///
    /// [`None`] if `error` is set. Otherwise a non-floating
    ///  [`glib::Variant`][struct@crate::glib::Variant] tuple with return values. Free with `g_variant_unref()`.
    #[doc(alias = "g_dbus_connection_call_sync")]
    pub fn call_sync(
        &self,
        bus_name: Option<&str>,
        object_path: &str,
        interface_name: &str,
        method_name: &str,
        parameters: Option<&glib::Variant>,
        reply_type: Option<&glib::VariantTy>,
        flags: DBusCallFlags,
        timeout_msec: i32,
        cancellable: Option<&impl IsA<Cancellable>>,
    ) -> Result<glib::Variant, glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let ret = ffi::g_dbus_connection_call_sync(
                self.to_glib_none().0,
                bus_name.to_glib_none().0,
                object_path.to_glib_none().0,
                interface_name.to_glib_none().0,
                method_name.to_glib_none().0,
                parameters.to_glib_none().0,
                reply_type.to_glib_none().0,
                flags.into_glib(),
                timeout_msec,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                &mut error,
            );
            if error.is_null() {
                Ok(from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Like [`call()`][Self::call()] but also takes a [`UnixFDList`][crate::UnixFDList] object.
    ///
    /// The file descriptors normally correspond to `G_VARIANT_TYPE_HANDLE`
    /// values in the body of the message. For example, if a message contains
    /// two file descriptors, `fd_list` would have length 2, and
    /// `g_variant_new_handle (0)` and `g_variant_new_handle (1)` would appear
    /// somewhere in the body of the message (not necessarily in that order!)
    /// to represent the file descriptors at indexes 0 and 1 respectively.
    ///
    /// When designing D-Bus APIs that are intended to be interoperable,
    /// please note that non-GDBus implementations of D-Bus can usually only
    /// access file descriptors if they are referenced in this way by a
    /// value of type `G_VARIANT_TYPE_HANDLE` in the body of the message.
    ///
    /// This method is only available on UNIX.
    /// ## `bus_name`
    /// a unique or well-known bus name or [`None`] if
    ///  `self` is not a message bus connection
    /// ## `object_path`
    /// path of remote object
    /// ## `interface_name`
    /// D-Bus interface to invoke method on
    /// ## `method_name`
    /// the name of the method to invoke
    /// ## `parameters`
    /// a [`glib::Variant`][struct@crate::glib::Variant] tuple with parameters for the method
    ///  or [`None`] if not passing parameters
    /// ## `reply_type`
    /// the expected type of the reply, or [`None`]
    /// ## `flags`
    /// flags from the [`DBusCallFlags`][crate::DBusCallFlags] enumeration
    /// ## `timeout_msec`
    /// the timeout in milliseconds, -1 to use the default
    ///  timeout or `G_MAXINT` for no timeout
    /// ## `fd_list`
    /// a [`UnixFDList`][crate::UnixFDList] or [`None`]
    /// ## `cancellable`
    /// a [`Cancellable`][crate::Cancellable] or [`None`]
    /// ## `callback`
    /// a `GAsyncReadyCallback` to call when the request is
    ///  satisfied or [`None`] if you don't * care about the result of the
    ///  method invocation
    #[cfg(any(unix, feature = "dox"))]
    #[cfg_attr(feature = "dox", doc(cfg(unix)))]
    #[doc(alias = "g_dbus_connection_call_with_unix_fd_list")]
    pub fn call_with_unix_fd_list<
        P: FnOnce(Result<(glib::Variant, UnixFDList), glib::Error>) + 'static,
    >(
        &self,
        bus_name: Option<&str>,
        object_path: &str,
        interface_name: &str,
        method_name: &str,
        parameters: Option<&glib::Variant>,
        reply_type: Option<&glib::VariantTy>,
        flags: DBusCallFlags,
        timeout_msec: i32,
        fd_list: Option<&impl IsA<UnixFDList>>,
        cancellable: Option<&impl IsA<Cancellable>>,
        callback: P,
    ) {
        let main_context = glib::MainContext::ref_thread_default();
        let is_main_context_owner = main_context.is_owner();
        let has_acquired_main_context = (!is_main_context_owner)
            .then(|| main_context.acquire().ok())
            .flatten();
        assert!(
            is_main_context_owner || has_acquired_main_context.is_some(),
            "Async operations only allowed if the thread is owning the MainContext"
        );

        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
        unsafe extern "C" fn call_with_unix_fd_list_trampoline<
            P: FnOnce(Result<(glib::Variant, UnixFDList), glib::Error>) + 'static,
        >(
            _source_object: *mut glib::gobject_ffi::GObject,
            res: *mut crate::ffi::GAsyncResult,
            user_data: glib::ffi::gpointer,
        ) {
            let mut error = ptr::null_mut();
            let mut out_fd_list = ptr::null_mut();
            let ret = ffi::g_dbus_connection_call_with_unix_fd_list_finish(
                _source_object as *mut _,
                &mut out_fd_list,
                res,
                &mut error,
            );
            let result = if error.is_null() {
                Ok((from_glib_full(ret), from_glib_full(out_fd_list)))
            } else {
                Err(from_glib_full(error))
            };
            let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
                Box_::from_raw(user_data as *mut _);
            let callback: P = callback.into_inner();
            callback(result);
        }
        let callback = call_with_unix_fd_list_trampoline::<P>;
        unsafe {
            ffi::g_dbus_connection_call_with_unix_fd_list(
                self.to_glib_none().0,
                bus_name.to_glib_none().0,
                object_path.to_glib_none().0,
                interface_name.to_glib_none().0,
                method_name.to_glib_none().0,
                parameters.to_glib_none().0,
                reply_type.to_glib_none().0,
                flags.into_glib(),
                timeout_msec,
                fd_list.map(|p| p.as_ref()).to_glib_none().0,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                Some(callback),
                Box_::into_raw(user_data) as *mut _,
            );
        }
    }

    #[cfg(any(unix, feature = "dox"))]
    #[cfg_attr(feature = "dox", doc(cfg(unix)))]
    pub fn call_with_unix_fd_list_future(
        &self,
        bus_name: Option<&str>,
        object_path: &str,
        interface_name: &str,
        method_name: &str,
        parameters: Option<&glib::Variant>,
        reply_type: Option<&glib::VariantTy>,
        flags: DBusCallFlags,
        timeout_msec: i32,
        fd_list: Option<&(impl IsA<UnixFDList> + Clone + 'static)>,
    ) -> Pin<
        Box_<
            dyn std::future::Future<Output = Result<(glib::Variant, UnixFDList), glib::Error>>
                + 'static,
        >,
    > {
        let bus_name = bus_name.map(ToOwned::to_owned);
        let object_path = String::from(object_path);
        let interface_name = String::from(interface_name);
        let method_name = String::from(method_name);
        let parameters = parameters.map(ToOwned::to_owned);
        let reply_type = reply_type.map(ToOwned::to_owned);
        let fd_list = fd_list.map(ToOwned::to_owned);
        Box_::pin(crate::GioFuture::new(
            self,
            move |obj, cancellable, send| {
                obj.call_with_unix_fd_list(
                    bus_name.as_ref().map(::std::borrow::Borrow::borrow),
                    &object_path,
                    &interface_name,
                    &method_name,
                    parameters.as_ref().map(::std::borrow::Borrow::borrow),
                    reply_type.as_ref().map(::std::borrow::Borrow::borrow),
                    flags,
                    timeout_msec,
                    fd_list.as_ref().map(::std::borrow::Borrow::borrow),
                    Some(cancellable),
                    move |res| {
                        send.resolve(res);
                    },
                );
            },
        ))
    }

    /// Like [`call_sync()`][Self::call_sync()] but also takes and returns [`UnixFDList`][crate::UnixFDList] objects.
    /// See [`call_with_unix_fd_list()`][Self::call_with_unix_fd_list()] and
    /// `g_dbus_connection_call_with_unix_fd_list_finish()` for more details.
    ///
    /// This method is only available on UNIX.
    /// ## `bus_name`
    /// a unique or well-known bus name or [`None`]
    ///  if `self` is not a message bus connection
    /// ## `object_path`
    /// path of remote object
    /// ## `interface_name`
    /// D-Bus interface to invoke method on
    /// ## `method_name`
    /// the name of the method to invoke
    /// ## `parameters`
    /// a [`glib::Variant`][struct@crate::glib::Variant] tuple with parameters for
    ///  the method or [`None`] if not passing parameters
    /// ## `reply_type`
    /// the expected type of the reply, or [`None`]
    /// ## `flags`
    /// flags from the [`DBusCallFlags`][crate::DBusCallFlags] enumeration
    /// ## `timeout_msec`
    /// the timeout in milliseconds, -1 to use the default
    ///  timeout or `G_MAXINT` for no timeout
    /// ## `fd_list`
    /// a [`UnixFDList`][crate::UnixFDList] or [`None`]
    /// ## `cancellable`
    /// a [`Cancellable`][crate::Cancellable] or [`None`]
    ///
    /// # Returns
    ///
    /// [`None`] if `error` is set. Otherwise a non-floating
    ///  [`glib::Variant`][struct@crate::glib::Variant] tuple with return values. Free with `g_variant_unref()`.
    ///
    /// ## `out_fd_list`
    /// return location for a [`UnixFDList`][crate::UnixFDList] or [`None`]
    #[cfg(any(unix, feature = "dox"))]
    #[cfg_attr(feature = "dox", doc(cfg(unix)))]
    #[doc(alias = "g_dbus_connection_call_with_unix_fd_list_sync")]
    pub fn call_with_unix_fd_list_sync(
        &self,
        bus_name: Option<&str>,
        object_path: &str,
        interface_name: &str,
        method_name: &str,
        parameters: Option<&glib::Variant>,
        reply_type: Option<&glib::VariantTy>,
        flags: DBusCallFlags,
        timeout_msec: i32,
        fd_list: Option<&impl IsA<UnixFDList>>,
        cancellable: Option<&impl IsA<Cancellable>>,
    ) -> Result<(glib::Variant, UnixFDList), glib::Error> {
        unsafe {
            let mut out_fd_list = ptr::null_mut();
            let mut error = ptr::null_mut();
            let ret = ffi::g_dbus_connection_call_with_unix_fd_list_sync(
                self.to_glib_none().0,
                bus_name.to_glib_none().0,
                object_path.to_glib_none().0,
                interface_name.to_glib_none().0,
                method_name.to_glib_none().0,
                parameters.to_glib_none().0,
                reply_type.to_glib_none().0,
                flags.into_glib(),
                timeout_msec,
                fd_list.map(|p| p.as_ref()).to_glib_none().0,
                &mut out_fd_list,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                &mut error,
            );
            if error.is_null() {
                Ok((from_glib_full(ret), from_glib_full(out_fd_list)))
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Closes `self`. Note that this never causes the process to
    /// exit (this might only happen if the other end of a shared message
    /// bus connection disconnects, see [`exit-on-close`][struct@crate::DBusConnection#exit-on-close]).
    ///
    /// Once the connection is closed, operations such as sending a message
    /// will return with the error [`IOErrorEnum::Closed`][crate::IOErrorEnum::Closed]. Closing a connection
    /// will not automatically flush the connection so queued messages may
    /// be lost. Use [`flush()`][Self::flush()] if you need such guarantees.
    ///
    /// If `self` is already closed, this method fails with
    /// [`IOErrorEnum::Closed`][crate::IOErrorEnum::Closed].
    ///
    /// When `self` has been closed, the [`closed`][struct@crate::DBusConnection#closed]
    /// signal is emitted in the
    /// [thread-default main context][g-main-context-push-thread-default]
    /// of the thread that `self` was constructed in.
    ///
    /// This is an asynchronous method. When the operation is finished,
    /// `callback` will be invoked in the
    /// [thread-default main context][g-main-context-push-thread-default]
    /// of the thread you are calling this method from. You can
    /// then call `g_dbus_connection_close_finish()` to get the result of the
    /// operation. See [`close_sync()`][Self::close_sync()] for the synchronous
    /// version.
    /// ## `cancellable`
    /// a [`Cancellable`][crate::Cancellable] or [`None`]
    /// ## `callback`
    /// a `GAsyncReadyCallback` to call when the request is
    ///  satisfied or [`None`] if you don't care about the result
    #[doc(alias = "g_dbus_connection_close")]
    pub fn close<P: FnOnce(Result<(), glib::Error>) + 'static>(
        &self,
        cancellable: Option<&impl IsA<Cancellable>>,
        callback: P,
    ) {
        let main_context = glib::MainContext::ref_thread_default();
        let is_main_context_owner = main_context.is_owner();
        let has_acquired_main_context = (!is_main_context_owner)
            .then(|| main_context.acquire().ok())
            .flatten();
        assert!(
            is_main_context_owner || has_acquired_main_context.is_some(),
            "Async operations only allowed if the thread is owning the MainContext"
        );

        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
        unsafe extern "C" fn close_trampoline<P: FnOnce(Result<(), glib::Error>) + 'static>(
            _source_object: *mut glib::gobject_ffi::GObject,
            res: *mut crate::ffi::GAsyncResult,
            user_data: glib::ffi::gpointer,
        ) {
            let mut error = ptr::null_mut();
            let _ = ffi::g_dbus_connection_close_finish(_source_object as *mut _, res, &mut error);
            let result = if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            };
            let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
                Box_::from_raw(user_data as *mut _);
            let callback: P = callback.into_inner();
            callback(result);
        }
        let callback = close_trampoline::<P>;
        unsafe {
            ffi::g_dbus_connection_close(
                self.to_glib_none().0,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                Some(callback),
                Box_::into_raw(user_data) as *mut _,
            );
        }
    }

    pub fn close_future(
        &self,
    ) -> Pin<Box_<dyn std::future::Future<Output = Result<(), glib::Error>> + 'static>> {
        Box_::pin(crate::GioFuture::new(
            self,
            move |obj, cancellable, send| {
                obj.close(Some(cancellable), move |res| {
                    send.resolve(res);
                });
            },
        ))
    }

    /// Synchronously closes `self`. The calling thread is blocked
    /// until this is done. See [`close()`][Self::close()] for the
    /// asynchronous version of this method and more details about what it
    /// does.
    /// ## `cancellable`
    /// a [`Cancellable`][crate::Cancellable] or [`None`]
    ///
    /// # Returns
    ///
    /// [`true`] if the operation succeeded, [`false`] if `error` is set
    #[doc(alias = "g_dbus_connection_close_sync")]
    pub fn close_sync(
        &self,
        cancellable: Option<&impl IsA<Cancellable>>,
    ) -> Result<(), glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let is_ok = ffi::g_dbus_connection_close_sync(
                self.to_glib_none().0,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                &mut error,
            );
            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Emits a signal.
    ///
    /// If the parameters GVariant is floating, it is consumed.
    ///
    /// This can only fail if `parameters` is not compatible with the D-Bus protocol
    /// ([`IOErrorEnum::InvalidArgument`][crate::IOErrorEnum::InvalidArgument]), or if `self` has been closed
    /// ([`IOErrorEnum::Closed`][crate::IOErrorEnum::Closed]).
    /// ## `destination_bus_name`
    /// the unique bus name for the destination
    ///  for the signal or [`None`] to emit to all listeners
    /// ## `object_path`
    /// path of remote object
    /// ## `interface_name`
    /// D-Bus interface to emit a signal on
    /// ## `signal_name`
    /// the name of the signal to emit
    /// ## `parameters`
    /// a [`glib::Variant`][struct@crate::glib::Variant] tuple with parameters for the signal
    ///  or [`None`] if not passing parameters
    ///
    /// # Returns
    ///
    /// [`true`] unless `error` is set
    #[doc(alias = "g_dbus_connection_emit_signal")]
    pub fn emit_signal(
        &self,
        destination_bus_name: Option<&str>,
        object_path: &str,
        interface_name: &str,
        signal_name: &str,
        parameters: Option<&glib::Variant>,
    ) -> Result<(), glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let is_ok = ffi::g_dbus_connection_emit_signal(
                self.to_glib_none().0,
                destination_bus_name.to_glib_none().0,
                object_path.to_glib_none().0,
                interface_name.to_glib_none().0,
                signal_name.to_glib_none().0,
                parameters.to_glib_none().0,
                &mut error,
            );
            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Asynchronously flushes `self`, that is, writes all queued
    /// outgoing message to the transport and then flushes the transport
    /// (using [`OutputStreamExt::flush_async()`][crate::prelude::OutputStreamExt::flush_async()]). This is useful in programs
    /// that wants to emit a D-Bus signal and then exit immediately. Without
    /// flushing the connection, there is no guaranteed that the message has
    /// been sent to the networking buffers in the OS kernel.
    ///
    /// This is an asynchronous method. When the operation is finished,
    /// `callback` will be invoked in the
    /// [thread-default main context][g-main-context-push-thread-default]
    /// of the thread you are calling this method from. You can
    /// then call `g_dbus_connection_flush_finish()` to get the result of the
    /// operation. See [`flush_sync()`][Self::flush_sync()] for the synchronous
    /// version.
    /// ## `cancellable`
    /// a [`Cancellable`][crate::Cancellable] or [`None`]
    /// ## `callback`
    /// a `GAsyncReadyCallback` to call when the
    ///  request is satisfied or [`None`] if you don't care about the result
    #[doc(alias = "g_dbus_connection_flush")]
    pub fn flush<P: FnOnce(Result<(), glib::Error>) + 'static>(
        &self,
        cancellable: Option<&impl IsA<Cancellable>>,
        callback: P,
    ) {
        let main_context = glib::MainContext::ref_thread_default();
        let is_main_context_owner = main_context.is_owner();
        let has_acquired_main_context = (!is_main_context_owner)
            .then(|| main_context.acquire().ok())
            .flatten();
        assert!(
            is_main_context_owner || has_acquired_main_context.is_some(),
            "Async operations only allowed if the thread is owning the MainContext"
        );

        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
        unsafe extern "C" fn flush_trampoline<P: FnOnce(Result<(), glib::Error>) + 'static>(
            _source_object: *mut glib::gobject_ffi::GObject,
            res: *mut crate::ffi::GAsyncResult,
            user_data: glib::ffi::gpointer,
        ) {
            let mut error = ptr::null_mut();
            let _ = ffi::g_dbus_connection_flush_finish(_source_object as *mut _, res, &mut error);
            let result = if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            };
            let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
                Box_::from_raw(user_data as *mut _);
            let callback: P = callback.into_inner();
            callback(result);
        }
        let callback = flush_trampoline::<P>;
        unsafe {
            ffi::g_dbus_connection_flush(
                self.to_glib_none().0,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                Some(callback),
                Box_::into_raw(user_data) as *mut _,
            );
        }
    }

    pub fn flush_future(
        &self,
    ) -> Pin<Box_<dyn std::future::Future<Output = Result<(), glib::Error>> + 'static>> {
        Box_::pin(crate::GioFuture::new(
            self,
            move |obj, cancellable, send| {
                obj.flush(Some(cancellable), move |res| {
                    send.resolve(res);
                });
            },
        ))
    }

    /// Synchronously flushes `self`. The calling thread is blocked
    /// until this is done. See [`flush()`][Self::flush()] for the
    /// asynchronous version of this method and more details about what it
    /// does.
    /// ## `cancellable`
    /// a [`Cancellable`][crate::Cancellable] or [`None`]
    ///
    /// # Returns
    ///
    /// [`true`] if the operation succeeded, [`false`] if `error` is set
    #[doc(alias = "g_dbus_connection_flush_sync")]
    pub fn flush_sync(
        &self,
        cancellable: Option<&impl IsA<Cancellable>>,
    ) -> Result<(), glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let is_ok = ffi::g_dbus_connection_flush_sync(
                self.to_glib_none().0,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                &mut error,
            );
            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Gets the capabilities negotiated with the remote peer
    ///
    /// # Returns
    ///
    /// zero or more flags from the [`DBusCapabilityFlags`][crate::DBusCapabilityFlags] enumeration
    #[doc(alias = "g_dbus_connection_get_capabilities")]
    #[doc(alias = "get_capabilities")]
    pub fn capabilities(&self) -> DBusCapabilityFlags {
        unsafe {
            from_glib(ffi::g_dbus_connection_get_capabilities(
                self.to_glib_none().0,
            ))
        }
    }

    /// Gets whether the process is terminated when `self` is
    /// closed by the remote peer. See
    /// [`exit-on-close`][struct@crate::DBusConnection#exit-on-close] for more details.
    ///
    /// # Returns
    ///
    /// whether the process is terminated when `self` is
    ///  closed by the remote peer
    #[doc(alias = "g_dbus_connection_get_exit_on_close")]
    #[doc(alias = "get_exit_on_close")]
    pub fn exits_on_close(&self) -> bool {
        unsafe {
            from_glib(ffi::g_dbus_connection_get_exit_on_close(
                self.to_glib_none().0,
            ))
        }
    }

    /// Gets the flags used to construct this connection
    ///
    /// # Returns
    ///
    /// zero or more flags from the [`DBusConnectionFlags`][crate::DBusConnectionFlags] enumeration
    #[cfg(any(feature = "v2_60", feature = "dox"))]
    #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_60")))]
    #[doc(alias = "g_dbus_connection_get_flags")]
    #[doc(alias = "get_flags")]
    pub fn flags(&self) -> DBusConnectionFlags {
        unsafe { from_glib(ffi::g_dbus_connection_get_flags(self.to_glib_none().0)) }
    }

    /// The GUID of the peer performing the role of server when
    /// authenticating. See [`guid`][struct@crate::DBusConnection#guid] for more details.
    ///
    /// # Returns
    ///
    /// The GUID. Do not free this string, it is owned by
    ///  `self`.
    #[doc(alias = "g_dbus_connection_get_guid")]
    #[doc(alias = "get_guid")]
    pub fn guid(&self) -> glib::GString {
        unsafe { from_glib_none(ffi::g_dbus_connection_get_guid(self.to_glib_none().0)) }
    }

    /// Retrieves the last serial number assigned to a [`DBusMessage`][crate::DBusMessage] on
    /// the current thread. This includes messages sent via both low-level
    /// API such as [`send_message()`][Self::send_message()] as well as
    /// high-level API such as [`emit_signal()`][Self::emit_signal()],
    /// [`call()`][Self::call()] or [`DBusProxyExt::call()`][crate::prelude::DBusProxyExt::call()].
    ///
    /// # Returns
    ///
    /// the last used serial or zero when no message has been sent
    ///  within the current thread
    #[doc(alias = "g_dbus_connection_get_last_serial")]
    #[doc(alias = "get_last_serial")]
    pub fn last_serial(&self) -> u32 {
        unsafe { ffi::g_dbus_connection_get_last_serial(self.to_glib_none().0) }
    }

    /// Gets the credentials of the authenticated peer. This will always
    /// return [`None`] unless `self` acted as a server
    /// (e.g. [`DBusConnectionFlags::AUTHENTICATION_SERVER`][crate::DBusConnectionFlags::AUTHENTICATION_SERVER] was passed)
    /// when set up and the client passed credentials as part of the
    /// authentication process.
    ///
    /// In a message bus setup, the message bus is always the server and
    /// each application is a client. So this method will always return
    /// [`None`] for message bus clients.
    ///
    /// # Returns
    ///
    /// a [`Credentials`][crate::Credentials] or [`None`] if not
    ///  available. Do not free this object, it is owned by `self`.
    #[doc(alias = "g_dbus_connection_get_peer_credentials")]
    #[doc(alias = "get_peer_credentials")]
    pub fn peer_credentials(&self) -> Option<Credentials> {
        unsafe {
            from_glib_none(ffi::g_dbus_connection_get_peer_credentials(
                self.to_glib_none().0,
            ))
        }
    }

    /// Gets the underlying stream used for IO.
    ///
    /// While the [`DBusConnection`][crate::DBusConnection] is active, it will interact with this
    /// stream from a worker thread, so it is not safe to interact with
    /// the stream directly.
    ///
    /// # Returns
    ///
    /// the stream used for IO
    #[doc(alias = "g_dbus_connection_get_stream")]
    #[doc(alias = "get_stream")]
    pub fn stream(&self) -> IOStream {
        unsafe { from_glib_none(ffi::g_dbus_connection_get_stream(self.to_glib_none().0)) }
    }

    /// Gets the unique name of `self` as assigned by the message
    /// bus. This can also be used to figure out if `self` is a
    /// message bus connection.
    ///
    /// # Returns
    ///
    /// the unique name or [`None`] if `self` is not a message
    ///  bus connection. Do not free this string, it is owned by
    ///  `self`.
    #[doc(alias = "g_dbus_connection_get_unique_name")]
    #[doc(alias = "get_unique_name")]
    pub fn unique_name(&self) -> Option<glib::GString> {
        unsafe {
            from_glib_none(ffi::g_dbus_connection_get_unique_name(
                self.to_glib_none().0,
            ))
        }
    }

    /// Gets whether `self` is closed.
    ///
    /// # Returns
    ///
    /// [`true`] if the connection is closed, [`false`] otherwise
    #[doc(alias = "g_dbus_connection_is_closed")]
    pub fn is_closed(&self) -> bool {
        unsafe { from_glib(ffi::g_dbus_connection_is_closed(self.to_glib_none().0)) }
    }

    //#[doc(alias = "g_dbus_connection_register_object")]
    //pub fn register_object(&self, object_path: &str, interface_info: &DBusInterfaceInfo, vtable: /*Ignored*/Option<&DBusInterfaceVTable>, user_data: /*Unimplemented*/Option<Basic: Pointer>) -> Result<(), glib::Error> {
    //    unsafe { TODO: call ffi:g_dbus_connection_register_object() }
    //}

    /// Asynchronously sends `message` to the peer represented by `self`.
    ///
    /// Unless `flags` contain the
    /// [`DBusSendMessageFlags::PRESERVE_SERIAL`][crate::DBusSendMessageFlags::PRESERVE_SERIAL] flag, the serial number
    /// will be assigned by `self` and set on `message` via
    /// [`DBusMessage::set_serial()`][crate::DBusMessage::set_serial()]. If `out_serial` is not [`None`], then the
    /// serial number used will be written to this location prior to
    /// submitting the message to the underlying transport. While it has a `volatile`
    /// qualifier, this is a historical artifact and the argument passed to it should
    /// not be `volatile`.
    ///
    /// If `self` is closed then the operation will fail with
    /// [`IOErrorEnum::Closed`][crate::IOErrorEnum::Closed]. If `message` is not well-formed,
    /// the operation fails with [`IOErrorEnum::InvalidArgument`][crate::IOErrorEnum::InvalidArgument].
    ///
    /// See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
    /// for an example of how to use this low-level API to send and receive
    /// UNIX file descriptors.
    ///
    /// Note that `message` must be unlocked, unless `flags` contain the
    /// [`DBusSendMessageFlags::PRESERVE_SERIAL`][crate::DBusSendMessageFlags::PRESERVE_SERIAL] flag.
    /// ## `message`
    /// a [`DBusMessage`][crate::DBusMessage]
    /// ## `flags`
    /// flags affecting how the message is sent
    ///
    /// # Returns
    ///
    /// [`true`] if the message was well-formed and queued for
    ///  transmission, [`false`] if `error` is set
    ///
    /// ## `out_serial`
    /// return location for serial number assigned
    ///  to `message` when sending it or [`None`]
    #[doc(alias = "g_dbus_connection_send_message")]
    pub fn send_message(
        &self,
        message: &DBusMessage,
        flags: DBusSendMessageFlags,
    ) -> Result<u32, glib::Error> {
        unsafe {
            let mut out_serial = mem::MaybeUninit::uninit();
            let mut error = ptr::null_mut();
            let is_ok = ffi::g_dbus_connection_send_message(
                self.to_glib_none().0,
                message.to_glib_none().0,
                flags.into_glib(),
                out_serial.as_mut_ptr(),
                &mut error,
            );
            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(out_serial.assume_init())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Asynchronously sends `message` to the peer represented by `self`.
    ///
    /// Unless `flags` contain the
    /// [`DBusSendMessageFlags::PRESERVE_SERIAL`][crate::DBusSendMessageFlags::PRESERVE_SERIAL] flag, the serial number
    /// will be assigned by `self` and set on `message` via
    /// [`DBusMessage::set_serial()`][crate::DBusMessage::set_serial()]. If `out_serial` is not [`None`], then the
    /// serial number used will be written to this location prior to
    /// submitting the message to the underlying transport. While it has a `volatile`
    /// qualifier, this is a historical artifact and the argument passed to it should
    /// not be `volatile`.
    ///
    /// If `self` is closed then the operation will fail with
    /// [`IOErrorEnum::Closed`][crate::IOErrorEnum::Closed]. If `cancellable` is canceled, the operation will
    /// fail with [`IOErrorEnum::Cancelled`][crate::IOErrorEnum::Cancelled]. If `message` is not well-formed,
    /// the operation fails with [`IOErrorEnum::InvalidArgument`][crate::IOErrorEnum::InvalidArgument].
    ///
    /// This is an asynchronous method. When the operation is finished, `callback`
    /// will be invoked in the
    /// [thread-default main context][g-main-context-push-thread-default]
    /// of the thread you are calling this method from. You can then call
    /// `g_dbus_connection_send_message_with_reply_finish()` to get the result of the operation.
    /// See [`send_message_with_reply_sync()`][Self::send_message_with_reply_sync()] for the synchronous version.
    ///
    /// Note that `message` must be unlocked, unless `flags` contain the
    /// [`DBusSendMessageFlags::PRESERVE_SERIAL`][crate::DBusSendMessageFlags::PRESERVE_SERIAL] flag.
    ///
    /// See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
    /// for an example of how to use this low-level API to send and receive
    /// UNIX file descriptors.
    /// ## `message`
    /// a [`DBusMessage`][crate::DBusMessage]
    /// ## `flags`
    /// flags affecting how the message is sent
    /// ## `timeout_msec`
    /// the timeout in milliseconds, -1 to use the default
    ///  timeout or `G_MAXINT` for no timeout
    /// ## `cancellable`
    /// a [`Cancellable`][crate::Cancellable] or [`None`]
    /// ## `callback`
    /// a `GAsyncReadyCallback` to call when the request
    ///  is satisfied or [`None`] if you don't care about the result
    ///
    /// # Returns
    ///
    ///
    /// ## `out_serial`
    /// return location for serial number assigned
    ///  to `message` when sending it or [`None`]
    #[doc(alias = "g_dbus_connection_send_message_with_reply")]
    pub fn send_message_with_reply<P: FnOnce(Result<DBusMessage, glib::Error>) + 'static>(
        &self,
        message: &DBusMessage,
        flags: DBusSendMessageFlags,
        timeout_msec: i32,
        cancellable: Option<&impl IsA<Cancellable>>,
        callback: P,
    ) -> u32 {
        let main_context = glib::MainContext::ref_thread_default();
        let is_main_context_owner = main_context.is_owner();
        let has_acquired_main_context = (!is_main_context_owner)
            .then(|| main_context.acquire().ok())
            .flatten();
        assert!(
            is_main_context_owner || has_acquired_main_context.is_some(),
            "Async operations only allowed if the thread is owning the MainContext"
        );

        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
        unsafe extern "C" fn send_message_with_reply_trampoline<
            P: FnOnce(Result<DBusMessage, glib::Error>) + 'static,
        >(
            _source_object: *mut glib::gobject_ffi::GObject,
            res: *mut crate::ffi::GAsyncResult,
            user_data: glib::ffi::gpointer,
        ) {
            let mut error = ptr::null_mut();
            let ret = ffi::g_dbus_connection_send_message_with_reply_finish(
                _source_object as *mut _,
                res,
                &mut error,
            );
            let result = if error.is_null() {
                Ok(from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            };
            let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
                Box_::from_raw(user_data as *mut _);
            let callback: P = callback.into_inner();
            callback(result);
        }
        let callback = send_message_with_reply_trampoline::<P>;
        unsafe {
            let mut out_serial = mem::MaybeUninit::uninit();
            ffi::g_dbus_connection_send_message_with_reply(
                self.to_glib_none().0,
                message.to_glib_none().0,
                flags.into_glib(),
                timeout_msec,
                out_serial.as_mut_ptr(),
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                Some(callback),
                Box_::into_raw(user_data) as *mut _,
            );
            out_serial.assume_init()
        }
    }

    pub fn send_message_with_reply_future(
        &self,
        message: &DBusMessage,
        flags: DBusSendMessageFlags,
        timeout_msec: i32,
    ) -> Pin<Box_<dyn std::future::Future<Output = Result<DBusMessage, glib::Error>> + 'static>>
    {
        let message = message.clone();
        Box_::pin(crate::GioFuture::new(
            self,
            move |obj, cancellable, send| {
                obj.send_message_with_reply(
                    &message,
                    flags,
                    timeout_msec,
                    Some(cancellable),
                    move |res| {
                        send.resolve(res);
                    },
                );
            },
        ))
    }

    /// Synchronously sends `message` to the peer represented by `self`
    /// and blocks the calling thread until a reply is received or the
    /// timeout is reached. See [`send_message_with_reply()`][Self::send_message_with_reply()]
    /// for the asynchronous version of this method.
    ///
    /// Unless `flags` contain the
    /// [`DBusSendMessageFlags::PRESERVE_SERIAL`][crate::DBusSendMessageFlags::PRESERVE_SERIAL] flag, the serial number
    /// will be assigned by `self` and set on `message` via
    /// [`DBusMessage::set_serial()`][crate::DBusMessage::set_serial()]. If `out_serial` is not [`None`], then the
    /// serial number used will be written to this location prior to
    /// submitting the message to the underlying transport. While it has a `volatile`
    /// qualifier, this is a historical artifact and the argument passed to it should
    /// not be `volatile`.
    ///
    /// If `self` is closed then the operation will fail with
    /// [`IOErrorEnum::Closed`][crate::IOErrorEnum::Closed]. If `cancellable` is canceled, the operation will
    /// fail with [`IOErrorEnum::Cancelled`][crate::IOErrorEnum::Cancelled]. If `message` is not well-formed,
    /// the operation fails with [`IOErrorEnum::InvalidArgument`][crate::IOErrorEnum::InvalidArgument].
    ///
    /// Note that `error` is only set if a local in-process error
    /// occurred. That is to say that the returned [`DBusMessage`][crate::DBusMessage] object may
    /// be of type [`DBusMessageType::Error`][crate::DBusMessageType::Error]. Use
    /// [`DBusMessage::to_gerror()`][crate::DBusMessage::to_gerror()] to transcode this to a [`glib::Error`][crate::glib::Error].
    ///
    /// See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
    /// for an example of how to use this low-level API to send and receive
    /// UNIX file descriptors.
    ///
    /// Note that `message` must be unlocked, unless `flags` contain the
    /// [`DBusSendMessageFlags::PRESERVE_SERIAL`][crate::DBusSendMessageFlags::PRESERVE_SERIAL] flag.
    /// ## `message`
    /// a [`DBusMessage`][crate::DBusMessage]
    /// ## `flags`
    /// flags affecting how the message is sent.
    /// ## `timeout_msec`
    /// the timeout in milliseconds, -1 to use the default
    ///  timeout or `G_MAXINT` for no timeout
    /// ## `cancellable`
    /// a [`Cancellable`][crate::Cancellable] or [`None`]
    ///
    /// # Returns
    ///
    /// a locked [`DBusMessage`][crate::DBusMessage] that is the reply
    ///  to `message` or [`None`] if `error` is set
    ///
    /// ## `out_serial`
    /// return location for serial number
    ///  assigned to `message` when sending it or [`None`]
    #[doc(alias = "g_dbus_connection_send_message_with_reply_sync")]
    pub fn send_message_with_reply_sync(
        &self,
        message: &DBusMessage,
        flags: DBusSendMessageFlags,
        timeout_msec: i32,
        cancellable: Option<&impl IsA<Cancellable>>,
    ) -> Result<(DBusMessage, u32), glib::Error> {
        unsafe {
            let mut out_serial = mem::MaybeUninit::uninit();
            let mut error = ptr::null_mut();
            let ret = ffi::g_dbus_connection_send_message_with_reply_sync(
                self.to_glib_none().0,
                message.to_glib_none().0,
                flags.into_glib(),
                timeout_msec,
                out_serial.as_mut_ptr(),
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                &mut error,
            );
            if error.is_null() {
                Ok((from_glib_full(ret), out_serial.assume_init()))
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Sets whether the process should be terminated when `self` is
    /// closed by the remote peer. See [`exit-on-close`][struct@crate::DBusConnection#exit-on-close] for
    /// more details.
    ///
    /// Note that this function should be used with care. Most modern UNIX
    /// desktops tie the notion of a user session with the session bus, and expect
    /// all of a user's applications to quit when their bus connection goes away.
    /// If you are setting `exit_on_close` to [`false`] for the shared session
    /// bus connection, you should make sure that your application exits
    /// when the user session ends.
    /// ## `exit_on_close`
    /// whether the process should be terminated
    ///  when `self` is closed by the remote peer
    #[doc(alias = "g_dbus_connection_set_exit_on_close")]
    pub fn set_exit_on_close(&self, exit_on_close: bool) {
        unsafe {
            ffi::g_dbus_connection_set_exit_on_close(
                self.to_glib_none().0,
                exit_on_close.into_glib(),
            );
        }
    }

    /// If `self` was created with
    /// [`DBusConnectionFlags::DELAY_MESSAGE_PROCESSING`][crate::DBusConnectionFlags::DELAY_MESSAGE_PROCESSING], this method
    /// starts processing messages. Does nothing on if `self` wasn't
    /// created with this flag or if the method has already been called.
    #[doc(alias = "g_dbus_connection_start_message_processing")]
    pub fn start_message_processing(&self) {
        unsafe {
            ffi::g_dbus_connection_start_message_processing(self.to_glib_none().0);
        }
    }

    /// Flags from the [`DBusConnectionFlags`][crate::DBusConnectionFlags] enumeration.
    pub fn get_property_flags(&self) -> DBusConnectionFlags {
        glib::ObjectExt::property(self, "flags")
    }

    /// Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
    /// with the end represented by `stream`.
    ///
    /// If `stream` is a [`SocketConnection`][crate::SocketConnection], then the corresponding [`Socket`][crate::Socket]
    /// will be put into non-blocking mode.
    ///
    /// The D-Bus connection will interact with `stream` from a worker thread.
    /// As a result, the caller should not interact with `stream` after this
    /// method has been called, except by calling `g_object_unref()` on it.
    ///
    /// If `observer` is not [`None`] it may be used to control the
    /// authentication process.
    ///
    /// When the operation is finished, `callback` will be invoked. You can
    /// then call `g_dbus_connection_new_finish()` to get the result of the
    /// operation.
    ///
    /// This is an asynchronous failable constructor. See
    /// [`new_sync()`][Self::new_sync()] for the synchronous
    /// version.
    /// ## `stream`
    /// a [`IOStream`][crate::IOStream]
    /// ## `guid`
    /// the GUID to use if authenticating as a server or [`None`]
    /// ## `flags`
    /// flags describing how to make the connection
    /// ## `observer`
    /// a [`DBusAuthObserver`][crate::DBusAuthObserver] or [`None`]
    /// ## `cancellable`
    /// a [`Cancellable`][crate::Cancellable] or [`None`]
    /// ## `callback`
    /// a `GAsyncReadyCallback` to call when the request is satisfied
    #[doc(alias = "g_dbus_connection_new")]
    pub fn new<P: FnOnce(Result<DBusConnection, glib::Error>) + 'static>(
        stream: &impl IsA<IOStream>,
        guid: Option<&str>,
        flags: DBusConnectionFlags,
        observer: Option<&DBusAuthObserver>,
        cancellable: Option<&impl IsA<Cancellable>>,
        callback: P,
    ) {
        let main_context = glib::MainContext::ref_thread_default();
        let is_main_context_owner = main_context.is_owner();
        let has_acquired_main_context = (!is_main_context_owner)
            .then(|| main_context.acquire().ok())
            .flatten();
        assert!(
            is_main_context_owner || has_acquired_main_context.is_some(),
            "Async operations only allowed if the thread is owning the MainContext"
        );

        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
        unsafe extern "C" fn new_trampoline<
            P: FnOnce(Result<DBusConnection, glib::Error>) + 'static,
        >(
            _source_object: *mut glib::gobject_ffi::GObject,
            res: *mut crate::ffi::GAsyncResult,
            user_data: glib::ffi::gpointer,
        ) {
            let mut error = ptr::null_mut();
            let ret = ffi::g_dbus_connection_new_finish(res, &mut error);
            let result = if error.is_null() {
                Ok(from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            };
            let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
                Box_::from_raw(user_data as *mut _);
            let callback: P = callback.into_inner();
            callback(result);
        }
        let callback = new_trampoline::<P>;
        unsafe {
            ffi::g_dbus_connection_new(
                stream.as_ref().to_glib_none().0,
                guid.to_glib_none().0,
                flags.into_glib(),
                observer.to_glib_none().0,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                Some(callback),
                Box_::into_raw(user_data) as *mut _,
            );
        }
    }

    pub fn new_future(
        stream: &(impl IsA<IOStream> + Clone + 'static),
        guid: Option<&str>,
        flags: DBusConnectionFlags,
        observer: Option<&DBusAuthObserver>,
    ) -> Pin<Box_<dyn std::future::Future<Output = Result<DBusConnection, glib::Error>> + 'static>>
    {
        let stream = stream.clone();
        let guid = guid.map(ToOwned::to_owned);
        let observer = observer.map(ToOwned::to_owned);
        Box_::pin(crate::GioFuture::new(
            &(),
            move |_obj, cancellable, send| {
                Self::new(
                    &stream,
                    guid.as_ref().map(::std::borrow::Borrow::borrow),
                    flags,
                    observer.as_ref().map(::std::borrow::Borrow::borrow),
                    Some(cancellable),
                    move |res| {
                        send.resolve(res);
                    },
                );
            },
        ))
    }

    /// Asynchronously connects and sets up a D-Bus client connection for
    /// exchanging D-Bus messages with an endpoint specified by `address`
    /// which must be in the
    /// [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html`addresses`).
    ///
    /// This constructor can only be used to initiate client-side
    /// connections - use [`new()`][Self::new()] if you need to act as the
    /// server. In particular, `flags` cannot contain the
    /// [`DBusConnectionFlags::AUTHENTICATION_SERVER`][crate::DBusConnectionFlags::AUTHENTICATION_SERVER],
    /// [`DBusConnectionFlags::AUTHENTICATION_ALLOW_ANONYMOUS`][crate::DBusConnectionFlags::AUTHENTICATION_ALLOW_ANONYMOUS] or
    /// [`DBusConnectionFlags::AUTHENTICATION_REQUIRE_SAME_USER`][crate::DBusConnectionFlags::AUTHENTICATION_REQUIRE_SAME_USER] flags.
    ///
    /// When the operation is finished, `callback` will be invoked. You can
    /// then call `g_dbus_connection_new_for_address_finish()` to get the result of
    /// the operation.
    ///
    /// If `observer` is not [`None`] it may be used to control the
    /// authentication process.
    ///
    /// This is an asynchronous failable constructor. See
    /// [`for_address_sync()`][Self::for_address_sync()] for the synchronous
    /// version.
    /// ## `address`
    /// a D-Bus address
    /// ## `flags`
    /// flags describing how to make the connection
    /// ## `observer`
    /// a [`DBusAuthObserver`][crate::DBusAuthObserver] or [`None`]
    /// ## `cancellable`
    /// a [`Cancellable`][crate::Cancellable] or [`None`]
    /// ## `callback`
    /// a `GAsyncReadyCallback` to call when the request is satisfied
    #[doc(alias = "g_dbus_connection_new_for_address")]
    #[doc(alias = "new_for_address")]
    pub fn for_address<P: FnOnce(Result<DBusConnection, glib::Error>) + 'static>(
        address: &str,
        flags: DBusConnectionFlags,
        observer: Option<&DBusAuthObserver>,
        cancellable: Option<&impl IsA<Cancellable>>,
        callback: P,
    ) {
        let main_context = glib::MainContext::ref_thread_default();
        let is_main_context_owner = main_context.is_owner();
        let has_acquired_main_context = (!is_main_context_owner)
            .then(|| main_context.acquire().ok())
            .flatten();
        assert!(
            is_main_context_owner || has_acquired_main_context.is_some(),
            "Async operations only allowed if the thread is owning the MainContext"
        );

        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
        unsafe extern "C" fn for_address_trampoline<
            P: FnOnce(Result<DBusConnection, glib::Error>) + 'static,
        >(
            _source_object: *mut glib::gobject_ffi::GObject,
            res: *mut crate::ffi::GAsyncResult,
            user_data: glib::ffi::gpointer,
        ) {
            let mut error = ptr::null_mut();
            let ret = ffi::g_dbus_connection_new_for_address_finish(res, &mut error);
            let result = if error.is_null() {
                Ok(from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            };
            let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
                Box_::from_raw(user_data as *mut _);
            let callback: P = callback.into_inner();
            callback(result);
        }
        let callback = for_address_trampoline::<P>;
        unsafe {
            ffi::g_dbus_connection_new_for_address(
                address.to_glib_none().0,
                flags.into_glib(),
                observer.to_glib_none().0,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                Some(callback),
                Box_::into_raw(user_data) as *mut _,
            );
        }
    }

    pub fn for_address_future(
        address: &str,
        flags: DBusConnectionFlags,
        observer: Option<&DBusAuthObserver>,
    ) -> Pin<Box_<dyn std::future::Future<Output = Result<DBusConnection, glib::Error>> + 'static>>
    {
        let address = String::from(address);
        let observer = observer.map(ToOwned::to_owned);
        Box_::pin(crate::GioFuture::new(
            &(),
            move |_obj, cancellable, send| {
                Self::for_address(
                    &address,
                    flags,
                    observer.as_ref().map(::std::borrow::Borrow::borrow),
                    Some(cancellable),
                    move |res| {
                        send.resolve(res);
                    },
                );
            },
        ))
    }

    /// Emitted when the connection is closed.
    ///
    /// The cause of this event can be
    ///
    /// - If [`close()`][Self::close()] is called. In this case
    ///  `remote_peer_vanished` is set to [`false`] and `error` is [`None`].
    ///
    /// - If the remote peer closes the connection. In this case
    ///  `remote_peer_vanished` is set to [`true`] and `error` is set.
    ///
    /// - If the remote peer sends invalid or malformed data. In this
    ///  case `remote_peer_vanished` is set to [`false`] and `error` is set.
    ///
    /// Upon receiving this signal, you should give up your reference to
    /// `connection`. You are guaranteed that this signal is emitted only
    /// once.
    /// ## `remote_peer_vanished`
    /// [`true`] if `connection` is closed because the
    ///  remote peer closed its end of the connection
    /// ## `error`
    /// a [`glib::Error`][crate::glib::Error] with more details about the event or [`None`]
    #[doc(alias = "closed")]
    pub fn connect_closed<F: Fn(&Self, bool, Option<&glib::Error>) + Send + Sync + 'static>(
        &self,
        f: F,
    ) -> SignalHandlerId {
        unsafe extern "C" fn closed_trampoline<
            F: Fn(&DBusConnection, bool, Option<&glib::Error>) + Send + Sync + 'static,
        >(
            this: *mut ffi::GDBusConnection,
            remote_peer_vanished: glib::ffi::gboolean,
            error: *mut glib::ffi::GError,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(
                &from_glib_borrow(this),
                from_glib(remote_peer_vanished),
                Option::<glib::Error>::from_glib_borrow(error)
                    .as_ref()
                    .as_ref(),
            )
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"closed\0".as_ptr() as *const _,
                Some(transmute::<_, unsafe extern "C" fn()>(
                    closed_trampoline::<F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }

    #[doc(alias = "capabilities")]
    pub fn connect_capabilities_notify<F: Fn(&Self) + Send + Sync + 'static>(
        &self,
        f: F,
    ) -> SignalHandlerId {
        unsafe extern "C" fn notify_capabilities_trampoline<
            F: Fn(&DBusConnection) + Send + Sync + 'static,
        >(
            this: *mut ffi::GDBusConnection,
            _param_spec: glib::ffi::gpointer,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(&from_glib_borrow(this))
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::capabilities\0".as_ptr() as *const _,
                Some(transmute::<_, unsafe extern "C" fn()>(
                    notify_capabilities_trampoline::<F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }

    #[doc(alias = "closed")]
    pub fn connect_closed_notify<F: Fn(&Self) + Send + Sync + 'static>(
        &self,
        f: F,
    ) -> SignalHandlerId {
        unsafe extern "C" fn notify_closed_trampoline<
            F: Fn(&DBusConnection) + Send + Sync + 'static,
        >(
            this: *mut ffi::GDBusConnection,
            _param_spec: glib::ffi::gpointer,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(&from_glib_borrow(this))
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::closed\0".as_ptr() as *const _,
                Some(transmute::<_, unsafe extern "C" fn()>(
                    notify_closed_trampoline::<F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }

    #[doc(alias = "exit-on-close")]
    pub fn connect_exit_on_close_notify<F: Fn(&Self) + Send + Sync + 'static>(
        &self,
        f: F,
    ) -> SignalHandlerId {
        unsafe extern "C" fn notify_exit_on_close_trampoline<
            F: Fn(&DBusConnection) + Send + Sync + 'static,
        >(
            this: *mut ffi::GDBusConnection,
            _param_spec: glib::ffi::gpointer,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(&from_glib_borrow(this))
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::exit-on-close\0".as_ptr() as *const _,
                Some(transmute::<_, unsafe extern "C" fn()>(
                    notify_exit_on_close_trampoline::<F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }

    #[doc(alias = "unique-name")]
    pub fn connect_unique_name_notify<F: Fn(&Self) + Send + Sync + 'static>(
        &self,
        f: F,
    ) -> SignalHandlerId {
        unsafe extern "C" fn notify_unique_name_trampoline<
            F: Fn(&DBusConnection) + Send + Sync + 'static,
        >(
            this: *mut ffi::GDBusConnection,
            _param_spec: glib::ffi::gpointer,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(&from_glib_borrow(this))
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::unique-name\0".as_ptr() as *const _,
                Some(transmute::<_, unsafe extern "C" fn()>(
                    notify_unique_name_trampoline::<F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }
}

unsafe impl Send for DBusConnection {}
unsafe impl Sync for DBusConnection {}

impl fmt::Display for DBusConnection {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("DBusConnection")
    }
}