Codebase list telepathy-glib / upstream/0.7.37 telepathy-glib / group-mixin.c
upstream/0.7.37

Tree @upstream/0.7.37 (Download .tar.gz)

group-mixin.c @upstream/0.7.37raw · history · blame

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
/*
 * group-mixin.c - Source for TpGroupMixin
 *
 * Copyright (C) 2006-2007 Collabora Ltd. <http://www.collabora.co.uk/>
 * Copyright (C) 2006-2007 Nokia Corporation
 *   @author Ole Andre Vadla Ravnaas <ole.andre.ravnaas@collabora.co.uk>
 *   @author Robert McQueen <robert.mcqueen@collabora.co.uk>
 *
 * 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
 */

/**
 * SECTION:group-mixin
 * @title: TpGroupMixin
 * @short_description: a mixin implementation of the groups interface
 * @see_also: #TpSvcChannelInterfaceGroup
 *
 * This mixin can be added to a channel GObject class to implement the
 * groups interface in a general way.
 *
 * To use the group mixin, include a #TpGroupMixinClass somewhere in your
 * class structure and a #TpGroupMixin somewhere in your instance structure,
 * and call tp_group_mixin_class_init() from your class_init function,
 * tp_group_mixin_init() from your init function or constructor, and
 * tp_group_mixin_finalize() from your dispose or finalize function.
 *
 * To use the group mixin as the implementation of
 * #TpSvcChannelInterfaceGroup, call
 * <literal>G_IMPLEMENT_INTERFACE (TP_TYPE_SVC_CHANNEL_INTERFACE_GROUP,
 * tp_group_mixin_iface_init)</literal> in the fourth argument to
 * <literal>G_DEFINE_TYPE_WITH_CODE</literal>.
 *
 * Since 0.5.13 you can also implement the group interface by forwarding all
 * group operations to the group mixin of an associated object (mainly useful
 * for Tubes channels). To do this, call tp_external_group_mixin_init()
 * in the constructor after the associated object has been set,
 * tp_external_group_mixin_finalize() in the dispose or finalize function, and
 * <literal>G_IMPLEMENT_INTERFACE (TP_TYPE_SVC_CHANNEL_INTERFACE_GROUP,
 * tp_external_group_mixin_iface_init)</literal> in the fourth argument to
 * <literal>G_DEFINE_TYPE_WITH_CODE</literal>.
 *
 * Since 0.7.10 you can also implement the properties of Group channels,
 * by calling tp_group_mixin_init_dbus_properties() or
 * tp_external_group_mixin_init_dbus_properties() (as appropriate).
 */

#include <telepathy-glib/group-mixin.h>

#include <dbus/dbus-glib.h>
#include <stdio.h>
#include <string.h>

#include <telepathy-glib/dbus.h>
#include <telepathy-glib/debug-ansi.h>
#include <telepathy-glib/errors.h>
#include <telepathy-glib/gtypes.h>
#include <telepathy-glib/interfaces.h>

#define DEBUG_FLAG TP_DEBUG_GROUPS

#include "debug-internal.h"

#include "_gen/signals-marshal.h"

static const char *
group_change_reason_str (guint reason)
{
  switch (reason)
    {
    case TP_CHANNEL_GROUP_CHANGE_REASON_NONE:
      return "unspecified reason";
    case TP_CHANNEL_GROUP_CHANGE_REASON_OFFLINE:
      return "offline";
    case TP_CHANNEL_GROUP_CHANGE_REASON_KICKED:
      return "kicked";
    case TP_CHANNEL_GROUP_CHANGE_REASON_BUSY:
      return "busy";
    case TP_CHANNEL_GROUP_CHANGE_REASON_INVITED:
      return "invited";
    case TP_CHANNEL_GROUP_CHANGE_REASON_BANNED:
      return "banned";
    case TP_CHANNEL_GROUP_CHANGE_REASON_ERROR:
      return "error";
    case TP_CHANNEL_GROUP_CHANGE_REASON_INVALID_CONTACT:
      return "invalid contact";
    case TP_CHANNEL_GROUP_CHANGE_REASON_NO_ANSWER:
      return "no answer";
    case TP_CHANNEL_GROUP_CHANGE_REASON_RENAMED:
      return "renamed";
    case TP_CHANNEL_GROUP_CHANGE_REASON_PERMISSION_DENIED:
      return "permission denied";
    case TP_CHANNEL_GROUP_CHANGE_REASON_SEPARATED:
      return "separated";
    default:
      return "(unknown reason code)";
    }
}

typedef struct {
  TpHandle actor;
  guint reason;
  const gchar *message;
  TpHandleRepoIface *repo;
} LocalPendingInfo;

static LocalPendingInfo *
local_pending_info_new (TpHandleRepoIface *repo,
                        TpHandle actor,
                        guint reason,
                        const gchar *message)
{
  LocalPendingInfo *info = g_slice_new0 (LocalPendingInfo);
  info->actor = actor;
  info->reason = reason;
  info->message = g_strdup (message);
  info->repo = repo;

  if (actor != 0)
    tp_handle_ref (repo, actor);

  return info;
}

static void
local_pending_info_free (LocalPendingInfo *info)
{
  g_free ((gchar *) info->message);

  if (info->actor != 0)
    tp_handle_unref (info->repo, info->actor);

  g_slice_free (LocalPendingInfo, info);
}

struct _TpGroupMixinClassPrivate {
    TpGroupMixinRemMemberWithReasonFunc remove_with_reason;
    unsigned allow_self_removal : 1;
};

struct _TpGroupMixinPrivate {
    TpHandleSet *actors;
    GHashTable *handle_owners;
    GHashTable *local_pending_info;
    GPtrArray *externals;
};


/**
 * tp_group_mixin_class_get_offset_quark:
 *
 * <!--Returns: says it all-->
 *
 * Returns: the quark used for storing mixin offset on a GObjectClass
 */
GQuark
tp_group_mixin_class_get_offset_quark ()
{
  static GQuark offset_quark = 0;
  if (!offset_quark)
    offset_quark = g_quark_from_static_string ("TpGroupMixinClassOffsetQuark");
  return offset_quark;
}

/**
 * tp_group_mixin_get_offset_quark:
 *
 * <!--Returns: says it all-->
 *
 * Returns: the quark used for storing mixin offset on a GObject
 */
GQuark
tp_group_mixin_get_offset_quark ()
{
  static GQuark offset_quark = 0;
  if (!offset_quark)
    offset_quark = g_quark_from_static_string ("TpGroupMixinOffsetQuark");
  return offset_quark;
}

/**
 * tp_group_mixin_class_set_remove_with_reason_func:
 * @cls: The class of an object implementing the group interface using this
 *  mixin
 * @func: A callback to be used to remove contacts from this group with a
 *  specified reason.
 *
 * Set a callback to be used to implement RemoveMembers() and
 * RemoveMembersWithReason(). If this function is called during class
 * initialization, the given callback will be used instead of the remove
 * callback passed to tp_group_mixin_class_init() (which must be %NULL
 * in this case).
 *
 * Since: 0.5.13
 */
void
tp_group_mixin_class_set_remove_with_reason_func (GObjectClass *cls,
                                      TpGroupMixinRemMemberWithReasonFunc func)
{
  TpGroupMixinClass *mixin_cls = TP_GROUP_MIXIN_CLASS (cls);

  g_return_if_fail (mixin_cls->remove_member == NULL);
  g_return_if_fail (mixin_cls->priv->remove_with_reason == NULL);
  mixin_cls->priv->remove_with_reason = func;
}

/**
 * tp_group_mixin_class_init:
 * @obj_cls: The class of an object implementing the group interface using this
 *  mixin
 * @offset: The offset of the TpGroupMixinClass structure within the class
 *  structure
 * @add_func: A callback to be used to add contacts to this group
 * @rem_func: A callback to be used to remove contacts from this group.
 *  This must be %NULL if you will subsequently call
 *  tp_group_mixin_class_set_remove_with_reason_func().
 *
 * Configure the mixin for use with the given class.
 */
void
tp_group_mixin_class_init (GObjectClass *obj_cls,
                           glong offset,
                           TpGroupMixinAddMemberFunc add_func,
                           TpGroupMixinRemMemberFunc rem_func)
{
  TpGroupMixinClass *mixin_cls;

  g_assert (G_IS_OBJECT_CLASS (obj_cls));

  g_type_set_qdata (G_OBJECT_CLASS_TYPE (obj_cls),
                    TP_GROUP_MIXIN_CLASS_OFFSET_QUARK,
                    GINT_TO_POINTER (offset));

  mixin_cls = TP_GROUP_MIXIN_CLASS (obj_cls);

  mixin_cls->add_member = add_func;
  mixin_cls->remove_member = rem_func;

  mixin_cls->priv = g_slice_new0 (TpGroupMixinClassPrivate);
}

/**
 * tp_group_mixin_class_allow_self_removal:
 * @obj_cls: The class of an object implementing the group interface using this
 *  mixin
 *
 * Configure the mixin to allow attempts to remove the SelfHandle from this
 * Group, even if the group flags would otherwise disallow this. The
 * channel's #TpGroupMixinRemMemberFunc or
 * #TpGroupMixinRemMemberWithReasonFunc will be called as usual for such
 * attempts, and may make them fail with %TP_ERROR_PERMISSION_DENIED if
 * required.
 *
 * This function should be called from the GObject @class_init callback,
 * after calling tp_group_mixin_class_init().
 *
 * (Recent telepathy-spec changes make it valid to try to remove the
 * self-handle at all times, regardless of group flags. However, if this was
 * implemented automatically in TpGroupMixin, this would risk crashing
 * connection manager implementations that assume that TpGroupMixin will
 * enforce the group flags strictly. As a result, connection managers should
 * call this function to indicate to the TpGroupMixin that it may call their
 * removal callback with the self-handle regardless of flag settings.)
 *
 * Since: 0.7.27
 */
void
tp_group_mixin_class_allow_self_removal (GObjectClass *obj_cls)
{
  TpGroupMixinClass *mixin_cls = TP_GROUP_MIXIN_CLASS (obj_cls);

  mixin_cls->priv->allow_self_removal = TRUE;
}

/**
 * tp_group_mixin_init:
 * @obj: An object implementing the group interface using this mixin
 * @offset: The offset of the TpGroupMixin structure within the instance
 *  structure
 * @handle_repo: The connection's handle repository for contacts
 * @self_handle: The handle of the local user in this group, if any
 *
 * Initialize the mixin.
 */
void
tp_group_mixin_init (GObject *obj,
                     glong offset,
                     TpHandleRepoIface *handle_repo,
                     TpHandle self_handle)
{
  TpGroupMixin *mixin;

  g_assert (G_IS_OBJECT (obj));

  g_type_set_qdata (G_OBJECT_TYPE (obj),
                    TP_GROUP_MIXIN_OFFSET_QUARK,
                    GINT_TO_POINTER (offset));

  mixin = TP_GROUP_MIXIN (obj);

  mixin->handle_repo = handle_repo;
  mixin->self_handle = self_handle;

  if (mixin->self_handle != 0)
    tp_handle_ref (handle_repo, mixin->self_handle);

  mixin->group_flags = 0;

  mixin->members = tp_handle_set_new (handle_repo);
  mixin->local_pending = tp_handle_set_new (handle_repo);
  mixin->remote_pending = tp_handle_set_new (handle_repo);

  mixin->priv = g_slice_new0 (TpGroupMixinPrivate);
  mixin->priv->handle_owners = g_hash_table_new (NULL, NULL);
  mixin->priv->local_pending_info = g_hash_table_new_full (NULL, NULL, NULL,
      (GDestroyNotify)local_pending_info_free);
  mixin->priv->actors = tp_handle_set_new (handle_repo);
  mixin->priv->externals = NULL;
}

static void
tp_group_mixin_add_external (GObject *obj, GObject *external)
{
  TpGroupMixin *mixin = TP_GROUP_MIXIN (obj);

  if (mixin->priv->externals == NULL)
    mixin->priv->externals = g_ptr_array_new ();
  g_ptr_array_add (mixin->priv->externals, external);
}

static void
tp_group_mixin_remove_external (GObject *obj, GObject *external)
{
  TpGroupMixin *mixin = TP_GROUP_MIXIN (obj);

  /* we can't have added it if we have no array to add it to... */
  g_return_if_fail (mixin->priv->externals != NULL);
  g_ptr_array_remove_fast (mixin->priv->externals, external);
}

static void
handle_owners_foreach_unref (gpointer key,
                             gpointer value,
                             gpointer user_data)
{
  TpGroupMixin *mixin = user_data;

  tp_handle_unref (mixin->handle_repo, GPOINTER_TO_UINT (key));

  if (GPOINTER_TO_UINT (value) != 0)
    tp_handle_unref (mixin->handle_repo, GPOINTER_TO_UINT (value));
}

/**
 * tp_group_mixin_finalize:
 * @obj: An object implementing the group interface using this mixin
 *
 * Unreference handles and free resources used by this mixin.
 */
void
tp_group_mixin_finalize (GObject *obj)
{
  TpGroupMixin *mixin = TP_GROUP_MIXIN (obj);

  tp_handle_set_destroy (mixin->priv->actors);

  g_hash_table_foreach (mixin->priv->handle_owners,
                        handle_owners_foreach_unref,
                        mixin);

  g_hash_table_destroy (mixin->priv->handle_owners);
  g_hash_table_destroy (mixin->priv->local_pending_info);

  if (mixin->priv->externals)
    g_ptr_array_free (mixin->priv->externals, TRUE);

  g_slice_free (TpGroupMixinPrivate, mixin->priv);

  if (mixin->self_handle != 0)
    tp_handle_unref (mixin->handle_repo, mixin->self_handle);

  tp_handle_set_destroy (mixin->members);
  tp_handle_set_destroy (mixin->local_pending);
  tp_handle_set_destroy (mixin->remote_pending);
}

/**
 * tp_group_mixin_get_self_handle:
 * @obj: An object implementing the group mixin using this interface
 * @ret: Used to return the local user's handle in this group
 * @error: Unused
 *
 * Set the guint pointed to by ret to the local user's handle in this
 * group, or to 0 if the local user is not present in this group.
 *
 * Returns: %TRUE.
 */
gboolean
tp_group_mixin_get_self_handle (GObject *obj,
                                guint *ret,
                                GError **error)
{
  TpGroupMixin *mixin = TP_GROUP_MIXIN (obj);

  if (tp_handle_set_is_member (mixin->members, mixin->self_handle) ||
      tp_handle_set_is_member (mixin->local_pending, mixin->self_handle) ||
      tp_handle_set_is_member (mixin->remote_pending, mixin->self_handle))
    {
      *ret = mixin->self_handle;
    }
  else
    {
      *ret = 0;
    }

  return TRUE;
}


/**
 * tp_group_mixin_change_self_handle:
 * @obj: An object implementing the group interface using this mixin
 * @new_self_handle: The new self-handle for this group
 *
 * Change the self-handle for this group to the given value.
 */
void
tp_group_mixin_change_self_handle (GObject *obj,
                                   TpHandle new_self_handle)
{
  TpGroupMixin *mixin = TP_GROUP_MIXIN (obj);
  TpHandle old_self_handle = mixin->self_handle;

  DEBUG ("%u '%s'", new_self_handle,
      tp_handle_inspect (mixin->handle_repo, new_self_handle));

  if (new_self_handle != 0)
    tp_handle_ref (mixin->handle_repo, new_self_handle);

  mixin->self_handle = new_self_handle;

  tp_svc_channel_interface_group_emit_self_handle_changed (obj,
      new_self_handle);

  if (old_self_handle != 0)
    tp_handle_unref (mixin->handle_repo, old_self_handle);
}


static void
tp_group_mixin_get_self_handle_async (TpSvcChannelInterfaceGroup *obj,
                                      DBusGMethodInvocation *context)
{
  guint ret;
  GError *error = NULL;

  if (tp_group_mixin_get_self_handle ((GObject *) obj, &ret, &error))
    {
      tp_svc_channel_interface_group_return_from_get_self_handle (
          context, ret);
    }
  else
    {
      dbus_g_method_return_error (context, error);
      g_error_free (error);
    }
}

/**
 * tp_group_mixin_get_group_flags:
 * @obj: An object implementing the group mixin using this interface
 * @ret: Used to return the flags
 * @error: Unused
 *
 * Set the guint pointed to by ret to this group's flags, to be
 * interpreted according to TpChannelGroupFlags.
 *
 * Returns: %TRUE
 */
gboolean
tp_group_mixin_get_group_flags (GObject *obj,
                                guint *ret,
                                GError **error)
{
  TpGroupMixin *mixin = TP_GROUP_MIXIN (obj);

  *ret = mixin->group_flags;

  return TRUE;
}

static void
tp_group_mixin_get_group_flags_async (TpSvcChannelInterfaceGroup *obj,
                                      DBusGMethodInvocation *context)
{
  guint ret;
  GError *error = NULL;

  if (tp_group_mixin_get_group_flags ((GObject *) obj, &ret, &error))
    {
      tp_svc_channel_interface_group_return_from_get_group_flags (
          context, ret);
    }
  else
    {
      dbus_g_method_return_error (context, error);
      g_error_free (error);
    }
}

/**
 * tp_group_mixin_add_members:
 * @obj: An object implementing the group interface using this mixin
 * @contacts: A GArray of guint representing contacts
 * @message: A message associated with the addition request, if supported
 * @error: Used to return an error if %FALSE is returned
 *
 * Request that the given contacts be added to the group as if in response
 * to user action. If the group's flags prohibit this, raise
 * PermissionDenied. If any of the handles is invalid, raise InvalidHandle.
 * Otherwise attempt to add the contacts by calling the callbacks provided
 * by the channel implementation.
 *
 * Returns: %TRUE on success
 */
gboolean
tp_group_mixin_add_members (GObject *obj,
                            const GArray *contacts,
                            const gchar *message,
                            GError **error)
{
  TpGroupMixinClass *mixin_cls = TP_GROUP_MIXIN_CLASS (G_OBJECT_GET_CLASS (obj));
  TpGroupMixin *mixin = TP_GROUP_MIXIN (obj);
  guint i;
  TpHandle handle;

  /* reject invalid handles */
  if (!tp_handles_are_valid (mixin->handle_repo, contacts, FALSE, error))
    return FALSE;

  /* check that adding is allowed by flags */
  for (i = 0; i < contacts->len; i++)
    {
      handle = g_array_index (contacts, TpHandle, i);

      if ((mixin->group_flags & TP_CHANNEL_GROUP_FLAG_CAN_ADD) == 0 &&
          !tp_handle_set_is_member (mixin->local_pending, handle))
        {
          DEBUG ("handle %u cannot be added to members without "
              "GROUP_FLAG_CAN_ADD", handle);

          g_set_error (error, TP_ERRORS, TP_ERROR_PERMISSION_DENIED,
              "handle %u cannot be added to members without "
              "GROUP_FLAG_CAN_ADD", handle);

          return FALSE;
        }
    }

  /* add handle by handle */
  for (i = 0; i < contacts->len; i++)
    {
      handle = g_array_index (contacts, TpHandle, i);

      if (tp_handle_set_is_member (mixin->members, handle))
        {
          DEBUG ("handle %u is already a member, skipping", handle);

          continue;
        }

      if (mixin_cls->add_member == NULL)
        {
          g_set_error (error, TP_ERRORS, TP_ERROR_NOT_IMPLEMENTED,
              "Adding members to this Group channel is not possible");
          return FALSE;
        }
      if (!mixin_cls->add_member (obj, handle, message, error))
        {
          return FALSE;
        }
    }

  return TRUE;
}

static void
tp_group_mixin_add_members_async (TpSvcChannelInterfaceGroup *obj,
                                  const GArray *contacts,
                                  const gchar *message,
                                  DBusGMethodInvocation *context)
{
  GError *error = NULL;

  if (tp_group_mixin_add_members ((GObject *) obj, contacts, message, &error))
    {
      tp_svc_channel_interface_group_return_from_add_members (context);
    }
  else
    {
      dbus_g_method_return_error (context, error);
      g_error_free (error);
    }
}

/**
 * tp_group_mixin_remove_members:
 * @obj: An object implementing the group interface using this mixin
 * @contacts: A GArray of guint representing contacts
 * @message: A message to be sent to those contacts, if supported
 * @error: Used to return an error if %FALSE is returned
 *
 * Request that the given contacts be removed from the group as if in response
 * to user action. If the group's flags prohibit this, raise
 * PermissionDenied. If any of the handles is invalid, raise InvalidHandle.
 * If any of the handles is absent from the group, raise NotAvailable.
 * Otherwise attempt to remove the contacts by calling the callbacks provided
 * by the channel implementation.
 *
 * Returns: %TRUE on success
 */
gboolean
tp_group_mixin_remove_members (GObject *obj,
                               const GArray *contacts,
                               const gchar *message,
                               GError **error)
{
  return tp_group_mixin_remove_members_with_reason (obj, contacts, message,
      TP_CHANNEL_GROUP_CHANGE_REASON_NONE, error);
}

/**
 * tp_group_mixin_remove_members_with_reason:
 * @obj: An object implementing the group interface using this mixin
 * @contacts: A GArray of guint representing contacts
 * @message: A message to be sent to those contacts, if supported
 * @reason: A #TpChannelGroupChangeReason
 * @error: Used to return an error if %FALSE is returned
 *
 * Request that the given contacts be removed from the group as if in response
 * to user action. If the group's flags prohibit this, raise
 * PermissionDenied. If any of the handles is invalid, raise InvalidHandle.
 * If any of the handles is absent from the group, raise NotAvailable.
 * Otherwise attempt to remove the contacts by calling the callbacks provided
 * by the channel implementation.
 *
 * Returns: %TRUE on success
 */
gboolean
tp_group_mixin_remove_members_with_reason (GObject *obj,
                               const GArray *contacts,
                               const gchar *message,
                               guint reason,
                               GError **error)
{
  TpGroupMixinClass *mixin_cls = TP_GROUP_MIXIN_CLASS (G_OBJECT_GET_CLASS (obj));
  TpGroupMixin *mixin = TP_GROUP_MIXIN (obj);
  guint i;
  TpHandle handle;

  /* reject invalid handles */
  if (!tp_handles_are_valid (mixin->handle_repo, contacts, FALSE, error))
    return FALSE;

  /* check removing is allowed by flags */
  for (i = 0; i < contacts->len; i++)
    {
      handle = g_array_index (contacts, TpHandle, i);

      if (mixin_cls->priv->allow_self_removal &&
          handle == mixin->self_handle &&
          (tp_handle_set_is_member (mixin->members, handle) ||
           tp_handle_set_is_member (mixin->remote_pending, handle) ||
           tp_handle_set_is_member (mixin->local_pending, handle)))
        {
          /* don't check the flags - attempting to remove the self-handle
           * is explicitly always allowed by this channel */
        }
      else if (tp_handle_set_is_member (mixin->members, handle))
        {
          if ((mixin->group_flags & TP_CHANNEL_GROUP_FLAG_CAN_REMOVE) == 0)
            {
              DEBUG ("handle %u cannot be removed from members without "
                  "GROUP_FLAG_CAN_REMOVE", handle);

              g_set_error (error, TP_ERRORS, TP_ERROR_PERMISSION_DENIED,
                  "handle %u cannot be removed from members without "
                  "GROUP_FLAG_CAN_REMOVE", handle);

              return FALSE;
            }
        }
      else if (tp_handle_set_is_member (mixin->remote_pending, handle))
        {
          if ((mixin->group_flags & TP_CHANNEL_GROUP_FLAG_CAN_RESCIND) == 0)
            {
              DEBUG ("handle %u cannot be removed from remote pending "
                  "without GROUP_FLAG_CAN_RESCIND", handle);

              g_set_error (error, TP_ERRORS, TP_ERROR_PERMISSION_DENIED,
                  "handle %u cannot be removed from remote pending without "
                  "GROUP_FLAG_CAN_RESCIND", handle);

              return FALSE;
            }
        }
      else if (!tp_handle_set_is_member (mixin->local_pending, handle))
        {
          DEBUG ("handle %u is not a current or pending member",
                   handle);

          g_set_error (error, TP_ERRORS, TP_ERROR_NOT_AVAILABLE,
              "handle %u is not a current or pending member", handle);

          return FALSE;
        }
    }

  /* remove handle by handle */
  for (i = 0; i < contacts->len; i++)
    {
      handle = g_array_index (contacts, TpHandle, i);

      if (mixin_cls->priv->remove_with_reason != NULL)
        {
          if (!mixin_cls->priv->remove_with_reason (obj, handle, message,
                                                    reason, error))
            {
              return FALSE;
            }
        }
      else if (mixin_cls->remove_member != NULL)
        {
          if (!mixin_cls->remove_member (obj, handle, message, error))
            {
              return FALSE;
            }
        }
      else
        {
          g_set_error (error, TP_ERRORS, TP_ERROR_NOT_IMPLEMENTED,
              "Removing contacts from this Group channel is not possible");
          return FALSE;
        }
    }

  return TRUE;
}

static void
tp_group_mixin_remove_members_with_reason_async
    (TpSvcChannelInterfaceGroup *obj,
     const GArray *contacts,
     const gchar *message,
     guint reason,
     DBusGMethodInvocation *context)
{
  GError *error = NULL;

  if (tp_group_mixin_remove_members_with_reason ((GObject *) obj, contacts,
        message, reason, &error))
    {
      tp_svc_channel_interface_group_return_from_remove_members_with_reason
        (context);
    }
  else
    {
      dbus_g_method_return_error (context, error);
      g_error_free (error);
    }
}

static void
tp_group_mixin_remove_members_async (TpSvcChannelInterfaceGroup *obj,
                                     const GArray *contacts,
                                     const gchar *message,
                                     DBusGMethodInvocation *context)
{
  GError *error = NULL;

  if (tp_group_mixin_remove_members_with_reason ((GObject *) obj, contacts,
        message, TP_CHANNEL_GROUP_CHANGE_REASON_NONE, &error))
    {
      tp_svc_channel_interface_group_return_from_remove_members (context);
    }
  else
    {
      dbus_g_method_return_error (context, error);
      g_error_free (error);
    }
}

/**
 * tp_group_mixin_get_members:
 * @obj: An object implementing the group interface using this mixin
 * @ret: Used to return a newly-allocated GArray of guint contact handles
 * @error: Unused
 *
 * Get the group's current members
 *
 * Returns: %TRUE
 */
gboolean
tp_group_mixin_get_members (GObject *obj,
                            GArray **ret,
                            GError **error)
{
  TpGroupMixin *mixin = TP_GROUP_MIXIN (obj);

  *ret = tp_handle_set_to_array (mixin->members);

  return TRUE;
}

static void
tp_group_mixin_get_members_async (TpSvcChannelInterfaceGroup *obj,
                                  DBusGMethodInvocation *context)
{
  GArray *ret;
  GError *error = NULL;

  if (tp_group_mixin_get_members ((GObject *) obj, &ret, &error))
    {
      tp_svc_channel_interface_group_return_from_get_members (
          context, ret);
      g_array_free (ret, TRUE);
    }
  else
    {
      dbus_g_method_return_error (context, error);
      g_error_free (error);
    }
}

/**
 * tp_group_mixin_get_local_pending_members:
 * @obj: An object implementing the group interface using this mixin
 * @ret: Used to return a newly-allocated GArray of guint contact handles
 * @error: Unused
 *
 * Get the group's local-pending members.
 *
 * Returns: %TRUE
 */
gboolean
tp_group_mixin_get_local_pending_members (GObject *obj,
                                          GArray **ret,
                                          GError **error)
{
  TpGroupMixin *mixin = TP_GROUP_MIXIN (obj);

  *ret = tp_handle_set_to_array (mixin->local_pending);

  return TRUE;
}

static void
tp_group_mixin_get_local_pending_members_async (TpSvcChannelInterfaceGroup *obj,
                                                DBusGMethodInvocation *context)
{
  GArray *ret;
  GError *error = NULL;

  if (tp_group_mixin_get_local_pending_members ((GObject *) obj, &ret, &error))
    {
      tp_svc_channel_interface_group_return_from_get_local_pending_members (
          context, ret);
      g_array_free (ret, TRUE);
    }
  else
    {
      dbus_g_method_return_error (context, error);
      g_error_free (error);
    }
}

typedef struct {
    TpGroupMixin *mixin;
    GPtrArray *array;
} _mixin_and_array_of_info;

static void
local_pending_members_with_info_foreach (TpHandleSet *set,
                                         TpHandle i,
                                         gpointer userdata)
{
  _mixin_and_array_of_info *data = userdata;
  TpGroupMixinPrivate *priv = data->mixin->priv;
  GType info_type = TP_STRUCT_TYPE_LOCAL_PENDING_INFO;
  GValue entry = { 0, };
  LocalPendingInfo *info = g_hash_table_lookup (priv->local_pending_info,
                                                GUINT_TO_POINTER(i));
  g_assert (info != NULL);

  g_value_init (&entry, info_type);
  g_value_take_boxed (&entry, dbus_g_type_specialized_construct (info_type));

  dbus_g_type_struct_set (&entry,
      0, i,
      1, info->actor,
      2, info->reason,
      3, info->message,
      G_MAXUINT);

  g_ptr_array_add (data->array, g_value_get_boxed (&entry));
}

/**
 * tp_group_mixin_get_local_pending_members_with_info:
 * @obj: An object implementing the group interface using this mixin
 * @ret: Used to return a newly-allocated GPtrArray of D-Bus structures each
 * containing the handle of a local-pending contact, the handle of a contact
 *  responsible for adding them to the group (or 0), the reason code
 *  and a related message (e.g. their request to join the group)
 * @error: Unused
 *
 * Get the group's local-pending members and information about their
 * requests to join the channel.
 *
 * Returns: %TRUE
 */
gboolean
tp_group_mixin_get_local_pending_members_with_info (
                                               GObject *obj,
                                               GPtrArray **ret,
                                               GError **error)
{
  TpGroupMixin *mixin = TP_GROUP_MIXIN (obj);
  _mixin_and_array_of_info data = { mixin, NULL };

  *ret = g_ptr_array_new ();
  data.array = *ret;

  tp_handle_set_foreach (mixin->local_pending,
      local_pending_members_with_info_foreach, &data);

  return TRUE;
}

static void
tp_group_mixin_get_local_pending_members_with_info_async (
                                                TpSvcChannelInterfaceGroup *obj,
                                                DBusGMethodInvocation *context)
{
  GPtrArray *ret;
  GError *error = NULL;

  if (tp_group_mixin_get_local_pending_members_with_info ((GObject *) obj,
        &ret, &error))
    {
      guint i;
      tp_svc_channel_interface_group_return_from_get_local_pending_members_with_info (
          context, ret);
      for (i = 0 ; i < ret->len; i++) {
        g_value_array_free (g_ptr_array_index (ret,i));
      }
      g_ptr_array_free (ret, TRUE);
    }
  else
    {
      dbus_g_method_return_error (context, error);
      g_error_free (error);
    }
}

/**
 * tp_group_mixin_get_remote_pending_members:
 * @obj: An object implementing the group interface using this mixin
 * @ret: Used to return a newly-allocated GArray of guint representing the
 * handles of the group's remote pending members
 * @error: Unused
 *
 * Get the group's remote-pending members.
 *
 * Returns: %TRUE
 */
gboolean
tp_group_mixin_get_remote_pending_members (GObject *obj,
                                           GArray **ret,
                                           GError **error)
{
  TpGroupMixin *mixin = TP_GROUP_MIXIN (obj);

  *ret = tp_handle_set_to_array (mixin->remote_pending);

  return TRUE;
}

static void
tp_group_mixin_get_remote_pending_members_async (TpSvcChannelInterfaceGroup *obj,
                                                 DBusGMethodInvocation *context)
{
  GArray *ret;
  GError *error = NULL;

  if (tp_group_mixin_get_remote_pending_members ((GObject *) obj,
        &ret, &error))
    {
      tp_svc_channel_interface_group_return_from_get_remote_pending_members (
          context, ret);
      g_array_free (ret, TRUE);
    }
  else
    {
      dbus_g_method_return_error (context, error);
      g_error_free (error);
    }
}

/**
 * tp_group_mixin_get_all_members:
 * @obj: An object implementing the group interface using this mixin
 * @members: Used to return a newly-allocated GArray of guint representing
 * the handles of the group's members
 * @local_pending: Used to return a newly-allocated GArray of guint
 * representing the handles of the group's local pending members
 * @remote_pending: Used to return a newly-allocated GArray of guint
 * representing the handles of the group's remote pending members
 * @error: Unused
 *
 * Get the group's current and pending members.
 *
 * Returns: %TRUE
 */
gboolean
tp_group_mixin_get_all_members (GObject *obj,
                                GArray **members,
                                GArray **local_pending,
                                GArray **remote_pending,
                                GError **error)
{
  TpGroupMixin *mixin = TP_GROUP_MIXIN (obj);

  *members = tp_handle_set_to_array (mixin->members);
  *local_pending = tp_handle_set_to_array (mixin->local_pending);
  *remote_pending = tp_handle_set_to_array (mixin->remote_pending);

  return TRUE;
}

static void
tp_group_mixin_get_all_members_async (TpSvcChannelInterfaceGroup *obj,
                                      DBusGMethodInvocation *context)
{
  GArray *mem, *local, *remote;
  GError *error = NULL;

  if (tp_group_mixin_get_all_members ((GObject *) obj, &mem, &local, &remote,
        &error))
    {
      tp_svc_channel_interface_group_return_from_get_all_members (
          context, mem, local, remote);
      g_array_free (mem, TRUE);
      g_array_free (local, TRUE);
      g_array_free (remote, TRUE);
    }
  else
    {
      dbus_g_method_return_error (context, error);
      g_error_free (error);
    }
}

/**
 * tp_group_mixin_get_handle_owners:
 * @obj: An object implementing the group interface with this mixin
 * @handles: An array of guint representing locally valid handles
 * @ret: Used to return an array of guint representing globally valid
 *  handles, or 0 where unavailable, if %TRUE is returned
 * @error: Used to return an error if %FALSE is returned
 *
 * If the mixin has the flag %TP_CHANNEL_GROUP_FLAG_CHANNEL_SPECIFIC_HANDLES,
 * return the global owners of the given local handles, or 0 where
 * unavailable.
 *
 * Returns: %TRUE (setting @ret) on success, %FALSE (setting @error) on
 * failure
 */
gboolean
tp_group_mixin_get_handle_owners (GObject *obj,
                                  const GArray *handles,
                                  GArray **ret,
                                  GError **error)
{
  TpGroupMixin *mixin = TP_GROUP_MIXIN (obj);
  TpGroupMixinPrivate *priv = mixin->priv;
  guint i;

  if ((mixin->group_flags &
        TP_CHANNEL_GROUP_FLAG_CHANNEL_SPECIFIC_HANDLES) == 0)
    {
      g_set_error (error, TP_ERRORS, TP_ERROR_NOT_AVAILABLE,
          "channel doesn't have channel specific handles");

      return FALSE;
    }

  if (!tp_handles_are_valid (mixin->handle_repo, handles, FALSE, error))
    {
      return FALSE;
    }

  *ret = g_array_sized_new (FALSE, FALSE, sizeof (TpHandle), handles->len);

  for (i = 0; i < handles->len; i++)
    {
      TpHandle local_handle = g_array_index (handles, TpHandle, i);
      TpHandle owner_handle;

      if (!tp_handle_set_is_member (mixin->members, local_handle))
        {
          g_set_error (error, TP_ERRORS, TP_ERROR_INVALID_ARGUMENT,
              "handle %u is not a member", local_handle);

          g_array_free (*ret, TRUE);
          *ret = NULL;

          return FALSE;
        }

      owner_handle = GPOINTER_TO_UINT (
          g_hash_table_lookup (priv->handle_owners,
                               GUINT_TO_POINTER (local_handle)));

      g_array_append_val (*ret, owner_handle);
    }

  return TRUE;
}

static void
tp_group_mixin_get_handle_owners_async (TpSvcChannelInterfaceGroup *obj,
                                        const GArray *handles,
                                        DBusGMethodInvocation *context)
{
  GArray *ret;
  GError *error = NULL;

  if (tp_group_mixin_get_handle_owners ((GObject *) obj, handles,
        &ret, &error))
    {
      tp_svc_channel_interface_group_return_from_get_handle_owners (
          context, ret);
      g_array_free (ret, TRUE);
    }
  else
    {
      dbus_g_method_return_error (context, error);
      g_error_free (error);
    }
}

#define GFTS_APPEND_FLAG_IF_SET(flag) \
  if (flags & flag) \
    { \
      if (i++ > 0) \
        g_string_append (str, "|"); \
      g_string_append (str, #flag + 22); \
      flags &= ~flag; \
    }

static gchar *
group_flags_to_string (TpChannelGroupFlags flags)
{
  gint i = 0;
  GString *str;

  str = g_string_new ("[" TP_ANSI_BOLD_OFF);

  GFTS_APPEND_FLAG_IF_SET (TP_CHANNEL_GROUP_FLAG_CAN_ADD);
  GFTS_APPEND_FLAG_IF_SET (TP_CHANNEL_GROUP_FLAG_CAN_REMOVE);
  GFTS_APPEND_FLAG_IF_SET (TP_CHANNEL_GROUP_FLAG_CAN_RESCIND);
  GFTS_APPEND_FLAG_IF_SET (TP_CHANNEL_GROUP_FLAG_MESSAGE_ADD);
  GFTS_APPEND_FLAG_IF_SET (TP_CHANNEL_GROUP_FLAG_MESSAGE_REMOVE);
  GFTS_APPEND_FLAG_IF_SET (TP_CHANNEL_GROUP_FLAG_MESSAGE_ACCEPT);
  GFTS_APPEND_FLAG_IF_SET (TP_CHANNEL_GROUP_FLAG_MESSAGE_REJECT);
  GFTS_APPEND_FLAG_IF_SET (TP_CHANNEL_GROUP_FLAG_MESSAGE_RESCIND);
  GFTS_APPEND_FLAG_IF_SET (TP_CHANNEL_GROUP_FLAG_CHANNEL_SPECIFIC_HANDLES);
  GFTS_APPEND_FLAG_IF_SET (TP_CHANNEL_GROUP_FLAG_ONLY_ONE_GROUP);
  GFTS_APPEND_FLAG_IF_SET (TP_CHANNEL_GROUP_FLAG_HANDLE_OWNERS_NOT_AVAILABLE);
  GFTS_APPEND_FLAG_IF_SET (TP_CHANNEL_GROUP_FLAG_PROPERTIES);
  GFTS_APPEND_FLAG_IF_SET (TP_CHANNEL_GROUP_FLAG_MEMBERS_CHANGED_DETAILED);

  /* Print out any remaining flags that weren't removed in the above cases
   * numerically.
   */
  if (flags != 0)
    {
      if (i > 0)
        g_string_append (str, "|");

      g_string_append_printf (str, "%u", flags);
    }

  g_string_append (str, TP_ANSI_BOLD_ON "]");

  return g_string_free (str, FALSE);
}

/**
 * tp_group_mixin_change_flags:
 * @obj: An object implementing the groups interface using this mixin
 * @add: Flags to be added
 * @del: Flags to be removed
 *
 * Request a change to be made to the flags. If any flags were actually
 * set or cleared, emits the GroupFlagsChanged signal with the changes.
 *
 * It is an error to set any of the same bits in both @add and @del.
 *
 * Changed in 0.7.7: the signal is not emitted if adding @add and
 *  removing @del had no effect on the existing group flags.
 */
void
tp_group_mixin_change_flags (GObject *obj,
                             TpChannelGroupFlags add,
                             TpChannelGroupFlags del)
{
  TpGroupMixin *mixin = TP_GROUP_MIXIN (obj);
  TpChannelGroupFlags added, removed;

  /* It's meaningless to want to add and remove the same capability */
  g_return_if_fail ((add & del) == 0);

  added = add & ~mixin->group_flags;
  mixin->group_flags |= added;

  removed = del & mixin->group_flags;
  mixin->group_flags &= ~removed;

  if (added == 0 && removed == 0)
    {
      DEBUG ("No change: %u includes all the bits of %u and none of %u",
          mixin->group_flags, add, del);
    }
  else
    {
      gchar *str_added, *str_removed, *str_flags;

      if (DEBUGGING)
        {
          str_added = group_flags_to_string (added);
          str_removed = group_flags_to_string (removed);
          str_flags = group_flags_to_string (mixin->group_flags);

          printf (TP_ANSI_BOLD_ON TP_ANSI_FG_WHITE
                  "%s: emitting group flags changed\n"
                  "  added    : %s\n"
                  "  removed  : %s\n"
                  "  flags now: %s\n" TP_ANSI_RESET,
                  G_STRFUNC, str_added, str_removed, str_flags);

          fflush (stdout);

          g_free (str_added);
          g_free (str_removed);
          g_free (str_flags);
        }

      tp_svc_channel_interface_group_emit_group_flags_changed (obj, added,
          removed);
      if (mixin->priv->externals != NULL)
        {
          guint i;

          for (i = 0; i < mixin->priv->externals->len; i++)
            {
              tp_svc_channel_interface_group_emit_group_flags_changed
                ((GObject *) g_ptr_array_index (mixin->priv->externals, i),
                 added, removed);
            }
        }
    }
}

static gchar *
member_array_to_string (TpHandleRepoIface *repo,
                        const GArray *array)
{
  GString *str;
  guint i;

  str = g_string_new ("[" TP_ANSI_BOLD_OFF);

  for (i = 0; i < array->len; i++)
    {
      TpHandle handle;
      const gchar *handle_str;

      handle = g_array_index (array, guint, i);
      handle_str = tp_handle_inspect (repo, handle);

      g_string_append_printf (str, "%s%u (%s)",
      /* indent to:   "  remote_pending: [" */
          (i > 0) ? "\n                   "
                  : "",
          handle, handle_str);
    }

  g_string_append (str, TP_ANSI_BOLD_ON "]");

  return g_string_free (str, FALSE);
}

static GArray *remove_handle_owners_if_exist (GObject *obj,
    GArray *array) G_GNUC_WARN_UNUSED_RESULT;

typedef struct {
    TpGroupMixin *mixin;
    LocalPendingInfo *info;
} _mixin_and_info;

static void
local_pending_added_foreach (guint i,
                             gpointer userdata)
{
  _mixin_and_info *data = userdata;
  TpGroupMixinPrivate *priv = data->mixin->priv;

  g_hash_table_insert (priv->local_pending_info,
      GUINT_TO_POINTER (i),
      local_pending_info_new (data->mixin->handle_repo,
      data->info->actor, data->info->reason, data->info->message));
}

static void
local_pending_added (TpGroupMixin *mixin,
                    TpIntSet *added,
                    TpHandle actor,
                    guint reason,
                    const gchar *message)
{
  LocalPendingInfo info;
  _mixin_and_info data = { mixin, &info };
  info.actor = actor;
  info.reason = reason;
  info.message = message;

  tp_intset_foreach (added, local_pending_added_foreach, &data);
}

static void
local_pending_remove_foreach (guint i,
                             gpointer userdata)
{
  TpGroupMixin *mixin = (TpGroupMixin *) userdata;
  TpGroupMixinPrivate *priv = mixin->priv;

  g_hash_table_remove (priv->local_pending_info, GUINT_TO_POINTER(i));
}

static void
local_pending_remove (TpGroupMixin *mixin,
                     TpIntSet *removed)
{
  tp_intset_foreach (removed, local_pending_remove_foreach, mixin);
}


static void
add_members_in_array (GHashTable *member_ids,
                      TpHandleRepoIface *repo,
                      const GArray *handles)
{
  guint i;

  for (i = 0; i < handles->len; i++)
    {
      TpHandle handle = g_array_index (handles, TpHandle, i);
      const gchar *id = tp_handle_inspect (repo, handle);

      g_hash_table_insert (member_ids, GUINT_TO_POINTER (handle), (gchar *) id);
    }
}


static gboolean
maybe_add_member_ids (TpGroupMixin *mixin,
                      const GArray *add,
                      const GArray *local_pending,
                      const GArray *remote_pending,
                      TpHandle actor,
                      GHashTable *details)
{
  GHashTable *member_ids;

  /* If the library user had its own ideas about which members' IDs to include
   * in the change details, we'll leave that intact.
   */
  if (tp_asv_lookup (details, "member-ids") != NULL)
    return FALSE;

  /* The library user didn't include the new members' IDs in details; let's add
   * the IDs of the handles being added to the group (but not removed, as per
   * the spec) and of the actor.
   */
  member_ids = g_hash_table_new (NULL, NULL);

  add_members_in_array (member_ids, mixin->handle_repo, add);
  add_members_in_array (member_ids, mixin->handle_repo, local_pending);
  add_members_in_array (member_ids, mixin->handle_repo, remote_pending);

  if (actor != 0)
    {
      const gchar *id = tp_handle_inspect (mixin->handle_repo, actor);

      g_hash_table_insert (member_ids, GUINT_TO_POINTER (actor), (gchar *) id);
    }

  g_hash_table_insert (details, "member-ids",
      tp_g_value_slice_new_take_boxed (TP_HASH_TYPE_HANDLE_IDENTIFIER_MAP,
          member_ids));

  return TRUE;
}


static void
remove_member_ids (GHashTable *details)
{
  GValue *member_ids_v = g_hash_table_lookup (details, "member-ids");

  g_assert (member_ids_v != NULL);
  g_hash_table_steal (details, "member-ids");

  tp_g_value_slice_free (member_ids_v);
}


static void
emit_members_changed_signals (GObject *channel,
                              const gchar *message,
                              const GArray *add,
                              const GArray *del,
                              const GArray *local_pending,
                              const GArray *remote_pending,
                              TpHandle actor,
                              TpChannelGroupChangeReason reason,
                              const GHashTable *details)
{
  TpGroupMixin *mixin = TP_GROUP_MIXIN (channel);
  GHashTable *details_ = (GHashTable *) details; /* Cast the pain away! */
  gboolean added_member_ids;

  if (DEBUGGING)
    {
      gchar *add_str, *rem_str, *local_str, *remote_str;

      add_str = member_array_to_string (mixin->handle_repo, add);
      rem_str = member_array_to_string (mixin->handle_repo, del);
      local_str = member_array_to_string (mixin->handle_repo, local_pending);
      remote_str = member_array_to_string (mixin->handle_repo, remote_pending);

      printf (TP_ANSI_BOLD_ON TP_ANSI_FG_CYAN
              "%s: emitting members changed\n"
              "  message       : \"%s\"\n"
              "  added         : %s\n"
              "  removed       : %s\n"
              "  local_pending : %s\n"
              "  remote_pending: %s\n"
              "  actor         : %u\n"
              "  reason        : %u: %s\n" TP_ANSI_RESET,
              G_STRFUNC, message, add_str, rem_str, local_str, remote_str,
              actor, reason, group_change_reason_str (reason));

      fflush (stdout);

      g_free (add_str);
      g_free (rem_str);
      g_free (local_str);
      g_free (remote_str);
    }

  added_member_ids = maybe_add_member_ids (mixin, add, local_pending,
      remote_pending, actor, details_);

  tp_svc_channel_interface_group_emit_members_changed (channel, message,
      add, del, local_pending, remote_pending, actor, reason);
  tp_svc_channel_interface_group_emit_members_changed_detailed (channel,
      add, del, local_pending, remote_pending, details_);

  if (mixin->priv->externals != NULL)
    {
      guint i;

      for (i = 0; i < mixin->priv->externals->len; i++)
        {
          GObject *external = g_ptr_array_index (mixin->priv->externals, i);

          tp_svc_channel_interface_group_emit_members_changed (external,
              message, add, del, local_pending, remote_pending, actor, reason);
          tp_svc_channel_interface_group_emit_members_changed_detailed (
              external, add, del, local_pending, remote_pending, details_);
        }
    }

  if (added_member_ids)
    remove_member_ids (details_);
}


static gboolean
change_members (GObject *obj,
                const gchar *message,
                TpIntSet *add,
                TpIntSet *del,
                TpIntSet *add_local_pending,
                TpIntSet *add_remote_pending,
                TpHandle actor,
                TpChannelGroupChangeReason reason,
                const GHashTable *details)
{
  TpGroupMixin *mixin = TP_GROUP_MIXIN (obj);
  TpIntSet *new_add, *new_remove, *new_local_pending,
           *new_remote_pending, *tmp, *tmp2, *empty;
  gboolean ret;

  empty = tp_intset_new ();

  if (message == NULL)
    message = "";

  if (add == NULL)
    add = empty;

  if (del == NULL)
    del = empty;

  if (add_local_pending == NULL)
    add_local_pending = empty;

  if (add_remote_pending == NULL)
    add_remote_pending = empty;

  /* remember the actor handle before any handle unreffing happens */
  if (actor)
    {
      tp_handle_set_add (mixin->priv->actors, actor);
    }

  /* members + add */
  new_add = tp_handle_set_update (mixin->members, add);

  /* members - del */
  new_remove = tp_handle_set_difference_update (mixin->members, del);

  /* members - add_local_pending */
  tmp = tp_handle_set_difference_update (mixin->members, add_local_pending);
  tp_intset_destroy (tmp);

  /* members - add_remote_pending */
  tmp = tp_handle_set_difference_update (mixin->members, add_remote_pending);
  tp_intset_destroy (tmp);


  /* local pending + add_local_pending */
  new_local_pending = tp_handle_set_update (mixin->local_pending,
      add_local_pending);
  local_pending_added (mixin, add_local_pending, actor, reason, message);

  /* local pending - add */
  tmp = tp_handle_set_difference_update (mixin->local_pending, add);
  local_pending_remove (mixin, tmp);
  tp_intset_destroy (tmp);

  /* local pending - del */
  tmp = tp_handle_set_difference_update (mixin->local_pending, del);
  local_pending_remove (mixin, tmp);

  tmp2 = tp_intset_union (new_remove, tmp);
  tp_intset_destroy (new_remove);
  tp_intset_destroy (tmp);
  new_remove = tmp2;

  /* local pending - add_remote_pending */
  tmp = tp_handle_set_difference_update (mixin->local_pending,
      add_remote_pending);
  local_pending_remove (mixin, tmp);
  tp_intset_destroy (tmp);


  /* remote pending + add_remote_pending */
  new_remote_pending = tp_handle_set_update (mixin->remote_pending,
      add_remote_pending);

  /* remote pending - add */
  tmp = tp_handle_set_difference_update (mixin->remote_pending, add);
  tp_intset_destroy (tmp);

  /* remote pending - del */
  tmp = tp_handle_set_difference_update (mixin->remote_pending, del);
  tmp2 = tp_intset_union (new_remove, tmp);
  tp_intset_destroy (new_remove);
  tp_intset_destroy (tmp);
  new_remove = tmp2;

  /* remote pending - local_pending */
  tmp = tp_handle_set_difference_update (mixin->remote_pending,
      add_local_pending);
  tp_intset_destroy (tmp);

  if (tp_intset_size (new_add) > 0 ||
      tp_intset_size (new_remove) > 0 ||
      tp_intset_size (new_local_pending) > 0 ||
      tp_intset_size (new_remote_pending) > 0)
    {
      GArray *arr_add, *arr_remove, *arr_local, *arr_remote;
      GArray *arr_owners_removed;

      /* translate intsets to arrays */
      arr_add = tp_intset_to_array (new_add);
      arr_remove = tp_intset_to_array (new_remove);
      arr_local = tp_intset_to_array (new_local_pending);
      arr_remote = tp_intset_to_array (new_remote_pending);

      /* remove any handle owner mappings */
      arr_owners_removed = remove_handle_owners_if_exist (obj, arr_remove);

      /* emit signals */
      emit_members_changed_signals (obj, message, arr_add, arr_remove,
          arr_local, arr_remote, actor, reason, details);

      if (arr_owners_removed->len > 0)
        {
          GHashTable *empty_hash_table = g_hash_table_new (NULL, NULL);

          tp_svc_channel_interface_group_emit_handle_owners_changed (obj,
              empty_hash_table, arr_owners_removed);

          if (mixin->priv->externals != NULL)
            {
              guint i;

              for (i = 0; i < mixin->priv->externals->len; i++)
                {
                  tp_svc_channel_interface_group_emit_handle_owners_changed (
                      g_ptr_array_index (mixin->priv->externals, i),
                      empty_hash_table, arr_owners_removed);
                }
            }

          tp_handles_unref (mixin->handle_repo, arr_owners_removed);

          g_hash_table_destroy (empty_hash_table);
        }

      /* free arrays */
      g_array_free (arr_add, TRUE);
      g_array_free (arr_remove, TRUE);
      g_array_free (arr_local, TRUE);
      g_array_free (arr_remote, TRUE);
      g_array_free (arr_owners_removed, TRUE);

      ret = TRUE;
    }
  else
    {
      DEBUG ("not emitting signal, nothing changed");

      ret = FALSE;
    }

  /* free intsets */
  tp_intset_destroy (new_add);
  tp_intset_destroy (new_remove);
  tp_intset_destroy (new_local_pending);
  tp_intset_destroy (new_remote_pending);
  tp_intset_destroy (empty);

  return ret;
}


/**
 * tp_group_mixin_change_members:
 * @obj: An object implementing the group interface using this mixin
 * @message: A message to be sent to the affected contacts if possible;
 *  %NULL is allowed, and is mapped to an empty string
 * @add: A set of contact handles to be added to the members (if not
 *  already present) and removed from local pending and remote pending
 *  (if present)
 * @del: A set of contact handles to be removed from members,
 *  local pending or remote pending, wherever they are present
 * @add_local_pending: A set of contact handles to be added to local pending,
 *  and removed from members and remote pending
 * @add_remote_pending: A set of contact handles to be added to remote pending,
 *  and removed from members and local pending
 * @actor: The handle of the contact responsible for this change
 * @reason: The reason for this change
 *
 * Change the sets of members as given by the arguments, and emit the
 * MembersChanged and MembersChangedDetailed signals if the changes were not a
 * no-op.
 *
 * This function must be called in response to events on the underlying
 * IM protocol, and must not be called in direct response to user input;
 * it does not respect the permissions flags, but changes the group directly.
 *
 * If any two of add, del, add_local_pending and add_remote_pending have
 * a non-empty intersection, the result is undefined. Don't do that.
 *
 * Each of the TpIntSet arguments may be %NULL, which is treated as
 * equivalent to an empty set.
 *
 * Returns: %TRUE if the group was changed and the MembersChanged(Detailed)
 *  signals were emitted; %FALSE if nothing actually changed and the signals
 *  were suppressed.
 */
gboolean
tp_group_mixin_change_members (GObject *obj,
                               const gchar *message,
                               TpIntSet *add,
                               TpIntSet *del,
                               TpIntSet *add_local_pending,
                               TpIntSet *add_remote_pending,
                               TpHandle actor,
                               TpChannelGroupChangeReason reason)
{
  GHashTable *details = g_hash_table_new_full (g_str_hash, g_str_equal,
      NULL, (GDestroyNotify) tp_g_value_slice_free);
  gboolean ret;

  if (actor != 0)
    {
      g_hash_table_insert (details, "actor",
          tp_g_value_slice_new_uint (actor));
    }

  if (reason != TP_CHANNEL_GROUP_CHANGE_REASON_NONE)
    {
      g_hash_table_insert (details, "change-reason",
          tp_g_value_slice_new_uint (reason));
    }

  if (message != NULL && message[0] != '\0')
    {
      g_hash_table_insert (details, "message",
          tp_g_value_slice_new_string (message));
    }

  ret = change_members (obj, message, add, del, add_local_pending,
      add_remote_pending, actor, reason, details);

  g_hash_table_destroy (details);
  return ret;
}

/**
 * tp_group_mixin_change_members_detailed:
 * @obj: An object implementing the group interface using this mixin
 * @add: A set of contact handles to be added to the members (if not
 *  already present) and removed from local pending and remote pending
 *  (if present)
 * @del: A set of contact handles to be removed from members,
 *  local pending or remote pending, wherever they are present
 * @add_local_pending: A set of contact handles to be added to local pending,
 *  and removed from members and remote pending
 * @add_remote_pending: A set of contact handles to be added to remote pending,
 *  and removed from members and local pending
 * @details: a map from strings to GValues detailing the change
 *
 * Change the sets of members as given by the arguments, and emit the
 * MembersChanged and MembersChangedDetailed signals if the changes were not a
 * no-op.
 *
 * This function must be called in response to events on the underlying
 * IM protocol, and must not be called in direct response to user input;
 * it does not respect the permissions flags, but changes the group directly.
 *
 * If any two of add, del, add_local_pending and add_remote_pending have
 * a non-empty intersection, the result is undefined. Don't do that.
 *
 * Each of the TpIntSet arguments may be %NULL, which is treated as
 * equivalent to an empty set.
 *
 * details may contain, among other entries, the well-known
 * keys (and corresponding type, wrapped in a GValue) defined by the
 * Group.MembersChangedDetailed signal's specification; these include "actor"
 * (a handle as G_TYPE_UINT), "change-reason" (an element of
 * #TpChannelGroupChangeReason as G_TYPE_UINT), "message" (G_TYPE_STRING),
 * "error" (G_TYPE_STRING), "debug-message" (G_TYPE_STRING).
 *
 * If all of the information in details could be passed to
 * tp_group_mixin_change_members() then calling this function instead provides
 * no benefit. Calling this function without setting
 * #TP_CHANNEL_GROUP_FLAG_MEMBERS_CHANGED_DETAILED with
 * tp_group_mixin_change_members() first is not very useful, as clients will
 * not know to listen for MembersChangedDetailed and thus will miss the
 * details.
 *
 * Returns: %TRUE if the group was changed and the MembersChanged(Detailed)
 *  signals were emitted; %FALSE if nothing actually changed and the signals
 *  were suppressed.
 *
 * @since 0.7.21
 */
gboolean
tp_group_mixin_change_members_detailed (GObject *obj,
                                        TpIntSet *add,
                                        TpIntSet *del,
                                        TpIntSet *add_local_pending,
                                        TpIntSet *add_remote_pending,
                                        const GHashTable *details)
{
  const gchar *message;
  TpHandle actor;
  TpChannelGroupChangeReason reason;
  gboolean valid;

  g_return_val_if_fail (details != NULL, FALSE);

  /* For each detail we're extracting for the benefit of old-school
   * MembersChanged, warn if it's present but badly typed.
   */

  message = tp_asv_get_string (details, "message");
  g_warn_if_fail (message != NULL || tp_asv_lookup (details, "message") == NULL);

  /* change_members will cry (via tp_handle_set_add) if actor is non-zero and
   * invalid.
   */
  actor = tp_asv_get_uint32 (details, "actor", &valid);
  g_warn_if_fail (valid || tp_asv_lookup (details, "actor") == NULL);

  reason = tp_asv_get_uint32 (details, "change-reason", &valid);
  g_warn_if_fail (valid || tp_asv_lookup (details, "change-reason") == NULL);

  return change_members (obj, message, add, del, add_local_pending,
      add_remote_pending, actor, reason, details);
}

/**
 * tp_group_mixin_add_handle_owner:
 * @obj: A GObject implementing the group interface with this mixin
 * @local_handle: A contact handle valid within this group (may not be 0)
 * @owner_handle: A contact handle valid globally, or 0 if the owner of the
 *  @local_handle is unknown
 *
 * Note that the given local handle is an alias within this group
 * for the given globally-valid handle. It will be returned from subsequent
 * GetHandleOwner queries where appropriate.
 *
 * Changed in 0.7.10: The @owner_handle may be 0. To comply with telepathy-spec
 *  0.17.6, before adding any channel-specific handle to the members,
 *  local-pending members or remote-pending members, you must call either
 *  this function or tp_group_mixin_add_handle_owners().
 */
void
tp_group_mixin_add_handle_owner (GObject *obj,
                                 TpHandle local_handle,
                                 TpHandle owner_handle)
{
  GHashTable *tmp;

  g_return_if_fail (local_handle != 0);

  tmp = g_hash_table_new (g_direct_hash, g_direct_equal);
  g_hash_table_insert (tmp, GUINT_TO_POINTER (local_handle),
      GUINT_TO_POINTER (owner_handle));

  tp_group_mixin_add_handle_owners (obj, tmp);

  g_hash_table_destroy (tmp);
}


static void
add_handle_owners_helper (gpointer key,
                          gpointer value,
                          gpointer user_data)
{
  TpHandle local_handle = GPOINTER_TO_UINT (key);
  TpHandle owner_handle = GPOINTER_TO_UINT (value);
  TpGroupMixin *mixin = user_data;
  gpointer orig_key, orig_value;

  g_return_if_fail (local_handle != 0);

  tp_handle_ref (mixin->handle_repo, local_handle);

  if (owner_handle != 0)
    tp_handle_ref (mixin->handle_repo, owner_handle);

  if (g_hash_table_lookup_extended (mixin->priv->handle_owners, key,
        &orig_key, &orig_value))
    {
      /* no need to actually remove - we're about to overwrite them anyway */

      tp_handle_unref (mixin->handle_repo, local_handle);

      if (GPOINTER_TO_UINT (orig_value) != 0)
        tp_handle_unref (mixin->handle_repo, GPOINTER_TO_UINT (orig_value));
    }

  g_hash_table_insert (mixin->priv->handle_owners, key, value);
}


/**
 * tp_group_mixin_add_handle_owners:
 * @obj: A GObject implementing the group interface with this mixin
 * @local_to_owner_handle: A map from contact handles valid within this group
 *  (which may not be 0) to either contact handles valid globally, or 0 if the
 *  owner of the corresponding key is unknown; all handles are stored using
 *  GUINT_TO_POINTER
 *
 * Note that the given local handles are aliases within this group
 * for the given globally-valid handles.
 *
 * To comply with telepathy-spec 0.17.6, before adding any channel-specific
 * handle to the members, local-pending members or remote-pending members, you
 * must call either this function or tp_group_mixin_add_handle_owner().
 *
 * @since 0.7.10
 */
void
tp_group_mixin_add_handle_owners (GObject *obj,
                                  GHashTable *local_to_owner_handle)
{
  TpGroupMixin *mixin = TP_GROUP_MIXIN (obj);
  GArray *empty_array;

  if (g_hash_table_size (local_to_owner_handle) == 0)
    return;

  empty_array = g_array_sized_new (FALSE, FALSE, sizeof (guint), 0);

  g_hash_table_foreach (local_to_owner_handle, add_handle_owners_helper,
      mixin);

  tp_svc_channel_interface_group_emit_handle_owners_changed (obj,
      local_to_owner_handle, empty_array);

  g_array_free (empty_array, TRUE);
}


static GArray *
remove_handle_owners_if_exist (GObject *obj,
                               GArray *array)
{
  TpGroupMixin *mixin = TP_GROUP_MIXIN (obj);
  TpGroupMixinPrivate *priv = mixin->priv;
  guint i;
  GArray *ret;

  ret = g_array_sized_new (FALSE, FALSE, sizeof (guint), array->len);

  for (i = 0; i < array->len; i++)
    {
      TpHandle handle = g_array_index (array, guint, i);
      gpointer local_handle, owner_handle;

      g_assert (handle != 0);

      if (g_hash_table_lookup_extended (priv->handle_owners,
                                        GUINT_TO_POINTER (handle),
                                        &local_handle,
                                        &owner_handle))
        {
          g_assert (GPOINTER_TO_UINT (local_handle) == handle);
          g_array_append_val (ret, handle);
          /* don't unref local_handle - ownership is transferred to ret */

          if (GPOINTER_TO_UINT (owner_handle) != 0)
            tp_handle_unref (mixin->handle_repo,
                GPOINTER_TO_UINT (owner_handle));

          g_hash_table_remove (priv->handle_owners, GUINT_TO_POINTER (handle));
        }
    }

  return ret;
}

/**
 * tp_group_mixin_iface_init:
 * @g_iface: A #TpSvcChannelInterfaceGroupClass
 * @iface_data: Unused
 *
 * Fill in the vtable entries needed to implement the group interface using
 * this mixin. This function should usually be called via
 * G_IMPLEMENT_INTERFACE.
 */
void
tp_group_mixin_iface_init (gpointer g_iface, gpointer iface_data)
{
  TpSvcChannelInterfaceGroupClass *klass = g_iface;

#define IMPLEMENT(x) tp_svc_channel_interface_group_implement_##x (klass,\
    tp_group_mixin_##x##_async)
  IMPLEMENT(add_members);
  IMPLEMENT(get_all_members);
  IMPLEMENT(get_group_flags);
  IMPLEMENT(get_handle_owners);
  IMPLEMENT(get_local_pending_members);
  IMPLEMENT(get_local_pending_members_with_info);
  IMPLEMENT(get_members);
  IMPLEMENT(get_remote_pending_members);
  IMPLEMENT(get_self_handle);
  IMPLEMENT(remove_members);
  IMPLEMENT(remove_members_with_reason);
#undef IMPLEMENT
}


enum {
    MIXIN_DP_GROUP_FLAGS,
    MIXIN_DP_HANDLE_OWNERS,
    MIXIN_DP_LOCAL_PENDING_MEMBERS,
    MIXIN_DP_MEMBERS,
    MIXIN_DP_REMOTE_PENDING_MEMBERS,
    MIXIN_DP_SELF_HANDLE,
    NUM_MIXIN_DBUS_PROPERTIES
};


/**
 * tp_group_mixin_get_dbus_property:
 * @object: An object with this mixin
 * @interface: Must be %TP_IFACE_QUARK_CHANNEL_INTERFACE_GROUP
 * @name: A quark representing the D-Bus property name, either
 *  "GroupFlags", "HandleOwners", "LocalPendingMembers", "Members",
 *  "RemotePendingMembers" or "SelfHandle"
 * @value: A GValue pre-initialized to the right type, into which to put the
 *  value
 * @unused: Ignored
 *
 * An implementation of #TpDBusPropertiesMixinGetter which assumes that the
 * @object has the group mixin. It can only be used for the Group interface.
 *
 * Since: 0.7.10
 */
void
tp_group_mixin_get_dbus_property (GObject *object,
                                  GQuark interface,
                                  GQuark name,
                                  GValue *value,
                                  gpointer unused G_GNUC_UNUSED)
{
  TpGroupMixin *mixin;
  static GQuark q[NUM_MIXIN_DBUS_PROPERTIES] = { 0 };

  if (G_UNLIKELY (q[0] == 0))
    {
      q[MIXIN_DP_GROUP_FLAGS] = g_quark_from_static_string ("GroupFlags");
      q[MIXIN_DP_HANDLE_OWNERS] = g_quark_from_static_string ("HandleOwners");
      q[MIXIN_DP_LOCAL_PENDING_MEMBERS] = g_quark_from_static_string (
          "LocalPendingMembers");
      q[MIXIN_DP_MEMBERS] = g_quark_from_static_string ("Members");
      q[MIXIN_DP_REMOTE_PENDING_MEMBERS] = g_quark_from_static_string (
          "RemotePendingMembers");
      q[MIXIN_DP_SELF_HANDLE] = g_quark_from_static_string ("SelfHandle");
    }

  g_return_if_fail (object != NULL);
  mixin = TP_GROUP_MIXIN (object);
  g_return_if_fail (mixin != NULL);
  g_return_if_fail (interface == TP_IFACE_QUARK_CHANNEL_INTERFACE_GROUP);
  g_return_if_fail (name != 0);
  g_return_if_fail (value != NULL);

  if (name == q[MIXIN_DP_GROUP_FLAGS])
    {
      g_return_if_fail (G_VALUE_HOLDS_UINT (value));
      g_value_set_uint (value, mixin->group_flags);
    }
  else if (name == q[MIXIN_DP_HANDLE_OWNERS])
    {
      g_return_if_fail (G_VALUE_HOLDS (value, TP_HASH_TYPE_HANDLE_OWNER_MAP));
      g_value_set_boxed (value, mixin->priv->handle_owners);
    }
  else if (name == q[MIXIN_DP_LOCAL_PENDING_MEMBERS])
    {
      GPtrArray *ret = NULL;
      gboolean success;

      g_return_if_fail (G_VALUE_HOLDS_BOXED (value));
      success = tp_group_mixin_get_local_pending_members_with_info (object,
          &ret, NULL);
      g_assert (success);     /* as of 0.7.8, cannot fail */
      g_value_take_boxed (value, ret);
    }
  else if (name == q[MIXIN_DP_MEMBERS])
    {
      GArray *ret = NULL;
      gboolean success;

      g_return_if_fail (G_VALUE_HOLDS_BOXED (value));
      success = tp_group_mixin_get_members (object, &ret, NULL);
      g_assert (success);     /* as of 0.7.8, cannot fail */
      g_value_take_boxed (value, ret);
    }
  else if (name == q[MIXIN_DP_REMOTE_PENDING_MEMBERS])
    {
      GArray *ret = NULL;
      gboolean success;

      g_return_if_fail (G_VALUE_HOLDS_BOXED (value));
      success = tp_group_mixin_get_remote_pending_members (object,
          &ret, NULL);
      g_assert (success);     /* as of 0.7.8, cannot fail */
      g_value_take_boxed (value, ret);
    }
  else if (name == q[MIXIN_DP_SELF_HANDLE])
    {
      g_return_if_fail (G_VALUE_HOLDS_UINT (value));
      g_value_set_uint (value, mixin->self_handle);
    }
  else
    {
      g_return_if_reached ();
    }
}

static TpDBusPropertiesMixinPropImpl known_group_props[] = {
    { "GroupFlags", NULL, NULL },
    { "HandleOwners", NULL, NULL },
    { "LocalPendingMembers", NULL, NULL },
    { "Members", NULL, NULL },
    { "RemotePendingMembers", NULL, NULL },
    { "SelfHandle", NULL, NULL },
    { NULL }
};

/**
 * tp_group_mixin_init_dbus_properties:
 * @cls: The class of an object with this mixin
 *
 * Set up #TpDBusPropertiesMixinClass to use this mixin's implementation of
 * the Group interface's properties.
 *
 * This uses tp_group_mixin_get_dbus_property() as the property getter and
 * sets up a list of the supported properties for it.  Having called this, you
 * should add #TP_CHANNEL_GROUP_FLAG_PROPERTIES to any channels of this class
 * with tp_group_mixin_change_flags() to indicate that the DBus properties are
 * available.
 *
 * Since: 0.7.10
 */
void
tp_group_mixin_init_dbus_properties (GObjectClass *cls)
{

  tp_dbus_properties_mixin_implement_interface (cls,
      TP_IFACE_QUARK_CHANNEL_INTERFACE_GROUP, tp_group_mixin_get_dbus_property,
      NULL, known_group_props);
}


#define TP_EXTERNAL_GROUP_MIXIN_OBJ(o) \
    ((GObject *) g_object_get_qdata (o, \
      _external_group_mixin_get_obj_quark ()))

static GQuark
_external_group_mixin_get_obj_quark (void)
{
  static GQuark quark = 0;
  if (!quark)
    quark = g_quark_from_static_string
        ("TpExternalGroupMixinQuark");
  return quark;
}

/**
 * tp_external_group_mixin_init:
 * @obj: An object implementing the groups interface using an external group
 *    mixin
 * @obj_with_mixin: A GObject with the group mixin
 *
 * Fill in the qdata needed to implement the group interface using
 * the group mixin of another object. This function should usually be called
 * in the instance constructor.
 *
 * Since: 0.5.13
 */
void
tp_external_group_mixin_init (GObject *obj, GObject *obj_with_mixin)
{
  g_object_ref (obj_with_mixin);
  g_object_set_qdata (obj, _external_group_mixin_get_obj_quark (),
      obj_with_mixin);
  tp_group_mixin_add_external (obj_with_mixin, obj);
}

/**
 * tp_external_group_mixin_finalize:
 * @obj: An object implementing the groups interface using an external group
 *    mixin
 *
 * Remove the external group mixin. This function should usually be called
 * in the dispose or finalize function.
 *
 * Since: 0.5.13
 */
void
tp_external_group_mixin_finalize (GObject *obj)
{
  GObject *obj_with_mixin = g_object_steal_qdata (obj,
      _external_group_mixin_get_obj_quark ());

  tp_group_mixin_remove_external (obj_with_mixin, obj);
  g_object_unref (obj_with_mixin);
}

/**
 * tp_external_group_mixin_init_dbus_properties:
 * @cls: The class of an object with this mixin
 *
 * Set up #TpDBusPropertiesMixinClass to use this mixin's implementation of
 * the Group interface's properties.
 *
 * This uses tp_group_mixin_get_dbus_property() as the property getter and
 * sets up a list of the supported properties for it.  Having called this, you
 * should add #TP_CHANNEL_GROUP_FLAG_PROPERTIES to channels containing the
 * mixin used by this class with tp_group_mixin_change_flags() to indicate that
 * the DBus properties are available.
 *
 * Since: 0.7.10
 */
void
tp_external_group_mixin_init_dbus_properties (GObjectClass *cls)
{

  tp_dbus_properties_mixin_implement_interface (cls,
      TP_IFACE_QUARK_CHANNEL_INTERFACE_GROUP,
      tp_external_group_mixin_get_dbus_property,
      NULL, known_group_props);
}

/**
 * tp_external_group_mixin_get_dbus_property:
 * @object: An object with this mixin
 * @interface: Must be %TP_IFACE_QUARK_CHANNEL_INTERFACE_GROUP
 * @name: A quark representing the D-Bus property name, either
 *  "GroupFlags", "HandleOwners", "LocalPendingMembers", "Members",
 *  "RemotePendingMembers" or "SelfHandle"
 * @value: A GValue pre-initialized to the right type, into which to put the
 *  value
 * @unused: Ignored
 *
 * An implementation of #TpDBusPropertiesMixinGetter which assumes that the
 * @object has the external group mixin. It can only be used for the Group
 * interface.
 *
 * Since: 0.7.10
 */
void
tp_external_group_mixin_get_dbus_property (GObject *object,
                                           GQuark interface,
                                           GQuark name,
                                           GValue *value,
                                           gpointer unused G_GNUC_UNUSED)
{
  GObject *group = TP_EXTERNAL_GROUP_MIXIN_OBJ (object);

  if (group != NULL)
    {
      tp_group_mixin_get_dbus_property (group, interface, name, value, NULL);
    }
  else if (G_VALUE_HOLDS_BOXED (value))
    {
      /* for certain boxed types we need to supply an empty value */

      if (G_VALUE_HOLDS (value, TP_HASH_TYPE_HANDLE_OWNER_MAP))
        g_value_take_boxed (value, g_hash_table_new (NULL, NULL));
      else if (G_VALUE_HOLDS (value, DBUS_TYPE_G_UINT_ARRAY))
        g_value_take_boxed (value, g_array_sized_new (FALSE, FALSE,
              sizeof (guint), 0));
      else if (G_VALUE_HOLDS (value, TP_ARRAY_TYPE_LOCAL_PENDING_INFO_LIST))
        g_value_take_boxed (value, g_ptr_array_sized_new (0));
    }
}

#define EXTERNAL_OR_DIE(var) \
    GObject *var = TP_EXTERNAL_GROUP_MIXIN_OBJ ((GObject *) obj); \
    \
    if (var == NULL) \
      { \
        GError na = { TP_ERRORS, TP_ERROR_NOT_AVAILABLE, "I'm sure I " \
                      "had a group object around here somewhere?" };\
        \
        dbus_g_method_return_error (context, &na); \
        return; \
      } \

static void
tp_external_group_mixin_add_members_async (TpSvcChannelInterfaceGroup *obj,
                                           const GArray *contacts,
                                           const gchar *message,
                                           DBusGMethodInvocation *context)
{
  EXTERNAL_OR_DIE (group)
  tp_group_mixin_add_members_async ((TpSvcChannelInterfaceGroup *) group,
      contacts, message, context);
}

static void
tp_external_group_mixin_get_self_handle_async (TpSvcChannelInterfaceGroup *obj,
                                               DBusGMethodInvocation *context)
{
  EXTERNAL_OR_DIE (group)
  tp_group_mixin_get_self_handle_async ((TpSvcChannelInterfaceGroup *) group,
      context);
}

static void
tp_external_group_mixin_get_group_flags_async (TpSvcChannelInterfaceGroup *obj,
                                               DBusGMethodInvocation *context)
{
  EXTERNAL_OR_DIE (group)
  tp_group_mixin_get_group_flags_async ((TpSvcChannelInterfaceGroup *) group,
      context);
}

static void
tp_external_group_mixin_get_members_async (TpSvcChannelInterfaceGroup *obj,
                                               DBusGMethodInvocation *context)
{
  EXTERNAL_OR_DIE (group)
  tp_group_mixin_get_members_async ((TpSvcChannelInterfaceGroup *) group,
      context);
}

static void
tp_external_group_mixin_get_local_pending_members_async
    (TpSvcChannelInterfaceGroup *obj, DBusGMethodInvocation *context)
{
  EXTERNAL_OR_DIE (group)
  tp_group_mixin_get_local_pending_members_async
      ((TpSvcChannelInterfaceGroup *) group, context);
}

static void
tp_external_group_mixin_get_local_pending_members_with_info_async
    (TpSvcChannelInterfaceGroup *obj, DBusGMethodInvocation *context)
{
  EXTERNAL_OR_DIE (group)
  tp_group_mixin_get_local_pending_members_with_info_async
      ((TpSvcChannelInterfaceGroup *) group, context);
}

static void
tp_external_group_mixin_get_remote_pending_members_async
    (TpSvcChannelInterfaceGroup *obj, DBusGMethodInvocation *context)
{
  EXTERNAL_OR_DIE (group)
  tp_group_mixin_get_remote_pending_members_async
      ((TpSvcChannelInterfaceGroup *) group, context);
}

static void
tp_external_group_mixin_get_all_members_async (TpSvcChannelInterfaceGroup *obj,
                                               DBusGMethodInvocation *context)
{
  EXTERNAL_OR_DIE (group)
  tp_group_mixin_get_all_members_async ((TpSvcChannelInterfaceGroup *) group,
      context);
}

static void
tp_external_group_mixin_get_handle_owners_async
    (TpSvcChannelInterfaceGroup *obj,
     const GArray *handles,
     DBusGMethodInvocation *context)
{
  EXTERNAL_OR_DIE (group)
  tp_group_mixin_get_handle_owners_async ((TpSvcChannelInterfaceGroup *) group,
      handles, context);
}

static void
tp_external_group_mixin_remove_members_async (TpSvcChannelInterfaceGroup *obj,
                                              const GArray *contacts,
                                              const gchar *message,
                                              DBusGMethodInvocation *context)
{
  EXTERNAL_OR_DIE (group)
  tp_group_mixin_remove_members_with_reason_async
      ((TpSvcChannelInterfaceGroup *) group, contacts, message,
       TP_CHANNEL_GROUP_CHANGE_REASON_NONE, context);
}


static void
tp_external_group_mixin_remove_members_with_reason_async
    (TpSvcChannelInterfaceGroup *obj,
     const GArray *contacts,
     const gchar *message,
     guint reason,
     DBusGMethodInvocation *context)
{
  EXTERNAL_OR_DIE (group)
  tp_group_mixin_remove_members_with_reason_async
      ((TpSvcChannelInterfaceGroup *) group, contacts, message, reason,
       context);
}
/**
 * tp_external_group_mixin_iface_init:
 * @g_iface: A #TpSvcChannelInterfaceGroupClass
 * @iface_data: Unused
 *
 * Fill in the vtable entries needed to implement the group interface using
 * the group mixin of another object. This function should usually be called
 * via G_IMPLEMENT_INTERFACE.
 *
 * Since: 0.5.13
 */
void
tp_external_group_mixin_iface_init (gpointer g_iface,
                                    gpointer iface_data)
{
  TpSvcChannelInterfaceGroupClass *klass = g_iface;

#define IMPLEMENT(x) tp_svc_channel_interface_group_implement_##x (klass,\
    tp_external_group_mixin_##x##_async)
  IMPLEMENT(add_members);
  IMPLEMENT(get_all_members);
  IMPLEMENT(get_group_flags);
  IMPLEMENT(get_handle_owners);
  IMPLEMENT(get_local_pending_members);
  IMPLEMENT(get_local_pending_members_with_info);
  IMPLEMENT(get_members);
  IMPLEMENT(get_remote_pending_members);
  IMPLEMENT(get_self_handle);
  IMPLEMENT(remove_members);
  IMPLEMENT(remove_members_with_reason);
#undef IMPLEMENT
}