summaryrefslogtreecommitdiffstats
path: root/src/libraries/qmfclient/qmailserviceaction.cpp
blob: 3745f1685833c4ed7c799b46ab1bdeb231dc3545 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
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
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Messaging Framework.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qmailserviceaction_p.h"
#include "qmailipc.h"
#include "qmailmessagekey.h"
#include "qmailstore.h"
#include "qmaillog.h"
#include "qmaildisconnected.h"
#include "qmailnamespace.h"
#include <qmailcontentmanager.h>
#include <QCoreApplication>
#include <QPair>
#include <QTimer>
#include <QDir>
#include <QTemporaryFile>

namespace {

uint messageCounter = 0;
const uint pid = static_cast<uint>(QCoreApplication::applicationPid() & 0xffffffff);

quint64 nextMessageAction()
{
    return ((quint64(pid) << 32) | quint64(++messageCounter));
}

QPair<uint, uint> messageActionParts(quint64 action)
{
    return qMakePair(uint(action >> 32), uint(action & 0xffffffff));
}

}


template<typename Subclass>
QMailServiceActionPrivate::QMailServiceActionPrivate(Subclass *p, QMailServiceAction *i)
    : QPrivateNoncopyableBase(p),
      _interface(i),
      _server(new QMailMessageServer(this)),
      _connectivity(QMailServiceAction::Offline),
      _activity(QMailServiceAction::Pending),
      _status(QMailServiceAction::Status::ErrNoError, QString(), QMailAccountId(), QMailFolderId(), QMailMessageId()),
      _total(0),
      _progress(0),
      _isValid(false),
      _action(0),
      _connectivityChanged(false),
      _activityChanged(false),
      _progressChanged(false),
      _statusChanged(false)
{
    connect(_server, SIGNAL(activityChanged(quint64, QMailServiceAction::Activity)),
            this, SLOT(activityChanged(quint64, QMailServiceAction::Activity)));
    connect(_server, SIGNAL(connectivityChanged(quint64, QMailServiceAction::Connectivity)),
            this, SLOT(connectivityChanged(quint64, QMailServiceAction::Connectivity)));
    connect(_server, SIGNAL(statusChanged(quint64, const QMailServiceAction::Status)),
            this, SLOT(statusChanged(quint64, const QMailServiceAction::Status)));
    connect(_server, SIGNAL(progressChanged(quint64, uint, uint)),
            this, SLOT(progressChanged(quint64, uint, uint)));
    connect(_server, SIGNAL(connectionDown()),
            this, SLOT(serverFailure()));
    connect(_server, SIGNAL(reconnectionTimeout()),
            this, SLOT(serverFailure()));
}

QMailServiceActionPrivate::~QMailServiceActionPrivate()
{
}

void QMailServiceActionPrivate::cancelOperation()
{
    Q_ASSERT(_action != 0 && _isValid);
    if (_isValid) {
        if (_pendingActions.count()) {
            _pendingActions.first().action->cancelOperation();
            clearSubActions();
            return;
        }
        _server->cancelTransfer(_action);
    }
}

void QMailServiceActionPrivate::setAction(quint64 action)
{
    _isValid = action != 0;
    _action = action;
}

void QMailServiceActionPrivate::activityChanged(quint64 action, QMailServiceAction::Activity activity)
{
    if (validAction(action)) {
        setActivity(activity);

        emitChanges();
    }
}

void QMailServiceActionPrivate::connectivityChanged(quint64 action, QMailServiceAction::Connectivity connectivity)
{
    if (validAction(action)) {
        setConnectivity(connectivity);

        emitChanges();
    }
}

void QMailServiceActionPrivate::statusChanged(quint64 action, const QMailServiceAction::Status status)
{
    if (validAction(action)) {
        setStatus(status);

        emitChanges();
    }
}

void QMailServiceActionPrivate::progressChanged(quint64 action, uint progress, uint total)
{
    if (validAction(action)) {
        setProgress(progress, total);

        emitChanges();
    }
}

void QMailServiceActionPrivate::subActionConnectivityChanged(QMailServiceAction::Connectivity c)
{
    connectivityChanged(_action, c);
}

void QMailServiceActionPrivate::subActionActivityChanged(QMailServiceAction::Activity a)
{
    if (a == QMailServiceAction::Failed) {
        clearSubActions();
    }
    if (a == QMailServiceAction::Successful) {
        if (_pendingActions.count()) {
            disconnectSubAction(_pendingActions.first().action);
            // Don't delete QObject while it's emitting a signal
            _pendingActions.first().action->deleteLater();
            _pendingActions.removeFirst();
        }
        if (_pendingActions.count()) {
            // Composite action does not finish until all sub actions finish
            _activityChanged = false;
            executeNextSubAction();
            return;
        }
    }
    activityChanged(_action, a);
}

void QMailServiceActionPrivate::subActionStatusChanged(const QMailServiceAction::Status &s)
{
    statusChanged(_action, s);
}

void QMailServiceActionPrivate::subActionProgressChanged(uint value, uint total)
{
    progressChanged(_action, value, total);
}

void QMailServiceActionPrivate::connectSubAction(QMailServiceAction *subAction)
{
    connect(subAction, SIGNAL(connectivityChanged(QMailServiceAction::Connectivity)),
            this, SLOT(subActionConnectivityChanged(QMailServiceAction::Connectivity)));
    connect(subAction, SIGNAL(activityChanged(QMailServiceAction::Activity)),
            this, SLOT(subActionActivityChanged(QMailServiceAction::Activity)));
    connect(subAction, SIGNAL(statusChanged(const QMailServiceAction::Status &)),
            this, SLOT(subActionStatusChanged(const QMailServiceAction::Status &)));
    connect(subAction, SIGNAL(progressChanged(uint, uint)),
            this, SLOT(subActionProgressChanged(uint, uint)));
}

void QMailServiceActionPrivate::disconnectSubAction(QMailServiceAction *subAction)
{
    disconnect(subAction, SIGNAL(connectivityChanged(QMailServiceAction::Connectivity)),
            this, SLOT(subActionConnectivityChanged(QMailServiceAction::Connectivity)));
    disconnect(subAction, SIGNAL(activityChanged(QMailServiceAction::Activity)),
            this, SLOT(subActionActivityChanged(QMailServiceAction::Activity)));
    disconnect(subAction, SIGNAL(statusChanged(const QMailServiceAction::Status &)),
            this, SLOT(subActionStatusChanged(const QMailServiceAction::Status &)));
    disconnect(subAction, SIGNAL(progressChanged(uint, uint)),
            this, SLOT(subActionProgressChanged(uint, uint)));
}

void QMailServiceActionPrivate::clearSubActions()
{
        if (_pendingActions.count())
            disconnectSubAction(_pendingActions.first().action);
        foreach(ActionCommand a, _pendingActions) {
            // Don't delete QObject while it's emitting a signal
            a.action->deleteLater();
        }
        _pendingActions.clear();
}

void QMailServiceActionPrivate::serverFailure()
{
    if (_isValid && _activity != QMailServiceAction::Failed) {
        _activity = QMailServiceAction::Failed;
        _activityChanged = true;
        emitChanges();
    }
}

void QMailServiceActionPrivate::init()
{
    _connectivity = QMailServiceAction::Offline;
    _activity = QMailServiceAction::Pending;
    _status = QMailServiceAction::Status(QMailServiceAction::Status::ErrNoError, QString(), QMailAccountId(), QMailFolderId(), QMailMessageId());
    _total = 0;
    _progress = 0;
    _action = 0;
    _connectivityChanged = false;
    _activityChanged = false;
    _progressChanged = false;
    _statusChanged = false;
    _isValid = false;
    _pendingActions.clear();
}

quint64 QMailServiceActionPrivate::newAction()
{
    if (_isValid) {
        qWarning() << "Unable to allocate new action - oustanding:" << messageActionParts(_action).second;
        return _action;
    }

    init();

    _action = nextMessageAction();
    _isValid = true;
    _activityChanged = true;
    emitChanges();

    return _action;
}

bool QMailServiceActionPrivate::validAction(quint64 action)
{
   return (action && _action == action);
}

void QMailServiceActionPrivate::appendSubAction(QMailServiceAction *subAction, QSharedPointer<QMailServiceActionCommand> command)
{
    ActionCommand a;
    a.action = subAction;
    a.command = command;
    _pendingActions.append(a);
}

void QMailServiceActionPrivate::executeNextSubAction()
{
    if (_pendingActions.isEmpty())
        return;

    connectSubAction(_pendingActions.first().action);
    _pendingActions.first().command->execute();
}

void QMailServiceActionPrivate::setConnectivity(QMailServiceAction::Connectivity newConnectivity)
{
    if (_isValid && (_connectivity != newConnectivity)) {
        _connectivity = newConnectivity;
        _connectivityChanged = true;
    }
}

void QMailServiceActionPrivate::setActivity(QMailServiceAction::Activity newActivity)
{
    if (_isValid && (_activity != newActivity)) {
        _activity = newActivity;

        if (_activity == QMailServiceAction::Failed || _activity == QMailServiceAction::Successful) {
            // We're finished
            _isValid = false;
        }

        _activityChanged = true;
    }
}

void QMailServiceActionPrivate::setStatus(const QMailServiceAction::Status &status)
{
    if (_isValid) {
        _status = status;
        _statusChanged = true;
    }
}

void QMailServiceActionPrivate::setStatus(QMailServiceAction::Status::ErrorCode code, const QString &text)
{
    setStatus(code, text, QMailAccountId(), QMailFolderId(), QMailMessageId());
}

void QMailServiceActionPrivate::setStatus(QMailServiceAction::Status::ErrorCode code,
                                          const QString &text,
                                          const QMailAccountId &accountId,
                                          const QMailFolderId &folderId,
                                          const QMailMessageId &messageId)
{
    if (_isValid) {
        _status = QMailServiceAction::Status(code, text, accountId, folderId, messageId);
        _statusChanged = true;
    }
}

void QMailServiceActionPrivate::setProgress(uint newProgress, uint newTotal)
{
    if (_isValid) {
        if (newTotal != _total) {
            _total = newTotal;
            _progressChanged = true;
        }

        newProgress = qMin(newProgress, _total);
        if (newProgress != _progress) {
            _progress = newProgress;
            _progressChanged = true;
        }
    }
}

void QMailServiceActionPrivate::emitChanges()
{
    if (_connectivityChanged) {
        _connectivityChanged = false;
        emit _interface->connectivityChanged(_connectivity);
    }
    if (_activityChanged) {
        _activityChanged = false;
        emit _interface->activityChanged(_activity);
    }
    if (_progressChanged) {
        _progressChanged = false;
        emit _interface->progressChanged(_progress, _total);
    }
    if (_statusChanged) {
        _statusChanged = false;
        emit _interface->statusChanged(_status);
    }
}


/*!
    \class QMailServiceAction::Status

    \preliminary
    \ingroup messaginglibrary

    \brief The Status class encapsulates the instantaneous state of a QMailServiceAction.

    QMailServiceAction::Status contains the pieces of information that describe the state of a
    requested action.  The \l errorCode reflects the overall state, and may be supplemented
    by a description in \l text.

    If \l errorCode is not equal to \l ErrNoError, then each of \l accountId, \l folderId and 
    \l messageId may have been set to a valid identifier, if pertinent to the situation.
*/

/*!
    \enum QMailServiceAction::Status::ErrorCode

    This enum type is used to identify common error conditions encountered when implementing service actions.

    \value ErrNoError               No error was encountered.
    \value ErrNotImplemented        The requested operation is not implemented by the relevant service component.
    \value ErrFrameworkFault        A fault in the messaging framework prevented the execution of the request.
    \value ErrSystemError           A system-level error prevented the execution of the request.
    \value ErrInternalServer        A system error on server.
    \value ErrCancel                The operation was cancelled by user intervention.
    \value ErrConfiguration         The configuration needed for the requested action is invalid.
    \value ErrNoConnection          A connection could not be established to the external service.
    \value ErrConnectionInUse       The connection to the external service is exclusively held by another user.
    \value ErrConnectionNotReady    The connection to the external service is not ready for operation.
    \value ErrUnknownResponse       The response from the external service could not be handled.
    \value ErrLoginFailed           The external service did not accept the supplied authentication details.
    \value ErrFileSystemFull        The action could not be performed due to insufficient storage space.
    \value ErrNonexistentMessage    The specified message does not exist.
    \value ErrEnqueueFailed         The specified message could not be enqueued for transmission.
    \value ErrInvalidAddress        The specified address is invalid for the requested action.
    \value ErrInvalidData           The supplied data is inappropriate for the requested action.
    \value ErrTimeout               The service failed to report any activity for an extended period.
    \value ErrInternalStateReset    The service was reset due to state change, such as an external process modifying the owner account.
    \value ErrorCodeMinimum         The lowest value of any error condition code.
    \value ErrorCodeMaximum         The highest value of any error condition code.
*/

/*! \variable QMailServiceAction::Status::errorCode
    
    Describes the error condition encountered by the action.
*/

/*! \variable QMailServiceAction::Status::text
    
    Provides a human-readable description of the error condition in \l errorCode.
*/

/*! \variable QMailServiceAction::Status::accountId
    
    If relevant to the \l errorCode, contains the ID of the associated account.
*/

/*! \variable QMailServiceAction::Status::folderId
    
    If relevant to the \l errorCode, contains the ID of the associated folder.
*/

/*! \variable QMailServiceAction::Status::messageId
    
    If relevant to the \l errorCode, contains the ID of the associated message.
*/

/*! 
    \fn QMailServiceAction::Status::Status()

    Constructs a status object with \l errorCode set to \l{QMailServiceAction::Status::ErrNoError}{ErrNoError}.
*/
QMailServiceAction::Status::Status()
    : errorCode(ErrNoError)
{
}

/*! 
    \fn QMailServiceAction::Status::Status(ErrorCode c, const QString &t, const QMailAccountId &a, const QMailFolderId &f, const QMailMessageId &m)

    Constructs a status object with 
    \l errorCode set to \a c, 
    \l text set to \a t, 
    \l accountId set to \a a, 
    \l folderId set to \a f and 
    \l messageId set to \a m.
*/
QMailServiceAction::Status::Status(ErrorCode c, const QString &t, const QMailAccountId &a, const QMailFolderId &f, const QMailMessageId &m)
    : errorCode(c),
      text(t),
      accountId(a),
      folderId(f),
      messageId(m)
{
}

/*! 
    \fn QMailServiceAction::Status::Status(const Status&)

    Constructs a status object which is a copy of \a other.
*/
QMailServiceAction::Status::Status(const QMailServiceAction::Status &other)
    : errorCode(other.errorCode),
      text(other.text),
      accountId(other.accountId),
      folderId(other.folderId),
      messageId(other.messageId)
{
}

/*! 
    \fn QMailServiceAction::Status::serialize(Stream&) const
    \internal 
*/
template <typename Stream> 
void QMailServiceAction::Status::serialize(Stream &stream) const
{
    stream << errorCode;
    stream << text;
    stream << accountId;
    stream << folderId;
    stream << messageId;
}

template void QMailServiceAction::Status::serialize(QDataStream &) const;

/*! 
    \fn QMailServiceAction::Status::deserialize(Stream&)
    \internal 
*/
template <typename Stream> 
void QMailServiceAction::Status::deserialize(Stream &stream)
{
    stream >> errorCode;
    stream >> text;
    stream >> accountId;
    stream >> folderId;
    stream >> messageId;
}

template void QMailServiceAction::Status::deserialize(QDataStream &);

/*!
    \class QMailServiceAction

    \preliminary
    \ingroup messaginglibrary

    \brief The QMailServiceAction class provides the interface for requesting actions from external message services.

    QMailServiceAction provides the mechanisms for messaging clients to request actions from 
    external services, and to receive information in response.  The details of requests
    differ for each derived action, and the specific data returned is also variable.  However,
    all actions present the same interface for communicating status, connectivity and 
    progress information.

    All actions communicate changes in their operational state by emitting the activityChanged()
    signal.  If the execution of the action requires connectivity to an external service, then
    changes in connectivity state are emitted via the connectivityChanged() signal.  Some actions
    are able to provide progress information as they execute; these changes are reported via the 
    progressChanged() signal.  If error conditions are encountered, the statusChanged() signal is
    emitted to report the new status.

    A user may attempt to cancel an operation after it has been initiated.  The cancelOperation()
    slot is provided for this purpose.

    A QMailServiceAction instance supports only a single request at any time.  An application
    may, however, use multiple QMailServiceAction instances to send independent requests concurrently.
    Each QMailServiceAction instance will report only the changes pertaining to the request
    that instance delivered.  Whether or not concurrent requests are concurrently serviced by 
    the message server depends on whether those requests must be serviced by the same 
    QMailMessageService instance.

    \sa QMailMessageService
*/

/*!
    \enum QMailServiceAction::Connectivity

    This enum type is used to describe the connectivity state of the service implementing an action.

    \value Offline          The service is offline.
    \value Connecting       The service is currently attempting to establish a connection.
    \value Connected        The service is connected.
    \value Disconnected     The service has been disconnected.
*/

/*!
    \enum QMailServiceAction::Activity

    This enum type is used to describe the activity state of the requested action.

    \value Pending          The action has not yet begun execution.
    \value InProgress       The action is currently executing.
    \value Successful       The action has completed successfully.
    \value Failed           The action could not be completed successfully, and has finished execution.
*/

/*!
    \fn QMailServiceAction::connectivityChanged(QMailServiceAction::Connectivity c)

    This signal is emitted when the connectivity status of the service performing 
    the action changes, with the new state described by \a c.

    \sa connectivity()
*/

/*!
    \fn QMailServiceAction::activityChanged(QMailServiceAction::Activity a)

    This signal is emitted when the activity status of the action changes,
    with the new state described by \a a.

    \sa activity()
*/

/*!
    \fn QMailServiceAction::statusChanged(const QMailServiceAction::Status &s)

    This signal is emitted when the error status of the action changes, with
    the new status described by \a s.

    \sa status()
*/

/*!
    \fn QMailServiceAction::progressChanged(uint value, uint total)

    This signal is emitted when the progress of the action changes, with
    the new state described by \a value and \a total.

    \sa progress()
*/

/*!
    \typedef QMailServiceAction::ImplementationType
    \internal
*/

/*!
    \fn QMailServiceAction::QMailServiceAction(Subclass*, QObject*)
    \internal
*/
template<typename Subclass>
QMailServiceAction::QMailServiceAction(Subclass* p, QObject *parent)
    : QObject(parent),
      QPrivatelyNoncopyable<QMailServiceActionPrivate>(p)
{
}

/*! \internal */
QMailServiceAction::~QMailServiceAction()
{
}

/*!
    Returns the current connectivity state of the service implementing this action.

    \sa connectivityChanged()
*/
QMailServiceAction::Connectivity QMailServiceAction::connectivity() const
{
    return impl(this)->_connectivity;
}

/*!
    Returns the current activity state of the action.

    \sa activityChanged()
*/
QMailServiceAction::Activity QMailServiceAction::activity() const
{
    return impl(this)->_activity;
}

/*!
    Returns the current status of the service action.

    \sa statusChanged()
*/
const QMailServiceAction::Status QMailServiceAction::status() const
{
    return impl(this)->_status;
}

/*!
    Returns the current progress of the service action.

    \sa progressChanged()
*/
QPair<uint, uint> QMailServiceAction::progress() const
{
    return qMakePair(impl(this)->_progress, impl(this)->_total);
}

/*!
    Returns if the service action is currently running (i.e. if it's doing something, but hasn't yet finished)
*/

bool QMailServiceAction::isRunning() const
{
    return impl(this)->_isValid;
}

/*!
    Attempts to cancel the last requested operation.
*/
void QMailServiceAction::cancelOperation()
{
    impl(this)->cancelOperation();
}

/*!
    Set the current status so that 
    \l{QMailServiceAction::Status::errorCode} errorCode is set to \a c and 
    \l{QMailServiceAction::Status::text} text is set to \a t.
*/
void QMailServiceAction::setStatus(QMailServiceAction::Status::ErrorCode c, const QString &t)
{
    impl(this)->setStatus(c, t, QMailAccountId(), QMailFolderId(), QMailMessageId());
}

/*!
    Set the current status so that 
    \l{QMailServiceAction::Status::errorCode} errorCode is set to \a c, 
    \l{QMailServiceAction::Status::text} text is set to \a t,
    \l{QMailServiceAction::Status::accountId} accountId is set to \a a, 
    \l{QMailServiceAction::Status::folderId} folderId is set to \a f and 
    \l{QMailServiceAction::Status::messageId} messageId is set to \a m.
*/
void QMailServiceAction::setStatus(QMailServiceAction::Status::ErrorCode c, const QString &t, const QMailAccountId &a, const QMailFolderId &f, const QMailMessageId &m)
{
    impl(this)->setStatus(c, t, a, f, m);
}


QMailRetrievalActionPrivate::QMailRetrievalActionPrivate(QMailRetrievalAction *i)
    : QMailServiceActionPrivate(this, i)
{
    connect(_server, SIGNAL(retrievalCompleted(quint64)),
            this, SLOT(retrievalCompleted(quint64)));

    init();
}

void QMailRetrievalActionPrivate::retrieveFolderListHelper(const QMailAccountId &accountId, const QMailFolderId &folderId, bool descending)
{
    _server->retrieveFolderList(newAction(), accountId, folderId, descending);
}

void QMailRetrievalActionPrivate::retrieveFolderList(const QMailAccountId &accountId, const QMailFolderId &folderId, bool descending)
{
    Q_ASSERT(!_pendingActions.count());
    retrieveFolderListHelper(accountId, folderId, descending);
}

void QMailRetrievalActionPrivate::retrieveMessageListHelper(const QMailAccountId &accountId, const QMailFolderId &folderId, uint minimum, const QMailMessageSortKey &sort)
{
    _server->retrieveMessageList(newAction(), accountId, folderId, minimum, sort);
}

void QMailRetrievalActionPrivate::retrieveMessageList(const QMailAccountId &accountId, const QMailFolderId &folderId, uint minimum, const QMailMessageSortKey &sort)
{
    Q_ASSERT(!_pendingActions.count());
    retrieveMessageListHelper(accountId, folderId, minimum, sort);
}

void QMailRetrievalActionPrivate::retrieveMessages(const QMailMessageIdList &messageIds, QMailRetrievalAction::RetrievalSpecification spec)
{
    _server->retrieveMessages(newAction(), messageIds, spec);
}

void QMailRetrievalActionPrivate::retrieveMessagePart(const QMailMessagePart::Location &partLocation)
{
    _server->retrieveMessagePart(newAction(), partLocation);
}

void QMailRetrievalActionPrivate::retrieveMessageRange(const QMailMessageId &messageId, uint minimum)
{
    _server->retrieveMessageRange(newAction(), messageId, minimum);
}

void QMailRetrievalActionPrivate::retrieveMessagePartRange(const QMailMessagePart::Location &partLocation, uint minimum)
{
    _server->retrieveMessagePartRange(newAction(), partLocation, minimum);
}

void QMailRetrievalActionPrivate::retrieveAll(const QMailAccountId &accountId)
{
    _server->retrieveAll(newAction(), accountId);
}

void QMailRetrievalActionPrivate::exportUpdatesHelper(const QMailAccountId &accountId)
{
    _server->exportUpdates(newAction(), accountId);
}

void QMailRetrievalActionPrivate::exportUpdates(const QMailAccountId &accountId)
{
    Q_ASSERT(!_pendingActions.count());
    exportUpdatesHelper(accountId);
}

void QMailRetrievalActionPrivate::synchronizeAllHelper(const QMailAccountId &accountId)
{
    _server->synchronize(newAction(), accountId);
}

void QMailRetrievalActionPrivate::synchronizeAll(const QMailAccountId &accountId)
{
    Q_ASSERT(!_pendingActions.count());
    synchronizeAllHelper(accountId);
}

void QMailRetrievalActionPrivate::synchronize(const QMailAccountId &accountId, uint minimum)
{
    Q_ASSERT(!_pendingActions.count());
    newAction();

    QMailRetrievalAction *exportAction = new QMailRetrievalAction();
    QMailExportUpdatesCommand *exportCommand = new QMailExportUpdatesCommand(exportAction->impl(exportAction), accountId);
    appendSubAction(exportAction, QSharedPointer<QMailServiceActionCommand>(exportCommand));

    QMailRetrievalAction *retrieveFolderListAction = new QMailRetrievalAction();
    QMailRetrieveFolderListCommand *retrieveFolderListCommand = new QMailRetrieveFolderListCommand(retrieveFolderListAction->impl(retrieveFolderListAction), accountId);
    appendSubAction(retrieveFolderListAction, QSharedPointer<QMailServiceActionCommand>(retrieveFolderListCommand));
    
    QMailRetrievalAction *retrieveMessageListAction = new QMailRetrievalAction();
    QMailRetrieveMessageListCommand *retrieveMessageListCommand = new QMailRetrieveMessageListCommand(retrieveMessageListAction->impl(retrieveMessageListAction), accountId, minimum);
    appendSubAction(retrieveMessageListAction, QSharedPointer<QMailServiceActionCommand>(retrieveMessageListCommand));
    
    executeNextSubAction();
}

void QMailRetrievalActionPrivate::retrievalCompleted(quint64 action)
{
    if (validAction(action)) {
        setActivity(QMailServiceAction::Successful);
        emitChanges();
    }
}


/*!
    \class QMailRetrievalAction

    \preliminary
    \ingroup messaginglibrary

    \brief The QMailRetrievalAction class provides the interface for retrieving messages from external message services.

    QMailRetrievalAction provides the mechanism for messaging clients to request that the message
    server retrieve messages from external services.  The retrieval action object reports on
    the progress and outcome of its activities via the signals inherited from QMailServiceAction.

    A range of functions are available to support varying client operations:

    The retrieveFolderList() function allows a client to retrieve the list of folders available for an account.
    The retrieveMessageList() function allows a client to retrieve a subset of messages available for an account or folder.

    The retrieveMessages() function allows a client to retrieve the flags, meta data or content of a 
    specific list of messages.

    The retrieveMessageRange() functions allows a portion of a message's content to be retrieved, rather than
    the entire content data.

    The retrieveMessagePart() function allows a specific part of a multi-part message to be retrieved.
    The retrieveMessagePartRange() function allows a portion of a specific part of a multi-part message to be retrieved.

    The exportUpdates() function allows a client to push local changes such as message-read notifications 
    and pending disconnected operations to the external server.
*/

/*!
    \enum QMailRetrievalAction::RetrievalSpecification

    This enum type is specify the form of retrieval that the message server should perform.

    \value Flags        Changes to the state of the message should be retrieved.
    \value MetaData     Only the meta data of the message should be retrieved.
    \value Content      The entire content of the message should be retrieved.
    \value Auto         Account specific settings are used during synchronization.
                        For example, this may mean skipping the attachments.
*/

/*!
    \typedef QMailRetrievalAction::ImplementationType
    \internal
*/

/*! 
    Constructs a new retrieval action object with the supplied \a parent.
*/
QMailRetrievalAction::QMailRetrievalAction(QObject *parent)
    : QMailServiceAction(new QMailRetrievalActionPrivate(this), parent)
{
}

/*! \internal */
QMailRetrievalAction::~QMailRetrievalAction()
{
}

/*!
    Requests that the message server retrieve the list of folders available for the 
    account \a accountId.  If \a folderId is valid, only the identified folder is 
    searched for child folders; otherwise the search begins at the root of the
    account.  If \a descending is true, the search should also recursively search 
    for child folders within folders discovered during the search.

    The QMailFolder::serverCount(), QMailFolder::serverUnreadCount() and 
    QMailFolder::serverUndiscoveredCount() properties will be updated for each 
    folder that is searched for child folders; these properties are not updated 
    for folders that are merely discovered by searching.
    
    \sa retrieveMessageList()
*/
void QMailRetrievalAction::retrieveFolderList(const QMailAccountId &accountId, const QMailFolderId &folderId, bool descending)
{
    impl(this)->retrieveFolderList(accountId, folderId, descending);
}

/*!
    Requests that the message server retrieve the list of messages available for the account \a accountId.
    If \a folderId is valid, then only messages within that folder should be retrieved; otherwise 
    messages within all folders in the account should be retrieved, and the lastSynchronized() time 
    of the account updated.  If \a minimum is non-zero, then that value will be used to restrict the 
    number of messages to be retrieved from each folder; otherwise, all messages will be retrieved.
    
    If \a sort is not empty, the external service will report the discovered messages in the 
    ordering indicated by the sort criterion, if possible.  Services are not required to support 
    this facility.

    If a folder messages are being retrieved from contains at least \a minimum messages then the 
    messageserver should ensure that at least \a minimum messages are available from the mail 
    store for that folder; otherwise if the folder contains less than \a minimum messages the 
    messageserver should ensure all the messages for that folder are available from the mail store.
    If a folder has messages locally available, then all previously undiscovered messages will be
    retrieved for that folder, even if that number exceeds \a minimum.
    
    The QMailFolder::serverCount(), QMailFolder::serverUnreadCount() and 
    QMailFolder::serverUndiscoveredCount() properties will be updated for each folder 
    from which messages are retrieved.
    
    New messages will be added to the mail store as they are discovered, and 
    marked with the \l QMailMessage::New status flag. Messages that are present
    in the mail store but found to be no longer available are marked with the 
    \l QMailMessage::Removed status flag.
    
    \sa QMailAccount::lastSynchronized()
*/
void QMailRetrievalAction::retrieveMessageList(const QMailAccountId &accountId, const QMailFolderId &folderId, uint minimum, const QMailMessageSortKey &sort)
{
    impl(this)->retrieveMessageList(accountId, folderId, minimum, sort);
}

/*!
    Requests that the message server retrieve data regarding the messages identified by \a messageIds.  

    If \a spec is \l QMailRetrievalAction::Flags, then the message server should detect if 
    the messages identified by \a messageIds have been marked as read or have been removed.
    Messages that have been read will be marked with the \l QMailMessage::ReadElsewhere flag, and
    messages that have been removed will be marked with the \l QMailMessage::Removed status flag.

    If \a spec is \l QMailRetrievalAction::MetaData, then the message server should 
    retrieve the meta data of the each message listed in \a messageIds.
    
    If \a spec is \l QMailRetrievalAction::Content, then the message server should 
    retrieve the entirety of each message listed in \a messageIds.
    
    The QMailFolder::serverCount(), QMailFolder::serverUnreadCount() and 
    QMailFolder::serverUndiscoveredCount() properties will be updated for each folder 
    from which messages are retrieved.
*/
void QMailRetrievalAction::retrieveMessages(const QMailMessageIdList &messageIds, RetrievalSpecification spec)
{
    impl(this)->retrieveMessages(messageIds, spec);
}

/*!
    Requests that the message server retrieve the message part that is indicated by the 
    location \a partLocation.
    
    The QMailFolder::serverCount(), QMailFolder::serverUnreadCount() and 
    QMailFolder::serverUndiscoveredCount() properties will be updated for the folder 
    from which the part is retrieved.
*/
void QMailRetrievalAction::retrieveMessagePart(const QMailMessagePart::Location &partLocation)
{
    impl(this)->retrieveMessagePart(partLocation);
}

/*!
    Requests that the message server retrieve a subset of the message \a messageId, such that
    at least \a minimum bytes are available from the mail store.
    
    The QMailFolder::serverCount(), QMailFolder::serverUnreadCount() and 
    QMailFolder::serverUndiscoveredCount() properties will be updated for the folder 
    from which the message is retrieved.
*/
void QMailRetrievalAction::retrieveMessageRange(const QMailMessageId &messageId, uint minimum)
{
    impl(this)->retrieveMessageRange(messageId, minimum);
}

/*!
    Requests that the message server retrieve a subset of the message part that is indicated 
    by the location \a partLocation.  The messageserver should ensure that at least 
    \a minimum bytes are available from the mail store.
    
    The total size of the part on the server is given by QMailMessagePart::contentDisposition().size(),
    the amount of the part available locally is given by QMailMessagePart::body().length().
    
    The QMailFolder::serverCount(), QMailFolder::serverUnreadCount() and 
    QMailFolder::serverUndiscoveredCount() properties will be updated for the folder 
    from which the part is retrieved.
*/
void QMailRetrievalAction::retrieveMessagePartRange(const QMailMessagePart::Location &partLocation, uint minimum)
{
    impl(this)->retrieveMessagePartRange(partLocation, minimum);
}

/*!
    \deprecated
  
    Requests that the message server retrieve all folders and meta data for messages available 
    for the account \a accountId.
    
    All folders within the account will be discovered and searched for child folders.
    The QMailFolder::serverCount(), QMailFolder::serverUnreadCount() and 
    QMailFolder::serverUndiscoveredCount() properties will be updated for each folder 
    in the account.

    Meta data will be retrieved for every message found in the account.
    New messages will be added to the mail store as they are retrieved, and 
    marked with the \l QMailMessage::New status flag.  Messages that are no longer 
    available will be marked with the \l QMailMessage::Removed status flag.  

    \sa retrieveFolderList(), retrieveMessageList()
*/
void QMailRetrievalAction::retrieveAll(const QMailAccountId &accountId)
{
    impl(this)->retrieveAll(accountId);
}

/*!
    Requests that the message server update the external server with changes that have 
    been effected on the local device for account \a accountId.
    Local changes to \l QMailMessage::Read, and \l QMailMessage::Important message status 
    flags should be exported to the external server, messages that have been removed
    using the \l QMailStore::CreateRemovalRecord option should be removed from the 
    external server, and any flag, copy or move operations that have been applied
    using \l QMailDisconnected should be applied to the external server.
*/
void QMailRetrievalAction::exportUpdates(const QMailAccountId &accountId)
{
    if (!QMailDisconnected::updatesOutstanding(accountId)) {
        // nothing to do
        impl(this)->newAction();
        impl(this)->setActivity(QMailServiceAction::Successful);
        impl(this)->emitChanges();
        return;
    }
        
    impl(this)->exportUpdates(accountId);
}

/*!
    \deprecated
  
    Requests that the message server synchronize the set of known folder and message 
    identifiers with those currently available for the account identified by \a accountId.
    Newly discovered messages should have their meta data retrieved, messages that have been 
    removed locally using the \l QMailStore::CreateRemovalRecord option should be removed 
    from the external server.
    
    Changes to the \l QMailMessage::Read, and \l QMailMessage::Important status flags of a 
    message should be exported to the external server, and the status flags of the message
    should be updated to reflect any changes to the message on the external server.

    New messages will be added to the mail store as they are discovered, and 
    marked with the \l QMailMessage::New status flag.  Messages that are no longer 
    available will be marked with the \l QMailMessage::Removed status flag.  

    The folder structure of the account will be synchronized with that available from 
    the external server.  The QMailFolder::serverCount(), QMailFolder::serverUnreadCount() and 
    QMailFolder::serverUndiscoveredCount() properties will be updated for each folder.

    \sa retrieveFolderList(), retrieveMessageList(), exportUpdates()
*/
void QMailRetrievalAction::synchronizeAll(const QMailAccountId &accountId)
{
    impl(this)->synchronizeAll(accountId);
}


/*!
    Essentially performs the same functions as calling exportUpdates(), retrieveFolderList() 
    and retrieveMessageList() consecutively using the given \a accountId and \a minimum, but 
    may perform optimizations such as retrieving the folder list at the same time as 
    retrieving messages, and retrieving messages in multiple folder simultaneously by using 
    multiple connections to the server.
    
    On a successful synchronization the lastSynchronized() value of the account should be updated.

    \sa exportUpdates(), retrieveMessageList(), retrieveFolderList(), QMailAccount::lastSynchronized() 
*/
void QMailRetrievalAction::synchronize(const QMailAccountId &accountId, uint minimum)
{
    impl(this)->synchronize(accountId, minimum);
}


QMailTransmitActionPrivate::QMailTransmitActionPrivate(QMailTransmitAction *i)
    : QMailServiceActionPrivate(this, i)
{
    connect(_server, SIGNAL(messagesTransmitted(quint64, QMailMessageIdList)),
            this, SLOT(messagesTransmitted(quint64, QMailMessageIdList)));
    connect(_server, SIGNAL(messagesFailedTransmission(quint64, QMailMessageIdList, QMailServiceAction::Status::ErrorCode)),
            this, SLOT(messagesFailedTransmission(quint64, QMailMessageIdList, QMailServiceAction::Status::ErrorCode)));
    connect(_server, SIGNAL(transmissionCompleted(quint64)),
            this, SLOT(transmissionCompleted(quint64)));

    init();
}

void QMailTransmitActionPrivate::transmitMessages(const QMailAccountId &accountId)
{
    _server->transmitMessages(newAction(), accountId);

    emitChanges();
}

void QMailTransmitActionPrivate::init()
{
    QMailServiceActionPrivate::init();
}

void QMailTransmitActionPrivate::messagesTransmitted(quint64 action, const QMailMessageIdList &ids)
{
    if (validAction(action)) {
        emit messagesTransmitted(ids);
    }
}

void QMailTransmitActionPrivate::messagesFailedTransmission(quint64 action, const QMailMessageIdList &ids, QMailServiceAction::Status::ErrorCode error)
{
    if (validAction(action)) {
        emit messagesFailedTransmission(ids, error);
    }
}

void QMailTransmitActionPrivate::transmissionCompleted(quint64 action)
{
    if (validAction(action)) {
        QMailServiceAction::Activity result(QMailServiceAction::Successful);
        setActivity(result);
        emitChanges();
    }
}


/*!
    \class QMailTransmitAction

    \preliminary
    \ingroup messaginglibrary

    \brief The QMailTransmitAction class provides the interface for transmitting messages to external message services.

    QMailSearchAction provides the mechanism for messaging clients to request that the message
    server transmit messages to external services.  The transmit action object reports on
    the progress and outcome of its activities via the signals inherited from QMailServiceAction.

    The send() slot requests that the message server transmit each identified message to the
    external service associated with each messages' account.

    Note: the slots exported by QMailTransmitAction are expected to change in future releases, as 
    the message server is extended to provide a finer-grained interface for message transmission.
*/

/*!
    \typedef QMailTransmitAction::ImplementationType
    \internal
*/

/*!
    \fn QMailTransmitAction::messagesTransmitted(const QMailMessageIdList &ids)

    This signal is emitted to report the successful transmission of the messages listed in \a ids.
*/

/*!
    \fn QMailTransmitAction::messagesFailedTransmission(const QMailMessageIdList &ids, QMailServiceAction::Status::ErrorCode error)

    This signal is emitted to report the failure of an attempt at transmission of the messages listed in \a ids.

    The failure is of type \a error.
*/


/*!
    Constructs a new transmit action object with the supplied \a parent.
*/
QMailTransmitAction::QMailTransmitAction(QObject *parent)
    : QMailServiceAction(new QMailTransmitActionPrivate(this), parent)
{
    connect(impl(this), SIGNAL(messagesTransmitted(QMailMessageIdList)), 
            this, SIGNAL(messagesTransmitted(QMailMessageIdList)));
    connect(impl(this), SIGNAL(messagesFailedTransmission(QMailMessageIdList, QMailServiceAction::Status::ErrorCode)), 
            this, SIGNAL(messagesFailedTransmission(QMailMessageIdList, QMailServiceAction::Status::ErrorCode)));
}

/*! \internal */
QMailTransmitAction::~QMailTransmitAction()
{
}

/*!
    Requests that the message server transmit each message belonging to the account identified
    by \a accountId that is currently scheduled for transmission (located in the Outbox folder).

    Any message successfully transmitted will be moved to the account's Sent folder.
*/
void QMailTransmitAction::transmitMessages(const QMailAccountId &accountId)
{
    impl(this)->transmitMessages(accountId);
}


QMailStorageActionPrivate::QMailStorageActionPrivate(QMailStorageAction *i)
    : QMailServiceActionPrivate(this, i)
{
    connect(_server, SIGNAL(messagesDeleted(quint64, QMailMessageIdList)),
            this, SLOT(messagesEffected(quint64, QMailMessageIdList)));
    connect(_server, SIGNAL(messagesMoved(quint64, QMailMessageIdList)),
            this, SLOT(messagesEffected(quint64, QMailMessageIdList)));
    connect(_server, SIGNAL(messagesCopied(quint64, QMailMessageIdList)),
            this, SLOT(messagesEffected(quint64, QMailMessageIdList)));
    connect(_server, SIGNAL(messagesFlagged(quint64, QMailMessageIdList)),
            this, SLOT(messagesEffected(quint64, QMailMessageIdList)));
    connect(_server, SIGNAL(messagesAdded(quint64, QMailMessageIdList)),
            this, SLOT(messagesAdded(quint64, QMailMessageIdList)));
    connect(_server, SIGNAL(messagesUpdated(quint64, QMailMessageIdList)),
            this, SLOT(messagesUpdated(quint64, QMailMessageIdList)));
    connect(_server, SIGNAL(storageActionCompleted(quint64)),
            this, SLOT(storageActionCompleted(quint64)));

    init();
}

void QMailStorageActionPrivate::deleteMessagesHelper(const QMailMessageIdList &ids)
{
    _server->deleteMessages(newAction(), ids, QMailStore::CreateRemovalRecord);
    // Successful as long as ids have been deleted, 
    // this action doesn't have to be the one to have deleted them
    _ids.clear();
    emitChanges();
}

void QMailStorageActionPrivate::deleteMessages(const QMailMessageIdList &ids)
{
    Q_ASSERT(!_pendingActions.count());
    deleteMessagesHelper(ids);
}

void QMailStorageActionPrivate::discardMessages(const QMailMessageIdList &ids)
{
    _server->deleteMessages(newAction(), ids, QMailStore::NoRemovalRecord);
    _ids = ids;
    emitChanges();
}

void QMailStorageActionPrivate::copyMessages(const QMailMessageIdList &ids, const QMailFolderId &destination)
{
    _server->copyMessages(newAction(), ids, destination);
    _ids = ids;
    emitChanges();
}

void QMailStorageActionPrivate::moveMessages(const QMailMessageIdList &ids, const QMailFolderId &destination)
{
    _server->moveMessages(newAction(), ids, destination);
    _ids = ids;
    emitChanges();
}

void QMailStorageActionPrivate::flagMessages(const QMailMessageIdList &ids, quint64 setMask, quint64 unsetMask)
{
    // Ensure that nothing is both set and unset
    setMask &= ~unsetMask;
    _server->flagMessages(newAction(), ids, setMask, unsetMask);

    _ids = ids;
    emitChanges();
}

void QMailStorageActionPrivate::addMessages(const QMailMessageList &list)
{
    _ids.clear();
    _addedOrUpdatedIds.clear();

    // Make non durable changes to the content manager
    // Existing message data in mail store and content manager should not be
    // changed directly by this function, instead the messageserver should do it.
    QMailMessageMetaDataList metadata;
    foreach (QMailMessage message, list) {
        if (message.contentScheme().isEmpty()) {
            message.setContentScheme(QMailContentManagerFactory::defaultScheme());
        }
        if (QMailContentManager *contentManager = QMailContentManagerFactory::create(message.contentScheme())) {
            QMailStore::ErrorCode code = contentManager->add(&message, QMailContentManager::NoDurability);
            if (code != QMailStore::NoError) {
                qWarning() << "Unable to ensure message content durability for scheme:" << message.contentScheme();
                if (validAction(newAction())) {
                    setActivity(QMailServiceAction::Failed);
                    emitChanges();
                }
                return;
            }
            metadata.append(message);
        }
    }
    _server->addMessages(newAction(), metadata);

    emitChanges();
}

void QMailStorageActionPrivate::updateMessages(const QMailMessageList &list)
{
    _ids.clear();
    _addedOrUpdatedIds.clear();

    // Ensure that message non metadata is written and flushed to the filesystem,
    // but not synced
    // Existing message data in mail store and content manager should not be
    // changed directly by this function, instead the messageserver should do it.
    QMailMessageMetaDataList metadata;
    foreach (QMailMessage message, list) {
        if (message.contentScheme().isEmpty()) {
            message.setContentScheme(QMailContentManagerFactory::defaultScheme());
        }
        message.setCustomField("qmf-obsolete-contentid", message.contentIdentifier());
        if (QMailContentManager *contentManager = QMailContentManagerFactory::create(message.contentScheme())) {
            QMailStore::ErrorCode code = contentManager->update(&message, QMailContentManager::EnsureDurability);
            if (code != QMailStore::NoError) {
                qWarning() << "Unable to ensure message content durability for scheme:" << message.contentScheme();
                if (validAction(newAction())) {
                    setActivity(QMailServiceAction::Failed);
                    emitChanges();
                }
                return;
            }
            metadata.append(message);
        }
    }
    _server->updateMessages(newAction(), metadata);

    emitChanges();
}

void QMailStorageActionPrivate::updateMessages(const QMailMessageMetaDataList &list)
{
    _ids.clear();
    _addedOrUpdatedIds.clear();

    QMailMessageMetaDataList metadata = list;
    _server->updateMessages(newAction(), metadata);

    emitChanges();
}

void QMailStorageActionPrivate::createFolder(const QString &name, const QMailAccountId &accountId, const QMailFolderId &parentId)
{
    _server->createFolder(newAction(), name, accountId, parentId);
    emitChanges();
}

void QMailStorageActionPrivate::renameFolder(const QMailFolderId &folderId, const QString &name)
{
    _server->renameFolder(newAction(), folderId, name);
    emitChanges();
}

void QMailStorageActionPrivate::deleteFolderHelper(const QMailFolderId &folderId)
{
    _server->deleteFolder(newAction(), folderId);
    emitChanges();
}

void QMailStorageActionPrivate::deleteFolder(const QMailFolderId &folderId)
{
    Q_ASSERT(!_pendingActions.count());
    deleteFolderHelper(folderId);
}

void QMailStorageActionPrivate::init()
{
    QMailServiceActionPrivate::init();

    _ids.clear();
}

void QMailStorageActionPrivate::messagesEffected(quint64 action, const QMailMessageIdList &ids)
{
    if (validAction(action)) {
        foreach (const QMailMessageId &id, ids)
            _ids.removeAll(id);
    }
}

void QMailStorageActionPrivate::messagesAdded(quint64 action, const QMailMessageIdList &ids)
{
    if (validAction(action)) {
        _addedOrUpdatedIds.append(ids);
    }
}

void QMailStorageActionPrivate::messagesUpdated(quint64 action, const QMailMessageIdList &ids)
{
    if (validAction(action)) {
        _addedOrUpdatedIds.append(ids);
    }
}

void QMailStorageActionPrivate::storageActionCompleted(quint64 action)
{
    if (validAction(action)) {
        QMailServiceAction::Activity result(_ids.isEmpty() ? QMailServiceAction::Successful : QMailServiceAction::Failed);
        setActivity(result);
        emitChanges();
    }
}


/*!
    \class QMailStorageAction

    \preliminary
    \ingroup messaginglibrary

    \brief The QMailStorageAction class provides the interface for requesting operations on the
    storage of messages within external message services.

    QMailStorageAction provides the mechanism for messaging clients to request that the message
    server move or copy messages within an external message service.  The storage action object 
    reports on the progress and outcome of its activities via the signals inherited from QMailServiceAction.

    The copyMessages() slot requests that the message server create a copy of each identified 
    message in the nominated destination folder.  The moveMessages() slot requests that the 
    message server move each identified message from its current location to the nominated destination 
    folder.  Messages cannot be moved or copied between accounts.
    
    A QMailServiceAction instance supports only a single request at a time. Attempting 
    to initiate an operation on a QMailServiceAction while another operation is already 
    in progress for that action is not supported. Instead clients should use multiple 
    QMailServiceAction instances to initiate a queue of requests.
*/

/*!
    \typedef QMailStorageAction::ImplementationType
    \internal
*/

/*!
    Constructs a new transmit action object with the supplied \a parent.
*/
QMailStorageAction::QMailStorageAction(QObject *parent)
    : QMailServiceAction(new QMailStorageActionPrivate(this), parent)
{
}

/*! \internal */
QMailStorageAction::~QMailStorageAction()
{
}

/*!
    Requests that the message server delete the messages listed in \a ids, both from the local device 
    and the external message source.  Whether the external messages resources are actually removed is 
    at the discretion of the relevant QMailMessageSource object.
*/
void QMailStorageAction::deleteMessages(const QMailMessageIdList &ids)
{
    impl(this)->deleteMessages(ids);
}

/*!
    Requests that the message server delete the messages listed in \a ids from the local device only.
*/
void QMailStorageAction::discardMessages(const QMailMessageIdList &ids)
{
    impl(this)->discardMessages(ids);
}

/*!
    Requests that the message server create a new copy of each message listed in \a ids within the folder 
    identified by \a destinationId.
*/
void QMailStorageAction::copyMessages(const QMailMessageIdList &ids, const QMailFolderId &destinationId)
{
    impl(this)->copyMessages(ids, destinationId);
}

/*!
    Requests that the message server move each message listed in \a ids from its current location 
    to the folder identified by \a destinationId.
*/
void QMailStorageAction::moveMessages(const QMailMessageIdList &ids, const QMailFolderId &destinationId)
{
    impl(this)->moveMessages(ids, destinationId);
}

/*!
    Requests that the message server flag each message listed in \a ids, by setting any status flags
    set in the \a setMask, and unsetting any status flags set in the \a unsetMask.  The status
    flag values should correspond to those of QMailMessage::status().

    The service implementing the account may choose to take further actions in response to flag
    changes, such as moving or deleting messages.

    \sa QMailMessage::setStatus(), QMailStore::updateMessagesMetaData()
*/
void QMailStorageAction::flagMessages(const QMailMessageIdList &ids, quint64 setMask, quint64 unsetMask)
{
    impl(this)->flagMessages(ids, setMask, unsetMask);
}

/*!
    Requests that the message server add \a messages to the mail store.

    The messages will be added asynchronously.

    All messages must use the same content scheme.

    \sa QMailStorageAction::messagesAdded, QMailMessageData::contentScheme
*/
void QMailStorageAction::addMessages(const QMailMessageList &messages)
{
    impl(this)->addMessages(messages);
}

/*!
    Returns the ids of the messages added to the mail store.
*/
QMailMessageIdList QMailStorageAction::messagesAdded() const
{
    return impl(this)->_addedOrUpdatedIds;
}

/*!
    Requests that the message server update \a messages in the mail store.

    The messages will be updated asynchronously.

    All messages must use the same content scheme.

    \sa QMailStorageAction::messagesUpdated, QMailMessageData::contentScheme
*/
void QMailStorageAction::updateMessages(const QMailMessageList &messages)
{
    impl(this)->updateMessages(messages);
}

/*!
    Requests that the message server updates the meta data of the existing 
    messages in the message store, to match each of the messages listed in 
    \a messages.

    The messages will be updated asynchronously.

    All messages must use the same content scheme.

    \sa QMailStorageAction::messagesUpdated, QMailMessageData::contentScheme
*/
void QMailStorageAction::updateMessages(const QMailMessageMetaDataList &messages)
{
    impl(this)->updateMessages(messages);
}

/*!
    Returns the ids of the messages updated in the mail store.
*/
QMailMessageIdList QMailStorageAction::messagesUpdated() const
{
    return impl(this)->_addedOrUpdatedIds;
}

/*!
    Requests that the message server create a new folder named \a name, created in the
    account identified by \a accountId.
    If \a parentId is a valid folder identifier the new folder will be a child of the parent;
    otherwise the folder will be have no parent and will be created at the highest level.

    \sa deleteFolder()
*/
void QMailStorageAction::createFolder(const QString &name, const QMailAccountId &accountId, const QMailFolderId &parentId)
{
    impl(this)->createFolder(name, accountId, parentId);
}

/*!
    Requests that the message server rename the folder identified by \a folderId to \a name.

    \sa createFolder()
*/
void QMailStorageAction::renameFolder(const QMailFolderId &folderId, const QString &name)
{
    impl(this)->renameFolder(folderId, name);
}

/*!
    Requests that the message server delete the folder identified by \a folderId.
    Any existing folders or messages contained by the folder will also be deleted.

    \sa createFolder(), renameFolder()
*/
void QMailStorageAction::deleteFolder(const QMailFolderId &folderId)
{
    impl(this)->deleteFolder(folderId);
}


QMailSearchActionPrivate::QMailSearchActionPrivate(QMailSearchAction *i)
    : QMailServiceActionPrivate(this, i)
{
    connect(_server, SIGNAL(matchingMessageIds(quint64, QMailMessageIdList)),
            this, SLOT(matchingMessageIds(quint64, QMailMessageIdList)));
    connect(_server, SIGNAL(searchCompleted(quint64)),
            this, SLOT(searchCompleted(quint64)));

    init();
}

QMailSearchActionPrivate::~QMailSearchActionPrivate()
{
    QMailMessageKey temporaryMessages = QMailMessageKey::status(QMailMessage::Temporary) & QMailMessageKey::id(_matchingIds);
    QMailStore::instance()->removeMessages(temporaryMessages, QMailStore::NoRemovalRecord);
}

void QMailSearchActionPrivate::searchMessages(const QMailMessageKey &filter, const QString &bodyText, QMailSearchAction::SearchSpecification spec, const QMailMessageSortKey &sort)
{
    _server->searchMessages(newAction(), filter, bodyText, spec, sort);
    emitChanges();
}

void QMailSearchActionPrivate::cancelOperation()
{
    Q_ASSERT(_isValid && _action != 0);
    if (_isValid)
        _server->cancelSearch(_action);
}

void QMailSearchActionPrivate::init()
{
    QMailServiceActionPrivate::init();

    _matchingIds.clear();
}

void QMailSearchActionPrivate::matchingMessageIds(quint64 action, const QMailMessageIdList &ids)
{
    if (validAction(action)) {
        _matchingIds += ids;

        emit messageIdsMatched(ids);
    }
}

void QMailSearchActionPrivate::searchCompleted(quint64 action)
{
    if (validAction(action)) {
        setActivity(QMailServiceAction::Successful);
        emitChanges();
    }
}

void QMailSearchActionPrivate::finaliseSearch()
{
    emit messageIdsMatched(_matchingIds);

    setActivity(QMailServiceAction::Successful);
    emitChanges();
}


/*!
    \class QMailSearchAction

    \preliminary
    \ingroup messaginglibrary

    \brief The QMailSearchAction class provides the interface for identifying messages that match a set of search criteria.

    QMailSearchAction provides the mechanism for messaging clients to request that the message
    server perform a search for messages that match the supplied search criteria.  For criteria
    pertaining to message meta data, the message server will search within the locally held
    meta data.  For a textual content criterion, the message server will search locally where
    the message content is held locally, and on the external server for messages whose content
    has not been retrieved (provided the external service provides a search facility).
*/

/*!
    \enum QMailSearchAction::SearchSpecification

    This enum type is specify the form of search that the message server should perform.

    \value Local    Only the message data stored on the local device should be searched.
    \value Remote   The search should be extended to message data stored on external servers.
*/

/*!
    \typedef QMailSearchAction::ImplementationType
    \internal
*/

/*!
    Constructs a new search action object with the supplied \a parent.
*/
QMailSearchAction::QMailSearchAction(QObject *parent)
    : QMailServiceAction(new QMailSearchActionPrivate(this), parent)
{
    connect(impl(this), SIGNAL(messageIdsMatched(QMailMessageIdList)), this, SIGNAL(messageIdsMatched(QMailMessageIdList)));
}

/*! \internal */
QMailSearchAction::~QMailSearchAction()
{
}

/*!
    Requests that the message server identify all messages that match the criteria
    specified by \a filter.  If \a bodyText is non-empty, identified messages must
    also contain the supplied text in their content.  

    If \a spec is \l{QMailSearchAction::Remote}{Remote}, then the external service 
    will be requested to perform the search for messages not stored locally. 

    If \a sort is not empty, the external service will return matching messages in 
    the ordering indicated by the sort criterion if possible.
*/
void QMailSearchAction::searchMessages(const QMailMessageKey &filter, const QString &bodyText, SearchSpecification spec, const QMailMessageSortKey &sort)
{
    impl(this)->searchMessages(filter, bodyText, spec, sort);
}

/*!
    Attempts to cancel the last requested search operation.
*/
void QMailSearchAction::cancelOperation()
{
    impl(this)->cancelOperation();
}

/*!
    Returns the list of message identifiers found to match the search criteria.
    Unless activity() returns \l Successful, an empty list is returned.
*/
QMailMessageIdList QMailSearchAction::matchingMessageIds() const
{
    return impl(this)->_matchingIds;
}

/*!
    Returns a key matching messages that are temporary messages existing only as 
    the result of a search action.
*/
QMailMessageKey QMailSearchAction::temporaryKey()
{
    return QMailMessageKey::status(QMailMessage::Temporary);
}

/*!
    \fn QMailSearchAction::messageIdsMatched(const QMailMessageIdList &ids)

    This signal is emitted when the messages in \a ids are discovered to match
    the criteria of the search in progress.

    \sa matchingMessageIds()
*/

QMailActionInfoPrivate::QMailActionInfoPrivate(quint64 action, QMailServerRequestType requestType, QMailActionInfo *i)
    : QMailServiceActionPrivate(this, i),
      _requestType(requestType),
      _actionCompleted(false)
{
    setAction(action);

    // Service handler really should be sending the activity,
    // rather than us faking it..
    connect(_server, SIGNAL(retrievalCompleted(quint64)),
            this, SLOT(activityCompleted(quint64)));
    connect(_server, SIGNAL(storageActionCompleted(quint64)),
            this, SLOT(activityCompleted(quint64)));
    connect(_server, SIGNAL(searchCompleted(quint64)),
            this, SLOT(activityCompleted(quint64)));
    connect(_server, SIGNAL(transmissionCompleted(quint64)),
            this, SLOT(activityCompleted(quint64)));

    init();
}

void QMailActionInfoPrivate::activityCompleted(quint64 action)
{
    if (validAction(action)) {
        setActivity(QMailServiceAction::Successful);
        emitChanges();
    }
}

float QMailActionInfoPrivate::totalProgress() const
{
    if (_total == 0)
        return 0.0;
    else
        return static_cast<float>(_progress) / _total;
}

void QMailActionInfoPrivate::theProgressChanged(uint, uint)
{
    emit totalProgressChanged(totalProgress());
}

void QMailActionInfoPrivate::theStatusChanged(const QMailServiceAction::Status &newStatus)
{
    if (_lastStatus.accountId != newStatus.accountId)
        emit statusAccountIdChanged(newStatus.accountId);
    if (_lastStatus.errorCode != newStatus.errorCode)
        emit statusErrorCodeChanged(newStatus.errorCode);
    if (_lastStatus.folderId != newStatus.folderId)
        emit statusFolderIdChanged(newStatus.folderId);
    if (_lastStatus.messageId != newStatus.messageId)
        emit statusMessageIdChanged(newStatus.messageId);

    _lastStatus = newStatus;
}

quint64 QMailActionInfoPrivate::actionId() const
{
    return _action;
}

QMailServerRequestType QMailActionInfoPrivate::requestType() const
{
    return _requestType;
}

QMailActionInfo::Status::ErrorCode QMailActionInfoPrivate::statusErrorCode() const
{
    return _status.errorCode;
}

QString QMailActionInfoPrivate::statusText() const
{
    return _status.text;
}

QMailAccountId QMailActionInfoPrivate::statusAccountId() const
{
    return _status.accountId;
}
QMailFolderId QMailActionInfoPrivate::statusFolderId() const
{
    return _status.folderId;
}

QMailMessageId QMailActionInfoPrivate::statusMessageId() const
{
    return _status.messageId;
}

/*!
    \class QMailActionInfo

    \preliminary
    \ingroup messaginglibrary

    \brief The QMailActionInfo class provides the interface for tracking individual actions

    QMailActionInfo provides the mechanism for messaging clients to track an action that is
    or has run on the server. QMailActionInfo objects can only be created by QMailActionObserver
    and derive most of their functionality and signals from \l QMailServiceAction.

    QMailActionInfo presents \l requestType() and \l id() to the the client. For future QML
    interoperability properties and notification signals have been added.
*/

/*!
    \typedef QMailActionInfo::ImplementationType
    \internal
*/

/*!
    \typedef QMailActionInfo::StatusErrorCode

    A typedef for QMailServiceAction::Status::ErrorCode so moc can parse it
*/

/*!
  \fn QMailActionInfo::statusErrorCodeChanged(QMailActionInfo::StatusErrorCode error)

  Signal emitted when \l statusErrorCode() has changed to a new value of \a error
*/

/*!
  \fn QMailActionInfo::statusTextChanged(const QString &text)

  Signal emittted when \l statusText() has changed to a new \a text.
*/

/*!
  \fn QMailActionInfo::statusAccountIdChanged(const QMailAccountId &accountId)

  Signal emitted when \l statusAccountId() has changed to a new \a accountId.
*/

/*!
  \fn QMailActionInfo::statusFolderIdChanged(const QMailFolderId &folderId)

  Signal emitted when \l statusFolderId() has changed to a new \a folderId.
*/

/*!
  \fn QMailActionInfo::statusMessageIdChanged(const QMailMessageId &messageId)

  Signal emitted when \l statusMessageId() has changed to a new \a messageId.
*/

/*!
    \fn QMailActionInfo::totalProgressChanged(float progress)

    Signal emitted when \l totalProgress() has changed to a new \a progress.
*/

/*! \internal */
QMailActionInfo::QMailActionInfo(quint64 action, QMailServerRequestType description)
    : QMailServiceAction(new QMailActionInfoPrivate(action, description, this), 0) // NB: No qobject parent!
{
    connect(impl(this), SIGNAL(statusAccountIdChanged(QMailAccountId)),
            this, SIGNAL(statusAccountIdChanged(QMailAccountId)));
    connect(impl(this), SIGNAL(statusErrorCodeChanged(QMailActionInfo::StatusErrorCode)),
             this, SIGNAL(statusErrorCodeChanged(QMailActionInfo::StatusErrorCode)));
    connect(impl(this), SIGNAL(statusTextChanged(QString)),
            this, SIGNAL(statusTextChanged(QString)));
    connect(impl(this), SIGNAL(statusFolderIdChanged(QMailFolderId)),
            this, SIGNAL(statusFolderIdChanged(QMailFolderId)));
    connect(impl(this), SIGNAL(statusMessageIdChanged(QMailMessageId)),
            this, SIGNAL(statusMessageIdChanged(QMailMessageId)));

    // Hack to get around _interface not being "ready" in the private class
    connect(this, SIGNAL(progressChanged(uint,uint)), impl(this), SLOT(theProgressChanged(uint,uint)));
    connect(this, SIGNAL(statusChanged(QMailServiceAction::Status)), impl(this), SLOT(theStatusChanged(QMailServiceAction::Status)));

}

/*!
    \fn QMailActionInfo::requestType() const
    Returns the \c QMailServiceRequestType of action is it tracking
*/
QMailServerRequestType QMailActionInfo::requestType() const
{
    return impl(this)->requestType();
}

/*!
    Returns the unique action id that was assigned to the action QMailActionInfo is tracking
*/
quint64 QMailActionInfo::id() const
{
    return impl(this)->actionId();
}

/*!
    \fn QMailActionInfo::totalProgress() const
    Returns a floating point between (0..1) indicating the actions progress. This is a convience
    method to \l QMailServiceAction::progress()
*/
float QMailActionInfo::totalProgress() const
{
    return impl(this)->totalProgress();
}

/*!
  \fn QMailActionInfo::statusErrorCode() const
  This is a convience accessor to \l QMailServiceAction::Status::errorCode
*/
QMailActionInfo::StatusErrorCode QMailActionInfo::statusErrorCode() const
{
    return impl(this)->statusErrorCode();
}

/*!
  \fn QMailActionInfo::statusText() const
  This is a convience accessor to \l QMailServiceAction::Status::text
*/
QString QMailActionInfo::statusText() const
{
    return impl(this)->statusText();
}

/*!
  \fn QMailActionInfo::statusAccountId() const
  This is a convience accessor to \l QMailServiceAction::Status::accountId
*/
QMailAccountId QMailActionInfo::statusAccountId() const
{
    return impl(this)->statusAccountId();
}

/*!
  \fn QMailActionInfo::statusFolderId() const
  This is a convience accessor to \l QMailServiceAction::Status::errorCode
*/
QMailFolderId QMailActionInfo::statusFolderId() const
{
    return impl(this)->statusFolderId();
}

/*!
  \fn QMailActionInfo::statusMessageId() const
  This is a convience accessor for \l QMailServiceAction::Status::messageId
*/

QMailMessageId QMailActionInfo::statusMessageId() const
{
    return impl(this)->statusMessageId();
}

QMailActionObserverPrivate::QMailActionObserverPrivate(QMailActionObserver *i)
    : QMailServiceActionPrivate(this, i),
      _isReady(false)
{
    connect(_server, SIGNAL(actionStarted(QMailActionData)),
            this, SLOT(actionStarted(QMailActionData)));
    connect(_server, SIGNAL(actionsListed(QMailActionDataList)),
            this, SLOT(actionsListed(QMailActionDataList)));

    _server->listActions();

    init();
}

QList< QSharedPointer<QMailActionInfo> > QMailActionObserverPrivate::runningActions() const
{
    return _runningActions.values();
}

void QMailActionObserverPrivate::listActionsRequest()
{
    _server->listActions();
}

void QMailActionObserverPrivate::actionsListed(const QMailActionDataList &actions)
{
    if (_isReady)
        _runningActions.clear();
    else
		_isReady = true;

    Q_ASSERT(_runningActions.isEmpty());

    foreach (QMailActionData const& action, actions) {
       addAction(action);
    }

    _isReady = true;
    emit actionsChanged(runningActions());
}

void QMailActionObserverPrivate::removeOldActions()
{
    Q_ASSERT(_isReady);
    bool changed(false);
    while(!_delayRemoveList.isEmpty()) {
        _runningActions.remove(_delayRemoveList.takeFirst());
        changed = true;
    }

    if (changed)
        emit actionsChanged(runningActions());
}

void QMailActionObserverPrivate::actionStarted(const QMailActionData &action)
{
    if (_isReady) {
        addAction(action);
        emit actionsChanged(runningActions());
    }
}

QSharedPointer<QMailActionInfo> QMailActionObserverPrivate::addAction(const QMailActionData &action)
{
        QSharedPointer<QMailActionInfo> actionInfo(new QMailActionInfo(action.first, action.second));
        connect(actionInfo.data(), SIGNAL(activityChanged(QMailServiceAction::Activity)),
                this, SLOT(anActionActivityChanged(QMailServiceAction::Activity)));
        _runningActions.insert(action.first, actionInfo);

        return actionInfo;
}

void QMailActionObserverPrivate::anActionActivityChanged(QMailServiceAction::Activity activity)
{
    const QMailActionInfo *theAction(qobject_cast<QMailActionInfo *>(sender()));
    if (theAction) {
        if (activity == QMailServiceAction::Successful || activity == QMailServiceAction::Failed) {
            // Avoid possibly deleting from within its own signal
            _delayRemoveList.append(theAction->id());
            QTimer::singleShot(0, this, SLOT(removeOldActions()));
        }
    } else {
        qWarning() << "Unable to determine who sent signal";
    }
}

/*! \class QMailActionObserver

   \preliminary
   \ingroup messaginglibrary

   \brief The QMailActionObserver class provides an interface for monitoring currently running actions

    QMailActionObserver provides a mechanism for messaging clients to observe what actions
    the messageserver is currently running. A list of currently running actions can be retrieved
    with \l actions(). When actions are started or finished \l actionsChanged() is emitted with the
    new list of actions.

    QMailActionObserver is initialised asynchronously, thus reading \l actions() immediately will
    return an empty list.
*/

/*!
    \typedef QMailActionObserver::ImplementationType
    \internal
*/

/*!
    \fn QMailActionObserver::actionsChanged(const QList< QSharedPointer<QMailActionInfo> > &newActions)

    This signal is emitted whenever the list of actions we are observing changes. This can be
    for three reasons: actions have started, actions have finished or the action list has just been
    initialized.

    New list given by \a newActions

    \sa actions()

*/

/*! Constructs a new QMailActionObserver with a supplied \a parent  */
QMailActionObserver::QMailActionObserver(QObject *parent)
    : QMailServiceAction(new QMailActionObserverPrivate(this), parent)
{
    connect(impl(this), SIGNAL(actionsChanged(QList<QSharedPointer<QMailActionInfo> >)), this,
            SIGNAL(actionsChanged(QList<QSharedPointer<QMailActionInfo> >)));
}

/*! Destructs QMailActionObserver */
QMailActionObserver::~QMailActionObserver()
{
}

/*!
    \fn QMailActionObserver::actions() const
    Returns a list of the currently running actions on the message server.

    \sa QMailActionInfo
*/
QList< QSharedPointer<QMailActionInfo> > QMailActionObserver::actions() const
{
    return impl(this)->runningActions();
}

/*!
    \fn QMailActionObserver::listActionsRequest()
    Makes request of running actions. Result will be returned with actionsChanged() signal.
*/
void QMailActionObserver::listActionsRequest()
{
    impl(this)->listActionsRequest();
}

QMailProtocolActionPrivate::QMailProtocolActionPrivate(QMailProtocolAction *i)
    : QMailServiceActionPrivate(this, i)
{
    connect(_server, SIGNAL(protocolResponse(quint64, QString, QVariant)),
            this, SLOT(protocolResponse(quint64, QString, QVariant)));
    connect(_server, SIGNAL(protocolRequestCompleted(quint64)),
            this, SLOT(protocolRequestCompleted(quint64)));

    init();
}

void QMailProtocolActionPrivate::protocolRequest(const QMailAccountId &accountId, const QString &request, const QVariant &data)
{
    _server->protocolRequest(newAction(), accountId, request, data);
}

void QMailProtocolActionPrivate::protocolResponse(quint64 action, const QString &response, const QVariant &data)
{
    if (validAction(action)) {
        emit protocolResponse(response, data);
    }
}

void QMailProtocolActionPrivate::protocolRequestCompleted(quint64 action)
{
    if (validAction(action)) {
        setActivity(QMailServiceAction::Successful);
        emitChanges();
    }
}


/*!
    \class QMailProtocolAction

    \preliminary
    \ingroup messaginglibrary

    \brief The QMailProtocolAction class provides a mechanism for messageserver clients
    and services to collaborate without messageserver involvement.

    QMailProtocolAction provides a mechanism for messaging clients to request actions from
    message services that are not implemented by the messageserver.  If a client can
    determine that the service implementing a specific account supports a particular
    operation (by inspecting the output of QMailAccount::messageSources()), it may
    invoke that operation by passing appropriately formatted data to the service via the
    protocolRequest() slot.

    If the service is able to provide the requested service, and extract the necessary 
    data from the received input, it should perform the requested operation.  If any
    output is produced, it may be passed back to the client application via the 
    protocolResponse() signal.
*/

/*!
    \typedef QMailProtocolAction::ImplementationType
    \internal
*/

/*!
    Constructs a new protocol action object with the supplied \a parent.
*/
QMailProtocolAction::QMailProtocolAction(QObject *parent)
    : QMailServiceAction(new QMailProtocolActionPrivate(this), parent)
{
    connect(impl(this), SIGNAL(protocolResponse(QString, QVariant)), this, SIGNAL(protocolResponse(QString, QVariant)));
}

/*! \internal */
QMailProtocolAction::~QMailProtocolAction()
{
}

/*!
    Requests that the message server forward the protocol-specific request \a request
    to the QMailMessageSource configured for the account identified by \a accountId.
    The request may have associated \a data, in a protocol-specific form.
*/
void QMailProtocolAction::protocolRequest(const QMailAccountId &accountId, const QString &request, const QVariant &data)
{
    impl(this)->protocolRequest(accountId, request, data);
}

/*!
    \fn QMailProtocolAction::protocolResponse(const QString &response, const QVariant &data)

    This signal is emitted when the response \a response is emitted by the messageserver,
    with the associated \a data.
*/