summaryrefslogtreecommitdiffstats
path: root/python/dbus_bindings.pyx
blob: 836dbf8e77dbcea5f1fc433cd2e06995b8592867 (plain)
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
# -*- Mode: Python -*-

# jdahlin is the most coolest and awesomest person in the world
# and wrote all the good parts of this code. all the bad parts
# where python conditionals have a ( ) around them, thus violating
# PEP-8 were written by the lame wannabe python programmer seth

#FIXME: find memory leaks that I am sure exist

cdef extern from "sys/types.h":
    ctypedef size_t
    ctypedef __int64_t
    ctypedef __uint64_t

cdef extern from "sys/cdefs.h":
    ctypedef __signed

cdef extern from "stdlib.h":
    cdef void *malloc(size_t size)
    cdef void free(void *ptr)
    cdef void *calloc(size_t nmemb, size_t size)

cdef extern from "Python.h":
    void Py_XINCREF (object)
    void Py_XDECREF (object)
    object PyString_FromStringAndSize(char *, int)
    ctypedef void *PyGILState_STATE
    void PyErr_Clear()
    PyGILState_STATE PyGILState_Ensure()
    void PyGILState_Release(PyGILState_STATE)

ctypedef struct DBusError:
    char *name
    char *message
    unsigned int dummy1 
    unsigned int dummy2
    unsigned int dummy3
    unsigned int dummy4
    unsigned int dummy5
    void *padding1
    
ctypedef struct DBusMessageIter:
    void *dummy1
    void *dummy2
    dbus_uint32_t dummy3
    int dummy4
    int dummy5
    int dummy6
    int dummy7
    int dummy8
    int dummy9
    int dummy10
    int dummy11
    int pad1
    int pad2
    void *pad3

ctypedef struct DBusObjectPathVTable:
  DBusObjectPathUnregisterFunction   unregister_function
  DBusObjectPathMessageFunction      message_function
  void (* dbus_internal_pad1) (void *)
  void (* dbus_internal_pad2) (void *)
  void (* dbus_internal_pad3) (void *)
  void (* dbus_internal_pad4) (void *)

class DBusException(Exception):
    pass

class ConnectionError(Exception):
    pass

class ObjectPath(str):
    def __init__(self, value):
        str.__init__(self, value)

class ByteArray(str):
    def __init__(self, value):
        str.__init__(self, value)

class SignatureIter(object):
    def __init__(self, string):
        object.__init__(self)
        self.remaining = string

    def next(self):
        if self.remaining == '':
            raise StopIteration

        signature = self.remaining
        block_depth = 0
        block_type = None
        end = len(signature)

        for marker in range(0, end):
            cur_sig = ord(signature[marker])

            if cur_sig == TYPE_ARRAY:
                pass
            elif cur_sig == DICT_ENTRY_BEGIN or cur_sig == STRUCT_BEGIN:
                if block_type == None:
                    block_type = cur_sig

                if block_type == cur_sig:
                    block_depth = block_depth + 1

            elif cur_sig == DICT_ENTRY_END:
                if block_type == DICT_ENTRY_BEGIN:
                    block_depth = block_depth - 1

                if block_depth == 0:
                    end = marker
                    break

            elif cur_sig == STRUCT_END:
                if block_type == STRUCT_BEGIN:
                    block_depth = block_depth - 1

                if block_depth == 0:
                    end = marker
                    break

            else:
                if block_depth == 0:
                    end = marker
                    break

        end = end + 1
        self.remaining = signature[end:]
        return Signature(signature[0:end])

class Signature(str):
    """An iterable method signature. Iterating gives the signature of each
    argument in turn."""
    def __init__(self, value):
        return str.__init__(self, value)

    def __iter__(self):
        return SignatureIter(self)

class VariantSignature(object):
    """A fake method signature which when iterated, is an endless stream
    of variants (handy with zip()). It has no string representation."""
    def __iter__(self):
        return self

    def next(self):
        return 'v'

class Byte(int):
    def __init__(self, value):
        int.__init__(self, value)

class Boolean(int):
    def __init__(self, value):
        int.__init__(self, value)

class Int16(int):
    def __init__(self, value):
        int.__init__(self, value)

class UInt16(int):
    def __init__(self, value):
        if value < 0:
            raise TypeError('Unsigned integers must not have a negitive value') 
        int.__init__(self, value)

class Int32(int):
    def __init__(self, value):
        int.__init__(self, value)

class UInt32(long):
    def __init__(self, value):
        if value < 0:
            raise TypeError('Unsigned integers must not have a negitive value') 
        long.__init__(self, value)

class Int64(long):
    def __init__(self, value):
        long.__init__(self, value)

class UInt64(long):
    def __init__(self, value):
        if value < 0:
            raise TypeError('Unsigned integers must not have a negitive value') 
        long.__init__(self, value)

class Double(float):
    def __init__(self, value):
        float.__init__(self, value)

class String(unicode):
    def __init__(self, value):
        unicode.__init__(self, value)

class Array(list):
    def __init__(self, value, type=None, signature=None):
        if signature and type:
            raise TypeError('Can not mix type and signature arguments in a D-BUS Array')
    
        self.type = type
        self.signature = signature
        list.__init__(self, value)

class Variant:
    def __init__(self, value, type=None, signature=None):
        self.value = value
        if signature and type:
            raise TypeError('Can not mix type and signature arguments in a D-BUS Variant')

        self.type = type
        self.signature = signature

    def __repr__(self):
        return repr(self.value)

    def __str__(self):
        return str(self.value)

class Struct(tuple):
    def __init__(self, value):
        tuple.__init__(self, value)

class Dictionary(dict):
    def __init__(self, value, key_type=None, value_type=None, signature=None):
        if key_type and not value_type:
             raise TypeError('When specifying a key_type you must also have a value_type in a D-BUS Dictionary')
        elif value_type and not key_type:
             raise TypeError('When specifying a value_type you must also have a key_type in a D-BUS Dictionary')
        elif key_type and signature:
              raise TypeError('Can not mix type arguments with signature arguments in a D-BUS Dictionary')
              
        self.key_type = key_type
        self.value_type = value_type
        self.signature = signature
        dict.__init__(self, value)

#forward delcerations
cdef class Message
cdef class PendingCall
cdef class Watch
cdef class MessageIter

cdef void _GIL_safe_cunregister_function_handler (DBusConnection *connection,
                                                  void *user_data):
    cdef Connection conn

    tup = <object>user_data
    assert (type(tup) == tuple)    
    function = tup[1]
    conn = Connection()
    conn.__cinit__(None, connection)

    args = (conn)
    function(*args)
    Py_XDECREF(tup) 

cdef void cunregister_function_handler (DBusConnection *connection,
                                        void *user_data):
    cdef PyGILState_STATE gil
    gil = PyGILState_Ensure()
    try:
        _GIL_safe_cunregister_function_handler (connection, user_data);
    finally:
        PyGILState_Release(gil)



cdef DBusHandlerResult _GIL_safe_cmessage_function_handler ( 
                                                  DBusConnection *connection,
                                                  DBusMessage *msg,
                                                  void *user_data):
    cdef Connection conn
    cdef Message message

    tup = <object>user_data
    assert (type(tup) == tuple)
    function = tup[0]
    message = EmptyMessage()

    #we don't own the message so we need to ref it
    dbus_message_ref(msg)
    message._set_msg(msg)
    conn = Connection()
    conn.__cinit__(None, connection)
    args = (conn,
            message)
 
    retval = function(*args)

    if (retval == None):
        retval = DBUS_HANDLER_RESULT_HANDLED
    return retval

cdef DBusHandlerResult cmessage_function_handler (DBusConnection *connection,
                                                  DBusMessage *msg,
                                                  void *user_data):
    cdef PyGILState_STATE gil
    gil = PyGILState_Ensure()
    try:
        return _GIL_safe_cmessage_function_handler (connection, msg, user_data);
    finally:
        PyGILState_Release(gil)


cdef class Connection:
    def __init__(self, address=None, Connection _conn=None):
        cdef DBusConnection *c_conn
        cdef char *c_address
        c_conn=NULL
        self.conn = NULL
        if (_conn != None):
            c_conn = _conn.conn

        if (address != None or _conn != None):
            self.__cinit__(c_address, c_conn)

    # hack to be able to pass in a c pointer to the constructor
    # while still alowing python programs to create a Connection object
    cdef __cinit__(self, address, DBusConnection *_conn):
        cdef DBusError error
        dbus_error_init(&error)
        if _conn != NULL:
            self.conn = _conn
            dbus_connection_ref(self.conn)
        else:
            self.conn = dbus_connection_open(address,
                                         &error)
            if dbus_error_is_set(&error):
                errormsg = error.message
                dbus_error_free (&error)
                raise DBusException, errormsg

    def __dealloc__(self):
        if self.conn != NULL:
            dbus_connection_unref(self.conn)

    cdef _set_conn(self, DBusConnection *conn):
        self.conn = conn
    
    cdef DBusConnection *_get_conn(self):
        return self.conn
    
    def get_unique_name(self):
        return bus_get_unique_name(self)

    def close(self):
        dbus_connection_close(self.conn)

    def get_is_connected(self):
        return dbus_connection_get_is_connected(self.conn)
    
    def get_is_authenticated(self):
        return dbus_connection_get_is_authenticated(self.conn)

    def flush(self):
        dbus_connection_flush(self.conn)

    def borrow_message(self):
        cdef Message m
        m = EmptyMessage()
        m._set_msg(dbus_connection_borrow_message(self.conn))
        return m
    
    def return_message(self, Message message):
        cdef DBusMessage *msg
        msg = message._get_msg()
        dbus_connection_return_message(self.conn, msg)

    def steal_borrowed_message(self, Message message):
        cdef DBusMessage *msg
        msg = message._get_msg()
        dbus_connection_steal_borrowed_message(self.conn,
                                               msg)
    
    def pop_message(self):
        cdef DBusMessage *msg
        cdef Message m
 
        msg = dbus_connection_pop_message(self.conn)
        if msg != NULL:
            m = EmptyMessage()
            m._set_msg(msg)
        else:
            m = None
        return m        

    def get_dispatch_status(self):
        return dbus_connection_get_dispatch_status(self.conn)
    
    def dispatch(self):
        return dbus_connection_dispatch(self.conn)

    def send(self, Message message):
        #cdef dbus_uint32_t client_serial
        #if type(message) != Message:
        #    raise TypeError
        cdef DBusMessage *msg
        msg = message._get_msg()
        retval = dbus_connection_send(self.conn,
                                      msg,
                                      NULL)
        return retval

    def send_with_reply_handlers(self, Message message, timeout_milliseconds, reply_handler, error_handler):
        retval = False
        try:
            (retval, pending_call) = self.send_with_reply(message, timeout_milliseconds)
            if pending_call:
                pending_call.set_notify(reply_handler, error_handler)
        except Exception, e:
            error_handler(e)
            
        return (retval, pending_call)

    def send_with_reply(self, Message message, timeout_milliseconds):
        cdef dbus_bool_t retval
        cdef DBusPendingCall *cpending_call
        cdef DBusMessage *msg
        cdef PendingCall pending_call

        cpending_call = NULL
        
        msg = message._get_msg()

        retval = dbus_connection_send_with_reply(self.conn,
                                                 msg,
                                                 &cpending_call,
                                                 timeout_milliseconds)

        if (cpending_call != NULL):
            pending_call = PendingCall()
            pending_call.__cinit__(cpending_call)
        else:
            pending_call = None

        return (retval, pending_call)
                                
    def send_with_reply_and_block(self, Message message,
                                  timeout_milliseconds=-1):
        cdef DBusMessage * retval
        cdef DBusError error
        cdef DBusMessage *msg
        cdef Message m

        dbus_error_init(&error)

        msg = message._get_msg()

        retval = dbus_connection_send_with_reply_and_block(
            self.conn,
            msg,
            timeout_milliseconds,
            &error)

        if dbus_error_is_set(&error):
            errormsg = error.message
            dbus_error_free (&error)
            raise DBusException, errormsg

        assert(retval != NULL)

        m = EmptyMessage()
        m._set_msg(retval)

        return m

    def set_watch_functions(self, add_function, remove_function, data):
        pass

    def set_timeout_functions(self, add_function, remove_function, data):
        pass

    def set_wakeup_main_function(self, wakeup_main_function, data):
        pass

    # FIXME: set_dispatch_status_function, get_unix_user, set_unix_user_function

    def add_filter(self, filter_function):
        user_data = (filter_function,)
        Py_XINCREF(user_data)
       
        return dbus_connection_add_filter(self.conn,
                                          cmessage_function_handler,
                                          <void*>user_data,
                                          NULL)


    #FIXME: remove_filter
    #       this is pretty tricky, we want to only remove the filter
    #       if we truly have no more calls to our message_function_handler...ugh

    def set_data(self, slot, data):
        pass

    def get_data(self, slot):
        pass

    def set_max_message_size(self, size):
        dbus_connection_set_max_message_size(self.conn, size)

    def get_max_message_size(self):
        return dbus_connection_get_max_message_size(self.conn)

    def set_max_received_size(self, size):
        dbus_connection_set_max_received_size(self.conn, size)

    def get_max_received_size(self):
        return dbus_connection_get_max_received_size(self.conn)

    def get_outgoing_size(self):
        return dbus_connection_get_outgoing_size(self.conn)    

    # preallocate_send, free_preallocated_send, send_preallocated

    def register_object_path(self, path, unregister_cb, message_cb):
        cdef DBusObjectPathVTable cvtable
        
        cvtable.unregister_function = cunregister_function_handler 
        cvtable.message_function    = cmessage_function_handler

        user_data = (message_cb, unregister_cb)
        Py_XINCREF(user_data)
        
        return dbus_connection_register_object_path(self.conn, path, &cvtable,
                                                    <void*>user_data) 

    def register_fallback(self, path, unregister_cb, message_cb):
        cdef DBusObjectPathVTable cvtable

        cvtable.unregister_function = cunregister_function_handler 
        cvtable.message_function    = cmessage_function_handler

        user_data = (message_cb, unregister_cb)
        Py_XINCREF(user_data)
       
        return dbus_connection_register_fallback(self.conn, path, &cvtable,
                                                 <void*>user_data) 

    #FIXME: unregister_object_path , see problems with remove_filter

    def list_registered (self, parent_path):
        cdef char **cchild_entries
        cdef dbus_bool_t retval
        
        retval = dbus_connection_list_registered(self.conn, parent_path, &cchild_entries)

        if (not retval):
            #FIXME: raise out of memory exception?
            return None

        i = 0
        child_entries = []

        while (cchild_entries[i] != NULL):
            child_entries.append(cchild_entries[i])
            i = i + 1

        dbus_free_string_array(cchild_entries)

        return child_entries

cdef void _GIL_safe_pending_call_notification (DBusPendingCall *pending_call, 
                                               void *user_data):
    cdef DBusMessage *dbus_message
    cdef Message message
  
    (reply_handler, error_handler) = <object>user_data
   
    dbus_message = dbus_pending_call_steal_reply(pending_call)
    message = EmptyMessage()
    message._set_msg(dbus_message)

    type = message.get_type()

    if type == MESSAGE_TYPE_METHOD_RETURN:
        args = message.get_args_list()
        reply_handler(*args)
    elif type == MESSAGE_TYPE_ERROR:
        args = message.get_args_list()
        if len(args) > 0:
            error_handler(DBusException(args[0]))
        else:
            error_handler(DBusException(""))
    else:
        error_handler(DBusException('Unexpected Message Type: ' + message.type_to_name(type)))

    dbus_pending_call_unref(pending_call)
    Py_XDECREF(<object>user_data)

cdef void _pending_call_notification(DBusPendingCall *pending_call, 
                                     void *user_data):
    cdef PyGILState_STATE gil
    gil = PyGILState_Ensure()
    try:
        _GIL_safe_pending_call_notification (pending_call, user_data);
    finally:
        PyGILState_Release(gil)

cdef void _pending_call_free_user_data(void *data):
    call_tuple = <object>data
    Py_XDECREF(call_tuple)

cdef class PendingCall:
    cdef DBusPendingCall *pending_call

    def __init__(self, PendingCall _pending_call=None):
        self.pending_call = NULL
        if (_pending_call != None):
            self.__cinit__(_pending_call.pending_call)

    cdef void __cinit__(self, DBusPendingCall *_pending_call):
        self.pending_call = _pending_call
        dbus_pending_call_ref(self.pending_call)

    def __dealloc__(self):
        if self.pending_call != NULL:
            dbus_pending_call_unref(self.pending_call)

    cdef DBusPendingCall *_get_pending_call(self):
        return self.pending_call

    def cancel(self):
        dbus_pending_call_cancel(self.pending_call)

    def get_completed(self):
        return dbus_pending_call_get_completed(self.pending_call)

    def get_reply(self):
        cdef Message message
        message = EmptyMessage()
        message._set_msg(dbus_pending_call_steal_reply(self.pending_call))
        return message

    def block(self):
        dbus_pending_call_block(self.pending_call)

    def set_notify(self, reply_handler, error_handler):
        user_data = (reply_handler, error_handler)
        Py_XINCREF(user_data)
        dbus_pending_call_ref(self.pending_call)
        dbus_pending_call_set_notify(self.pending_call, _pending_call_notification, 
                                     <void *>user_data, _pending_call_free_user_data)
        

cdef class Watch:
    cdef DBusWatch* watch

    def __init__(self):
        pass

    cdef __cinit__(self, DBusWatch *cwatch):
        self.watch = cwatch

    def get_fd(self):
        return dbus_watch_get_fd(self.watch)

    # FIXME: not picked up correctly by extract.py
    #def get_flags(self):
    #    return dbus_watch_get_flags(self.watch)

    def handle(self, flags):
        return dbus_watch_handle(self.watch, flags)

    def get_enabled(self):
        return dbus_watch_get_enabled(self.watch)
    
cdef class MessageIter:
    cdef DBusMessageIter *iter
    cdef DBusMessageIter real_iter
    cdef dbus_uint32_t level

    def __init__(self, level=0):
        self.iter = &self.real_iter
        self.level = level
        if(self.level > 32):
            raise TypeError, 'Type recurion is too deep' 

    cdef __cinit__(self, DBusMessageIter *iter):
        self.real_iter = iter[0]

    cdef DBusMessageIter *_get_iter(self):
        return self.iter

    def has_next(self):
        return dbus_message_iter_has_next(self.iter)
    
    def next(self):
        return dbus_message_iter_next(self.iter)

    def get(self, arg_type=None):
        if(arg_type == None):
            arg_type = self.get_arg_type()

        if arg_type == TYPE_INVALID:
            raise TypeError, 'Invalid arg type in MessageIter'
        elif arg_type == TYPE_STRING:
            retval = self.get_string()
        elif arg_type == TYPE_INT16:
            retval = self.get_int16()
        elif arg_type == TYPE_UINT16:
            retval = self.get_uint16()
        elif arg_type == TYPE_INT32:
            retval = self.get_int32()
        elif arg_type == TYPE_UINT32:
            retval = self.get_uint32()
        elif arg_type == TYPE_INT64:
            retval = self.get_int64()
        elif arg_type == TYPE_UINT64:
            retval = self.get_uint64()
        elif arg_type == TYPE_DOUBLE:
            retval = self.get_double()
        elif arg_type == TYPE_BYTE:
            retval = self.get_byte()
        elif arg_type == TYPE_BOOLEAN:
            retval = self.get_boolean()
        elif arg_type == TYPE_SIGNATURE:
            retval = self.get_signature()
        elif arg_type == TYPE_ARRAY:
            array_type = self.get_element_type()
            if array_type == TYPE_DICT_ENTRY:
                retval = self.get_dict()
            else:
                retval = self.get_array(array_type)
        elif arg_type == TYPE_OBJECT_PATH:
            retval = self.get_object_path()
        elif arg_type == TYPE_STRUCT:
            retval = self.get_struct()
        elif arg_type == TYPE_VARIANT:
            retval = self.get_variant()
        elif arg_type == TYPE_DICT_ENTRY:
            raise TypeError, 'Dictionary Entries can only appear as part of an array container'
        else:
            raise TypeError, 'Unknown arg type %d in MessageIter' % (arg_type)

        return retval

    def get_arg_type(self):
        return dbus_message_iter_get_arg_type(self.iter)

    def get_element_type(self):
        return dbus_message_iter_get_element_type(self.iter)

    def get_byte(self):
        cdef unsigned char c_val
        dbus_message_iter_get_basic(self.iter, <unsigned char *>&c_val)
        return c_val

    def get_boolean(self):
        cdef dbus_bool_t c_val
        dbus_message_iter_get_basic(self.iter, <dbus_bool_t *>&c_val)

        if c_val:
            return True
        else:
            return False 

    def get_signature(self):
        signature_string = self.get_string()
        return Signature(signature_string)

    def get_int16(self):
        cdef dbus_int16_t c_val
        dbus_message_iter_get_basic(self.iter, <dbus_int16_t *>&c_val)

        return c_val

    def get_uint16(self):
        cdef dbus_uint16_t c_val
        dbus_message_iter_get_basic(self.iter, <dbus_uint16_t *>&c_val)
        return c_val

    def get_int32(self):
        cdef dbus_int32_t c_val
        dbus_message_iter_get_basic(self.iter, <dbus_int32_t *>&c_val)
        return c_val
        
    def get_uint32(self):
        cdef dbus_uint32_t c_val
        dbus_message_iter_get_basic(self.iter, <dbus_uint32_t *>&c_val)
        return c_val
        
    def get_int64(self):
        cdef dbus_int64_t c_val
        dbus_message_iter_get_basic(self.iter, <dbus_int64_t *>&c_val)
        return c_val

    def get_uint64(self):
        cdef dbus_uint64_t c_val
        dbus_message_iter_get_basic(self.iter, <dbus_uint64_t *>&c_val)
        return c_val

    def get_double(self):
        cdef double c_val
        dbus_message_iter_get_basic(self.iter, <double *>&c_val)
        return c_val

    def get_string(self):
        cdef char *c_str
        dbus_message_iter_get_basic(self.iter, <char **>&c_str)
        ret = c_str.decode('utf8')

        return ret

    def get_object_path(self):
        object_path_string = self.get_string()
        return ObjectPath(object_path_string)

    def get_dict(self):
        cdef DBusMessageIter c_dict_iter
        cdef MessageIter dict_iter
        level = self.level + 1

        dbus_message_iter_recurse(self.iter, <DBusMessageIter *>&c_dict_iter)
        dict_iter = MessageIter(level)
        dict_iter.__cinit__(&c_dict_iter)
        
        python_dict = {}
        cur_arg_type = dict_iter.get_arg_type()
        while cur_arg_type == TYPE_DICT_ENTRY:
            if cur_arg_type != TYPE_DICT_ENTRY:
                raise TypeError, "Dictionary elements must be of type TYPE_DICT_ENTRY '%s != %s'" % (TYPE_DICT_ENTRY, cur_arg_type)
                
            dict_entry = dict_iter.get_struct()
            if len(dict_entry) != 2:
                raise TypeError, "Dictionary entries must be structs of two elements.  This entry had %i elements.'" % (len(dict_entry))

            python_dict[dict_entry[0]] = dict_entry[1]
            
            dict_iter.next()
            cur_arg_type = dict_iter.get_arg_type()

        return python_dict
   
    def get_array(self, type):
        cdef DBusMessageIter c_array_iter
        cdef MessageIter array_iter
        level = self.level + 1

        dbus_message_iter_recurse(self.iter, <DBusMessageIter *>&c_array_iter)
        array_iter = MessageIter(level)
        array_iter.__cinit__(&c_array_iter)
        
        python_list = []
        cur_arg_type = array_iter.get_arg_type()
        while cur_arg_type != TYPE_INVALID:
            if cur_arg_type != type:
                raise TypeError, "Array elements must be of the same type '%s != %s'" % (type, cur_arg_type)
                
            value = array_iter.get(type)
            python_list.append(value)
            
            array_iter.next()
            cur_arg_type = array_iter.get_arg_type()

        return python_list

    def get_variant(self):
        cdef DBusMessageIter c_var_iter
        cdef MessageIter var_iter
        level = self.level + 1

        dbus_message_iter_recurse(self.iter, <DBusMessageIter *>&c_var_iter)
        var_iter = MessageIter(level)
        var_iter.__cinit__(&c_var_iter)
        
        return var_iter.get() 

    def get_struct(self):
        cdef DBusMessageIter c_struct_iter
        cdef MessageIter struct_iter
        level = self.level + 1

        dbus_message_iter_recurse(self.iter, <DBusMessageIter *>&c_struct_iter)
        struct_iter = MessageIter(level)
        struct_iter.__cinit__(&c_struct_iter)

        python_list = []
        while struct_iter.get_arg_type() != TYPE_INVALID:
            value = struct_iter.get()
            python_list.append(value)
            
            struct_iter.next()

        return tuple(python_list)

    def python_value_to_dbus_sig(self, value, level = 0):

        if(level > 32):
            raise TypeError, 'Type recurion is too deep' 

        level = level + 1

        ptype = type(value)
        ret = ""
        if ptype == bool:
            ret = TYPE_BOOLEAN
            ret = str(chr(ret))
        elif ptype == int:
            ret = TYPE_INT32
            ret = str(chr(ret))
        elif ptype == long:
            ret = TYPE_INT64
            ret = str(chr(ret))
        elif (ptype == str or ptype == unicode):
            ret = TYPE_STRING
            ret = str(chr(ret))
        elif ptype == float:
            ret = TYPE_DOUBLE
            ret = str(chr(ret))
        elif ptype == dict:
            dict_list = value.items()
            key, value = dict_list[0]

            ret = str(chr(TYPE_ARRAY)) + str(chr(DICT_ENTRY_BEGIN))
            ret = ret + self.python_value_to_dbus_sig(key, level)
            ret = ret + self.python_value_to_dbus_sig(value, level)
            ret = ret + str(chr(DICT_ENTRY_END))

        elif ptype == tuple:
            ret = str(chr(STRUCT_BEGIN))
            for item in value:
                ret = ret + self.python_value_to_dbus_sig(item, level)
            ret = ret + str(chr(STRUCT_END))
        elif ptype == list:
            ret = str(chr(TYPE_ARRAY))
            ret = ret + self.python_value_to_dbus_sig(value[0], level)
        elif isinstance(value, ObjectPath) or value == ObjectPath:

            ret = TYPE_OBJECT_PATH
            ret = str(chr(ret))
        elif isinstance(value, ByteArray) or value == ByteArray:
            ret = str(chr(TYPE_ARRAY)) + str(chr(TYPE_BYTE))
        elif isinstance(value, Signature) or value == Signature:
            ret = TYPE_SIGNATURE
            ret = str(chr(ret))
        elif isinstance(value, Byte) or value == Byte:
            ret = TYPE_BYTE
            ret = str(chr(ret))
        elif isinstance(value, Boolean) or value == Boolean:
            ret = TYPE_BOOLEAN
            ret = str(chr(ret))
        elif isinstance(value, Int16) or value == Int16:
            ret = TYPE_INT16
            ret = str(chr(ret))
        elif isinstance(value, UInt16) or value == UInt16:
            ret = TYPE_UINT16
            ret = str(chr(ret))
        elif isinstance(value, Int32) or value == Int32:
            ret = TYPE_INT32
            ret = str(chr(ret))
        elif isinstance(value, UInt32) or value == UInt32:
            ret = TYPE_UINT32
            ret = str(chr(ret))
        elif isinstance(value, Int64) or value == Int64:
            ret = TYPE_INT64
            ret = str(chr(ret))
        elif isinstance(value, UInt64) or value == UInt64:
            ret = TYPE_UINT64
            ret = str(chr(ret))
        elif isinstance(value, Double) or value == Double:
            ret = TYPE_DOUBLE
            ret = str(chr(ret))
        elif isinstance(value, String) or value == String:
            ret = TYPE_STRING
            ret = str(chr(ret))
        elif isinstance(value, Array):
            ret = str(chr(TYPE_ARRAY))
            if value.type == None:
                if value.signature:
                    ret = ret + value.signature
                else:
                    ret = ret + self.python_value_to_dbus_sig(value[0], level)
            else:
                ret = ret + self.python_value_to_dbus_sig(value.type, level)

        elif isinstance(value, Struct) or value == Struct:
            ret = str(chr(STRUCT_BEGIN))
            for item in value:
                ret = ret + self.python_value_to_dbus_sig(item, level)
            ret = ret + str(chr(STRUCT_END))
        elif isinstance(value, Dictionary):
            ret = str(chr(TYPE_ARRAY)) + str(chr(DICT_ENTRY_BEGIN))
            
            if value.key_type and value.value_type:
                ret = ret + self.python_value_to_dbus_sig(value.key_type, level)
                ret = ret + self.python_value_to_dbus_sig(value.value_type, level)
            elif value.signature:
                ret = ret + value.signature
            else:
                dict_list = value.items()

                key, val = dict_list[0]
                ret = ret + self.python_value_to_dbus_sig(key, level)
                ret = ret + self.python_value_to_dbus_sig(val, level)
                
            ret = ret + str(chr(DICT_ENTRY_END))
        elif isinstance(value, Variant) or value == Variant:
            ret = ret + str(chr(TYPE_VARIANT))
        else:
            raise TypeError, "Argument of unknown type '%s'" % (ptype)

        return ret

    def append_strict(self, value, sig):
    
        if sig == TYPE_INVALID or sig == None:
            raise TypeError, 'Invalid arg type sent to append_strict'

        sig_type = ord(sig[0])
	    
        if sig_type == TYPE_STRING:
            retval = self.append_string(value)
        elif sig_type == TYPE_INT16:
            retval = self.append_int16(value)
        elif sig_type == TYPE_UINT16:
            retval = self.append_uint16(value)
        elif sig_type == TYPE_INT32:
            retval = self.append_int32(value)
        elif sig_type == TYPE_UINT32:
            retval = self.append_uint32(value)
        elif sig_type == TYPE_INT64:
            retval = self.append_int64(value)
        elif sig_type == TYPE_UINT64:
            retval = self.append_uint64(value)
        elif sig_type == TYPE_DOUBLE:
            retval = self.append_double(value)
        elif sig_type == TYPE_BYTE:
            retval = self.append_byte(value)
        elif sig_type == TYPE_BOOLEAN:
            retval = self.append_boolean(value)
        elif sig_type == TYPE_SIGNATURE:
            retval = self.append_signature(value)
        elif sig_type == TYPE_ARRAY:
            if len(sig) < 2:
                raise TypeError, "Invalid array signature in append_strict.  Arrays must be followed by a type."

            array_type = ord(sig[1])            
            if array_type == DICT_ENTRY_BEGIN:
                if ord(sig[-1]) != DICT_ENTRY_END:
                    raise TypeError, "Invalid dict entry in append_strict.  No termination in signature %s."%(sig)

                tmp_sig = sig[2:-1]
                retval = self.append_dict(Dictionary(value, signature=tmp_sig))
            else:
                tmp_sig = sig[1:]
                retval = self.append_array(Array(value, signature=tmp_sig))
        elif sig_type == TYPE_OBJECT_PATH:
            retval = self.append_object_path(value)
        elif sig_type == STRUCT_BEGIN:
            if ord(sig[-1]) != STRUCT_END:
                raise TypeError, "Invalid struct entry in append_strict. No termination in signature %s." % (sig)

            tmp_sig = sig[1:-1]
            retval = self.append_struct(value, signature = tmp_sig)
        elif sig_type == TYPE_VARIANT:
            if isinstance(value, Variant):
                retval = self.append_variant(value)
            else:
                retval = self.append_variant(Variant(value))
        elif sig_type == DICT_ENTRY_BEGIN:
            raise TypeError, "Signiture is invalid in append_strict. A dict entry must be part of an array." 
        else:
            raise TypeError, "Argument of unknown type '%s' in append_strict" % (sig)

        return retval

    def append(self, value):
        value_type = type(value)
        if value_type == bool:
            retval = self.append_boolean(value)
        elif value_type == int:
            retval = self.append_int32(value)
        elif value_type == long:
            retval = self.append_int64(value)
        elif (value_type == str or value_type == unicode):
            retval = self.append_string(value)
        elif value_type == float:
            retval = self.append_double(value)
        elif value_type == dict:
            retval = self.append_dict(value)
        elif value_type == tuple:
            retval = self.append_struct(value)
        elif value_type == list:
             retval = self.append_array(value)
        #elif value_type == None.__class__:
        #    retval = self.append_nil()
        elif isinstance(value, ObjectPath):
            retval = self.append_object_path(value)
        elif isinstance(value, ByteArray):
            retval = self.append_array(value)
        elif isinstance(value, Signature):
            retval = self.append_signature(value)
        elif isinstance(value, Byte):
            retval = self.append_byte(value)
        elif isinstance(value, Boolean):
            retval = self.append_boolean(value)
        elif isinstance(value, Int16):
            retval = self.append_int16(value)
        elif isinstance(value, UInt16):
            retval = self.append_uint16(value)
        elif isinstance(value, Int32):
            retval = self.append_int32(value)
        elif isinstance(value, UInt32):
            retval = self.append_uint32(value)
        elif isinstance(value, Int64):
            retval = self.append_int64(value)
        elif isinstance(value, UInt64):
            retval = self.append_uint64(value)
        elif isinstance(value, Double):
            retval = self.append_double(value)
        elif isinstance(value, String):
            retval = self.append_string(value)
        elif isinstance(value, Array):
            retval = self.append_array(value)
        elif isinstance(value, Struct):
            retval = self.append_struct(value)
        elif isinstance(value, Dictionary):
            retval = self.append_dict(value)
        elif isinstance(value, Variant):
            retval = self.append_variant(value)
        else:
            raise TypeError, "Argument of unknown type '%s'" % (value_type)

        return retval

    def append_boolean(self, value):
        cdef dbus_bool_t c_value
        c_value = value
        return dbus_message_iter_append_basic(self.iter, TYPE_BOOLEAN, <dbus_bool_t *>&c_value)

    def append_byte(self, value):
        cdef char b
        if type(value) == str and len(value) == 1:
                b = ord(value)
        elif type(value) == Byte:
                b = value
        else:
            raise TypeError

        return dbus_message_iter_append_basic(self.iter, TYPE_BYTE, <char *>&b)

    def append_int16(self, value):
        cdef dbus_int16_t c_value
        c_value = value
        return dbus_message_iter_append_basic(self.iter, TYPE_INT16, <dbus_int16_t *>&c_value)

    def append_uint16(self, value):
        cdef dbus_uint16_t c_value
        c_value = value
        return dbus_message_iter_append_basic(self.iter, TYPE_UINT16, <dbus_uint16_t *>&c_value)

    def append_int32(self, value):
        cdef dbus_int32_t c_value
        c_value = value
        return dbus_message_iter_append_basic(self.iter, TYPE_INT32, <dbus_int32_t *>&c_value)

    def append_uint32(self, value):
        cdef dbus_uint32_t c_value
        c_value = value
        return dbus_message_iter_append_basic(self.iter, TYPE_UINT32, <dbus_uint32_t *>&c_value)

    def append_int64(self, value):
        cdef dbus_int64_t c_value
        c_value = value
        return dbus_message_iter_append_basic(self.iter, TYPE_INT64, <dbus_int64_t *>&c_value)

    def append_uint64(self, value):
        cdef dbus_uint64_t c_value
        c_value = value
        return dbus_message_iter_append_basic(self.iter, TYPE_UINT64, <dbus_uint64_t *>&c_value)

    def append_double(self, value):
        cdef double c_value
        c_value = value
        return dbus_message_iter_append_basic(self.iter, TYPE_DOUBLE, <double *>&c_value)

    def append_string(self, value):
        cdef char *c_value
        tmp = value.encode('utf8')
        c_value = tmp
        return dbus_message_iter_append_basic(self.iter, TYPE_STRING, <char **>&c_value)

    def append_object_path(self, value):
        cdef char *c_value
        c_value = value
        return dbus_message_iter_append_basic(self.iter, TYPE_OBJECT_PATH, <char **>&c_value)

    def append_signature(self, value):
        cdef char *c_value
        c_value = value
        return dbus_message_iter_append_basic(self.iter, TYPE_SIGNATURE, <char **>&c_value)


    def append_dict(self, python_dict):
        cdef DBusMessageIter c_dict_iter, c_dict_entry_iter
        cdef MessageIter dict_iter, dict_entry_iter
        
        level = self.level + 1

        key = None
        value = None

        sig = str(chr(DICT_ENTRY_BEGIN))

        if isinstance(python_dict, Dictionary):
            key = python_dict.key_type
            value = python_dict.value_type
            signature = python_dict.signature

        dict_list = python_dict.items()

        if signature:
            sig = sig + signature
        else: 
            if not (key and value):
                key, value = dict_list[0]

            sig = sig + self.python_value_to_dbus_sig(key)
            sig = sig + self.python_value_to_dbus_sig(value)

        sig = sig + str(chr(DICT_ENTRY_END))

        dbus_message_iter_open_container(self.iter, TYPE_ARRAY, sig, <DBusMessageIter *>&c_dict_iter)
        dict_iter = MessageIter(level)
        dict_iter.__cinit__(&c_dict_iter)

        for key, value in dict_list:
            dbus_message_iter_open_container(dict_iter.iter, TYPE_DICT_ENTRY, sig, <DBusMessageIter *>&c_dict_entry_iter)
            dict_entry_iter = MessageIter(level)
            dict_entry_iter.__cinit__(&c_dict_entry_iter)

            if signature:
                signature_iter = iter(Signature(signature))
                tmp_sig = signature_iter.next()
                if not dict_entry_iter.append_strict(key, tmp_sig):
                    dbus_message_iter_close_container(dict_iter.iter, dict_entry_iter.iter)
                    dbus_message_iter_close_container(self.iter, dict_iter.iter)
                    return False

                tmp_sig = signature_iter.next()
                if not dict_entry_iter.append_strict(value, tmp_sig):
                    dbus_message_iter_close_container(dict_iter.iter, dict_entry_iter.iter)
                    dbus_message_iter_close_container(self.iter, dict_iter.iter)
                    return False

            else:
                if not dict_entry_iter.append(key):
                    dbus_message_iter_close_container(dict_iter.iter, dict_entry_iter.iter)
                    dbus_message_iter_close_container(self.iter, dict_iter.iter)
                    return False
                
                if not dict_entry_iter.append(value):
                    dbus_message_iter_close_container(dict_iter.iter, dict_entry_iter.iter)
                    dbus_message_iter_close_container(self.iter, dict_iter.iter)
                    return False

            dbus_message_iter_close_container(dict_iter.iter, dict_entry_iter.iter)

        dbus_message_iter_close_container(self.iter, dict_iter.iter)

        return True

    def append_struct(self, python_struct, signature = None):
        cdef DBusMessageIter c_struct_iter
        cdef MessageIter struct_iter

        level = self.level + 1
        dbus_message_iter_open_container(self.iter, TYPE_STRUCT, NULL, <DBusMessageIter *>&c_struct_iter)
        struct_iter = MessageIter(level)
        struct_iter.__cinit__(&c_struct_iter)

        signature_iter = iter(Signature(signature))
        for item in python_struct:
            if signature:
                sig = signature_iter.next()

                if sig == '':
                    dbus_message_iter_close_container(self.iter, struct_iter.iter)
                    return False

                if not struct_iter.append_strict(item, sig):
                    dbus_message_iter_close_container(self.iter, struct_iter.iter)
                    return False
            else:
                if not struct_iter.append(item):
                    dbus_message_iter_close_container(self.iter, struct_iter.iter)
                    return False

        dbus_message_iter_close_container(self.iter, struct_iter.iter)

        return True

    def append_array(self, python_list):
        cdef DBusMessageIter c_array_iter
        cdef MessageIter array_iter

        level = self.level + 1

        sig = None
        if isinstance(python_list, Array):
            if python_list.type:
                sig = self.python_value_to_dbus_sig(python_list.type)
            elif python_list.signature:
                sig = python_list.signature
            else:
                sig = self.python_value_to_dbus_sig(python_list[0])
        else:
            sig = self.python_value_to_dbus_sig(python_list[0])

        dbus_message_iter_open_container(self.iter, TYPE_ARRAY, sig, <DBusMessageIter *>&c_array_iter)
        array_iter = MessageIter(level)
        array_iter.__cinit__(&c_array_iter)

        length = len(python_list)
        for item in python_list:
            if not array_iter.append_strict(item, sig):
                dbus_message_iter_close_container(self.iter, array_iter.iter)
                return False

        dbus_message_iter_close_container(self.iter, array_iter.iter)

        return True

    def append_variant(self, value):
        cdef DBusMessageIter c_variant_iter
        cdef MessageIter variant_iter

        level = self.level + 1
    
        if value.signature:
            sig = value.signature
        elif value.type:
            sig = self.python_value_to_dbus_sig(value.type)
        else:
            sig = self.python_value_to_dbus_sig(value.value)
    
        dbus_message_iter_open_container(self.iter, TYPE_VARIANT, sig, <DBusMessageIter *>&c_variant_iter)
        
        variant_iter = MessageIter(level)
        variant_iter.__cinit__(&c_variant_iter)

        if not variant_iter.append(value.value):
            dbus_message_iter_close_container(self.iter, variant_iter.iter)
            return False

        dbus_message_iter_close_container(self.iter, variant_iter.iter)
        return True

    def __str__(self):
        cdef DBusMessageIter c_array_iter
        cdef MessageIter array_iter

        value_at_iter = True
        retval = ""
        while (value_at_iter):
            type = self.get_arg_type()
            if type == TYPE_INVALID:
                break
            elif type == TYPE_STRING:
                str = iter.get_string()
                arg = 'string:%s\n' % (str)
            elif type == TYPE_OBJECT_PATH:
                path = iter.get_object_path()
                arg = 'object_path:%s\n' % (path)
            elif type == TYPE_INT16:
                num = iter.get_int16()
                arg = 'int16:%d\n' % (num)
            elif type == TYPE_UINT16:
                num = iter.get_uint16()
                arg = 'uint16:%u\n' % (num)
            elif type == TYPE_INT32:
                num = iter.get_int32()
                arg = 'int32:%d\n' % (num)
            elif type == TYPE_UINT32:
                num = iter.get_uint32()
                arg = 'uint32:%u\n' % (num)
            elif type == TYPE_INT64:
                num = iter.get_int64()
                arg = 'int64:%d\n' % (num)
            elif type == TYPE_UINT64:
                num = iter.get_uint64()
                arg = 'uint64:%u\n' % (num)
            elif type == TYPE_DOUBLE:
                num = iter.get_double()
                arg = 'double:%f\n' % (num)
            elif type == TYPE_BYTE:
                num = iter.get_byte()
                arg = 'byte:%x(%s)\n' % (num, str(chr(num)))
            elif type == TYPE_BOOLEAN:
                bool = iter.get_boolean()
                if (bool):
                    str = "true"
                else:
                    str = "false"
                arg = 'boolean:%s\n' % (str)
            elif type == TYPE_ARRAY:
                dbus_message_iter_recurse(self.iter, <DBusMessageIter *>&c_array_iter)
                array_iter = MessageIter(self.level + 1)
                array_iter.__cinit__(&c_array_iter)
                if array_iter.has_next():
                    arg = 'array [' + str(array_iter) + ']'
                else:
                    arg = 'array []'
            else:
                arg = '(unknown arg type %d)\n' % type

            retval = retval + arg
            value_at_iter = self.next()

        return retval


(MESSAGE_TYPE_INVALID, MESSAGE_TYPE_METHOD_CALL, MESSAGE_TYPE_METHOD_RETURN, MESSAGE_TYPE_ERROR, MESSAGE_TYPE_SIGNAL) = range(5)
(TYPE_INVALID, TYPE_BYTE, TYPE_BOOLEAN, TYPE_INT16, TYPE_UINT16, TYPE_INT32, TYPE_UINT32, TYPE_INT64, TYPE_UINT64, TYPE_DOUBLE, TYPE_STRING, TYPE_OBJECT_PATH, TYPE_SIGNATURE, TYPE_ARRAY, TYPE_STRUCT, STRUCT_BEGIN, STRUCT_END, TYPE_VARIANT, TYPE_DICT_ENTRY, DICT_ENTRY_BEGIN, DICT_ENTRY_END) = (0, ord('y'), ord('b'), ord('n'), ord('q'), ord('i'), ord('u'), ord('x'), ord('t'), ord('d'), ord('s'), ord('o'), ord('g'), ord('a'), ord('r'), ord('('), ord(')'), ord('v'), ord('e'), ord('{'), ord('}'))
(HANDLER_RESULT_HANDLED, HANDLER_RESULT_NOT_YET_HANDLED, HANDLER_RESULT_NEED_MEMORY) = range(3)
    
cdef class Message:
    cdef DBusMessage *msg

    def __init__(self, message_type=MESSAGE_TYPE_INVALID,
                 service=None, path=None, dbus_interface=None, method=None,
                 Message method_call=None,
                 name=None,
                 Message reply_to=None, error_name=None, error_message=None,
                 _create=1):

        self.msg = NULL

        cdef char *cservice
        cdef char *ciface
        cdef DBusMessage *cmsg

        ciface = NULL
        if (dbus_interface != None):
            ciface = dbus_interface

        cservice = NULL
        if (service != None):
            cservice = service
            
        if _create:
            if message_type == MESSAGE_TYPE_METHOD_CALL:
                self.msg = dbus_message_new_method_call(cservice, path, ciface, method)
            elif message_type == MESSAGE_TYPE_METHOD_RETURN:
                cmsg = method_call._get_msg()
                self.msg = dbus_message_new_method_return(cmsg)
            elif message_type == MESSAGE_TYPE_SIGNAL:
                self.msg = dbus_message_new_signal(path, ciface, name)
            elif message_type == MESSAGE_TYPE_ERROR:
                cmsg = reply_to._get_msg()
                self.msg = dbus_message_new_error(cmsg, error_name, error_message)
 

    def __dealloc__(self):
        if self.msg != NULL:
            dbus_message_unref(self.msg)
            
    def type_to_name(self, type):
        if type == MESSAGE_TYPE_SIGNAL:
            return "signal"
        elif type == MESSAGE_TYPE_METHOD_CALL:
            return "method call"
        elif type == MESSAGE_TYPE_METHOD_RETURN:
            return "method return"
        elif type == MESSAGE_TYPE_ERROR:
            return "error"
        else:
            return "(unknown message type)"

    def __str__(self):
        message_type = self.get_type()
        sender = self.get_sender()

        if sender == None:
            sender = "(no sender)"

        if (message_type == MESSAGE_TYPE_METHOD_CALL) or (message_type == MESSAGE_TYPE_SIGNAL):
            retval = '%s interface=%s; member=%s; sender=%s' % (self.type_to_name(message_type),
                                                                self.get_interface(),
                                                                self.get_member(),
                                                                sender)
        elif message_type == MESSAGE_TYPE_METHOD_RETURN:
            retval = '%s sender=%s' % (self.type_to_name(message_type),
                                        sender)
        elif message_type == MESSAGE_TYPE_ERROR:
            retval = '%s name=%s; sender=%s' % (self.type_to_name(message_type),
                                                self.get_error_name(),
                                                sender)
        else:
            retval = "Message of unknown type %d" % (message_type)


        # FIXME: should really use self.convert_to_tuple() here
        
        iter = self.get_iter()

        retval = retval + "\n" + str(iter) 

        return retval
    
    cdef _set_msg(self, DBusMessage *msg):
        self.msg = msg

    cdef DBusMessage *_get_msg(self):
        return self.msg

    def get_iter(self, append=False):
        cdef DBusMessageIter iter
        cdef MessageIter message_iter
        cdef DBusMessage *msg

        msg = self._get_msg()

        if append:
            dbus_message_iter_init_append(msg, &iter)
        else:
            dbus_message_iter_init(msg, &iter)

        message_iter = MessageIter(0)
        message_iter.__cinit__(&iter)

        return message_iter

    def get_args_list(self):
        retval = [ ]

        iter = self.get_iter()
        try:
            retval.append(iter.get())
        except TypeError, e:
            return [ ]
            
        value_at_iter = iter.next()
        while (value_at_iter):
            retval.append(iter.get())
            value_at_iter = iter.next()        

        return retval
            
    # FIXME: implement dbus_message_copy?

    def get_type(self):
        return dbus_message_get_type(self.msg)

    def set_path(self, object_path):
        return dbus_message_set_path(self.msg, object_path)
    
    def get_path(self):
        return dbus_message_get_path(self.msg)
    
    def set_interface(self, interface):
        return dbus_message_set_interface(self.msg, interface)

    def get_interface(self):
        return dbus_message_get_interface(self.msg)    

    def set_member(self, member):
        return dbus_message_set_member(self.msg, member)

    def get_member(self):
        return dbus_message_get_member(self.msg)

    def set_error_name(self, name):
        return dbus_message_set_error_name(self.msg, name)

    def get_error_name(self):
        return dbus_message_get_error_name(self.msg)

    def set_destination(self, destination):
        return dbus_message_set_destination(self.msg, destination)

    def get_destination(self):
        return dbus_message_get_destination(self.msg)

    def set_sender(self, sender):
        return dbus_message_set_sender(self.msg, sender)
    
    def get_sender(self):
        cdef char *sender
        sender = dbus_message_get_sender(self.msg)
        if (sender == NULL):
            return None
        else:
            return sender

    def set_no_reply(self, no_reply):
        dbus_message_set_no_reply(self.msg, no_reply)

    def get_no_reply(self):
        return dbus_message_get_no_reply(self.msg)

    def is_method_call(self, interface, method):
        return dbus_message_is_method_call(self.msg, interface, method)

    def is_signal(self, interface, signal_name):
        return dbus_message_is_signal(self.msg, interface, signal_name)

    def is_error(self, error_name):
        return dbus_message_is_error(self.msg, error_name)

    def has_destination(self, service):
        return dbus_message_has_destination(self.msg, service)

    def has_sender(self, service):
        return dbus_message_has_sender(self.msg, service)

    def get_serial(self):
        return dbus_message_get_serial(self.msg)

    def set_reply_serial(self, reply_serial):
        return dbus_message_set_reply_serial(self.msg, reply_serial)

    def get_reply_serial(self):
        return dbus_message_get_reply_serial(self.msg)    

    #FIXME: dbus_message_get_path_decomposed
    
    # FIXME: all the different dbus_message_*args* methods

class Signal(Message):
    def __init__(self, spath, sinterface, sname):
        Message.__init__(self, MESSAGE_TYPE_SIGNAL, path=spath, dbus_interface=sinterface, name=sname)

class EmptyMessage(Message):
    def __init__(self):
        Message.__init__(self, _create=False)

class MethodCall(Message):
    def __init__(self, mpath, minterface, mmethod):
        Message.__init__(self, MESSAGE_TYPE_METHOD_CALL, path=mpath, dbus_interface=minterface, method=mmethod)

class MethodReturn(Message):
    def __init__(self, method_call):
        Message.__init__(self, MESSAGE_TYPE_METHOD_RETURN, method_call=method_call)

class Error(Message):
    def __init__(self, reply_to, error_name, error_message):
        Message.__init__(self, MESSAGE_TYPE_ERROR, reply_to=reply_to, error_name=error_name, error_message=error_message)
        
cdef class Server:
    cdef DBusServer *server
    def __init__(self, address):
        cdef DBusError error
        dbus_error_init(&error)
        self.server = dbus_server_listen(address,
                                         &error)
        if dbus_error_is_set(&error):
            errormsg = error.message
            dbus_error_free (&error)
            raise DBusException, errormsg

    def disconnect(self):
        dbus_server_disconnect(self.server)

    def get_is_connected(self):
        return dbus_server_get_is_connected(self.server)

#    def set_new_connection_function(self, function, data):
#        dbus_server_set_new_connection_function(self.conn, function,
#                                                data, NULL)
        
#    def set_watch_functions(self, add_function, remove_function, data):
#        dbus_server_set_watch_functions(self.server,
#                                        add_function, remove_function,
#                                        data, NULL)
        
#    def set_timeout_functions(self, add_function, remove_function, data):
#        dbus_server_set_timeout_functions(self.server,
#                                          add_function, remove_function,
#                                          data, NULL)
        
#    def handle_watch(self, watch, condition):
#        dbus_server_handle_watch(self.conn, watch, condition)

BUS_SESSION = DBUS_BUS_SESSION
BUS_SYSTEM = DBUS_BUS_SYSTEM
BUS_STARTER = DBUS_BUS_STARTER

def bus_get (bus_type, private=False):
    cdef DBusError error
    cdef Connection conn
    cdef DBusConnection *connection

    dbus_error_init(&error)
    if private:
        connection = dbus_bus_get_private(bus_type,
                                          &error)
    else:
        connection = dbus_bus_get(bus_type,
                                  &error)

    if dbus_error_is_set(&error):
        errormsg = error.message
        dbus_error_free(&error)
        raise DBusException, errormsg 

    conn = Connection()
    conn.__cinit__(None, connection)
    return conn 

def bus_get_unique_name(Connection connection):
    cdef DBusConnection *conn
    conn = connection._get_conn()
    return dbus_bus_get_unique_name(conn)

def bus_get_unix_user(Connection connection, service_name):
    cdef DBusError error
    dbus_error_init(&error)
    cdef int retval
    cdef DBusConnection *conn

    conn = connection._get_conn()
    retval = dbus_bus_get_unix_user(conn, service_name, &error)

    if dbus_error_is_set(&error):
        errormsg = error.message
        dbus_error_free(&error)
        raise DBusException, errormsg 

    return retval

# these are defines, not enums, so they aren't auto generated
DBUS_START_REPLY_SUCCESS = 0
DBUS_START_REPLY_ALREADY_RUNNING = 1

def bus_start_service_by_name(Connection connection, service_name, flags=0):
    cdef DBusError error
    dbus_error_init(&error)
    cdef dbus_bool_t retval
    cdef dbus_uint32_t results
    cdef DBusConnection *conn

    conn = connection._get_conn()

    retval = dbus_bus_start_service_by_name(conn, service_name, flags, &results, &error)

    if dbus_error_is_set(&error):
        errormsg = error.message
        dbus_error_free(&error)
        raise DBusException, errormsg

    return (retval, results) 

def bus_register(Connection connection):
    cdef DBusError error
    dbus_error_init(&error)
    cdef dbus_bool_t retval
    cdef DBusConnection *conn

    conn = connection._get_conn()
    retval = dbus_bus_register(conn,
                               &error)
    if dbus_error_is_set(&error):
        msg = error.message
        dbus_error_free(&error)
        raise DBusException, errormsg 

    return retval

NAME_FLAG_ALLOW_REPLACEMENT    = 0x1
NAME_FLAG_REPLACE_EXISTING     = 0x2
NAME_FLAG_DO_NOT_QUEUE         = 0x4

REQUEST_NAME_REPLY_PRIMARY_OWNER = 1
REQUEST_NAME_REPLY_IN_QUEUE      = 2
REQUEST_NAME_REPLY_EXISTS        = 3
REQUEST_NAME_REPLY_ALREADY_OWNER = 4

def bus_request_name(Connection connection, service_name, flags=0):
    cdef DBusError error
    dbus_error_init(&error)
    cdef int retval
    cdef DBusConnection *conn

    conn = connection._get_conn()
    retval = dbus_bus_request_name(conn,
                                   service_name,
                                   flags,
                                   &error)
    if dbus_error_is_set(&error):
        errormsg = error.message
        dbus_error_free(&error)
        raise DBusException, errormsg

    return retval

RELEASE_NAME_REPLY_RELEASED = 1
RELEASE_NAME_REPLY_NON_EXISTENT = 2
RELEASE_NAME_REPLY_NOT_OWNER = 3

def bus_release_name(Connection connection, service_name):
    cdef DBusError error
    dbus_error_init(&error)
    cdef int retval
    cdef DBusConnection *conn

    conn = connection._get_conn()
    retval = dbus_bus_release_name(conn,
                                   service_name,
                                   &error)
    if dbus_error_is_set(&error):
        errormsg = error.message
        dbus_error_free(&error)
        raise DBusException, errormsg

    return retval

def bus_name_has_owner(Connection connection, service_name):
    cdef DBusError error
    dbus_error_init(&error)
    cdef dbus_bool_t retval
    cdef DBusConnection *conn

    conn = connection._get_conn()
    retval = dbus_bus_name_has_owner(conn,
                                     service_name,
                                     &error)
    if dbus_error_is_set(&error):
        errormsg = error.message
        dbus_error_free(&error)
        raise DBusException, errormsg
        
    return retval

def bus_add_match(Connection connection, rule):
    cdef DBusError error
    cdef DBusConnection *conn

    dbus_error_init(&error)
    
    conn = connection._get_conn()
    dbus_bus_add_match (conn, rule, &error)
    
    if dbus_error_is_set(&error):
        errormsg = error.message
        dbus_error_free(&error)
        raise DBusException, errormsg

def bus_remove_match(Connection connection, rule):
    cdef DBusError error
    cdef DBusConnection *conn

    dbus_error_init(&error)

    conn = connection._get_conn()
    dbus_bus_remove_match (conn, rule, &error)
    
    if dbus_error_is_set(&error):
        errormsg = error.message
        dbus_error_free(&error)
        raise DBusException, errormsg