summaryrefslogtreecommitdiff
path: root/TelepathyQt4/connection.cpp
blob: 1c6d26c963bd55bf275292e64f648efb089863fd (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
/*
 * This file is part of TelepathyQt4
 *
 * Copyright (C) 2008, 2009 Collabora Ltd. <http://www.collabora.co.uk/>
 * Copyright (C) 2008, 2009 Nokia Corporation
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <TelepathyQt4/Connection>
#include "TelepathyQt4/connection-internal.h"

#include "TelepathyQt4/_gen/cli-connection.moc.hpp"
#include "TelepathyQt4/_gen/cli-connection-body.hpp"
#include "TelepathyQt4/_gen/connection.moc.hpp"
#include "TelepathyQt4/_gen/connection-internal.moc.hpp"

#include "TelepathyQt4/debug-internal.h"

#include <TelepathyQt4/ConnectionCapabilities>
#include <TelepathyQt4/ContactManager>
#include <TelepathyQt4/PendingChannel>
#include <TelepathyQt4/PendingContactAttributes>
#include <TelepathyQt4/PendingContacts>
#include <TelepathyQt4/PendingFailure>
#include <TelepathyQt4/PendingHandles>
#include <TelepathyQt4/PendingReady>
#include <TelepathyQt4/PendingVoid>
#include <TelepathyQt4/ReferencedHandles>

#include <QMap>
#include <QMetaObject>
#include <QMutex>
#include <QMutexLocker>
#include <QPair>
#include <QQueue>
#include <QString>
#include <QTimer>
#include <QtGlobal>

/**
 * \addtogroup clientsideproxies Client-side proxies
 *
 * Proxy objects representing remote service objects accessed via D-Bus.
 *
 * In addition to providing direct access to methods, signals and properties
 * exported by the remote objects, some of these proxies offer features like
 * automatic inspection of remote object capabilities, property tracking,
 * backwards compatibility helpers for older services and other utilities.
 */

/**
 * \defgroup clientconn Connection proxies
 * \ingroup clientsideproxies
 *
 * Proxy objects representing remote Telepathy Connection objects.
 */

namespace Tp
{

struct TELEPATHY_QT4_NO_EXPORT Connection::Private
{
    Private(Connection *parent);
    ~Private();

    void init();

    static void introspectMain(Private *self);
    void introspectCapabilities();
    void introspectSelfHandle();
    void introspectContacts();
    static void introspectSelfContact(Private *self);
    static void introspectSimplePresence(Private *self);
    static void introspectRoster(Private *self);
    static void introspectRosterGroups(Private *self);

    void checkFeatureRosterGroupsReady();

    struct HandleContext;

    // Public object
    Connection *parent;

    // Instance of generated interface class
    Client::ConnectionInterface *baseInterface;

    // Optional interface proxies
    Client::DBus::PropertiesInterface *properties;
    Client::ConnectionInterfaceSimplePresenceInterface *simplePresence;

    ReadinessHelper *readinessHelper;

    // Introspection

    // Introspected properties
    // keep pendingStatus and pendingStatusReason until we emit statusChanged
    // so Connection::status() and Connection::statusReason() are consistent
    uint pendingStatus;
    uint pendingStatusReason;
    uint status;
    uint statusReason;

    SimpleStatusSpecMap simplePresenceStatuses;
    ContactPtr selfContact;
    QStringList contactAttributeInterfaces;
    uint selfHandle;
    ConnectionCapabilities *caps;
    QMap<uint, ContactManager::ContactListChannel> contactListChannels;
    uint contactListChannelsReady;
    QList<ChannelPtr> contactListGroupChannels;
    // Number of things left to do before the Groups feature is ready
    // 1 for Get("Channels") + 1 per channel not ready
    uint featureRosterGroupsTodo;

    // (Bus connection name, service name) -> HandleContext
    static QMap<QPair<QString, QString>, HandleContext *> handleContexts;
    static QMutex handleContextsLock;
    HandleContext *handleContext;

    ContactManager *contactManager;
};

// Handle tracking
struct TELEPATHY_QT4_NO_EXPORT Connection::Private::HandleContext
{
    struct Type
    {
        QMap<uint, uint> refcounts;
        QSet<uint> toRelease;
        uint requestsInFlight;
        bool releaseScheduled;

        Type()
            : requestsInFlight(0),
              releaseScheduled(false)
        {
        }
    };

    HandleContext()
        : refcount(0)
    {
    }

    int refcount;
    QMutex lock;
    QMap<uint, Type> types;
};

Connection::Private::Private(Connection *parent)
    : parent(parent),
      baseInterface(new Client::ConnectionInterface(parent->dbusConnection(),
                    parent->busName(), parent->objectPath(), parent)),
      properties(0),
      simplePresence(0),
      readinessHelper(parent->readinessHelper()),
      pendingStatus(Connection::StatusUnknown),
      pendingStatusReason(ConnectionStatusReasonNoneSpecified),
      status(Connection::StatusUnknown),
      statusReason(ConnectionStatusReasonNoneSpecified),
      selfHandle(0),
      caps(0),
      contactListChannelsReady(0),
      featureRosterGroupsTodo(0),
      handleContext(0),
      contactManager(0)
{
    ReadinessHelper::Introspectables introspectables;

    ReadinessHelper::Introspectable introspectableCore(
        QSet<uint>() << Connection::StatusDisconnected << Connection::StatusConnected, // makesSenseForStatuses
        Features(),                                                                    // dependsOnFeatures (none)
        QStringList(),                                                                 // dependsOnInterfaces (none)
        (ReadinessHelper::IntrospectFunc) &Private::introspectMain,
        this);
    introspectables[FeatureCore] = introspectableCore;

    ReadinessHelper::Introspectable introspectableSelfContact(
        QSet<uint>() << Connection::StatusConnected,                                   // makesSenseForStatuses
        Features() << FeatureCore,                                                     // dependsOnFeatures (core)
        QStringList(),                                                                 // dependsOnInterfaces
        (ReadinessHelper::IntrospectFunc) &Private::introspectSelfContact,
        this);
    introspectables[FeatureSelfContact] = introspectableSelfContact;

    ReadinessHelper::Introspectable introspectableSimplePresence(
        QSet<uint>() << Connection::StatusConnected,                                   // makesSenseForStatuses
        Features() << FeatureCore,                                                     // dependsOnFeatures (core)
        QStringList() << TELEPATHY_INTERFACE_CONNECTION_INTERFACE_SIMPLE_PRESENCE,     // dependsOnInterfaces
        (ReadinessHelper::IntrospectFunc) &Private::introspectSimplePresence,
        this);
    introspectables[FeatureSimplePresence] = introspectableSimplePresence;

    ReadinessHelper::Introspectable introspectableRoster(
        QSet<uint>() << Connection::StatusConnected,                                   // makesSenseForStatuses
        Features() << FeatureCore,                                                     // dependsOnFeatures (core)
        QStringList() << TELEPATHY_INTERFACE_CONNECTION_INTERFACE_CONTACTS,            // dependsOnInterfaces
        (ReadinessHelper::IntrospectFunc) &Private::introspectRoster,
        this);
    introspectables[FeatureRoster] = introspectableRoster;

    ReadinessHelper::Introspectable introspectableRosterGroups(
        QSet<uint>() << Connection::StatusConnected,                                   // makesSenseForStatuses
        Features() << FeatureRoster,                                                   // dependsOnFeatures (core)
        QStringList() << TELEPATHY_INTERFACE_CONNECTION_INTERFACE_REQUESTS,            // dependsOnInterfaces
        (ReadinessHelper::IntrospectFunc) &Private::introspectRosterGroups,
        this);
    introspectables[FeatureRosterGroups] = introspectableRosterGroups;

    readinessHelper->addIntrospectables(introspectables);
    readinessHelper->setCurrentStatus(status);
    parent->connect(readinessHelper,
            SIGNAL(statusReady(uint)),
            SLOT(onStatusReady(uint)));
    readinessHelper->becomeReady(Features() << FeatureCore);

    init();
}

Connection::Private::~Private()
{
    // Clear selfContact so its handle will be released cleanly before the handleContext
    selfContact.clear();

    // FIXME: This doesn't look right! In fact, looks absolutely horrendous.
    if (!handleContext) {
        // initial introspection is not done
        return;
    }

    QMutexLocker locker(&handleContextsLock);

    // All handle contexts locked, so safe
    if (!--handleContext->refcount) {
        debug() << "Destroying HandleContext";

        foreach (uint handleType, handleContext->types.keys()) {
            HandleContext::Type type = handleContext->types[handleType];

            if (!type.refcounts.empty()) {
                debug() << " Still had references to" <<
                    type.refcounts.size() << "handles, releasing now";
                baseInterface->ReleaseHandles(handleType, type.refcounts.keys());
            }

            if (!type.toRelease.empty()) {
                debug() << " Was going to release" <<
                    type.toRelease.size() << "handles, doing that now";
                baseInterface->ReleaseHandles(handleType, type.toRelease.toList());
            }
        }

        handleContexts.remove(qMakePair(baseInterface->connection().name(),
                    baseInterface->service()));
        delete handleContext;
    }
    else {
        Q_ASSERT(handleContext->refcount > 0);
    }
}

void Connection::Private::init()
{
    debug() << "Connecting to StatusChanged()";
    parent->connect(baseInterface,
                    SIGNAL(StatusChanged(uint, uint)),
                    SLOT(onStatusChanged(uint, uint)));

    debug() << "Calling GetStatus()";
    QDBusPendingCallWatcher *watcher =
        new QDBusPendingCallWatcher(baseInterface->GetStatus(), parent);
    parent->connect(watcher,
                    SIGNAL(finished(QDBusPendingCallWatcher *)),
                    SLOT(gotStatus(QDBusPendingCallWatcher *)));

    QMutexLocker locker(&handleContextsLock);
    QString busConnectionName = baseInterface->connection().name();
    QString busName = baseInterface->service();

    if (handleContexts.contains(qMakePair(busConnectionName, busName))) {
        debug() << "Reusing existing HandleContext";
        handleContext = handleContexts[qMakePair(busConnectionName, busName)];
    }
    else {
        debug() << "Creating new HandleContext";
        handleContext = new HandleContext;
        handleContexts[qMakePair(busConnectionName, busName)] = handleContext;
    }

    // All handle contexts locked, so safe
    ++handleContext->refcount;
}

void Connection::Private::introspectMain(Connection::Private *self)
{
    if (!self->contactManager) {
        self->contactManager = new ContactManager(
                ConnectionPtr(self->parent));
    }

    // Introspecting the main interface is currently just calling
    // GetInterfaces(), but it might include other stuff in the future if we
    // gain GetAll-able properties on the connection
    debug() << "Calling GetInterfaces()";
    QDBusPendingCallWatcher *watcher =
        new QDBusPendingCallWatcher(self->baseInterface->GetInterfaces(),
                self->parent);
    self->parent->connect(watcher,
            SIGNAL(finished(QDBusPendingCallWatcher *)),
            SLOT(gotInterfaces(QDBusPendingCallWatcher *)));
}

void Connection::Private::introspectContacts()
{
    if (!properties) {
        properties = parent->propertiesInterface();
        Q_ASSERT(properties != 0);
    }

    debug() << "Getting available interfaces for GetContactAttributes";
    QDBusPendingCall call =
        properties->Get(TELEPATHY_INTERFACE_CONNECTION_INTERFACE_CONTACTS,
                        "ContactAttributeInterfaces");
    QDBusPendingCallWatcher *watcher =
        new QDBusPendingCallWatcher(call, parent);
    parent->connect(watcher,
                    SIGNAL(finished(QDBusPendingCallWatcher *)),
                    SLOT(gotContactAttributeInterfaces(QDBusPendingCallWatcher *)));
}

void Connection::Private::introspectSimplePresence(Connection::Private *self)
{
    if (!self->properties) {
        self->properties = self->parent->propertiesInterface();
        Q_ASSERT(self->properties != 0);
    }

    debug() << "Getting available SimplePresence statuses";
    QDBusPendingCall call =
        self->properties->Get(TELEPATHY_INTERFACE_CONNECTION_INTERFACE_SIMPLE_PRESENCE,
                "Statuses");
    QDBusPendingCallWatcher *watcher =
        new QDBusPendingCallWatcher(call, self->parent);
    self->parent->connect(watcher,
            SIGNAL(finished(QDBusPendingCallWatcher *)),
            SLOT(gotSimpleStatuses(QDBusPendingCallWatcher *)));
}

void Connection::Private::introspectSelfContact(Connection::Private *self)
{
    debug() << "Building self contact";
    // FIXME: these should be features when Connection is sanitized
    PendingContacts *contacts = self->contactManager->contactsForHandles(
            UIntList() << self->selfHandle);
    self->parent->connect(contacts,
            SIGNAL(finished(Tp::PendingOperation *)),
            SLOT(gotSelfContact(Tp::PendingOperation *)));
}

void Connection::Private::introspectSelfHandle()
{
    parent->connect(baseInterface,
                    SIGNAL(SelfHandleChanged(uint)),
                    SLOT(onSelfHandleChanged(uint)));

    debug() << "Getting self handle";
    QDBusPendingCall call = baseInterface->GetSelfHandle();
    QDBusPendingCallWatcher *watcher =
        new QDBusPendingCallWatcher(call, parent);
    parent->connect(watcher,
                    SIGNAL(finished(QDBusPendingCallWatcher *)),
                    SLOT(gotSelfHandle(QDBusPendingCallWatcher *)));
}

void Connection::Private::introspectCapabilities()
{
    if (!properties) {
        properties = parent->propertiesInterface();
        Q_ASSERT(properties != 0);
    }

    debug() << "Retrieving capabilities";
    QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(
            properties->Get(
                TELEPATHY_INTERFACE_CONNECTION_INTERFACE_REQUESTS,
                "RequestableChannelClasses"), parent);
    parent->connect(watcher,
            SIGNAL(finished(QDBusPendingCallWatcher *)),
            SLOT(gotCapabilities(QDBusPendingCallWatcher *)));
}

void Connection::Private::introspectRoster(Connection::Private *self)
{
    debug() << "Requesting handles for contact lists";

    for (uint i = 0; i < ContactManager::ContactListChannel::LastType; ++i) {
        self->contactListChannels.insert(i,
                ContactManager::ContactListChannel(
                    (ContactManager::ContactListChannel::Type) i));

        PendingHandles *pending = self->parent->requestHandles(
                HandleTypeList,
                QStringList() << ContactManager::ContactListChannel::identifierForType(
                    (ContactManager::ContactListChannel::Type) i));
        self->parent->connect(pending,
                SIGNAL(finished(Tp::PendingOperation*)),
                SLOT(gotContactListsHandles(Tp::PendingOperation*)));
    }
}

void Connection::Private::introspectRosterGroups(Connection::Private *self)
{
    debug() << "Introspecting roster groups";

    ++self->featureRosterGroupsTodo; // decremented in gotChannels

    // we already checked if requests interface exists, so bypass requests
    // interface checking
    Client::ConnectionInterfaceRequestsInterface *iface =
        self->parent->requestsInterface(BypassInterfaceCheck);

    debug() << "Connecting to Requests.NewChannels";
    self->parent->connect(iface,
            SIGNAL(NewChannels(const Tp::ChannelDetailsList&)),
            SLOT(onNewChannels(const Tp::ChannelDetailsList&)));

    debug() << "Retrieving channels";
    QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(
            self->parent->propertiesInterface()->Get(
                TELEPATHY_INTERFACE_CONNECTION_INTERFACE_REQUESTS,
                "Channels"), self->parent);
    self->parent->connect(watcher,
            SIGNAL(finished(QDBusPendingCallWatcher*)),
            SLOT(gotChannels(QDBusPendingCallWatcher*)));
}

void Connection::Private::checkFeatureRosterGroupsReady()
{
    if (featureRosterGroupsTodo != 0) {
        return;
    }

    debug() << "FeatureRosterGroups ready";
    contactManager->setContactListGroupChannels(
            contactListGroupChannels);
    readinessHelper->setIntrospectCompleted(
            FeatureRosterGroups, true);
    contactListGroupChannels.clear();
}

Connection::PendingConnect::PendingConnect(Connection *parent, const Features &requestedFeatures)
    : PendingReady(requestedFeatures, parent, parent)
{
    QDBusPendingCall call = parent->baseInterface()->Connect();
    QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(call, parent);
    connect(watcher,
            SIGNAL(finished(QDBusPendingCallWatcher*)),
            this,
            SLOT(onConnectReply(QDBusPendingCallWatcher*)));
}

void Connection::PendingConnect::onConnectReply(QDBusPendingCallWatcher *watcher)
{
    if (watcher->isError()) {
        setFinishedWithError(watcher->error());
    }
    else {
        connect(qobject_cast<Connection*>(parent())->becomeReady(requestedFeatures()),
                SIGNAL(finished(Tp::PendingOperation*)),
                SLOT(onBecomeReadyReply(Tp::PendingOperation*)));
    }
}

void Connection::PendingConnect::onBecomeReadyReply(Tp::PendingOperation *op)
{
    if (op->isError()) {
        setFinishedWithError(op->errorName(), op->errorMessage());
    }
    else {
        setFinished();
    }
}

QMap<QPair<QString, QString>, Connection::Private::HandleContext*> Connection::Private::handleContexts;
QMutex Connection::Private::handleContextsLock;

/**
 * \class Connection
 * \ingroup clientconn
 * \headerfile <TelepathyQt4/connection.h> <TelepathyQt4/Connection>
 *
 * Object representing a Telepathy connection.
 *
 * It adds the following features compared to using ConnectionInterface
 * directly:
 * <ul>
 *  <li>%Connection status tracking</li>
 *  <li>Getting the list of supported interfaces automatically</li>
 *  <li>Getting the valid presence statuses automatically</li>
 *  <li>Shared optional interface proxy instances</li>
 * </ul>
 *
 * The remote object state accessor functions on this object (status(),
 * statusReason(), and so on) don't make any DBus calls; instead,
 * they return values cached from a previous introspection run. The
 * introspection process populates their values in the most efficient way
 * possible based on what the service implements. Their return value is mostly
 * undefined until the introspection process is completed; a status change to
 * StatusConnected indicates that the introspection process is finished. See the
 * individual accessor descriptions for details on which functions can be used
 * in the different states.
 */

const Feature Connection::FeatureCore = Feature(Connection::staticMetaObject.className(), 0, true);
const Feature Connection::FeatureSelfContact = Feature(Connection::staticMetaObject.className(), 1);
const Feature Connection::FeatureSimplePresence = Feature(Connection::staticMetaObject.className(), 2);
const Feature Connection::FeatureRoster = Feature(Connection::staticMetaObject.className(), 4);
const Feature Connection::FeatureRosterGroups = Feature(Connection::staticMetaObject.className(), 5);

ConnectionPtr Connection::create(const QString &busName,
        const QString &objectPath)
{
    return ConnectionPtr(new Connection(busName, objectPath));
}

ConnectionPtr Connection::create(const QDBusConnection &bus,
        const QString &busName, const QString &objectPath)
{
    return ConnectionPtr(new Connection(bus, busName, objectPath));
}

/**
 * Construct a new Connection object.
 *
 * \param busName The connection's well-known or unique bus name
 *                (sometimes called a "service name")
 * \param objectPath The connection's object path
 */
Connection::Connection(const QString &busName,
                       const QString &objectPath)
    : StatefulDBusProxy(QDBusConnection::sessionBus(),
            busName, objectPath),
      OptionalInterfaceFactory<Connection>(this),
      ReadyObject(this, FeatureCore),
      mPriv(new Private(this))
{
}

/**
 * Construct a new Connection object.
 *
 * \param bus QDBusConnection to use
 * \param busName The connection's well-known or unique bus name
 *                (sometimes called a "service name")
 * \param objectPath The connection's object path
 */
Connection::Connection(const QDBusConnection &bus,
                       const QString &busName,
                       const QString &objectPath)
    : StatefulDBusProxy(bus, busName, objectPath),
      OptionalInterfaceFactory<Connection>(this),
      ReadyObject(this, FeatureCore),
      mPriv(new Private(this))
{
}

/**
 * Class destructor.
 */
Connection::~Connection()
{
    delete mPriv;
}

/**
 * Return the connection's status.
 *
 * The returned value may have changed whenever statusChanged() is
 * emitted.
 *
 * \return The status, as defined in Status.
 */
uint Connection::status() const
{
    return mPriv->status;
}

/**
 * Return the reason for the connection's status (which is returned by
 * status()). The validity and change rules are the same as for status().
 *
 * \return The reason, as defined in Status.
 */
uint Connection::statusReason() const
{
    return mPriv->statusReason;
}

/**
 * Return the handle which represents the user on this connection, which will remain
 * valid for the lifetime of this connection, or until a change in the user's
 * identifier is signalled by the selfHandleChanged signal. If the connection is
 * not yet in the StatusConnected state, the value of this property MAY be zero.
 *
 * \return Self handle.
 */
uint Connection::selfHandle() const
{
    return mPriv->selfHandle;
}

/**
 * Return a dictionary of presence statuses valid for use with the new(er)
 * Telepathy SimplePresence interface on the remote object.
 *
 * The value is undefined if the list returned by interfaces() doesn't
 * contain %TELEPATHY_INTERFACE_CONNECTION_INTERFACE_SIMPLE_PRESENCE.
 *
 * The value may have changed arbitrarily during the time the
 * Connection spends in status StatusConnecting,
 * again staying fixed for the entire time in StatusConnected.
 *
 * \return Dictionary from string identifiers to structs for each valid
 * status.
 */
SimpleStatusSpecMap Connection::allowedPresenceStatuses() const
{
    if (!isReady(Features() << FeatureSimplePresence)) {
        warning() << "Trying to retrieve simple presence from connection, but "
                     "simple presence is not supported or was not requested. "
                     "Use becomeReady(FeatureSimplePresence)";
    }

    return mPriv->simplePresenceStatuses;
}

/**
 * Set the self presence status.
 *
 * \a status must be one of the allowed statuses returned by
 * allowedPresenceStatuses().
 *
 * Note that clients SHOULD set the status message for the local user to the empty string,
 * unless the user has actually provided a specific message (i.e. one that
 * conveys more information than the Status).
 *
 * \param status The desired status.
 * \param statusMessage The desired status message.
 * \return A PendingOperation which will emit PendingOperation::finished
 *         when the call has finished.
 *
 * \sa allowedPresenceStatuses()
 */
PendingOperation *Connection::setSelfPresence(const QString &status,
        const QString &statusMessage)
{
    if (!interfaces().contains(TELEPATHY_INTERFACE_CONNECTION_INTERFACE_SIMPLE_PRESENCE)) {
        return new PendingFailure(TELEPATHY_ERROR_NOT_IMPLEMENTED,
                "Connection does not support SimplePresence", this);
    }
    return new PendingVoid(
            simplePresenceInterface()->SetPresence(status, statusMessage),
            this);
}

ContactPtr Connection::selfContact() const
{
    if (!isReady()) {
        warning() << "Connection::selfContact() used before the connection is ready!";
    }
    // FIXME: add checks for the SelfContact feature having been requested when Connection features
    // actually work sensibly and selfContact is made a feature

    return mPriv->selfContact;
}

/**
 * Return the capabilities that are expected to be available on this connection,
 * i.e. those for which createChannel() can reasonably be expected to succeed.
 * User interfaces can use this information to show or hide UI components.
 *
 * This property cannot change after the connection has gone to state()
 * %Tp::Connection_Status_Connected, so there is no change notification.
 *
 * This method requires Connection::FeatureCore to be enabled.
 *
 * @return An object representing the connection capabilities or 0 if
 *         FeatureCore is not ready.
 */
ConnectionCapabilities *Connection::capabilities() const
{
    if (!isReady()) {
        warning() << "Connection::capabilities() used before connection "
            "FeatureCore is ready";
    }

    return mPriv->caps;
}

/**
 * \fn Connection::optionalInterface(InterfaceSupportedChecking check) const
 *
 * Get a pointer to a valid instance of a given %Connection optional
 * interface class, associated with the same remote object the Connection is
 * associated with, and destroyed at the same time the Connection is
 * destroyed.
 *
 * If the list returned by interfaces() doesn't contain the name of the
 * interface requested <code>0</code> is returned. This check can be
 * bypassed by specifying #BypassInterfaceCheck for <code>check</code>, in
 * which case a valid instance is always returned.
 *
 * If the object is not ready, the list returned by interfaces() isn't
 * guaranteed to yet represent the full set of interfaces supported by the
 * remote object.
 * Hence the check might fail even if the remote object actually supports
 * the requested interface; using #BypassInterfaceCheck is suggested when
 * the Connection is not suitably ready.
 *
 * \sa OptionalInterfaceFactory::interface
 *
 * \tparam Interface Class of the optional interface to get.
 * \param check Should an instance be returned even if it can't be
 *              determined that the remote object supports the
 *              requested interface.
 * \return Pointer to an instance of the interface class, or <code>0</code>.
 */

/**
 * \fn ConnectionInterfaceAliasingInterface *Connection::aliasingInterface(InterfaceSupportedChecking check) const
 *
 * Convenience function for getting an Aliasing interface proxy.
 *
 * \param check Passed to optionalInterface()
 * \return <code>optionalInterface<ConnectionInterfaceAliasingInterface>(check)</code>
 */

/**
 * \fn ConnectionInterfaceAvatarsInterface *Connection::avatarsInterface(InterfaceSupportedChecking check) const
 *
 * Convenience function for getting an Avatars interface proxy.
 *
 * \param check Passed to optionalInterface()
 * \return <code>optionalInterface<ConnectionInterfaceAvatarsInterface>(check)</code>
 */

/**
 * \fn ConnectionInterfaceCapabilitiesInterface *Connection::capabilitiesInterface(InterfaceSupportedChecking check) const
 *
 * Convenience function for getting a Capabilities interface proxy.
 *
 * \param check Passed to optionalInterface()
 * \return <code>optionalInterface<ConnectionInterfaceCapabilitiesInterface>(check)</code>
 */

/**
 * \fn ConnectionInterfacePresenceInterface *Connection::presenceInterface(InterfaceSupportedChecking check) const
 *
 * Convenience function for getting a Presence interface proxy.
 *
 * \param check Passed to optionalInterface()
 * \return <code>optionalInterface<ConnectionInterfacePresenceInterface>(check)</code>
 */

/**
 * \fn ConnectionInterfaceSimplePresenceInterface *Connection::simplePresenceInterface(InterfaceSupportedChecking check) const
 *
 * Convenience function for getting a SimplePresence interface proxy.
 *
 * \param check Passed to optionalInterface()
 * \return <code>optionalInterface<ConnectionInterfaceSimplePresenceInterface>(check)</code>
 */

/**
 * \fn DBus::PropertiesInterface *Connection::propertiesInterface() const
 *
 * Convenience function for getting a Properties interface proxy. The
 * Properties interface is not necessarily reported by the services, so a
 * <code>check</code> parameter is not provided, and the interface is
 * always assumed to be present.
 *
 * \sa optionalInterface()
 *
 * \return <code>optionalInterface<DBus::PropertiesInterface>(BypassInterfaceCheck)</code>
 */

void Connection::onStatusReady(uint status)
{
    Q_ASSERT(status == mPriv->pendingStatus);

    mPriv->status = status;
    mPriv->statusReason = mPriv->pendingStatusReason;
    emit statusChanged(mPriv->status, mPriv->statusReason);
}

void Connection::onStatusChanged(uint status, uint reason)
{
    debug() << "StatusChanged from" << mPriv->pendingStatus
            << "to" << status << "with reason" << reason;

    if (mPriv->pendingStatus == status) {
        warning() << "New status was the same as the old status! Ignoring redundant StatusChanged";
        return;
    }

    mPriv->pendingStatus = status;
    mPriv->pendingStatusReason = reason;

    switch (status) {
        case ConnectionStatusConnected:
            debug() << "Performing introspection for the Connected status";
            mPriv->readinessHelper->setCurrentStatus(status);
            break;

        case ConnectionStatusConnecting:
            mPriv->readinessHelper->setCurrentStatus(status);
            break;

        case ConnectionStatusDisconnected:
            const char *errorName;

            // This is the best we can do right now: in an imminent
            // spec version we should define a different D-Bus error name
            // for each ConnectionStatusReason

            switch (reason) {
                case ConnectionStatusReasonNoneSpecified:
                case ConnectionStatusReasonRequested:
                    errorName = TELEPATHY_ERROR_DISCONNECTED;
                    break;

                case ConnectionStatusReasonNetworkError:
                case ConnectionStatusReasonAuthenticationFailed:
                case ConnectionStatusReasonEncryptionError:
                    errorName = TELEPATHY_ERROR_NETWORK_ERROR;
                    break;

                case ConnectionStatusReasonNameInUse:
                    errorName = TELEPATHY_ERROR_NOT_YOURS;
                    break;

                case ConnectionStatusReasonCertNotProvided:
                case ConnectionStatusReasonCertUntrusted:
                case ConnectionStatusReasonCertExpired:
                case ConnectionStatusReasonCertNotActivated:
                case ConnectionStatusReasonCertHostnameMismatch:
                case ConnectionStatusReasonCertFingerprintMismatch:
                case ConnectionStatusReasonCertSelfSigned:
                case ConnectionStatusReasonCertOtherError:
                    errorName = TELEPATHY_ERROR_NETWORK_ERROR;

                default:
                    errorName = TELEPATHY_ERROR_DISCONNECTED;
            }

            // TODO should we signal statusChanged to Disconnected here or just
            //      invalidate?
            //      Also none of the pendingOperations will finish. The
            //      user should just consider them to fail as the connection
            //      is invalid
            onStatusReady(StatusDisconnected);
            invalidate(QLatin1String(errorName),
                    QString("ConnectionStatusReason = %1").arg(uint(reason)));
            break;

        default:
            warning() << "Unknown connection status" << status;
            break;
    }
}

void Connection::gotStatus(QDBusPendingCallWatcher *watcher)
{
    QDBusPendingReply<uint> reply = *watcher;

    if (mPriv->pendingStatus != StatusUnknown) {
        // we already got the status from StatusChanged, ignoring here
        return;
    }

    if (reply.isError()) {
        warning().nospace() << "GetStatus() failed with " <<
            reply.error().name() << ":" << reply.error().message();

        invalidate(reply.error());
        return;
    }

    uint status = reply.value();
    debug() << "Got connection status" << status;

    mPriv->pendingStatus = status;
    mPriv->readinessHelper->setCurrentStatus(status);

    watcher->deleteLater();
}

void Connection::gotInterfaces(QDBusPendingCallWatcher *watcher)
{
    QDBusPendingReply<QStringList> reply = *watcher;

    if (!reply.isError()) {
        setInterfaces(reply.value());
        debug() << "Got reply to GetInterfaces():" << interfaces();
        mPriv->readinessHelper->setInterfaces(interfaces());
    }
    else {
        warning().nospace() << "GetInterfaces() failed with " <<
            reply.error().name() << ":" << reply.error().message() <<
            " - assuming no new interfaces";
        // do not fail if GetInterfaces fail
    }

    if (mPriv->pendingStatus == StatusConnected) {
        if (interfaces().contains(TELEPATHY_INTERFACE_CONNECTION_INTERFACE_REQUESTS)) {
            mPriv->introspectCapabilities();
        } else {
            // we don't support Requests interface, so let's create an empty
            // ConnectionCapabilities object
            mPriv->caps = new ConnectionCapabilities();

            mPriv->introspectSelfHandle();
        }
    } else {
        mPriv->readinessHelper->setIntrospectCompleted(FeatureCore, true);
    }

    watcher->deleteLater();
}

void Connection::gotContactAttributeInterfaces(QDBusPendingCallWatcher *watcher)
{
    QDBusPendingReply<QDBusVariant> reply = *watcher;

    if (!reply.isError()) {
        mPriv->contactAttributeInterfaces = qdbus_cast<QStringList>(reply.value().variant());
        debug() << "Got" << mPriv->contactAttributeInterfaces.size() << "contact attribute interfaces";
    } else {
        warning().nospace() << "Getting contact attribute interfaces failed with " <<
            reply.error().name() << ":" << reply.error().message();

        // TODO should we remove Contacts interface from interfaces?
        warning() << "Connection supports Contacts interface but contactAttributeInterfaces "
            "can't be retrieved";
    }

    mPriv->readinessHelper->setIntrospectCompleted(FeatureCore, true);

    watcher->deleteLater();
}

void Connection::gotSelfContact(PendingOperation *op)
{
    PendingContacts *pending = qobject_cast<PendingContacts *>(op);

    if (pending->isValid()) {
        Q_ASSERT(pending->contacts().size() == 1);
        ContactPtr contact = pending->contacts()[0];

        if (mPriv->selfContact != contact) {
            mPriv->selfContact = contact;

            // first time
            if (!mPriv->readinessHelper->actualFeatures().contains(FeatureSelfContact)) {
                mPriv->readinessHelper->setIntrospectCompleted(FeatureSelfContact, true);
            }

            emit selfContactChanged();
        }
    } else {
        warning().nospace() << "Getting self contact failed with " <<
            pending->errorName() << ":" << pending->errorMessage();

        // check if the feature is already there, and for some reason introspectSelfContact
        // failed when called the second time
        if (!mPriv->readinessHelper->missingFeatures().contains(FeatureSelfContact)) {
            mPriv->readinessHelper->setIntrospectCompleted(FeatureSelfContact, false,
                    op->errorName(), op->errorMessage());
        }
    }
}

void Connection::gotSimpleStatuses(QDBusPendingCallWatcher *watcher)
{
    QDBusPendingReply<QDBusVariant> reply = *watcher;

    if (!reply.isError()) {
        mPriv->simplePresenceStatuses = qdbus_cast<SimpleStatusSpecMap>(reply.value().variant());
        debug() << "Got" << mPriv->simplePresenceStatuses.size() << "simple presence statuses";
        mPriv->readinessHelper->setIntrospectCompleted(FeatureSimplePresence, true);
    }
    else {
        warning().nospace() << "Getting simple presence statuses failed with " <<
            reply.error().name() << ":" << reply.error().message();
        mPriv->readinessHelper->setIntrospectCompleted(FeatureSimplePresence, false, reply.error());
    }

    watcher->deleteLater();
}

void Connection::gotSelfHandle(QDBusPendingCallWatcher *watcher)
{
    QDBusPendingReply<uint> reply = *watcher;

    if (!reply.isError()) {
        mPriv->selfHandle = reply.value();
        debug() << "Got self handle" << mPriv->selfHandle;

        if (interfaces().contains(TELEPATHY_INTERFACE_CONNECTION_INTERFACE_CONTACTS)) {
            mPriv->introspectContacts();
        } else {
            mPriv->readinessHelper->setIntrospectCompleted(FeatureCore, true);
        }
    } else {
        warning().nospace() << "Getting self handle failed with " <<
            reply.error().name() << ":" << reply.error().message();
        mPriv->readinessHelper->setIntrospectCompleted(FeatureCore, false, reply.error());
    }

    watcher->deleteLater();
}

void Connection::gotCapabilities(QDBusPendingCallWatcher *watcher)
{
    QDBusPendingReply<QDBusVariant> reply = *watcher;

    if (!reply.isError()) {
        debug() << "Got capabilities";
        mPriv->caps = new ConnectionCapabilities(
                qdbus_cast<RequestableChannelClassList>(reply.value().variant()));
    } else {
        warning().nospace() << "Getting capabilities failed with " <<
            reply.error().name() << ":" << reply.error().message();
        // Some error occurred, so let's create an empty
        // ConnectionCapabilities object
        mPriv->caps = new ConnectionCapabilities();
    }

    mPriv->introspectSelfHandle();

    watcher->deleteLater();
}

void Connection::gotContactListsHandles(PendingOperation *op)
{
    if (op->isError()) {
        // let's not fail, because the contact lists are not supported
        debug() << "Unable to retrieve contact list handle, ignoring";
        contactListChannelReady();
        return;
    }

    debug() << "Got handles for contact lists";
    PendingHandles *pending = qobject_cast<PendingHandles*>(op);

    if (pending->invalidNames().size() == 1) {
        // let's not fail, because the contact lists are not supported
        debug() << "Unable to retrieve contact list handle, ignoring";
        contactListChannelReady();
        return;
    }

    debug() << "Requesting channels for contact lists";
    QVariantMap request;
    request.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType"),
                   TELEPATHY_INTERFACE_CHANNEL_TYPE_CONTACT_LIST);
    request.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType"),
                   (uint) HandleTypeList);

    Q_ASSERT(pending->handles().size() == 1);
    Q_ASSERT(pending->namesRequested().size() == 1);
    ReferencedHandles handle = pending->handles();
    uint type = ContactManager::ContactListChannel::typeForIdentifier(
            pending->namesRequested().first());
    Q_ASSERT(type != (uint) -1 && type < ContactManager::ContactListChannel::LastType);
    mPriv->contactListChannels[type].handle = handle;
    request[QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandle")] = handle[0];
    connect(ensureChannel(request),
            SIGNAL(finished(Tp::PendingOperation*)),
            SLOT(gotContactListChannel(Tp::PendingOperation*)));
}

void Connection::gotContactListChannel(PendingOperation *op)
{
    if (op->isError()) {
        contactListChannelReady();
        return;
    }

    PendingChannel *pending = qobject_cast<PendingChannel*>(op);
    ChannelPtr channel = pending->channel();
    uint handle = pending->targetHandle();
    Q_ASSERT(channel);
    Q_ASSERT(handle);
    for (int i = 0; i < ContactManager::ContactListChannel::LastType; ++i) {
        if (mPriv->contactListChannels[i].handle.size() > 0 &&
            mPriv->contactListChannels[i].handle[0] == handle) {
            Q_ASSERT(!mPriv->contactListChannels[i].channel);
            mPriv->contactListChannels[i].channel = channel;
            connect(channel->becomeReady(),
                    SIGNAL(finished(Tp::PendingOperation *)),
                    SLOT(contactListChannelReady()));
        }
    }
}

void Connection::contactListChannelReady()
{
    if (++mPriv->contactListChannelsReady ==
            ContactManager::ContactListChannel::LastType) {
        debug() << "FeatureRoster ready";
        mPriv->contactManager->setContactListChannels(mPriv->contactListChannels);
        mPriv->readinessHelper->setIntrospectCompleted(FeatureRoster, true);
    }
}

void Connection::onNewChannels(const Tp::ChannelDetailsList &channelDetailsList)
{
    QString channelType;
    uint handleType;
    foreach (const ChannelDetails &channelDetails, channelDetailsList) {
        channelType = channelDetails.properties.value(
                QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType")).toString();
        if (channelType != TELEPATHY_INTERFACE_CHANNEL_TYPE_CONTACT_LIST) {
            continue;
        }

        handleType = channelDetails.properties.value(
                QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType")).toUInt();
        if (handleType != Tp::HandleTypeGroup) {
            continue;
        }

        ++mPriv->featureRosterGroupsTodo; // decremented in onContactListGroupChannelReady
        ChannelPtr channel = Channel::create(ConnectionPtr(this),
                channelDetails.channel.path(), channelDetails.properties);
        mPriv->contactListGroupChannels.append(channel);
        connect(channel->becomeReady(),
                SIGNAL(finished(Tp::PendingOperation*)),
                SLOT(onContactListGroupChannelReady(Tp::PendingOperation*)));
    }
}

void Connection::onContactListGroupChannelReady(Tp::PendingOperation *op)
{
    --mPriv->featureRosterGroupsTodo; // incremented in onNewChannels

    if (!isReady(FeatureRosterGroups)) {
        mPriv->checkFeatureRosterGroupsReady();
    } else {
        PendingReady *pr = qobject_cast<PendingReady*>(op);
        ChannelPtr channel = ChannelPtr(qobject_cast<Channel*>(pr->object()));
        mPriv->contactManager->addContactListGroupChannel(channel);
        mPriv->contactListGroupChannels.removeOne(channel);
    }
}

void Connection::gotChannels(QDBusPendingCallWatcher *watcher)
{
    QDBusPendingReply<QVariant> reply = *watcher;

    --mPriv->featureRosterGroupsTodo; // incremented in introspectRosterGroups

    if (!reply.isError()) {
        debug() << "Got channels";
        onNewChannels(qdbus_cast<ChannelDetailsList>(reply.value()));
    } else {
        warning().nospace() << "Getting channels failed with " <<
            reply.error().name() << ":" << reply.error().message();
    }

    mPriv->checkFeatureRosterGroupsReady();

    watcher->deleteLater();
}

/**
 * Get the ConnectionInterface for this Connection. This
 * method is protected since the convenience methods provided by this
 * class should generally be used instead of calling D-Bus methods
 * directly.
 *
 * \return A pointer to the existing ConnectionInterface for this
 *         Connection.
 */
Client::ConnectionInterface *Connection::baseInterface() const
{
    return mPriv->baseInterface;
}

/**
 * Asynchronously creates a channel satisfying the given request.
 *
 * The request MUST contain the following keys:
 *   org.freedesktop.Telepathy.Account.ChannelType
 *   org.freedesktop.Telepathy.Account.TargetHandleType
 *
 * Upon completion, the reply to the request can be retrieved through the
 * returned PendingChannel object. The object also provides access to the
 * parameters with which the call was made and a signal to connect to get
 * notification of the request finishing processing. See the documentation
 * for that class for more info.
 *
 * The returned PendingChannel object should be freed using
 * its QObject::deleteLater() method after it is no longer used. However,
 * all PendingChannel objects resulting from requests to a particular
 * Connection will be freed when the Connection itself is freed. Conversely,
 * this means that the PendingChannel object should not be used after the
 * Connection is destroyed.
 *
 * \sa PendingChannel
 *
 * \param request A dictionary containing the desirable properties.
 * \return Pointer to a newly constructed PendingChannel object, tracking
 *         the progress of the request.
 */
PendingChannel *Connection::createChannel(const QVariantMap &request)
{
    if (mPriv->pendingStatus != StatusConnected) {
        warning() << "Calling createChannel with connection not yet connected";
        return new PendingChannel(ConnectionPtr(this),
                TELEPATHY_ERROR_NOT_AVAILABLE,
                "Connection not yet connected");
    }

    if (!interfaces().contains(TELEPATHY_INTERFACE_CONNECTION_INTERFACE_REQUESTS)) {
        warning() << "Requests interface is not support by this connection";
        return new PendingChannel(ConnectionPtr(this),
                TELEPATHY_ERROR_NOT_IMPLEMENTED,
                "Connection does not support Requests Interface");
    }

    if (!request.contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType"))) {
        return new PendingChannel(ConnectionPtr(this),
                TELEPATHY_ERROR_INVALID_ARGUMENT,
                "Invalid 'request' argument");
    }

    debug() << "Creating a Channel";
    PendingChannel *channel =
        new PendingChannel(ConnectionPtr(this),
                request, true);
    return channel;
}

/**
 * Asynchronously ensures a channel exists satisfying the given request.
 *
 * The request MUST contain the following keys:
 *   org.freedesktop.Telepathy.Account.ChannelType
 *   org.freedesktop.Telepathy.Account.TargetHandleType
 *
 * Upon completion, the reply to the request can be retrieved through the
 * returned PendingChannel object. The object also provides access to the
 * parameters with which the call was made and a signal to connect to get
 * notification of the request finishing processing. See the documentation
 * for that class for more info.
 *
 * The returned PendingChannel object should be freed using
 * its QObject::deleteLater() method after it is no longer used. However,
 * all PendingChannel objects resulting from requests to a particular
 * Connection will be freed when the Connection itself is freed. Conversely,
 * this means that the PendingChannel object should not be used after the
 * Connection is destroyed.
 *
 * \sa PendingChannel
 *
 * \param request A dictionary containing the desirable properties.
 * \return Pointer to a newly constructed PendingChannel object, tracking
 *         the progress of the request.
 */
PendingChannel *Connection::ensureChannel(const QVariantMap &request)
{
    if (mPriv->pendingStatus != StatusConnected) {
        warning() << "Calling ensureChannel with connection not yet connected";
        return new PendingChannel(ConnectionPtr(this),
                TELEPATHY_ERROR_NOT_AVAILABLE,
                "Connection not yet connected");
    }

    if (!interfaces().contains(TELEPATHY_INTERFACE_CONNECTION_INTERFACE_REQUESTS)) {
        warning() << "Requests interface is not support by this connection";
        return new PendingChannel(ConnectionPtr(this),
                TELEPATHY_ERROR_NOT_IMPLEMENTED,
                "Connection does not support Requests Interface");
    }

    if (!request.contains(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType"))) {
        return new PendingChannel(ConnectionPtr(this),
                TELEPATHY_ERROR_INVALID_ARGUMENT,
                "Invalid 'request' argument");
    }

    debug() << "Creating a Channel";
    PendingChannel *channel =
        new PendingChannel(ConnectionPtr(this), request, false);
    return channel;
}

/**
 * Request handles of the given type for the given entities (contacts,
 * rooms, lists, etc.).
 *
 * Upon completion, the reply to the request can be retrieved through the
 * returned PendingHandles object. The object also provides access to the
 * parameters with which the call was made and a signal to connect to to get
 * notification of the request finishing processing. See the documentation
 * for that class for more info.
 *
 * The returned PendingHandles object should be freed using
 * its QObject::deleteLater() method after it is no longer used. However,
 * all PendingHandles objects resulting from requests to a particular
 * Connection will be freed when the Connection itself is freed. Conversely,
 * this means that the PendingHandles object should not be used after the
 * Connection is destroyed.
 *
 * \sa PendingHandles
 *
 * \param handleType Type for the handles to request, as specified in
 *                   #HandleType.
 * \param names Names of the entities to request handles for.
 * \return Pointer to a newly constructed PendingHandles object, tracking
 *         the progress of the request.
 */
PendingHandles *Connection::requestHandles(uint handleType, const QStringList &names)
{
    debug() << "Request for" << names.length() << "handles of type" << handleType;

    {
        Private::HandleContext *handleContext = mPriv->handleContext;
        QMutexLocker locker(&handleContext->lock);
        handleContext->types[handleType].requestsInFlight++;
    }

    PendingHandles *pending =
        new PendingHandles(ConnectionPtr(this), handleType, names);
    return pending;
}

/**
 * Request a reference to the given handles. Handles not explicitly
 * requested (via requestHandles()) but eg. observed in a signal need to be
 * referenced to guarantee them staying valid.
 *
 * Upon completion, the reply to the operation can be retrieved through the
 * returned PendingHandles object. The object also provides access to the
 * parameters with which the call was made and a signal to connect to to get
 * notification of the request finishing processing. See the documentation
 * for that class for more info.
 *
 * The returned PendingHandles object should be freed using
 * its QObject::deleteLater() method after it is no longer used. However,
 * all PendingHandles objects resulting from requests to a particular
 * Connection will be freed when the Connection itself is freed. Conversely,
 * this means that the PendingHandles object should not be used after the
 * Connection is destroyed.
 *
 * \sa PendingHandles
 *
 * \param handleType Type of the handles given, as specified in #HandleType.
 * \param handles Handles to request a reference to.
 * \return Pointer to a newly constructed PendingHandles object, tracking
 *         the progress of the request.
 */
PendingHandles *Connection::referenceHandles(uint handleType, const UIntList &handles)
{
    debug() << "Reference of" << handles.length() << "handles of type" << handleType;

    UIntList alreadyHeld;
    UIntList notYetHeld;
    {
        Private::HandleContext *handleContext = mPriv->handleContext;
        QMutexLocker locker(&handleContext->lock);

        foreach (uint handle, handles) {
            if (handleContext->types[handleType].refcounts.contains(handle) ||
                handleContext->types[handleType].toRelease.contains(handle)) {
                alreadyHeld.push_back(handle);
            }
            else {
                notYetHeld.push_back(handle);
            }
        }
    }

    debug() << " Already holding" << alreadyHeld.size() <<
        "of the handles -" << notYetHeld.size() << "to go";

    PendingHandles *pending =
        new PendingHandles(ConnectionPtr(this), handleType, handles,
                alreadyHeld, notYetHeld);
    return pending;
}

/**
 * Start an asynchronous request that the connection be connected.
 *
 * The returned PendingOperation will finish successfully when the connection
 * has reached StatusConnected and the requested \a features are all ready, or
 * finish with an error if a fatal error occurs during that process.
 *
 * \param requestedFeatures The features which should be enabled
 * \return A PendingReady object which will emit finished
 *         when the Connection has reached StatusConnected, and initial setup
 *         for basic functionality, plus the given features, has succeeded or
 *         failed
 */
PendingReady *Connection::requestConnect(const Features &requestedFeatures)
{
    return new PendingConnect(this, requestedFeatures);
}

/**
 * Start an asynchronous request that the connection be disconnected.
 * The returned PendingOperation object will signal the success or failure
 * of this request; under normal circumstances, it can be expected to
 * succeed.
 *
 * \return A %PendingOperation, which will emit finished when the
 *         request finishes.
 */
PendingOperation *Connection::requestDisconnect()
{
    return new PendingVoid(baseInterface()->Disconnect(), this);
}

/**
 * Requests attributes for contacts. Optionally, the handles of the contacts will be referenced
 * automatically. Essentially, this method wraps
 * ConnectionInterfaceContactsInterface::GetContactAttributes(), integrating it with the rest of the
 * handle-referencing machinery.
 *
 * Upon completion, the reply to the request can be retrieved through the returned
 * PendingContactAttributes object. The object also provides access to the parameters with which the
 * call was made and a signal to connect to to get notification of the request finishing processing.
 * See the documentation for that class for more info.
 *
 * If the remote object doesn't support the Contacts interface (as signified by the list returned by
 * interfaces() not containing TELEPATHY_INTERFACE_CONNECTION_INTERFACE_CONTACTS), the returned
 * PendingContactAttributes instance will fail instantly with the error
 * TELEPATHY_ERROR_NOT_IMPLEMENTED.
 *
 * Similarly, if the connection isn't both connected and ready (<code>status() == StatusConnected &&
 * isReady()</code>), the returned PendingContactAttributes instance will fail instantly with the
 * error TELEPATHY_ERROR_NOT_AVAILABLE.
 *
 * \sa PendingContactAttributes
 *
 * \param handles A list of handles of type HandleTypeContact
 * \param interfaces D-Bus interfaces for which the client requires information
 * \param reference Whether the handles should additionally be referenced.
 * \return Pointer to a newly constructed PendingContactAttributes, tracking the progress of the
 *         request.
 */
PendingContactAttributes *Connection::getContactAttributes(const UIntList &handles,
        const QStringList &interfaces, bool reference)
{
    debug() << "Request for attributes for" << handles.size() << "contacts";

    PendingContactAttributes *pending =
        new PendingContactAttributes(ConnectionPtr(this),
                handles, interfaces, reference);
    if (!isReady()) {
        warning() << "Connection::getContactAttributes() used when not ready";
        pending->failImmediately(TELEPATHY_ERROR_NOT_AVAILABLE, "The connection isn't ready");
        return pending;
    } /* FIXME: readd this check when Connection isn't FSCKING broken anymore: else if (status() != StatusConnected) {
        warning() << "Connection::getContactAttributes() used with status" << status() << "!= StatusConnected";
        pending->failImmediately(TELEPATHY_ERROR_NOT_AVAILABLE,
                "The connection isn't Connected");
        return pending;
    } */else if (!this->interfaces().contains(TELEPATHY_INTERFACE_CONNECTION_INTERFACE_CONTACTS)) {
        warning() << "Connection::getContactAttributes() used without the remote object supporting"
                  << "the Contacts interface";
        pending->failImmediately(TELEPATHY_ERROR_NOT_IMPLEMENTED,
                "The connection doesn't support the Contacts interface");
        return pending;
    }

    {
        Private::HandleContext *handleContext = mPriv->handleContext;
        QMutexLocker locker(&handleContext->lock);
        handleContext->types[HandleTypeContact].requestsInFlight++;
    }

    Client::ConnectionInterfaceContactsInterface *contactsInterface =
        optionalInterface<Client::ConnectionInterfaceContactsInterface>();
    QDBusPendingCallWatcher *watcher =
        new QDBusPendingCallWatcher(contactsInterface->GetContactAttributes(handles, interfaces,
                    reference));
    pending->connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)),
                              SLOT(onCallFinished(QDBusPendingCallWatcher*)));
    return pending;
}

QStringList Connection::contactAttributeInterfaces() const
{
    if (mPriv->pendingStatus != StatusConnected) {
        warning() << "Connection::contactAttributeInterfaces() used with status"
            << status() << "!= StatusConnected";
    } else if (!this->interfaces().contains(TELEPATHY_INTERFACE_CONNECTION_INTERFACE_CONTACTS)) {
        warning() << "Connection::contactAttributeInterfaces() used without the remote object supporting"
                  << "the Contacts interface";
    }

    return mPriv->contactAttributeInterfaces;
}

ContactManager *Connection::contactManager() const
{
    if (!isReady()) {
        return 0;
    }
    return mPriv->contactManager;
}

void Connection::refHandle(uint type, uint handle)
{
    Private::HandleContext *handleContext = mPriv->handleContext;
    QMutexLocker locker(&handleContext->lock);

    if (handleContext->types[type].toRelease.contains(handle)) {
        handleContext->types[type].toRelease.remove(handle);
    }

    handleContext->types[type].refcounts[handle]++;
}

void Connection::unrefHandle(uint type, uint handle)
{
    Private::HandleContext *handleContext = mPriv->handleContext;
    QMutexLocker locker(&handleContext->lock);

    Q_ASSERT(handleContext->types.contains(type));
    Q_ASSERT(handleContext->types[type].refcounts.contains(handle));

    if (!--handleContext->types[type].refcounts[handle]) {
        handleContext->types[type].refcounts.remove(handle);
        handleContext->types[type].toRelease.insert(handle);

        if (!handleContext->types[type].releaseScheduled) {
            if (!handleContext->types[type].requestsInFlight) {
                debug() << "Lost last reference to at least one handle of type" <<
                    type << "and no requests in flight for that type - scheduling a release sweep";
                QMetaObject::invokeMethod(this, "doReleaseSweep",
                        Qt::QueuedConnection, Q_ARG(uint, type));
                handleContext->types[type].releaseScheduled = true;
            }
        }
    }
}

void Connection::doReleaseSweep(uint type)
{
    Private::HandleContext *handleContext = mPriv->handleContext;
    QMutexLocker locker(&handleContext->lock);

    Q_ASSERT(handleContext->types.contains(type));
    Q_ASSERT(handleContext->types[type].releaseScheduled);

    debug() << "Entering handle release sweep for type" << type;
    handleContext->types[type].releaseScheduled = false;

    if (handleContext->types[type].requestsInFlight > 0) {
        debug() << " There are requests in flight, deferring sweep to when they have been completed";
        return;
    }

    if (handleContext->types[type].toRelease.isEmpty()) {
        debug() << " No handles to release - every one has been resurrected";
        return;
    }

    debug() << " Releasing" << handleContext->types[type].toRelease.size() << "handles";

    mPriv->baseInterface->ReleaseHandles(type, handleContext->types[type].toRelease.toList());
    handleContext->types[type].toRelease.clear();
}

void Connection::handleRequestLanded(uint type)
{
    Private::HandleContext *handleContext = mPriv->handleContext;
    QMutexLocker locker(&handleContext->lock);

    Q_ASSERT(handleContext->types.contains(type));
    Q_ASSERT(handleContext->types[type].requestsInFlight > 0);

    if (!--handleContext->types[type].requestsInFlight &&
        !handleContext->types[type].toRelease.isEmpty() &&
        !handleContext->types[type].releaseScheduled) {
        debug() << "All handle requests for type" << type <<
            "landed and there are handles of that type to release - scheduling a release sweep";
        QMetaObject::invokeMethod(this, "doReleaseSweep", Qt::QueuedConnection, Q_ARG(uint, type));
        handleContext->types[type].releaseScheduled = true;
    }
}

void Connection::onSelfHandleChanged(uint handle)
{
    mPriv->selfHandle = handle;
    emit selfHandleChanged(handle);

    if (mPriv->readinessHelper->actualFeatures().contains(FeatureSelfContact)) {
        Private::introspectSelfContact(mPriv);
    }
}

} // Tp