summaryrefslogtreecommitdiffstats
path: root/src/organizer/qorganizermanagerengine.cpp
blob: 3036e8134c103492723dd9f22eff3c183bd17375 (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
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
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $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 "qorganizermanagerengine.h"
#include "qorganizeritemengineid.h"

#include "qorganizeritemdetaildefinition.h"
#include "qorganizeritemdetailfielddefinition.h"
#include "qorganizeritemdetails.h"
#include "qorganizeritemsortorder.h"
#include "qorganizeritemfilters.h"
#include "qorganizerabstractrequest.h"
#include "qorganizerabstractrequest_p.h"
#include "qorganizeritemrequests.h"
#include "qorganizeritemrequests_p.h"
#include "qorganizeritem.h"
#include "qorganizeritemfetchhint.h"

#include "qorganizercollection_p.h"
#include "qorganizeritem_p.h"
#include "qorganizeritemdetail_p.h"

QTM_BEGIN_NAMESPACE

/*!
  \class QOrganizerManagerEngine
  \brief The QOrganizerManagerEngine class provides the interface for all
  implementations of the organizer item manager backend functionality.

  \inmodule QtOrganizer
  \ingroup organizer-backends

  Instances of this class are usually provided by a
  \l QOrganizerManagerEngineFactory, which is loaded from a plugin.

  The default implementation of this interface provides a basic
  level of functionality for some functions so that specific engines
  can simply implement the functionality that is supported by
  the specific organizer items engine that is being adapted.

  More information on writing an organizer engine plugin is available in
  the \l{Qt Organizer Manager Engines} documentation.

  Engines that support the QOrganizerManagerEngine interface but not the
  QOrganizerManagerEngineV2 interface will be wrapped by the QOrganizerManager
  by a class that emulates the extra functionality of the
  QOrganizerManagerEngineV2 interface.

  The additional features of a V2 engine compared to the original QOrganizerManagerEngine are:
  \list
  \o The items function which takes a \i{maxCount} parameter
  \o The result of the items functions must be sorted by date according to the sort order defined by
     \l itemLessThan
  \o The corresponding changes to QOrganizerItemFetchRequest
  \endlist

  \sa QOrganizerManager, QOrganizerManagerEngineFactory
 */

/*!
  \fn QOrganizerManagerEngine::QOrganizerManagerEngine()

  A default, empty constructor.
 */

/*!
  \fn QOrganizerManagerEngine::dataChanged()

  This signal is emitted some time after changes occur to the data managed by this
  engine, and the engine is unable to determine which changes occurred, or if the
  engine considers the changes to be radical enough to require clients to reload all data.

  If this signal is emitted, no other signals may be emitted for the associated changes.

  As it is possible that other processes (or other devices) may have caused the
  changes, the timing can not be determined.

  \sa itemsAdded(), itemsChanged(), itemsRemoved()
 */

/*!
  \fn QOrganizerManagerEngine::itemsAdded(const QList<QOrganizerItemId>& organizeritemIds);

  This signal is emitted some time after a set of organizer items has been added to
  this engine where the \l dataChanged() signal was not emitted for those changes.
  As it is possible that other processes (or other devices) may
  have added the organizer items, the timing cannot be determined.

  The list of ids of organizer items added is given by \a organizeritemIds.  There may be one or more
  ids in the list.

  \sa dataChanged()
 */

/*!
  \fn QOrganizerManagerEngine::itemsChanged(const QList<QOrganizerItemId>& organizeritemIds);

  This signal is emitted some time after a set of organizer items has been modified in
  this engine where the \l dataChanged() signal was not emitted for those changes.
  As it is possible that other processes (or other devices) may
  have modified the organizer items, the timing cannot be determined.

  The list of ids of changed organizer items is given by \a organizeritemIds.  There may be one or more
  ids in the list.

  \sa dataChanged()
 */

/*!
  \fn QOrganizerManagerEngine::itemsRemoved(const QList<QOrganizerItemId>& organizeritemIds);

  This signal is emitted some time after a set of organizer items has been removed from
  this engine where the \l dataChanged() signal was not emitted for those changes.
  As it is possible that other processes (or other devices) may
  have removed the organizer items, the timing cannot be determined.

  The list of ids of removed organizer items is given by \a organizeritemIds.  There may be one or more
  ids in the list.

  \sa dataChanged()
 */

/*!
  \fn QOrganizerManagerEngine::collectionsAdded(const QList<QOrganizerCollectionId>& collectionIds)
  This signal should be emitted at some point once the collections identified by \a collectionIds have been added to a datastore managed by this engine.
  This signal must not be emitted if the dataChanged() signal was previously emitted for these changes.
 */

/*!
  \fn QOrganizerManagerEngine::collectionsChanged(const QList<QOrganizerCollectionId>& collectionIds)
  This signal should be emitted at some point once the metadata for the collections identified by \a collectionIds have been modified in a datastore managed by this engine.
  This signal is not emitted if one of the items in this collection has changed - itemsChanged() will be emitted instead.
  This signal must not be emitted if the dataChanged() signal was previously emitted for these changes.
 */

/*!
  \fn QOrganizerManagerEngine::collectionsRemoved(const QList<QOrganizerCollectionId>& collectionIds)
  This signal should be emitted at some point once the collections identified by \a collectionIds have been removed from a datastore managed by this engine.
  This signal must not be emitted if the dataChanged() signal was previously emitted for these changes.
 */



/*! Returns the manager name for this QOrganizerManagerEngine */
QString QOrganizerManagerEngine::managerName() const
{
    return QString(QLatin1String("base"));
}

/*!
  Returns the parameters with which this engine was constructed.  Note that
  the engine may have discarded unused or invalid parameters at the time of
  construction, and these will not be returned.
 */
QMap<QString, QString> QOrganizerManagerEngine::managerParameters() const
{
    return QMap<QString, QString>(); // default implementation requires no parameters.
}

/*!
  Returns the unique URI of this manager, which is built from the manager name and the parameters
  used to construct it.
 */
QString QOrganizerManagerEngine::managerUri() const
{
    return QOrganizerManager::buildUri(managerName(), managerParameters());
}

/*!
  Return the list of a maximum of \a maxCount organizer item instances which are occurrences of the
  given \a parentItem recurring item, which occur between the given \a periodStart date and the given
  \a periodEnd date.

  If \a periodStart is after \a periodEnd, the operation will fail, and \a error will be set to \c
  QOrganizerManager::BadArgumentError.
  If \a maxCount is negative, it is backend specific as to how many occurrences will be returned.
  Some backends may return no instances, others may return some limited number of occurrences.

  If the \a parentItem is an item of type QOrganizerItemType::TypeEvent, a list of items of type
  QOrganizerItemType::TypeEventOccurrence will be returned, representing the expansion of the
  parent item according to its QOrganizerItemRecurrence detail.  Similarly, a \a parentItem of type
  QOrganizerItemType::TypeTodo will result in a list of QOrganizerItemType::TypeTodoOccurrence
  items.  If the \a parentItem is of any other type, it is returned by itself from the backend.

  The occurrence-typed items returned should have a QOrganizerItemParent detail that refers
  to the parent item and the original instance that the event would have occurred on (if it is an
  exception).  No returned item should contain a QOrganizerItemRecurrence detail.

  If the \a parentItem does not exist in the backend, or if there are no instances matching the
  criteria, an empty list should be returned.

  The \a fetchHint parameter is a hint to the manager about which details the client is interested
  in.  It allows the manager to optimize retrieval of occurrences.  The manager may ignore the
  \a fetchHint, but if it does so each item occurrence it returns must include all of the details
  associated with it in the database.
  */
QList<QOrganizerItem> QOrganizerManagerEngine::itemOccurrences(const QOrganizerItem& parentItem, const QDateTime& periodStart, const QDateTime& periodEnd, int maxCount, const QOrganizerItemFetchHint& fetchHint, QOrganizerManager::Error* error) const
{
    Q_UNUSED(parentItem);
    Q_UNUSED(periodStart);
    Q_UNUSED(periodEnd);
    Q_UNUSED(maxCount);
    Q_UNUSED(fetchHint);

    *error = QOrganizerManager::NotSupportedError;
    return QList<QOrganizerItem>();
}

/*!
  Returns a list of organizer item ids that match the given \a filter, sorted according to the given
  list of \a sortOrders, for any item which occurs (or has an occurrence which occurs) in the range
  specified by the given \a startDate and \a endDate.  A default-constructed (invalid) \a startDate
  specifies an open start date (matches anything which occurs up until the \a endDate), and a
  default-constructed (invalid) \a endDate specifies an open end date (matches anything which occurs
  after the \a startDate).  If both the \a startDate and \a endDate are invalid, this function will
  return the ids of all items which match the \a filter criteria.

  Depending on the backend, this filtering operation may involve retrieving
  all the organizer items.  Any error which occurs will be saved in \a error.
 */
QList<QOrganizerItemId> QOrganizerManagerEngine::itemIds(const QDateTime& startDate, const QDateTime& endDate, const QOrganizerItemFilter& filter, const QList<QOrganizerItemSortOrder>& sortOrders, QOrganizerManager::Error* error) const
{
    Q_UNUSED(startDate);
    Q_UNUSED(endDate);
    Q_UNUSED(filter);
    Q_UNUSED(sortOrders);

    *error = QOrganizerManager::NotSupportedError;
    return QList<QOrganizerItemId>();
}

/*!
  Returns the list of organizer items which match the given \a filter stored in the manager sorted according to the given list of \a sortOrders,
  for any item or item occurrence which occurs in the range specified by the given \a startDate and \a endDate.
  A default-constructed (invalid) \a startDate specifies an open start date (matches anything which occurs up until the \a endDate),
  and a default-constructed (invalid) \a endDate specifies an open end date (matches anything which occurs after the \a startDate).
  If both the \a startDate and \a endDate are invalid, this function will return all items which match the \a filter criteria.

  Any operation error which occurs will be saved in \a error.

  The \a fetchHint parameter describes the optimization hints that a manager may take.  If the \a
  fetchHint is the default constructed hint, all existing details in the matching organizer items
  will be returned.

  \sa QOrganizerItemFetchHint
 */
QList<QOrganizerItem> QOrganizerManagerEngine::items(const QDateTime& startDate, const QDateTime& endDate, const QOrganizerItemFilter& filter, const QList<QOrganizerItemSortOrder>& sortOrders, const QOrganizerItemFetchHint& fetchHint, QOrganizerManager::Error* error) const
{
    Q_UNUSED(startDate);
    Q_UNUSED(endDate);
    Q_UNUSED(filter);
    Q_UNUSED(sortOrders);
    Q_UNUSED(fetchHint);
    *error = QOrganizerManager::NotSupportedError;
    return QList<QOrganizerItem>();
}

/*!
  Returns the list of organizer items which match the given \a filter stored in the manager sorted according to the given list of \a sortOrders,
  for any persisted item which occurs (or has an occurrence which occurs) in the range specified by the given \a startDate and \a endDate.
  A default-constructed (invalid) \a startDate specifies an open start date (matches anything which occurs up until the \a endDate),
  and a default-constructed (invalid) \a endDate specifies an open end date (matches anything which occurs after the \a startDate).
  If both the \a startDate and \a endDate are invalid, this function will return all items which match the \a filter criteria.

  Any operation error which occurs will be saved in \a error.

  The \a fetchHint parameter describes the optimization hints that a manager may take.  If the \a
  fetchHint is the default constructed hint, all existing details in the matching organizer items
  will be returned.

  Items of type EventOccurrence and TodoOccurrence should only be returned when they represent an
  exceptional occurrence; ie. if the client has specifically saved the item occurrence in the
  manager.  Occurrence-typed items that are generated purely from a recurrence specification of
  another detail should not be returned in this list.

  All items returned should have a non-zero ID.

  \sa QOrganizerItemFetchHint
 */
QList<QOrganizerItem> QOrganizerManagerEngine::itemsForExport(const QDateTime& startDate, const QDateTime& endDate, const QOrganizerItemFilter& filter, const QList<QOrganizerItemSortOrder>& sortOrders, const QOrganizerItemFetchHint& fetchHint, QOrganizerManager::Error* error) const
{
    Q_UNUSED(startDate);
    Q_UNUSED(endDate);
    Q_UNUSED(filter);
    Q_UNUSED(sortOrders);
    Q_UNUSED(fetchHint);
    *error = QOrganizerManager::NotSupportedError;
    return QList<QOrganizerItem>();
}

/*!
  Returns the organizer item in the database identified by \a organizeritemId.

  If the item does not exist, an empty, default constructed QOrganizerItem will be returned,
  and the \a error will be set to  \c QOrganizerManager::DoesNotExistError.

  Any operation error which occurs will be saved in \a error.

  The \a fetchHint parameter describes the optimization hints that a manager may take.  If the \a
  fetchHint is the default constructed hint, all existing details in the matching organizer items
  will be returned.

  \sa QOrganizerItemFetchHint
 */
QOrganizerItem QOrganizerManagerEngine::item(const QOrganizerItemId& organizeritemId, const QOrganizerItemFetchHint& fetchHint, QOrganizerManager::Error* error) const
{
    Q_UNUSED(organizeritemId);
    Q_UNUSED(fetchHint);
    *error = QOrganizerManager::NotSupportedError;
    return QOrganizerItem();
}

/*!
  Returns true if the given \a feature is supported by this engine for organizer items of the given \a organizeritemType
 */
bool QOrganizerManagerEngine::hasFeature(QOrganizerManager::ManagerFeature feature, const QString& organizeritemType) const
{
    Q_UNUSED(feature);
    Q_UNUSED(organizeritemType);

    return false;
}

/*!
  Given an input \a filter, returns the canonical version of the filter.

  Some of the following transformations may be applied:
  \list
   \o Any QOrganizerItemInvalidFilters contained in a union filter will be removed
   \o Any default QOrganizerItemFilters contained in an intersection filter will be removed
   \o Any QOrganizerItemIntersectionFilters with a QOrganizerItemInvalidFilter contained will be
     replaced with a QOrganizerItemInvalidFilter
   \o Any QOrganizerItemUnionFilters with a default QOrganizerItemFilter contained will be replaced
     with a default QOrganizerItemFilter
   \o An empty QOrganizerItemIntersectionFilter will be replaced with a QOrganizerItemDefaultFilter
   \o An empty QOrganizerItemUnionFilter will be replaced with a QOrganizerItemInvalidFilter
   \o An empty QOrganizerItemIdFilter will be replaced with a QOrganizerItemInvalidFilter
   \o An intersection or union filter with a single entry will be replaced by that entry
   \o A QOrganizerItemDetailFilter or QOrganizerItemDetailRangeFilter with no definition name will be replaced with a QOrganizerItemInvalidFilter
   \o A QOrganizerItemDetailRangeFilter with no range specified will be converted to a QOrganizerItemDetailFilter
  \endlist
*/
QOrganizerItemFilter QOrganizerManagerEngine::canonicalizedFilter(const QOrganizerItemFilter &filter)
{
    switch(filter.type()) {
        case QOrganizerItemFilter::IntersectionFilter:
        {
            QOrganizerItemIntersectionFilter f(filter);
            QList<QOrganizerItemFilter> filters = f.filters();
            QList<QOrganizerItemFilter>::iterator it = filters.begin();

            // XXX in theory we can remove duplicates in a set filter
            while (it != filters.end()) {
                QOrganizerItemFilter canon = canonicalizedFilter(*it);
                if (canon.type() == QOrganizerItemFilter::DefaultFilter) {
                    it = filters.erase(it);
                } else if (canon.type() == QOrganizerItemFilter::InvalidFilter) {
                    return QOrganizerItemInvalidFilter();
                } else {
                    *it = canon;
                    ++it;
                }
            }

            if (filters.count() == 0)
                return QOrganizerItemFilter();
            if (filters.count() == 1)
                return filters.first();

            f.setFilters(filters);
            return f;
        }
        // unreachable

        case QOrganizerItemFilter::UnionFilter:
        {
            QOrganizerItemUnionFilter f(filter);
            QList<QOrganizerItemFilter> filters = f.filters();
            QList<QOrganizerItemFilter>::iterator it = filters.begin();

            // XXX in theory we can remove duplicates in a set filter
            while (it != filters.end()) {
                QOrganizerItemFilter canon = canonicalizedFilter(*it);
                if (canon.type() == QOrganizerItemFilter::InvalidFilter) {
                    it = filters.erase(it);
                } else if (canon.type() == QOrganizerItemFilter::DefaultFilter) {
                    return QOrganizerItemFilter();
                } else {
                    *it = canon;
                    ++it;
                }
            }

            if (filters.count() == 0)
                return QOrganizerItemInvalidFilter();
            if (filters.count() == 1)
                return filters.first();

            f.setFilters(filters);
            return f;
        }
        // unreachable

        case QOrganizerItemFilter::IdFilter:
        {
            QOrganizerItemIdFilter f(filter);
            if (f.ids().count() == 0)
                return QOrganizerItemInvalidFilter();
        }
        break; // fall through to return at end

        case QOrganizerItemFilter::OrganizerItemDetailRangeFilter:
        {
            QOrganizerItemDetailRangeFilter f(filter);
            if (f.detailDefinitionName().isEmpty())
                return QOrganizerItemInvalidFilter();
            if (f.minValue() == f.maxValue()
                && f.rangeFlags() == (QOrganizerItemDetailRangeFilter::ExcludeLower | QOrganizerItemDetailRangeFilter::ExcludeUpper))
                return QOrganizerItemInvalidFilter();
            if ((f.minValue().isNull() && f.maxValue().isNull()) || (f.minValue() == f.maxValue())) {
                QOrganizerItemDetailFilter df;
                df.setDetailDefinitionName(f.detailDefinitionName(), f.detailFieldName());
                df.setMatchFlags(f.matchFlags());
                df.setValue(f.minValue());
                return df;
            }
        }
        break; // fall through to return at end

        case QOrganizerItemFilter::OrganizerItemDetailFilter:
        {
            QOrganizerItemDetailFilter f(filter);
            if (f.detailDefinitionName().isEmpty())
                return QOrganizerItemInvalidFilter();
        }
        break; // fall through to return at end

        default:
            break; // fall through to return at end
    }
    return filter;
}


/*!
  Returns a whether the supplied \a filter can be implemented
  natively by this engine.  If not, the base class implementation
  will emulate the functionality.
 */
bool QOrganizerManagerEngine::isFilterSupported(const QOrganizerItemFilter& filter) const
{
    Q_UNUSED(filter);

    return false;
}

/*!
  Returns the list of item types which are supported by this engine.
  This is a convenience function, equivalent to retrieving the allowable values
  for the \c QOrganizerItemType::FieldType field of the QOrganizerItemType definition
  which is valid in this engine.
 */
QStringList QOrganizerManagerEngine::supportedItemTypes() const
{
    QOrganizerManager::Error error;
    // XXX TODO: ensure that the TYPE field value for EVERY SINGLE TYPE contains all possible types...
    // XXX TODO: don't use TypeNote because some collections won't support Notes, only Journals / Events...
    QList<QVariant> allowableVals = detailDefinition(QOrganizerItemType::DefinitionName, QOrganizerItemType::TypeNote, &error).fields().value(QOrganizerItemType::FieldType).allowableValues();
    QStringList retn;
    for (int i = 0; i < allowableVals.size(); i++)
        retn += allowableVals.at(i).toString();
    return retn;
}

/*!
  \fn int QOrganizerManagerEngine::managerVersion() const

  Returns the engine backend implementation version number
 */

/*!
   Returns the default schema definitions for the given \a version of the schema.
   Version 1 of the schema corresponds to version 1.1 of the Qt Mobility APIs.
 */
QMap<QString, QMap<QString, QOrganizerItemDetailDefinition> > QOrganizerManagerEngine::schemaDefinitions(int version)
{
    // This implementation provides the base schema.
    // The schema documentation (organizeritemsschema.qdoc)
    // MUST BE KEPT UP TO DATE as definitions are added here.

    // the map we will eventually return
    QMap<QString, QMap<QString, QOrganizerItemDetailDefinition> > retnSchema;
    QMap<QString, QOrganizerItemDetailDefinition> retn; // each type has a different schema.

    // local variables for reuse
    QMap<QString, QOrganizerItemDetailFieldDefinition> fields;
    QOrganizerItemDetailFieldDefinition f;
    QOrganizerItemDetailDefinition d;

    // build the schema for the NOTEs  =============================
    retn.clear();

    // type
    d.setName(QOrganizerItemType::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList()
                         << QString(QLatin1String(QOrganizerItemType::TypeEvent))
                         << QString(QLatin1String(QOrganizerItemType::TypeEventOccurrence))
                         << QString(QLatin1String(QOrganizerItemType::TypeJournal))
                         << QString(QLatin1String(QOrganizerItemType::TypeNote))
                         << QString(QLatin1String(QOrganizerItemType::TypeTodo))
                         << QString(QLatin1String(QOrganizerItemType::TypeTodoOccurrence)));
    fields.insert(QOrganizerItemType::FieldType, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // guid
    d.setName(QOrganizerItemGuid::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemGuid::FieldGuid, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // timestamp
    d.setName(QOrganizerItemTimestamp::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::DateTime);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemTimestamp::FieldModificationTimestamp, f);
    fields.insert(QOrganizerItemTimestamp::FieldCreationTimestamp, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // display label
    d.setName(QOrganizerItemDisplayLabel::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemDisplayLabel::FieldLabel, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // description
    d.setName(QOrganizerItemDescription::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemDescription::FieldDescription, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // comment
    d.setName(QOrganizerItemComment::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemComment::FieldComment, f);
    d.setFields(fields);
    d.setUnique(false);
    retn.insert(d.name(), d);

    // tag
    d.setName(QOrganizerItemTag::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemTag::FieldTag, f);
    d.setFields(fields);
    d.setUnique(false);
    retn.insert(d.name(), d);

    retnSchema.insert(QOrganizerItemType::TypeNote, retn);

    // and then again for EVENTs =============================
    retn.clear();

    // type
    d.setName(QOrganizerItemType::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList()
                         << QString(QLatin1String(QOrganizerItemType::TypeEvent))
                         << QString(QLatin1String(QOrganizerItemType::TypeEventOccurrence))
                         << QString(QLatin1String(QOrganizerItemType::TypeJournal))
                         << QString(QLatin1String(QOrganizerItemType::TypeNote))
                         << QString(QLatin1String(QOrganizerItemType::TypeTodo))
                         << QString(QLatin1String(QOrganizerItemType::TypeTodoOccurrence)));
    fields.insert(QOrganizerItemType::FieldType, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // guid
    d.setName(QOrganizerItemGuid::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemGuid::FieldGuid, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // timestamp
    d.setName(QOrganizerItemTimestamp::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::DateTime);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemTimestamp::FieldModificationTimestamp, f);
    fields.insert(QOrganizerItemTimestamp::FieldCreationTimestamp, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // display label
    d.setName(QOrganizerItemDisplayLabel::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemDisplayLabel::FieldLabel, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // description
    d.setName(QOrganizerItemDescription::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemDescription::FieldDescription, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // recurrence information
    d.setName(QOrganizerItemRecurrence::DefinitionName);
    fields.clear();
    f.setDataType(qMetaTypeId< QSet<QDate> >());
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemRecurrence::FieldExceptionDates, f);
    fields.insert(QOrganizerItemRecurrence::FieldRecurrenceDates, f);
    f.setDataType(qMetaTypeId< QSet<QOrganizerRecurrenceRule> >());
    fields.insert(QOrganizerItemRecurrence::FieldExceptionRules, f);
    fields.insert(QOrganizerItemRecurrence::FieldRecurrenceRules, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // reminder
    d.setName(QOrganizerItemReminder::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::Int);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemReminder::FieldSecondsBeforeStart, f);
    fields.insert(QOrganizerItemReminder::FieldRepetitionCount, f);
    fields.insert(QOrganizerItemReminder::FieldRepetitionDelay, f);
    d.setFields(fields);
    d.setUnique(false); // can have multiple alarms at different times for the same event
    retn.insert(d.name(), d);

    // audible reminder
    d.setName(QOrganizerItemAudibleReminder::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::Int);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemReminder::FieldSecondsBeforeStart, f);
    fields.insert(QOrganizerItemReminder::FieldRepetitionCount, f);
    fields.insert(QOrganizerItemReminder::FieldRepetitionDelay, f);
    f.setDataType(QVariant::Url);
    fields.insert(QOrganizerItemAudibleReminder::FieldDataUrl, f);
    d.setFields(fields);
    d.setUnique(false); // can have multiple alarms at different times for the same event
    retn.insert(d.name(), d);

    // email reminder
    d.setName(QOrganizerItemEmailReminder::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::Int);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemReminder::FieldSecondsBeforeStart, f);
    fields.insert(QOrganizerItemReminder::FieldRepetitionCount, f);
    fields.insert(QOrganizerItemReminder::FieldRepetitionDelay, f);
    f.setDataType(QVariant::String);
    fields.insert(QOrganizerItemEmailReminder::FieldBody, f);
    fields.insert(QOrganizerItemEmailReminder::FieldSubject, f);
    f.setDataType(QVariant::StringList);
    fields.insert(QOrganizerItemEmailReminder::FieldRecipients, f);
    f.setDataType(QVariant::List);
    fields.insert(QOrganizerItemEmailReminder::FieldAttachments, f);
    d.setFields(fields);
    d.setUnique(false); // can have multiple alarms at different times for the same event
    retn.insert(d.name(), d);

    // visual reminder
    d.setName(QOrganizerItemVisualReminder::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::Int);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemReminder::FieldSecondsBeforeStart, f);
    fields.insert(QOrganizerItemReminder::FieldRepetitionCount, f);
    fields.insert(QOrganizerItemReminder::FieldRepetitionDelay, f);
    f.setDataType(QVariant::String);
    fields.insert(QOrganizerItemVisualReminder::FieldMessage, f);
    f.setDataType(QVariant::Url);
    fields.insert(QOrganizerItemVisualReminder::FieldDataUrl, f);
    d.setFields(fields);
    d.setUnique(false); // can have multiple alarms at different times for the same event
    retn.insert(d.name(), d);

    // event time range
    d.setName(QOrganizerEventTime::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::DateTime);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerEventTime::FieldStartDateTime, f);
    fields.insert(QOrganizerEventTime::FieldEndDateTime, f);
    f.setDataType(QVariant::Bool);
    fields.insert(QOrganizerEventTime::FieldAllDay, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // priority
    d.setName(QOrganizerItemPriority::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::Int);
    f.setAllowableValues(QVariantList()
                         << static_cast<int>(QOrganizerItemPriority::UnknownPriority)
                         << static_cast<int>(QOrganizerItemPriority::HighestPriority)
                         << static_cast<int>(QOrganizerItemPriority::ExtremelyHighPriority)
                         << static_cast<int>(QOrganizerItemPriority::VeryHighPriority)
                         << static_cast<int>(QOrganizerItemPriority::HighPriority)
                         << static_cast<int>(QOrganizerItemPriority::MediumPriority)
                         << static_cast<int>(QOrganizerItemPriority::LowPriority)
                         << static_cast<int>(QOrganizerItemPriority::VeryLowPriority)
                         << static_cast<int>(QOrganizerItemPriority::ExtremelyLowPriority)
                         << static_cast<int>(QOrganizerItemPriority::LowestPriority));
    fields.insert(QOrganizerItemPriority::FieldPriority, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // location
    d.setName(QOrganizerItemLocation::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::Double);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemLocation::FieldLatitude, f);
    fields.insert(QOrganizerItemLocation::FieldLongitude, f);
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemLocation::FieldLabel, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // comment
    d.setName(QOrganizerItemComment::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemComment::FieldComment, f);
    d.setFields(fields);
    d.setUnique(false);
    retn.insert(d.name(), d);

    // tag
    d.setName(QOrganizerItemTag::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemTag::FieldTag, f);
    d.setFields(fields);
    d.setUnique(false);
    retn.insert(d.name(), d);

    retnSchema.insert(QOrganizerItemType::TypeEvent, retn);

    // and then again for EVENTOCCURRENCEs =============================
    retn.clear();

    // type
    d.setName(QOrganizerItemType::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList()
                         << QString(QLatin1String(QOrganizerItemType::TypeEvent))
                         << QString(QLatin1String(QOrganizerItemType::TypeEventOccurrence))
                         << QString(QLatin1String(QOrganizerItemType::TypeJournal))
                         << QString(QLatin1String(QOrganizerItemType::TypeNote))
                         << QString(QLatin1String(QOrganizerItemType::TypeTodo))
                         << QString(QLatin1String(QOrganizerItemType::TypeTodoOccurrence)));
    fields.insert(QOrganizerItemType::FieldType, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // guid
    d.setName(QOrganizerItemGuid::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemGuid::FieldGuid, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // timestamp
    d.setName(QOrganizerItemTimestamp::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::DateTime);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemTimestamp::FieldModificationTimestamp, f);
    fields.insert(QOrganizerItemTimestamp::FieldCreationTimestamp, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // display label
    d.setName(QOrganizerItemDisplayLabel::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemDisplayLabel::FieldLabel, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // description
    d.setName(QOrganizerItemDescription::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemDescription::FieldDescription, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // instance origin
    d.setName(QOrganizerItemParent::DefinitionName);
    fields.clear();
    f.setDataType(qMetaTypeId<QOrganizerItemId>());
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemParent::FieldParentId, f);
    f.setDataType(QVariant::Date);
    fields.insert(QOrganizerItemParent::FieldOriginalDate, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // event time range
    d.setName(QOrganizerEventTime::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::DateTime);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerEventTime::FieldStartDateTime, f);
    fields.insert(QOrganizerEventTime::FieldEndDateTime, f);
    f.setDataType(QVariant::Bool);
    fields.insert(QOrganizerEventTime::FieldAllDay, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // priority
    d.setName(QOrganizerItemPriority::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::Int);
    f.setAllowableValues(QVariantList()
                         << static_cast<int>(QOrganizerItemPriority::UnknownPriority)
                         << static_cast<int>(QOrganizerItemPriority::HighestPriority)
                         << static_cast<int>(QOrganizerItemPriority::ExtremelyHighPriority)
                         << static_cast<int>(QOrganizerItemPriority::VeryHighPriority)
                         << static_cast<int>(QOrganizerItemPriority::HighPriority)
                         << static_cast<int>(QOrganizerItemPriority::MediumPriority)
                         << static_cast<int>(QOrganizerItemPriority::LowPriority)
                         << static_cast<int>(QOrganizerItemPriority::VeryLowPriority)
                         << static_cast<int>(QOrganizerItemPriority::ExtremelyLowPriority)
                         << static_cast<int>(QOrganizerItemPriority::LowestPriority));
    fields.insert(QOrganizerItemPriority::FieldPriority, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // location
    d.setName(QOrganizerItemLocation::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::Double);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemLocation::FieldLatitude, f);
    fields.insert(QOrganizerItemLocation::FieldLongitude, f);
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemLocation::FieldLabel, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // reminder
    d.setName(QOrganizerItemReminder::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::Int);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemReminder::FieldSecondsBeforeStart, f);
    fields.insert(QOrganizerItemReminder::FieldRepetitionCount, f);
    fields.insert(QOrganizerItemReminder::FieldRepetitionDelay, f);
    d.setFields(fields);
    d.setUnique(false); // can have multiple alarms at different times for the same event occurrence
    retn.insert(d.name(), d);

    // audible reminder
    d.setName(QOrganizerItemAudibleReminder::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::Int);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemReminder::FieldSecondsBeforeStart, f);
    fields.insert(QOrganizerItemReminder::FieldRepetitionCount, f);
    fields.insert(QOrganizerItemReminder::FieldRepetitionDelay, f);
    f.setDataType(QVariant::Url);
    fields.insert(QOrganizerItemAudibleReminder::FieldDataUrl, f);
    d.setFields(fields);
    d.setUnique(false); // can have multiple alarms at different times for the same event occurrence
    retn.insert(d.name(), d);

    // email reminder
    d.setName(QOrganizerItemEmailReminder::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::Int);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemReminder::FieldSecondsBeforeStart, f);
    fields.insert(QOrganizerItemReminder::FieldRepetitionCount, f);
    fields.insert(QOrganizerItemReminder::FieldRepetitionDelay, f);
    f.setDataType(QVariant::String);
    fields.insert(QOrganizerItemEmailReminder::FieldBody, f);
    fields.insert(QOrganizerItemEmailReminder::FieldSubject, f);
    f.setDataType(QVariant::StringList);
    fields.insert(QOrganizerItemEmailReminder::FieldRecipients, f);
    f.setDataType(QVariant::List);
    fields.insert(QOrganizerItemEmailReminder::FieldAttachments, f);
    d.setFields(fields);
    d.setUnique(false); // can have multiple alarms at different times for the same event occurrence
    retn.insert(d.name(), d);

    // visual reminder
    d.setName(QOrganizerItemVisualReminder::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::Int);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemReminder::FieldSecondsBeforeStart, f);
    fields.insert(QOrganizerItemReminder::FieldRepetitionCount, f);
    fields.insert(QOrganizerItemReminder::FieldRepetitionDelay, f);
    f.setDataType(QVariant::String);
    fields.insert(QOrganizerItemVisualReminder::FieldMessage, f);
    f.setDataType(QVariant::Url);
    fields.insert(QOrganizerItemVisualReminder::FieldDataUrl, f);
    d.setFields(fields);
    d.setUnique(false); // can have multiple alarms at different times for the same event occurrence
    retn.insert(d.name(), d);

    // comment
    d.setName(QOrganizerItemComment::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemComment::FieldComment, f);
    d.setFields(fields);
    d.setUnique(false);
    retn.insert(d.name(), d);

    // tag
    d.setName(QOrganizerItemTag::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemTag::FieldTag, f);
    d.setFields(fields);
    d.setUnique(false);
    retn.insert(d.name(), d);

    retnSchema.insert(QOrganizerItemType::TypeEventOccurrence, retn);

    // and then again for TODOs =============================
    retn.clear();

    // type
    d.setName(QOrganizerItemType::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList()
                         << QString(QLatin1String(QOrganizerItemType::TypeEvent))
                         << QString(QLatin1String(QOrganizerItemType::TypeEventOccurrence))
                         << QString(QLatin1String(QOrganizerItemType::TypeJournal))
                         << QString(QLatin1String(QOrganizerItemType::TypeNote))
                         << QString(QLatin1String(QOrganizerItemType::TypeTodo))
                         << QString(QLatin1String(QOrganizerItemType::TypeTodoOccurrence)));
    fields.insert(QOrganizerItemType::FieldType, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // guid
    d.setName(QOrganizerItemGuid::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemGuid::FieldGuid, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // timestamp
    d.setName(QOrganizerItemTimestamp::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::DateTime);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemTimestamp::FieldModificationTimestamp, f);
    fields.insert(QOrganizerItemTimestamp::FieldCreationTimestamp, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // display label
    d.setName(QOrganizerItemDisplayLabel::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemDisplayLabel::FieldLabel, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // description
    d.setName(QOrganizerItemDescription::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemDescription::FieldDescription, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // recurrence information
    d.setName(QOrganizerItemRecurrence::DefinitionName);
    fields.clear();
    f.setDataType(qMetaTypeId< QSet<QDate> >());
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemRecurrence::FieldExceptionDates, f);
    fields.insert(QOrganizerItemRecurrence::FieldRecurrenceDates, f);
    f.setDataType(qMetaTypeId< QSet<QOrganizerRecurrenceRule> >());
    fields.insert(QOrganizerItemRecurrence::FieldExceptionRules, f);
    fields.insert(QOrganizerItemRecurrence::FieldRecurrenceRules, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // reminder
    d.setName(QOrganizerItemReminder::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::Int);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemReminder::FieldSecondsBeforeStart, f);
    fields.insert(QOrganizerItemReminder::FieldRepetitionCount, f);
    fields.insert(QOrganizerItemReminder::FieldRepetitionDelay, f);
    d.setFields(fields);
    d.setUnique(false); // can have multiple alarms at different times for the same todo
    retn.insert(d.name(), d);

    // audible reminder
    d.setName(QOrganizerItemAudibleReminder::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::Int);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemReminder::FieldSecondsBeforeStart, f);
    fields.insert(QOrganizerItemReminder::FieldRepetitionCount, f);
    fields.insert(QOrganizerItemReminder::FieldRepetitionDelay, f);
    f.setDataType(QVariant::Url);
    fields.insert(QOrganizerItemAudibleReminder::FieldDataUrl, f);
    d.setFields(fields);
    d.setUnique(false); // can have multiple alarms at different times for the same todo
    retn.insert(d.name(), d);

    // email reminder
    d.setName(QOrganizerItemEmailReminder::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::Int);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemReminder::FieldSecondsBeforeStart, f);
    fields.insert(QOrganizerItemReminder::FieldRepetitionCount, f);
    fields.insert(QOrganizerItemReminder::FieldRepetitionDelay, f);
    f.setDataType(QVariant::String);
    fields.insert(QOrganizerItemEmailReminder::FieldBody, f);
    fields.insert(QOrganizerItemEmailReminder::FieldSubject, f);
    f.setDataType(QVariant::StringList);
    fields.insert(QOrganizerItemEmailReminder::FieldRecipients, f);
    f.setDataType(QVariant::List);
    fields.insert(QOrganizerItemEmailReminder::FieldAttachments, f);
    d.setFields(fields);
    d.setUnique(false); // can have multiple alarms at different times for the same todo
    retn.insert(d.name(), d);

    // visual reminder
    d.setName(QOrganizerItemVisualReminder::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::Int);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemReminder::FieldSecondsBeforeStart, f);
    fields.insert(QOrganizerItemReminder::FieldRepetitionCount, f);
    fields.insert(QOrganizerItemReminder::FieldRepetitionDelay, f);
    f.setDataType(QVariant::String);
    fields.insert(QOrganizerItemVisualReminder::FieldMessage, f);
    f.setDataType(QVariant::Url);
    fields.insert(QOrganizerItemVisualReminder::FieldDataUrl, f);
    d.setFields(fields);
    d.setUnique(false); // can have multiple alarms at different times for the same todo
    retn.insert(d.name(), d);

    // todo progress
    d.setName(QOrganizerTodoProgress::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::DateTime);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerTodoProgress::FieldFinishedDateTime, f);
    f.setDataType(QVariant::Int);
    fields.insert(QOrganizerTodoProgress::FieldPercentageComplete, f);
    fields.insert(QOrganizerTodoProgress::FieldStatus, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // todo time range
    d.setName(QOrganizerTodoTime::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::DateTime);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerTodoTime::FieldStartDateTime, f);
    fields.insert(QOrganizerTodoTime::FieldDueDateTime, f);
    f.setDataType(QVariant::Bool);
    fields.insert(QOrganizerTodoTime::FieldAllDay, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // priority
    d.setName(QOrganizerItemPriority::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::Int);
    f.setAllowableValues(QVariantList()
                         << static_cast<int>(QOrganizerItemPriority::UnknownPriority)
                         << static_cast<int>(QOrganizerItemPriority::HighestPriority)
                         << static_cast<int>(QOrganizerItemPriority::ExtremelyHighPriority)
                         << static_cast<int>(QOrganizerItemPriority::VeryHighPriority)
                         << static_cast<int>(QOrganizerItemPriority::HighPriority)
                         << static_cast<int>(QOrganizerItemPriority::MediumPriority)
                         << static_cast<int>(QOrganizerItemPriority::LowPriority)
                         << static_cast<int>(QOrganizerItemPriority::VeryLowPriority)
                         << static_cast<int>(QOrganizerItemPriority::ExtremelyLowPriority)
                         << static_cast<int>(QOrganizerItemPriority::LowestPriority));
    fields.insert(QOrganizerItemPriority::FieldPriority, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // comment
    d.setName(QOrganizerItemComment::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemComment::FieldComment, f);
    d.setFields(fields);
    d.setUnique(false);
    retn.insert(d.name(), d);

    // tag
    d.setName(QOrganizerItemTag::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemTag::FieldTag, f);
    d.setFields(fields);
    d.setUnique(false);
    retn.insert(d.name(), d);

    retnSchema.insert(QOrganizerItemType::TypeTodo, retn);

    // and then again for TODOOCCURRENCEs =============================
    retn.clear();

    // type
    d.setName(QOrganizerItemType::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList()
                         << QString(QLatin1String(QOrganizerItemType::TypeEvent))
                         << QString(QLatin1String(QOrganizerItemType::TypeEventOccurrence))
                         << QString(QLatin1String(QOrganizerItemType::TypeJournal))
                         << QString(QLatin1String(QOrganizerItemType::TypeNote))
                         << QString(QLatin1String(QOrganizerItemType::TypeTodo))
                         << QString(QLatin1String(QOrganizerItemType::TypeTodoOccurrence)));
    fields.insert(QOrganizerItemType::FieldType, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // guid
    d.setName(QOrganizerItemGuid::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemGuid::FieldGuid, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // timestamp
    d.setName(QOrganizerItemTimestamp::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::DateTime);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemTimestamp::FieldModificationTimestamp, f);
    fields.insert(QOrganizerItemTimestamp::FieldCreationTimestamp, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // display label
    d.setName(QOrganizerItemDisplayLabel::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemDisplayLabel::FieldLabel, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // description
    d.setName(QOrganizerItemDescription::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemDescription::FieldDescription, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // instance origin
    d.setName(QOrganizerItemParent::DefinitionName);
    fields.clear();
    f.setDataType(qMetaTypeId<QOrganizerItemId>());
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemParent::FieldParentId, f);
    f.setDataType(QVariant::Date);
    fields.insert(QOrganizerItemParent::FieldOriginalDate, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // todo progress
    d.setName(QOrganizerTodoProgress::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::DateTime);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerTodoProgress::FieldFinishedDateTime, f);
    f.setDataType(QVariant::Int);
    fields.insert(QOrganizerTodoProgress::FieldPercentageComplete, f);
    fields.insert(QOrganizerTodoProgress::FieldStatus, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // reminder
    d.setName(QOrganizerItemReminder::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::Int);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemReminder::FieldSecondsBeforeStart, f);
    fields.insert(QOrganizerItemReminder::FieldRepetitionCount, f);
    fields.insert(QOrganizerItemReminder::FieldRepetitionDelay, f);
    d.setFields(fields);
    d.setUnique(false); // can have multiple alarms at different times for the same todo occurrence
    retn.insert(d.name(), d);

    // audible reminder
    d.setName(QOrganizerItemAudibleReminder::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::Int);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemReminder::FieldSecondsBeforeStart, f);
    fields.insert(QOrganizerItemReminder::FieldRepetitionCount, f);
    fields.insert(QOrganizerItemReminder::FieldRepetitionDelay, f);
    f.setDataType(QVariant::Url);
    fields.insert(QOrganizerItemAudibleReminder::FieldDataUrl, f);
    d.setFields(fields);
    d.setUnique(false); // can have multiple alarms at different times for the same todo occurrence
    retn.insert(d.name(), d);

    // email reminder
    d.setName(QOrganizerItemEmailReminder::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::Int);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemReminder::FieldSecondsBeforeStart, f);
    fields.insert(QOrganizerItemReminder::FieldRepetitionCount, f);
    fields.insert(QOrganizerItemReminder::FieldRepetitionDelay, f);
    f.setDataType(QVariant::String);
    fields.insert(QOrganizerItemEmailReminder::FieldBody, f);
    fields.insert(QOrganizerItemEmailReminder::FieldSubject, f);
    f.setDataType(QVariant::StringList);
    fields.insert(QOrganizerItemEmailReminder::FieldRecipients, f);
    f.setDataType(QVariant::List);
    fields.insert(QOrganizerItemEmailReminder::FieldAttachments, f);
    d.setFields(fields);
    d.setUnique(false); // can have multiple alarms at different times for the same todo occurrence
    retn.insert(d.name(), d);

    // visual reminder
    d.setName(QOrganizerItemVisualReminder::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::Int);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemReminder::FieldSecondsBeforeStart, f);
    fields.insert(QOrganizerItemReminder::FieldRepetitionCount, f);
    fields.insert(QOrganizerItemReminder::FieldRepetitionDelay, f);
    f.setDataType(QVariant::String);
    fields.insert(QOrganizerItemVisualReminder::FieldMessage, f);
    f.setDataType(QVariant::Url);
    fields.insert(QOrganizerItemVisualReminder::FieldDataUrl, f);
    d.setFields(fields);
    d.setUnique(false); // can have multiple alarms at different times for the same todo occurrence
    retn.insert(d.name(), d);

    // todo time range
    d.setName(QOrganizerTodoTime::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::DateTime);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerTodoTime::FieldStartDateTime, f);
    fields.insert(QOrganizerTodoTime::FieldDueDateTime, f);
    f.setDataType(QVariant::Bool);
    fields.insert(QOrganizerTodoTime::FieldAllDay, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // priority
    d.setName(QOrganizerItemPriority::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::Int);
    f.setAllowableValues(QVariantList()
                         << static_cast<int>(QOrganizerItemPriority::UnknownPriority)
                         << static_cast<int>(QOrganizerItemPriority::HighestPriority)
                         << static_cast<int>(QOrganizerItemPriority::ExtremelyHighPriority)
                         << static_cast<int>(QOrganizerItemPriority::VeryHighPriority)
                         << static_cast<int>(QOrganizerItemPriority::HighPriority)
                         << static_cast<int>(QOrganizerItemPriority::MediumPriority)
                         << static_cast<int>(QOrganizerItemPriority::LowPriority)
                         << static_cast<int>(QOrganizerItemPriority::VeryLowPriority)
                         << static_cast<int>(QOrganizerItemPriority::ExtremelyLowPriority)
                         << static_cast<int>(QOrganizerItemPriority::LowestPriority));
    fields.insert(QOrganizerItemPriority::FieldPriority, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // comment
    d.setName(QOrganizerItemComment::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemComment::FieldComment, f);
    d.setFields(fields);
    d.setUnique(false);
    retn.insert(d.name(), d);

    // tag
    d.setName(QOrganizerItemTag::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemTag::FieldTag, f);
    d.setFields(fields);
    d.setUnique(false);
    retn.insert(d.name(), d);

    retnSchema.insert(QOrganizerItemType::TypeTodoOccurrence, retn);

    // and then again for JOURNALs =============================
    retn.clear();

    // type
    d.setName(QOrganizerItemType::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList()
                         << QString(QLatin1String(QOrganizerItemType::TypeEvent))
                         << QString(QLatin1String(QOrganizerItemType::TypeEventOccurrence))
                         << QString(QLatin1String(QOrganizerItemType::TypeJournal))
                         << QString(QLatin1String(QOrganizerItemType::TypeNote))
                         << QString(QLatin1String(QOrganizerItemType::TypeTodo))
                         << QString(QLatin1String(QOrganizerItemType::TypeTodoOccurrence)));
    fields.insert(QOrganizerItemType::FieldType, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // guid
    d.setName(QOrganizerItemGuid::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemGuid::FieldGuid, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // timestamp
    d.setName(QOrganizerItemTimestamp::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::DateTime);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemTimestamp::FieldModificationTimestamp, f);
    fields.insert(QOrganizerItemTimestamp::FieldCreationTimestamp, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // display label
    d.setName(QOrganizerItemDisplayLabel::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemDisplayLabel::FieldLabel, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // description
    d.setName(QOrganizerItemDescription::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemDescription::FieldDescription, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // journal time range
    d.setName(QOrganizerJournalTime::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::DateTime);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerJournalTime::FieldEntryDateTime, f);
    d.setFields(fields);
    d.setUnique(true);
    retn.insert(d.name(), d);

    // comment
    d.setName(QOrganizerItemComment::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemComment::FieldComment, f);
    d.setFields(fields);
    d.setUnique(false);
    retn.insert(d.name(), d);

    // tag
    d.setName(QOrganizerItemTag::DefinitionName);
    fields.clear();
    f.setDataType(QVariant::String);
    f.setAllowableValues(QVariantList());
    fields.insert(QOrganizerItemTag::FieldTag, f);
    d.setFields(fields);
    d.setUnique(false);
    retn.insert(d.name(), d);

    retnSchema.insert(QOrganizerItemType::TypeJournal, retn);

    if (version == 1) {
        return retnSchema;
    }

    // the most recent version of the schema is version 1.
    QMap<QString, QMap<QString, QOrganizerItemDetailDefinition> > empty;
    return empty;
}

/*!
  Checks that the given item \a item does not have details which
  don't conform to a valid definition, violate uniqueness constraints,
  or contain values for nonexistent fields, and that the values contained are
  of the correct type for each field, and are allowable values for that field.

  Note that this function is unable to ensure that the access constraints
  (such as CreateOnly and ReadOnly) are observed; backend specific code
  must be written if you wish to enforce these constraints.

  Returns true if the \a item is valid according to the definitions for
  its details, otherwise returns false.

  Any errors encountered during this operation should be stored to
  \a error.
 */
bool QOrganizerManagerEngine::validateItem(const QOrganizerItem& item, QOrganizerManager::Error* error) const
{
    QList<QString> uniqueDefinitionIds;

    // check that each detail conforms to its definition as supported by this manager.
    foreach (const QOrganizerItemDetail& detail, item.details()) {
        QVariantMap values = detail.variantValues();
        QOrganizerItemDetailDefinition def = detailDefinition(detail.definitionName(), item.type(), error);
        // check that the definition is supported
        if (*error != QOrganizerManager::NoError) {
            *error = QOrganizerManager::InvalidDetailError;
            return false; // this definition is not supported.
        }

        // check uniqueness
        if (def.isUnique()) {
            if (uniqueDefinitionIds.contains(def.name())) {
                *error = QOrganizerManager::AlreadyExistsError;
                return false; // can't have two of a unique detail.
            }
            uniqueDefinitionIds.append(def.name());
        }

        QMapIterator<QString,QVariant> fieldIt(values);
        while (fieldIt.hasNext()) {
            fieldIt.next();
            const QString& key = fieldIt.key();
            const QVariant& variant = fieldIt.value();
            // check that no values exist for nonexistent fields.
            if (!def.fields().contains(key)) {
                *error = QOrganizerManager::InvalidDetailError;
                return false; // value for nonexistent field.
            }

            QOrganizerItemDetailFieldDefinition field = def.fields().value(key);
            // check that the type of each value corresponds to the allowable field type
            if (static_cast<int>(field.dataType()) != variant.userType()) {
                *error = QOrganizerManager::InvalidDetailError;
                return false; // type doesn't match.
            }

            // check that the value is allowable
            // if the allowable values is an empty list, any are allowed.
            if (!field.allowableValues().isEmpty()) {
                // if the field datatype is a list, check that it contains only allowable values
                if (field.dataType() == QVariant::List || field.dataType() == QVariant::StringList) {
                    QList<QVariant> innerValues = variant.toList();
                    QListIterator<QVariant> it(innerValues);
                    while (it.hasNext()) {
                        if (!field.allowableValues().contains(it.next())) {
                            *error = QOrganizerManager::InvalidDetailError;
                            return false; // value not allowed.
                        }
                    }
                } else if (!field.allowableValues().contains(variant)) {
                    // the datatype is not a list; the value wasn't allowed.
                    *error = QOrganizerManager::InvalidDetailError;
                    return false; // value not allowed.
                }
            }
        }
    }

    return true;
}

/*!
  Returns true if the \a collection is valid and can be saved in the engine.
  By default, modifiable collections are not supported, so this function returns false,
  and \a error is set to QOrganizerManager::NotSupportedError.
  Engines which do implement mutable collections should reimplement this function.
 */
bool QOrganizerManagerEngine::validateCollection(const QOrganizerCollection& collection, QOrganizerManager::Error* error) const
{
    Q_UNUSED(collection);
    *error = QOrganizerManager::NotSupportedError;
    return false;
}

/*!
  Checks that the given detail definition \a definition seems valid,
  with a correct id, defined fields, and any specified value types
  are supported by this engine.  This function is called before
  trying to save a definition.

  Returns true if the \a definition seems valid, otherwise returns
  false.

  Any errors encountered during this operation should be stored to
  \a error.
 */
bool QOrganizerManagerEngine::validateDefinition(const QOrganizerItemDetailDefinition& definition, QOrganizerManager::Error* error) const
{
    if (definition.name().isEmpty()) {
        *error = QOrganizerManager::BadArgumentError;
        return false;
    }

    if (definition.fields().count() == 0) {
        *error = QOrganizerManager::BadArgumentError;
        return false;
    }

    // Check each field now
    QMapIterator<QString, QOrganizerItemDetailFieldDefinition> it(definition.fields());
    while(it.hasNext()) {
        it.next();
        if (it.key().isEmpty()) {
            *error = QOrganizerManager::BadArgumentError;
            return false;
        }

        // Check that each allowed value is the same type
        for (int i=0; i < it.value().allowableValues().count(); i++) {
            if (it.value().allowableValues().at(i).userType() != it.value().dataType()) {
                *error = QOrganizerManager::BadArgumentError;
                return false;
            }
        }
    }
    *error = QOrganizerManager::NoError;
    return true;
}

/*!
  Returns the registered detail definitions which are valid for organizer items whose type is of the given \a organizeritemType in this engine.

  Any errors encountered during this operation should be stored to
  \a error.
 */
QMap<QString, QOrganizerItemDetailDefinition> QOrganizerManagerEngine::detailDefinitions(const QString& organizeritemType, QOrganizerManager::Error* error) const
{
    Q_UNUSED(organizeritemType);
    *error = QOrganizerManager::NotSupportedError;
    return QMap<QString, QOrganizerItemDetailDefinition>();
}

/*!
  Returns the definition identified by the given \a definitionName that
  is valid for organizer items whose type is of the given \a organizeritemType in this store, or a default-constructed QOrganizerItemDetailDefinition
  if no such definition exists

  Any errors encountered during this operation should be stored to
  \a error.
 */
QOrganizerItemDetailDefinition QOrganizerManagerEngine::detailDefinition(const QString& definitionName, const QString& organizeritemType, QOrganizerManager::Error* error) const
{
    QMap<QString, QOrganizerItemDetailDefinition> definitions = detailDefinitions(organizeritemType, error);
    if (definitions.contains(definitionName))  {
        *error = QOrganizerManager::NoError;
        return definitions.value(definitionName);
    } else {
        *error = QOrganizerManager::DoesNotExistError;
        return QOrganizerItemDetailDefinition();
    }
}

/*!
  Persists the given definition \a def in the database, which is valid for organizer items whose type is the given \a organizeritemType.

  Returns true if the definition was saved successfully, and otherwise returns false.

  The backend must emit the appropriate signals to inform clients of changes
  to the database resulting from this operation.

  Any errors encountered during this operation should be stored to
  \a error.
 */
bool QOrganizerManagerEngine::saveDetailDefinition(const QOrganizerItemDetailDefinition& def, const QString& organizeritemType, QOrganizerManager::Error* error)
{
    Q_UNUSED(def);
    Q_UNUSED(organizeritemType);

    *error = QOrganizerManager::NotSupportedError;
    return false;
}

/*!
  Removes the definition identified by the given \a definitionName from the database, where it was valid for organizer items whose type was the given \a organizeritemType.

  Returns true if the definition was removed successfully, otherwise returns false.

  The backend must emit the appropriate signals to inform clients of changes
  to the database resulting from this operation.

  Any errors encountered during this operation should be stored to
  \a error.
 */
bool QOrganizerManagerEngine::removeDetailDefinition(const QString& definitionName, const QString& organizeritemType, QOrganizerManager::Error* error)
{
    Q_UNUSED(definitionName);
    Q_UNUSED(organizeritemType);

    *error = QOrganizerManager::NotSupportedError;
    return false;
}

/*!
  Sets the access constraints of \a detail to the supplied \a constraints.

  This function is provided to allow engine implementations to report the
  access constraints of retrieved details, without generally allowing the
  access constraints to be modified after retrieval.

  Application code should not call this function, since validation of the
  detail will happen in the engine in any case.
 */
void QOrganizerManagerEngine::setDetailAccessConstraints(QOrganizerItemDetail *detail, QOrganizerItemDetail::AccessConstraints constraints)
{
    if (detail) {
        QOrganizerItemDetailPrivate::setAccessConstraints(detail, constraints);
    }
}

/*!
  Adds the given \a item to the database if \a item has a
  default-constructed id, or an id with the manager URI set to the URI of
  this manager and a id of zero, otherwise updates the organizer item in
  the database which has the same id to be the given \a item.
  If the id is non-zero but does not identify any item stored in the
  manager, the function will return false and \a error will be set to
  \c QOrganizerManager::DoesNotExistError.

  The \a item will be added to the collection identified by the
  collectionId specified in the item (accessible via item->organizerId())
  if it exists, and the item conforms to the schema supported
  for that collection.  If the collection exists but the item does not conform
  to the schema supported for that collection, the function will return false,
  and the \a error will be set to QOrganizerManager::InvalidDetailError.

  If the collectionId is not the default (zero) id, but does not identify
  a valid collection, the function will return false, and \a error will be set
  to QOrganizerManager::InvalidCollectionError.  If the collectionId
  is the default (zero) id, the item should be saved in the collection in which
  it is already saved (if it is already saved in this manager), or in the default
  collection (if it is a new item in this manager).

  Returns true if the save operation completed successfully, otherwise
  returns false.  Any error which occurs will be saved in \a error.

  The default implementation will convert this into a call to saveItems.

  \sa managerUri()
 */
bool QOrganizerManagerEngine::saveItem(QOrganizerItem* item, QOrganizerManager::Error* error)
{
    // Convert to a list op
    if (item) {
        QList<QOrganizerItem> list;
        list.append(*item);

        QMap<int, QOrganizerManager::Error> errors;
        bool ret = saveItems(&list, &errors, error);

        if (errors.count() > 0)
            *error = errors.begin().value();

        *item = list.value(0);
        return ret;
    } else {
        *error = QOrganizerManager::BadArgumentError;
        return false;
    }
}

/*!
  Remove the item identified by \a organizeritemId from the database.
  Returns true if the item was removed successfully, otherwise
  returns false.

  Any error which occurs will be saved in \a error.

  The default implementation will convert this into a call to removeItems.
 */
bool QOrganizerManagerEngine::removeItem(const QOrganizerItemId& organizeritemId, QOrganizerManager::Error* error)
{
    // Convert to a list op
    QList<QOrganizerItemId> list;
    list.append(organizeritemId);

    QMap<int, QOrganizerManager::Error> errors;
    bool ret = removeItems(list, &errors, error);

    if (errors.count() > 0)
        *error = errors.begin().value();

    return ret;
}

/*!
  Adds the list of organizer items given by \a items list to the database.
  Returns true if the organizer items were saved successfully, otherwise false.

  The engine might populate \a errorMap (the map of indices of the \a items list to
  the error which occurred when saving the item at that index) for
  every index for which the item could not be saved, if it is able.
  The \l QOrganizerManager::error() function will only return \c QOrganizerManager::NoError
  if all organizer items were saved successfully.

  For each newly saved item that was successful, the id of the item
  in the \a items list will be updated with the new value.

  Each item in the given list \a items will be added to the collection
  identified in the item (accessible via item->collectionId()) if it exists, and if
  the item conform to the schema supported for that collection.  If the collection
  exists but the item does not conform to the schema supported for that collection,
  the function will return false, and the error in the \a errorMap for the item at
  that index will be set to QOrganizerManager::InvalidDetailError.

  If the collectionId is not the default (zero) id, but does not identify
  a valid collection, the function will return false, and \a error will be set
  to QOrganizerManager::InvalidCollectionError.  If the collectionId
  is the default (zero) id, the item should be saved in the collection in which
  it is already saved (if they are already saved in this manager), or in the default
  collection (if they are new items in this manager).

  Any errors encountered during this operation should be stored to
  \a error.

  \sa QOrganizerManager::saveItem()
 */
bool QOrganizerManagerEngine::saveItems(QList<QOrganizerItem>* items, QMap<int, QOrganizerManager::Error>* errorMap, QOrganizerManager::Error* error)
{
    Q_UNUSED(items);
    Q_UNUSED(errorMap);

    *error = QOrganizerManager::NotSupportedError;
    return false;
}

/*!
  Remove every item whose id is contained in the list of organizer items ids
  \a organizeritemIds.  Returns true if all organizer items were removed successfully,
  otherwise false.

  The manager might populate \a errorMap (the map of indices of the \a organizeritemIds list to
  the error which occurred when saving the item at that index) for every
  index for which the item could not be removed, if it is able.
  The \l QOrganizerManager::error() function will
  only return \c QOrganizerManager::NoError if all organizer items were removed
  successfully.

  If the list contains ids which do not identify a valid item in the manager, the function will
  remove any organizer items which are identified by ids in the \a organizeritemIds list, insert
  \c QOrganizerManager::DoesNotExist entries into the \a errorMap for the indices of invalid ids
  in the \a organizeritemIds list, return false, and set the overall operation error to
  \c QOrganizerManager::DoesNotExistError.

  Any errors encountered during this operation should be stored to
  \a error.

  \sa QOrganizerManager::removeItem()
 */
bool QOrganizerManagerEngine::removeItems(const QList<QOrganizerItemId>& organizeritemIds, QMap<int, QOrganizerManager::Error>* errorMap, QOrganizerManager::Error* error)
{
    Q_UNUSED(organizeritemIds);
    Q_UNUSED(errorMap);
    *error = QOrganizerManager::NotSupportedError;
    return false;
}

/*!
    Returns the default collection of the manager.
    Any errors encountered during this operation should be stored to
   \a error.
*/
QOrganizerCollection QOrganizerManagerEngine::defaultCollection(QOrganizerManager::Error* error) const
{
    *error = QOrganizerManager::NotSupportedError;
    return QOrganizerCollection();
}

/*!
    Returns the collection identified by the given \a collectionId in the manager.
    Any errors encountered during this operation should be stored to \a error.
    If the given \a collectionId does not specify a valid collection, \a error will
    be set to \c QOrganizerManager::DoesNotExistError.
*/
QOrganizerCollection QOrganizerManagerEngine::collection(const QOrganizerCollectionId& collectionId, QOrganizerManager::Error* error) const
{
    Q_UNUSED(collectionId);
    *error = QOrganizerManager::NotSupportedError;
    return QOrganizerCollection();
}

/*!
    Returns the list of all of the collections managed by this manager.
    Any errors encountered during this operation should be stored to
    \a error.
 */
QList<QOrganizerCollection> QOrganizerManagerEngine::collections(QOrganizerManager::Error* error) const
{
    *error = QOrganizerManager::NotSupportedError;
    return QList<QOrganizerCollection>();
}

/*!
    Returns true if the saving of the \a collection was successfull otherwise false.
    Any errors encountered during this operation should be stored to
    \a error.
*/
bool QOrganizerManagerEngine::saveCollection(QOrganizerCollection* collection, QOrganizerManager::Error* error)
{
    Q_UNUSED(collection);

    *error = QOrganizerManager::NotSupportedError;
    return false;
}

/*!
    Returns true if the removing of the \a collectionId was successfull otherwise false.
    Any errors encountered during this operation should be stored to
    \a error.
*/
bool QOrganizerManagerEngine::removeCollection(const QOrganizerCollectionId& collectionId, QOrganizerManager::Error* error)
{
    Q_UNUSED(collectionId);

    *error = QOrganizerManager::NotSupportedError;
    return false;
}

/*!
  Returns a pruned or modified version of the \a original item which is valid and can be saved in the manager.
  The returned item might have details removed or arbitrarily changed.
  Any error which occurs will be saved to \a error.
 */
QOrganizerItem QOrganizerManagerEngine::compatibleItem(const QOrganizerItem& original, QOrganizerManager::Error* error) const
{
    QOrganizerItem conforming;
    conforming.setType(original.type());
    conforming.setId(original.id());
    QOrganizerManager::Error tempError;
    QList<QString> uniqueDefinitionIds;
    foreach (QOrganizerItemDetail detail, original.details()) {
        // check that the detail conforms to the definition in this manager.
        // if so, then add it to the conforming item to be returned.  if not, prune it.

        QVariantMap values = detail.variantValues();
        QOrganizerItemDetailDefinition def = detailDefinition(detail.definitionName(), original.type(), &tempError);
        // check that the definition is supported
        if (tempError != QOrganizerManager::NoError) {
            continue; // this definition is not supported.
        }

        // check uniqueness
        if (def.isUnique()) {
            if (uniqueDefinitionIds.contains(def.name())) {
                continue; // can't have two of a unique detail.
            }
            uniqueDefinitionIds.append(def.name());
        }

        QMapIterator<QString,QVariant> fieldIt(values);
        while (fieldIt.hasNext()) {
            fieldIt.next();
            const QString& key = fieldIt.key();
            const QVariant& variant = fieldIt.value();
            // prune values for nonexistent fields.
            if (!def.fields().contains(key)) {
                detail.removeValue(key);
            }

            QOrganizerItemDetailFieldDefinition field = def.fields().value(key);
            // prune values that do not correspond to the allowable field type
            if (static_cast<int>(field.dataType()) != variant.userType()) {
                detail.removeValue(key);
            }

            // check that the value is allowable
            // if the allowable values is an empty list, any are allowed.
            if (!field.allowableValues().isEmpty()) {
                // if the field datatype is a list, remove non-allowable values
                if (field.dataType() == QVariant::List || field.dataType() == QVariant::StringList) {
                    QList<QVariant> innerValues = variant.toList();
                    QMutableListIterator<QVariant> it(innerValues);
                    while (it.hasNext()) {
                        if (!field.allowableValues().contains(it.next())) {
                            it.remove();
                        }
                    }
                    if (innerValues.isEmpty()) {
                        detail.removeValue(key);
                    } else {
                        detail.setValue(key, innerValues);
                    }
                } else if (!field.allowableValues().contains(variant)) {
                    detail.removeValue(key);
                }
            }
        }

        // if it hasn't been pruned away to nothing, save it in the conforming item
        if (!detail.isEmpty()) {
            conforming.saveDetail(&detail);
        }
    }

    *error = QOrganizerManager::NoError;
    if (conforming.isEmpty())
        *error = QOrganizerManager::DoesNotExistError;
    return conforming;
}

/*!
  Returns a pruned or modified version of the \a original collection which is valid and can be saved in the manager.
  The returned item might have meta data removed or arbitrarily changed.  Any error which occurs will be saved to \a error.
  By default, modifiable collections are not supported, and so this function always returns false.
  Any engine which supports mutable collections should reimplement this function.
 */
QOrganizerCollection QOrganizerManagerEngine::compatibleCollection(const QOrganizerCollection& original, QOrganizerManager::Error* error) const
{
    Q_UNUSED(original);
    *error = QOrganizerManager::NotSupportedError;
    return QOrganizerCollection();
}

/*!
  Compares \a first against \a second.  If the types are
  strings (QVariant::String), the \a sensitivity argument controls
  case sensitivity when comparing.

  Returns:
  <0 if \a first is less than \a second
   0 if \a first is equal to \a second
  >0 if \a first is greater than \a second.

  The results are undefined if the variants are different types, or
  cannot be compared.
 */
int QOrganizerManagerEngine::compareVariant(const QVariant& first, const QVariant& second, Qt::CaseSensitivity sensitivity)
{
    switch(first.type()) {
        case QVariant::Int:
            return first.toInt() - second.toInt();

        case QVariant::LongLong:
            return first.toLongLong() - second.toLongLong();

        case QVariant::Bool:
        case QVariant::Char:
        case QVariant::UInt:
            return first.toUInt() - second.toUInt();

        case QVariant::ULongLong:
            return first.toULongLong() - second.toULongLong();

       case QVariant::String:
            return first.toString().compare(second.toString(), sensitivity);

        case QVariant::Double:
            {
                const double a = first.toDouble();
                const double b = second.toDouble();
                return (a < b) ? -1 : ((a == b) ? 0 : 1);
            }

        case QVariant::DateTime:
            {
                const QDateTime a = first.toDateTime();
                const QDateTime b = second.toDateTime();
                return (a < b) ? -1 : ((a == b) ? 0 : 1);
            }

        case QVariant::Date:
            return first.toDate().toJulianDay() - second.toDate().toJulianDay();

        case QVariant::Time:
            {
                const QTime a = first.toTime();
                const QTime b = second.toTime();
                return (a < b) ? -1 : ((a == b) ? 0 : 1);
            }

        default:
            return 0;
    }
}

/*!
  Returns true if the supplied item \a item matches the supplied filter \a filter.

  This function will test each condition in the filter, possibly recursing.
 */
bool QOrganizerManagerEngine::testFilter(const QOrganizerItemFilter &filter, const QOrganizerItem &item)
{
    switch(filter.type()) {
        case QOrganizerItemFilter::InvalidFilter:
        case QOrganizerItemFilter::ActionFilter:
            return false;

        case QOrganizerItemFilter::DefaultFilter:
            return true;

        case QOrganizerItemFilter::IdFilter:
            {
                const QOrganizerItemIdFilter idf(filter);
                if (idf.ids().contains(item.id()))
                    return true;
            }
            // Fall through to end
            break;

        case QOrganizerItemFilter::OrganizerItemDetailFilter:
            {
                const QOrganizerItemDetailFilter cdf(filter);
                if (cdf.detailDefinitionName().isEmpty())
                    return false;

                /* See if this organizer item has one of these details in it */
                const QList<QOrganizerItemDetail>& details = item.details(cdf.detailDefinitionName());

                if (details.count() == 0)
                    return false; /* can't match */

                /* See if we need to check the values */
                if (cdf.detailFieldName().isEmpty())
                    return true;  /* just testing for the presence of a detail of the specified definition */

                /* Now figure out what tests we are doing */
                const bool valueTest = cdf.value().isValid();
                const bool presenceTest = !valueTest;

                /* See if we need to test any values at all */
                if (presenceTest) {
                    for(int j=0; j < details.count(); j++) {
                        const QOrganizerItemDetail& detail = details.at(j);

                        /* Check that the field is present and has a non-empty value */
                        if (detail.variantValues().contains(cdf.detailFieldName()) && !detail.value(cdf.detailFieldName()).isEmpty())
                            return true;
                    }
                    return false;
                }

                /* Case sensitivity, for those parts that use it */
                Qt::CaseSensitivity cs = (cdf.matchFlags() & QOrganizerItemFilter::MatchCaseSensitive) ? Qt::CaseSensitive : Qt::CaseInsensitive;

                /* See what flags are requested, since we're looking at a value */
                if (cdf.matchFlags() & (QOrganizerItemFilter::MatchEndsWith | QOrganizerItemFilter::MatchStartsWith | QOrganizerItemFilter::MatchContains | QOrganizerItemFilter::MatchFixedString)) {
                    /* We're strictly doing string comparisons here */
                    bool matchStarts = (cdf.matchFlags() & 7) == QOrganizerItemFilter::MatchStartsWith;
                    bool matchEnds = (cdf.matchFlags() & 7) == QOrganizerItemFilter::MatchEndsWith;
                    bool matchContains = (cdf.matchFlags() & 7) == QOrganizerItemFilter::MatchContains;

                    /* Value equality test */
                    for(int j=0; j < details.count(); j++) {
                        const QOrganizerItemDetail& detail = details.at(j);
                        const QString& var = detail.value(cdf.detailFieldName());
                        const QString& needle = cdf.value().toString();
                        if (matchStarts && var.startsWith(needle, cs))
                            return true;
                        if (matchEnds && var.endsWith(needle, cs))
                            return true;
                        if (matchContains && var.contains(needle, cs))
                            return true;
                        if (QString::compare(var, needle, cs) == 0)
                            return true;
                    }
                    return false;
                } else {
                    /* Nope, testing the values as a variant */
                    /* Value equality test */
                    for(int j = 0; j < details.count(); j++) {
                        const QOrganizerItemDetail& detail = details.at(j);
                        const QVariant& var = detail.variantValue(cdf.detailFieldName());
                        if (!var.isNull() && compareVariant(var, cdf.value(), cs) == 0)
                            return true;
                    }
                }
            }
            break;

        case QOrganizerItemFilter::OrganizerItemDetailRangeFilter:
            {
                const QOrganizerItemDetailRangeFilter cdf(filter);
                if (cdf.detailDefinitionName().isEmpty())
                    return false; /* we do not know which field to check */

                /* See if this organizer item has one of these details in it */
                const QList<QOrganizerItemDetail>& details = item.details(cdf.detailDefinitionName());

                if (details.count() == 0)
                    return false; /* can't match */

                /* Check for a detail presence test */
                if (cdf.detailFieldName().isEmpty())
                    return true;

                /* See if this is a field presence test */
                if (!cdf.minValue().isValid() && !cdf.maxValue().isValid()) {
                    for(int j=0; j < details.count(); j++) {
                        const QOrganizerItemDetail& detail = details.at(j);
                        if (detail.variantValues().contains(cdf.detailFieldName()))
                            return true;
                    }
                    return false;
                }

                /* open or closed interval testing support */
                const int minComp = cdf.rangeFlags() & QOrganizerItemDetailRangeFilter::ExcludeLower ? 1 : 0;
                const int maxComp = cdf.rangeFlags() & QOrganizerItemDetailRangeFilter::IncludeUpper ? 1 : 0;

                const bool testMin = cdf.minValue().isValid();
                const bool testMax = cdf.maxValue().isValid();

                /* At this point we know that at least of testMin & testMax is true */

                /* Case sensitivity, for those parts that use it */
                Qt::CaseSensitivity cs = (cdf.matchFlags() & QOrganizerItemFilter::MatchCaseSensitive) ? Qt::CaseSensitive : Qt::CaseInsensitive;

                /* See what flags are requested, since we're looking at a value */
                if (cdf.matchFlags() & (QOrganizerItemFilter::MatchEndsWith | QOrganizerItemFilter::MatchStartsWith | QOrganizerItemFilter::MatchContains | QOrganizerItemFilter::MatchFixedString)) {
                    /* We're strictly doing string comparisons here */
                    //bool matchStarts = (cdf.matchFlags() & 7) == QOrganizerItemFilter::MatchStartsWith;
                    bool matchEnds = (cdf.matchFlags() & 7) == QOrganizerItemFilter::MatchEndsWith;
                    bool matchContains = (cdf.matchFlags() & 7) == QOrganizerItemFilter::MatchContains;

                    /* Min/Max and contains do not make sense */
                    if (matchContains)
                        return false;

                    QString minVal = cdf.minValue().toString();
                    QString maxVal = cdf.maxValue().toString();

                    /* Starts with is the normal compare case, endsWith is a bit trickier */
                    for(int j=0; j < details.count(); j++) {
                        const QOrganizerItemDetail& detail = details.at(j);
                        const QString& var = detail.value(cdf.detailFieldName());
                        if (!matchEnds) {
                            // MatchStarts or MatchFixedString
                            if (testMin && QString::compare(var, minVal, cs) < minComp)
                                continue;
                            if (testMax && QString::compare(var, maxVal, cs) >= maxComp)
                                continue;
                            return true;
                        } else {
                            /* Have to test the length of min & max */
                            // using refs means the parameter order is backwards, so negate the result of compare
                            if (testMin && -QString::compare(minVal, var.rightRef(minVal.length()), cs) < minComp)
                                continue;
                            if (testMax && -QString::compare(maxVal, var.rightRef(maxVal.length()), cs) >= maxComp)
                                continue;
                            return true;
                        }
                    }
                    // Fall through to end
                } else {
                    /* Nope, testing the values as a variant */
                    for(int j=0; j < details.count(); j++) {
                        const QOrganizerItemDetail& detail = details.at(j);
                        const QVariant& var = detail.variantValue(cdf.detailFieldName());

                        if (testMin && compareVariant(var, cdf.minValue(), cs) < minComp)
                            continue;
                        if (testMax && compareVariant(var, cdf.maxValue(), cs) >= maxComp)
                            continue;
                        return true;
                    }
                    // Fall through to end
                }
            }
            break;

        case QOrganizerItemFilter::ChangeLogFilter:
            {
                QOrganizerItemChangeLogFilter ccf(filter);

                // See what we can do...
                QOrganizerItemTimestamp ts = item.detail(QOrganizerItemTimestamp::DefinitionName);

                // See if timestamps are even supported
                if (ts.isEmpty())
                    break;

                if (ccf.eventType() == QOrganizerItemChangeLogFilter::EventAdded)
                    return ccf.since() <= ts.created();
                if (ccf.eventType() == QOrganizerItemChangeLogFilter::EventChanged)
                    return ccf.since() <= ts.lastModified();

                // You can't emulate a removed..
                // Fall through to end
            }
            break;

        case QOrganizerItemFilter::IntersectionFilter:
            {
                /* XXX In theory we could reorder the terms to put the native tests first */
                const QOrganizerItemIntersectionFilter bf(filter);
                const QList<QOrganizerItemFilter>& terms = bf.filters();
                if (terms.count() > 0) {
                    for(int j = 0; j < terms.count(); j++) {
                        if (!testFilter(terms.at(j), item)) {
                            return false;
                        }
                    }
                    return true;
                }
                // Fall through to end
            }
            break;

        case QOrganizerItemFilter::UnionFilter:
            {
                /* XXX In theory we could reorder the terms to put the native tests first */
                const QOrganizerItemUnionFilter bf(filter);
                const QList<QOrganizerItemFilter>& terms = bf.filters();
                if (terms.count() > 0) {
                    for(int j = 0; j < terms.count(); j++) {
                        if (testFilter(terms.at(j), item)) {
                            return true;
                        }
                    }
                    return false;
                }
                // Fall through to end
            }
            break;

    case QOrganizerItemFilter::CollectionFilter:
            {
                const QOrganizerItemCollectionFilter cf(filter);
                const QSet<QOrganizerCollectionId>& ids = cf.collectionIds();
                if (ids.contains(item.collectionId()))
                    return true;
                return false;
            }
    }
    return false;
}

/*!
  Returns true if the given \a item (or an occurrence of the item) occurs within the range
  specified by the \a startPeriod and the \a endPeriod, inclusive.
  A default-constructed \a startPeriod signifies that the lower bound of the range is
  infinitely small (i.e., will match anything up to the \a endPeriod) and a default-constructed
  \a endPeriod signifies that the upper bound of the range is infinitely large
  (i.e., will match anything which occurs after the \a startPeriod).
 */
bool QOrganizerManagerEngine::isItemBetweenDates(const QOrganizerItem& item, const QDateTime& startPeriod, const QDateTime& endPeriod)
{
    if (startPeriod.isNull() && endPeriod.isNull())
        return true;

    QDateTime itemDateStart;
    QDateTime itemDateEnd;

    if (item.type() == QOrganizerItemType::TypeEvent || item.type() == QOrganizerItemType::TypeEventOccurrence) {
        QOrganizerEventTime etr = item.detail<QOrganizerEventTime>();
        itemDateStart = etr.startDateTime();
        itemDateEnd = etr.endDateTime();
    } else if (item.type() == QOrganizerItemType::TypeTodo || item.type() == QOrganizerItemType::TypeTodoOccurrence) {
        QOrganizerTodoTime ttr = item.detail<QOrganizerTodoTime>();
        itemDateStart = ttr.startDateTime();
        itemDateEnd = ttr.dueDateTime();
    } else if (item.type() == QOrganizerItemType::TypeJournal) {
        QOrganizerJournal journal = item;
        itemDateStart = itemDateEnd = journal.dateTime();
    } else if (item.type() == QOrganizerItemType::TypeNote) {
        //for note, there is no such start/end datetime so we always return false
        return false;
    }

    // if period start date is not given, check that item is starting or ending before period end
    if (startPeriod.isNull()) // endPeriod must be non-null because of initial test
        return (!itemDateStart.isNull() && itemDateStart <= endPeriod) ||
               (!itemDateEnd.isNull() && itemDateEnd <= endPeriod);

    // if period end date is not given, check that item is starting or ending after the period start
    if (endPeriod.isNull())   // startPeriod must be non-null because of initial test
        return (!itemDateEnd.isNull() && itemDateEnd >= startPeriod) ||
               (!itemDateStart.isNull() && itemDateStart >= startPeriod);

    // Both startPeriod and endPeriod are not null
    // check if item start date is between the period start and end date
    if (!itemDateStart.isNull() && itemDateStart >= startPeriod && itemDateStart <= endPeriod)
        return true;

    // check if item end date is between the period start and end date
    if (!itemDateEnd.isNull() && itemDateEnd >= startPeriod && itemDateEnd <= endPeriod)
        return true;

    // check if item interval is including the period interval
    if (!itemDateStart.isNull() && !itemDateEnd.isNull() && itemDateStart <= startPeriod && itemDateEnd >= endPeriod)
        return true;

    return false;
}

/*!
 * Returns the date associated with \a item that can be used for the purpose of date-sorting
 * the item.
 */
QDateTime getDateForSorting(const QOrganizerItem& item)
{
    QDateTime retn;
    {
        QOrganizerEventTime detail = item.detail<QOrganizerEventTime>();
        if (!detail.isEmpty()) {
            retn = detail.startDateTime();
            if (!retn.isValid())
                retn = detail.endDateTime();
            if (retn.isValid() && detail.isAllDay()) {
                // set it to a millisecond before the given date to have it sorted correctly
                retn.setTime(QTime(23, 59, 59, 999));
                retn.addDays(-1);
            }
            return retn;
        }
    }
    {
        QOrganizerTodoTime detail = item.detail<QOrganizerTodoTime>();
        if (!detail.isEmpty()) {
            retn = detail.startDateTime();
            if (!retn.isValid())
                retn = detail.dueDateTime();
            if (retn.isValid() && detail.isAllDay()) {
                // set it to a millisecond before the given date to have it sorted correctly
                retn.setTime(QTime(23, 59, 59, 999));
                retn.addDays(-1);
            }
            return retn;
        }
    }

    // If it's a note, this will just return null, as expected
    return item.detail<QOrganizerJournalTime>().entryDateTime();
}

/*!
 * Returns true if and only if \a a is temporally less than \a b.  Items with an earlier date are
 * temporally less than items with a later date, or items with no date.  All day items are
 * temporally less than non-all day items on the same date.  For events and todos, the
 * start date is used, or if null, the end date is used.  This function defines a total ordering
 * suitable for use in a sort function.
 */
bool QOrganizerManagerEngine::itemLessThan(const QOrganizerItem& a, const QOrganizerItem& b)
{
    QDateTime date1 = getDateForSorting(a);
    if (!date1.isValid()) {
        return false;
    } else {
        QDateTime date2 = getDateForSorting(b);
        if (!date2.isValid())
            return true;
        else
            return date1 < date2;
    }
}

/*!
  Compares two organizer items (\a a and \a b) using the given list of \a sortOrders.  Returns a negative number if \a a should appear
  before \a b according to the sort order, a positive number if \a a should appear after \a b according to the sort order,
  and zero if the two are unable to be sorted.
 */
int QOrganizerManagerEngine::compareItem(const QOrganizerItem& a, const QOrganizerItem& b, const QList<QOrganizerItemSortOrder>& sortOrders)
{
    QList<QOrganizerItemSortOrder> copy = sortOrders;
    while (copy.size()) {
        // retrieve the next sort order in the list
        QOrganizerItemSortOrder sortOrder = copy.takeFirst();
        if (!sortOrder.isValid())
            break;

        // obtain the values which this sort order concerns
        const QVariant& aVal = a.detail(sortOrder.detailDefinitionName()).variantValue(sortOrder.detailFieldName());
        const QVariant& bVal = b.detail(sortOrder.detailDefinitionName()).variantValue(sortOrder.detailFieldName());

        bool aIsNull = false;
        bool bIsNull = false;

        // treat empty strings as null qvariants.
        if ((aVal.type() == QVariant::String && aVal.toString().isEmpty()) || aVal.isNull()) {
            aIsNull = true;
        }
        if ((bVal.type() == QVariant::String && bVal.toString().isEmpty()) || bVal.isNull()) {
            bIsNull = true;
        }

        // early exit error checking
        if (aIsNull && bIsNull)
            continue; // use next sort criteria.
        if (aIsNull)
            return (sortOrder.blankPolicy() == QOrganizerItemSortOrder::BlanksFirst ? -1 : 1);
        if (bIsNull)
            return (sortOrder.blankPolicy() == QOrganizerItemSortOrder::BlanksFirst ? 1 : -1);

        // real comparison
        int comparison = compareVariant(aVal, bVal, sortOrder.caseSensitivity()) * (sortOrder.direction() == Qt::AscendingOrder ? 1 : -1);
        if (comparison == 0)
            continue;
        return comparison;
    }

    return 0; // or according to id? return (a.id() < b.id() ? -1 : 1);
}


/*!
  Performs insertion sort of the item \a toAdd into the \a sorted list, according to the provided \a sortOrders list.
  The first QOrganizerItemSortOrder in the list has the highest priority; if the item \a toAdd is deemed equal to another
  in the \a sorted list, the second QOrganizerItemSortOrder in the list is used (and so on until either the item is inserted
  or there are no more sort order objects in the list).
 */
void QOrganizerManagerEngine::addSorted(QList<QOrganizerItem>* sorted, const QOrganizerItem& toAdd, const QList<QOrganizerItemSortOrder>& sortOrders)
{
    if (sortOrders.count() > 0) {
        for (int i = 0; i < sorted->size(); i++) {
            // check to see if the new item should be inserted here
            int comparison = compareItem(sorted->at(i), toAdd, sortOrders);
            if (comparison > 0) {
                sorted->insert(i, toAdd);
                return;
            }
        }
    }

    // hasn't been inserted yet?  append to the list.
    sorted->append(toAdd);
}

/*!
  Returns the engine id from the given \a id.
  The caller does not take ownership of the pointer, and should not delete returned id or undefined behavior may occur.
 */
const QOrganizerItemEngineId* QOrganizerManagerEngine::engineItemId(const QOrganizerItemId& id)
{
    return id.d.data();
}

/*!
  Returns the engine id from the given \a id.
  The caller does not take ownership of the pointer, and should not delete returned id or undefined behavior may occur.
 */
const QOrganizerCollectionEngineId* QOrganizerManagerEngine::engineCollectionId(const QOrganizerCollectionId& id)
{
    return id.d.data();
}

/*!
  Notifies the manager engine that the given request \a req has been destroyed.

  This notifies the engine that:
  \list
  \o the client doesn't care about the request any more.  The engine can still complete it,
     but completion is not required.
  \o it can't reliably access any properties of the request pointer any more.  The pointer will
     be invalid once this function returns.
  \endlist
  
  This means that if there is a worker thread, the engine needs to let that thread know that the
  request object is not valid and block until that thread acknowledges it.  One way to do this is to
  have a QSet<QOrganizerAbstractRequest*> (or QMap<QOrganizerAbstractRequest,
  MyCustomRequestState>) that tracks active requests, and insert into that set in startRequest, and
  remove in requestDestroyed (or when it finishes or is cancelled).  Protect that set/map with a
  mutex, and make sure you take the mutex in the worker thread before calling any of the
  QOrganizerAbstractRequest::updateXXXXXXRequest functions.  And be careful of lock ordering
  problems :D
 */
void QOrganizerManagerEngine::requestDestroyed(QOrganizerAbstractRequest* req)
{
    Q_UNUSED(req);
}

/*!
  Asks the manager engine to begin the given request \a req which is currently in a (re)startable
  state.  Returns true if the request was started successfully, else returns false.

  Generally, the engine queues the request and processes it at some later time (probably in another
  thread).
  
  Once a request is started, the engine should call the updateRequestState and/or the specific
  updateXXXXXRequest functions to mark it in the active state.
  
  If the engine is particularly fast, or the operation involves only in memory data, the request can
  be processed and completed without queueing it.
  
  Note that when the client is threaded, and the request might live on a different thread, the
  engine needs to be careful with locking.  In particular, the request might be deleted while the
  engine is still working on it.  In this case, the requestDestroyed function will be called while
  the request is still valid, and that function should block until the worker thread (etc.) has been
  notified not to touch that request any more.

  \sa QOrganizerAbstractRequest::start()
 */
bool QOrganizerManagerEngine::startRequest(QOrganizerAbstractRequest* req)
{
    Q_UNUSED(req);
    return false;
}

/*!
  Asks the manager engine to cancel the given request \a req which was
  previously started and is currently in a cancellable state.
  Returns true if cancellation of the request was started successfully,
  otherwise returns false.

  \sa startRequest(), QOrganizerAbstractRequest::cancel()
 */
bool QOrganizerManagerEngine::cancelRequest(QOrganizerAbstractRequest* req)
{
    Q_UNUSED(req);
    return false;
}

/*!
  Blocks until the manager engine has completed the given request \a req
  which was previously started, or until \a msecs milliseconds have passed.
  Returns true if the request was completed, and false if the request was not in the
  \c QOrganizerAbstractRequest::Active state or no progress could be reported.

  It is important that this function is implemented by the engine, at least merely as a delay, since
  clients may call it in a loop.

  \sa startRequest()
 */
bool QOrganizerManagerEngine::waitForRequestFinished(QOrganizerAbstractRequest* req, int msecs)
{
    Q_UNUSED(req);
    Q_UNUSED(msecs);
    return false;
}

/*!
  Updates the given asynchronous request \a req by setting the new \a state
  of the request.  If the new state is different, the stateChanged() signal
  will be emitted by the request.
 */
void QOrganizerManagerEngine::updateRequestState(QOrganizerAbstractRequest* req, QOrganizerAbstractRequest::State state)
{
    if (req) {
        QMutexLocker ml(&req->d_ptr->m_mutex);
        if (req->d_ptr->m_state != state) {
            req->d_ptr->m_state = state;
            ml.unlock();
            emit req->stateChanged(state);
        }
    }
}

/*!
  Updates the given QOrganizerItemOccurrenceFetchRequest \a req with the latest results \a result, and operation error \a error.
  In addition, the state of the request will be changed to \a newState.

  It then causes the request to emit its resultsAvailable() signal to notify clients of the request progress.

  If the new request state is different from the previous state, the stateChanged() signal will also be emitted from the request.
 */
void QOrganizerManagerEngine::updateItemOccurrenceFetchRequest(QOrganizerItemOccurrenceFetchRequest* req, const QList<QOrganizerItem>& result, QOrganizerManager::Error error, QOrganizerAbstractRequest::State newState)
{
    if (req) {
        QWeakPointer<QOrganizerItemOccurrenceFetchRequest> ireq(req); // Take this in case the first emit deletes us
        QOrganizerItemOccurrenceFetchRequestPrivate* rd = static_cast<QOrganizerItemOccurrenceFetchRequestPrivate*>(req->d_ptr);
        QMutexLocker ml(&rd->m_mutex);
        bool emitState = rd->m_state != newState;
        rd->m_organizeritems = result;
        rd->m_error = error;
        rd->m_state = newState;
        ml.unlock();
        emit ireq.data()->resultsAvailable();
        if (emitState && ireq)
            emit ireq.data()->stateChanged(newState);
    }
}

/*!
  Updates the given QOrganizerItemIdFetchRequest \a req with the latest results \a result, and operation error \a error.
  In addition, the state of the request will be changed to \a newState.

  It then causes the request to emit its resultsAvailable() signal to notify clients of the request progress.

  If the new request state is different from the previous state, the stateChanged() signal will also be emitted from the request.
 */
void QOrganizerManagerEngine::updateItemIdFetchRequest(QOrganizerItemIdFetchRequest* req, const QList<QOrganizerItemId>& result, QOrganizerManager::Error error, QOrganizerAbstractRequest::State newState)
{
    if (req) {
        QWeakPointer<QOrganizerItemIdFetchRequest> ireq(req); // Take this in case the first emit deletes us
        QOrganizerItemIdFetchRequestPrivate* rd = static_cast<QOrganizerItemIdFetchRequestPrivate*>(ireq.data()->d_ptr);
        QMutexLocker ml(&rd->m_mutex);
        bool emitState = rd->m_state != newState;
        rd->m_ids = result;
        rd->m_error = error;
        rd->m_state = newState;
        ml.unlock();
        emit ireq.data()->resultsAvailable();
        if (emitState && ireq)
            emit ireq.data()->stateChanged(newState);
    }
}

/*!
  Updates the given QOrganizerItemFetchRequest \a req with the latest results \a result, and operation error \a error.
  In addition, the state of the request will be changed to \a newState.

  It then causes the request to emit its resultsAvailable() signal to notify clients of the request progress.

  If the new request state is different from the previous state, the stateChanged() signal will also be emitted from the request.
 */
void QOrganizerManagerEngine::updateItemFetchRequest(QOrganizerItemFetchRequest* req, const QList<QOrganizerItem>& result, QOrganizerManager::Error error, QOrganizerAbstractRequest::State newState)
{
    if (req) {
        QWeakPointer<QOrganizerItemFetchRequest> ireq(req); // Take this in case the first emit deletes us
        QOrganizerItemFetchRequestPrivate* rd = static_cast<QOrganizerItemFetchRequestPrivate*>(ireq.data()->d_ptr);
        QMutexLocker ml(&rd->m_mutex);
        bool emitState = rd->m_state != newState;
        rd->m_organizeritems = result;
        rd->m_error = error;
        rd->m_state = newState;
        ml.unlock();
        emit ireq.data()->resultsAvailable();
        if (emitState && ireq)
            emit ireq.data()->stateChanged(newState);
    }
}

/*!
  Updates the given QOrganizerItemFetchForExportRequest \a req with the latest results \a result, and operation error \a error.
  In addition, the state of the request will be changed to \a newState.

  It then causes the request to emit its resultsAvailable() signal to notify clients of the request progress.

  If the new request state is different from the previous state, the stateChanged() signal will also be emitted from the request.
 */
void QOrganizerManagerEngine::updateItemFetchForExportRequest(QOrganizerItemFetchForExportRequest* req, const QList<QOrganizerItem>& result, QOrganizerManager::Error error, QOrganizerAbstractRequest::State newState)
{
    if (req) {
        QWeakPointer<QOrganizerItemFetchForExportRequest> ireq(req); // Take this in case the first emit deletes us
        QOrganizerItemFetchForExportRequestPrivate* rd = static_cast<QOrganizerItemFetchForExportRequestPrivate*>(ireq.data()->d_ptr);
        QMutexLocker ml(&rd->m_mutex);
        bool emitState = rd->m_state != newState;
        rd->m_organizeritems = result;
        rd->m_error = error;
        rd->m_state = newState;
        ml.unlock();
        emit ireq.data()->resultsAvailable();
        if (emitState && ireq)
            emit ireq.data()->stateChanged(newState);
    }
}

/*!
  Updates the given QOrganizerItemRemoveRequest \a req with the operation error \a error, and map of input index to individual error \a errorMap.
  In addition, the state of the request will be changed to \a newState.

  It then causes the request to emit its resultsAvailable() signal to notify clients of the request progress.

  If the new request state is different from the previous state, the stateChanged() signal will also be emitted from the request.
 */
void QOrganizerManagerEngine::updateItemRemoveRequest(QOrganizerItemRemoveRequest* req, QOrganizerManager::Error error, const QMap<int, QOrganizerManager::Error>& errorMap, QOrganizerAbstractRequest::State newState)
{
    if (req) {
        QWeakPointer<QOrganizerItemRemoveRequest> ireq(req); // Take this in case the first emit deletes us
        QOrganizerItemRemoveRequestPrivate* rd = static_cast<QOrganizerItemRemoveRequestPrivate*>(ireq.data()->d_ptr);
        QMutexLocker ml(&rd->m_mutex);
        bool emitState = rd->m_state != newState;
        rd->m_errors = errorMap;
        rd->m_error = error;
        rd->m_state = newState;
        ml.unlock();
        emit ireq.data()->resultsAvailable();
        if (emitState && ireq)
            emit ireq.data()->stateChanged(newState);
    }
}

/*!
  Updates the given QOrganizerItemSaveRequest \a req with the latest results \a result, operation error \a error, and map of input index to individual error \a errorMap.
  In addition, the state of the request will be changed to \a newState.

  It then causes the request to emit its resultsAvailable() signal to notify clients of the request progress.

  If the new request state is different from the previous state, the stateChanged() signal will also be emitted from the request.
 */
void QOrganizerManagerEngine::updateItemSaveRequest(QOrganizerItemSaveRequest* req, const QList<QOrganizerItem>& result, QOrganizerManager::Error error, const QMap<int, QOrganizerManager::Error>& errorMap, QOrganizerAbstractRequest::State newState)
{
    if (req) {
        QWeakPointer<QOrganizerItemSaveRequest> ireq(req); // Take this in case the first emit deletes us
        QOrganizerItemSaveRequestPrivate* rd = static_cast<QOrganizerItemSaveRequestPrivate*>(ireq.data()->d_ptr);
        QMutexLocker ml(&rd->m_mutex);
        bool emitState = rd->m_state != newState;
        rd->m_organizeritems = result;
        rd->m_errors = errorMap;
        rd->m_error = error;
        rd->m_state = newState;
        ml.unlock();
        emit ireq.data()->resultsAvailable();
        if (emitState && ireq)
            emit ireq.data()->stateChanged(newState);
    }
}

/*!
  Updates the given QOrganizerItemDetailDefinitionSaveRequest \a req with the latest results \a result, operation error \a error, and map of input index to individual error \a errorMap.
  In addition, the state of the request will be changed to \a newState.

  It then causes the request to emit its resultsAvailable() signal to notify clients of the request progress.

  If the new request state is different from the previous state, the stateChanged() signal will also be emitted from the request.
 */
void QOrganizerManagerEngine::updateDefinitionSaveRequest(QOrganizerItemDetailDefinitionSaveRequest* req, const QList<QOrganizerItemDetailDefinition>& result, QOrganizerManager::Error error, const QMap<int, QOrganizerManager::Error>& errorMap, QOrganizerAbstractRequest::State newState)
{
    if (req) {
        QWeakPointer<QOrganizerItemDetailDefinitionSaveRequest> ireq(req); // Take this in case the first emit deletes us
        QOrganizerItemDetailDefinitionSaveRequestPrivate* rd = static_cast<QOrganizerItemDetailDefinitionSaveRequestPrivate*>(req->d_ptr);
        QMutexLocker ml(&rd->m_mutex);
        bool emitState = rd->m_state != newState;
        rd->m_definitions = result;
        rd->m_errors = errorMap;
        rd->m_error = error;
        rd->m_state = newState;
        ml.unlock();
        emit ireq.data()->resultsAvailable();
        if (emitState && ireq)
            emit ireq.data()->stateChanged(newState);
    }
}

/*!
  Updates the given QOrganizerItemDetailDefinitionRemoveRequest \a req with the operation error \a error, and map of input index to individual error \a errorMap.
  In addition, the state of the request will be changed to \a newState.

  It then causes the request to emit its resultsAvailable() signal to notify clients of the request progress.

  If the new request state is different from the previous state, the stateChanged() signal will also be emitted from the request.
 */
void QOrganizerManagerEngine::updateDefinitionRemoveRequest(QOrganizerItemDetailDefinitionRemoveRequest* req, QOrganizerManager::Error error, const QMap<int, QOrganizerManager::Error>& errorMap, QOrganizerAbstractRequest::State newState)
{
    if (req) {
        QWeakPointer<QOrganizerItemDetailDefinitionRemoveRequest> ireq(req); // Take this in case the first emit deletes us
        QOrganizerItemDetailDefinitionRemoveRequestPrivate* rd = static_cast<QOrganizerItemDetailDefinitionRemoveRequestPrivate*>(req->d_ptr);
        QMutexLocker ml(&rd->m_mutex);
        bool emitState = rd->m_state != newState;
        rd->m_errors = errorMap;
        rd->m_error = error;
        rd->m_state = newState;
        ml.unlock();
        emit ireq.data()->resultsAvailable();
        if (emitState && ireq)
            emit ireq.data()->stateChanged(newState);
    }
}

/*!
  Updates the given QOrganizerItemDetailDefinitionFetchRequest \a req with the latest results \a result, operation error \a error, and map of input index to individual error \a errorMap.
  In addition, the state of the request will be changed to \a newState.

  It then causes the request to emit its resultsAvailable() signal to notify clients of the request progress.

  If the new request state is different from the previous state, the stateChanged() signal will also be emitted from the request.
 */
void QOrganizerManagerEngine::updateDefinitionFetchRequest(QOrganizerItemDetailDefinitionFetchRequest* req, const QMap<QString, QOrganizerItemDetailDefinition>& result, QOrganizerManager::Error error, const QMap<int, QOrganizerManager::Error>& errorMap, QOrganizerAbstractRequest::State newState)
{
    if (req) {
        QWeakPointer<QOrganizerItemDetailDefinitionFetchRequest> ireq(req); // Take this in case the first emit deletes us
        QOrganizerItemDetailDefinitionFetchRequestPrivate* rd = static_cast<QOrganizerItemDetailDefinitionFetchRequestPrivate*>(req->d_ptr);
        QMutexLocker ml(&rd->m_mutex);
        bool emitState = rd->m_state != newState;
        rd->m_definitions = result;
        rd->m_errors = errorMap;
        rd->m_error = error;
        rd->m_state = newState;
        ml.unlock();
        emit ireq.data()->resultsAvailable();
        if (emitState && ireq)
            emit ireq.data()->stateChanged(newState);
    }
}

/*!
  Updates the given QOrganizerCollectionFetchRequest \a req with the latest results \a result, operation error \a error, and a error map list \a errorMap.
  In addition, the state of the request will be changed to \a newState.

  It then causes the request to emit its resultsAvailable() signal to notify clients of the request progress.
  If the new request state is different from the previous state, the stateChanged() signal will also be emitted from the request.
 */
void QOrganizerManagerEngine::updateCollectionFetchRequest(QOrganizerCollectionFetchRequest* req, const QList<QOrganizerCollection>& result, QOrganizerManager::Error error, QOrganizerAbstractRequest::State newState)
{
    if (req) {
        QWeakPointer<QOrganizerCollectionFetchRequest> ireq(req); // Take this in case the first emit deletes us
        QOrganizerCollectionFetchRequestPrivate* rd = static_cast<QOrganizerCollectionFetchRequestPrivate*>(ireq.data()->d_ptr);
        QMutexLocker ml(&rd->m_mutex);
        bool emitState = rd->m_state != newState;
        rd->m_collections = result;
        rd->m_error = error;
        rd->m_state = newState;
        ml.unlock();
        emit ireq.data()->resultsAvailable();
        if (emitState && ireq)
            emit ireq.data()->stateChanged(newState);
    }
}

/*!
  Updates the given QOrganizerCollectionRemoveRequest \a req with the operation error \a error, and map of input index to individual error \a errorMap.
  In addition, the state of the request will be changed to \a newState.

  It then causes the request to emit its resultsAvailable() signal to notify clients of the request progress.
  If the new request state is different from the previous state, the stateChanged() signal will also be emitted from the request.
 */
void QOrganizerManagerEngine::updateCollectionRemoveRequest(QOrganizerCollectionRemoveRequest* req, QOrganizerManager::Error error, const QMap<int, QOrganizerManager::Error>& errorMap, QOrganizerAbstractRequest::State newState)
{
    if (req) {
        QWeakPointer<QOrganizerCollectionRemoveRequest> ireq(req); // Take this in case the first emit deletes us
        QOrganizerCollectionRemoveRequestPrivate* rd = static_cast<QOrganizerCollectionRemoveRequestPrivate*>(ireq.data()->d_ptr);
        QMutexLocker ml(&rd->m_mutex);
        bool emitState = rd->m_state != newState;
        rd->m_errors = errorMap;
        rd->m_error = error;
        rd->m_state = newState;
        ml.unlock();
        emit ireq.data()->resultsAvailable();
        if (emitState && ireq)
            emit ireq.data()->stateChanged(newState);
    }
}

/*!
  Updates the given QOrganizerCollectionSaveRequest \a req with the latest results \a result, operation error \a error, and map of input index to individual error \a errorMap.
  In addition, the state of the request will be changed to \a newState.

  It then causes the request to emit its resultsAvailable() signal to notify clients of the request progress.
  If the new request state is different from the previous state, the stateChanged() signal will also be emitted from the request.
 */
void QOrganizerManagerEngine::updateCollectionSaveRequest(QOrganizerCollectionSaveRequest* req, const QList<QOrganizerCollection>& result, QOrganizerManager::Error error, const QMap<int, QOrganizerManager::Error>& errorMap, QOrganizerAbstractRequest::State newState)
{
    if (req) {
        QWeakPointer<QOrganizerCollectionSaveRequest> ireq(req); // Take this in case the first emit deletes us
        QOrganizerCollectionSaveRequestPrivate* rd = static_cast<QOrganizerCollectionSaveRequestPrivate*>(ireq.data()->d_ptr);
        QMutexLocker ml(&rd->m_mutex);
        bool emitState = rd->m_state != newState;
        rd->m_collections = result;
        rd->m_errors = errorMap;
        rd->m_error = error;
        rd->m_state = newState;
        ml.unlock();
        emit ireq.data()->resultsAvailable();
        if (emitState && ireq)
            emit ireq.data()->stateChanged(newState);
    }
}

/*!
  Returns the list of organizer items which match the given \a filter stored in the manager sorted
  according to the given list of \a sortOrders, for any item or item occurrence which occurs in the
  range specified by the given \a startDate and \a endDate.  A default-constructed (invalid) \a
  startDate specifies an open start date (matches anything which occurs up until the \a endDate),
  and a default-constructed (invalid) \a endDate specifies an open end date (matches anything which
  occurs after the \a startDate).  If both the \a startDate and \a endDate are invalid, this
  function will return all items which match the \a filter criteria.

  Any operation error which occurs will be saved in \a error.

  If \a sortOrders is the empty list, the returned items will be sorted by date.

  The \a fetchHint parameter describes the optimization hints that a manager may take.  If the \a
  fetchHint is the default constructed hint, all existing details in the matching
  organizer items will be returned.

  \sa QOrganizerItemFetchHint
 */
QList<QOrganizerItem> QOrganizerManagerEngineV2::items(const QDateTime& startDate, const QDateTime& endDate, const QOrganizerItemFilter& filter, const QList<QOrganizerItemSortOrder>& sortOrders, const QOrganizerItemFetchHint& fetchHint, QOrganizerManager::Error* error) const
{
    return QOrganizerManagerEngine::items(
            startDate, endDate, filter, sortOrders, fetchHint, error);
}


/*!
  Returns a list of organizer items in the range specified by the given \a startDate and \a endDate,
  inclusive.  The list will contain the first \a maxCount such items which match the given \a
  filter.  A default-constructed (invalid) \a startDate specifies an open start date (matches
  anything which occurs up until the \a endDate), and a default-constructed (invalid) \a endDate
  specifies an open end date (matches anything which occurs after the \a startDate).  The list is
  sorted by date.

  Any operation error which occurs will be saved in \a error.

  The \a fetchHint parameter describes the optimization hints that a manager may take.  If the \a
  fetchHint is the default constructed hint, all existing details in the matching
  organizer items will be returned.

  \sa QOrganizerItemFetchHint
 */
QList<QOrganizerItem> QOrganizerManagerEngineV2::items(const QDateTime& startDate, const QDateTime& endDate, int maxCount, const QOrganizerItemFilter& filter, const QOrganizerItemFetchHint& fetchHint, QOrganizerManager::Error* error) const
{
    QList<QOrganizerItem> list = items(
            startDate, endDate, filter, QList<QOrganizerItemSortOrder>(), fetchHint, error);
    return list.mid(0, maxCount);
}

/*! \reimp */
bool QOrganizerManagerEngineV2::saveItems(QList<QOrganizerItem>* items, QMap<int, QOrganizerManager::Error>* errorMap, QOrganizerManager::Error* error)
{
    return QOrganizerManagerEngine::saveItems(items, errorMap, error);
}

/*!
  For each item in \a items, either add it to the database or update an existing one.

  This function accepts a \a definitionMask, which specifies which details of the items should be
  updated.  Details with definition names not included in the definitionMask will not be updated
  or added.

  The manager should populate \a errorMap (the map of indices of the \a items list to the error
  which occurred when saving the item at that index) for every index for which the item could
  not be saved, if it is able.

  The supplied \a errorMap parameter may be null, if the client does not desire detailed error information.
  If supplied, it will be empty upon entry to this function.

  The \l QOrganizerManager::error() function will only return \c QOrganizerManager::NoError if all
  items were saved successfully.

  For each newly saved item that was successful, the id of the item in the \a items list
  will be updated with the new value.

  Any errors encountered during this operation should be stored to \a error.
 */
bool QOrganizerManagerEngineV2::saveItems(QList<QOrganizerItem> *items, const QStringList &definitionMask, QMap<int, QOrganizerManager::Error> *errorMap, QOrganizerManager::Error *error)
{
    // TODO should the default implementation do the right thing, or return false?
    if (definitionMask.isEmpty()) {
        // Non partial, just pass it on
        return saveItems(items, errorMap, error);
    } else {
        // Partial item save.
        // Basically

        // Need to:
        // 1) fetch existing items
        // 2) strip out details in definitionMask for existing items
        // 3) copy the details from the passed in list for existing items
        // 4) for any new items, copy the masked details to a blank item
        // 5) save the modified ones
        // 6) update the id of any new items
        // 7) transfer any errors from saving to errorMap

        QList<QOrganizerItemId> existingItemIds;

        // Error conditions:
        // 1) bad id passed in (can't fetch)
        // 2) bad fetch (can't save partial update)
        // 3) bad save error
        // all of which needs to be returned in the error map

        QHash<int, int> existingIdMap; // items index to existingItems index

        // Try to figure out which of our arguments are new items
        for(int i = 0; i < items->count(); i++) {
            // See if there's a itemId that's not from this manager
            const QOrganizerItem item = items->at(i);
            if (item.id().managerUri() == managerUri()) {
                if (!item.id().isNull()) {
                    existingIdMap.insert(i, existingItemIds.count());
                    existingItemIds.append(item.id());
                } else {
                    // Strange. it's just a new item
                }
            } else if (!item.id().managerUri().isEmpty() || !item.id().isNull()) {
                // Hmm, error (wrong manager)
                errorMap->insert(i, QOrganizerManager::DoesNotExistError);
            } // else new item
        }

        // Now fetch the existing items
        QMap<int, QOrganizerManager::Error> fetchErrors;
        QOrganizerManager::Error fetchError = QOrganizerManager::NoError;
        QList<QOrganizerItem> existingItems = this->itemsForExport(existingItemIds, QOrganizerItemFetchHint(), &fetchErrors, &fetchError);

        // Prepare the list to save
        QList<QOrganizerItem> itemsToSave;
        QList<int> savedToOriginalMap; // itemsToSave index to items index
        QSet<QString> mask = definitionMask.toSet();

        for (int i = 0; i < items->count(); i++) {
            // See if this is an existing item or a new one
            const int fetchedIdx = existingIdMap.value(i, -1);
            QOrganizerItem itemToSave;
            if (fetchedIdx >= 0) {
                // See if we had an error
                if (fetchErrors[fetchedIdx] != QOrganizerManager::NoError) {
                    errorMap->insert(i, fetchErrors[fetchedIdx]);
                    continue;
                }

                // Existing item we should have fetched
                itemToSave = existingItems.at(fetchedIdx);

                QSharedDataPointer<QOrganizerItemData>& data = QOrganizerItemData::itemData(itemToSave);
                data->removeOnly(mask);
            } else if (errorMap->contains(i)) {
                // A bad argument.  Leave it out of the itemsToSave list
                continue;
            } // else new item

            // Now copy in the details from the arguments
            const QOrganizerItem& item = items->at(i);

            // Perhaps this could do this directly rather than through saveDetail
            // but that would duplicate the checks for display label etc
            foreach (const QString& name, mask) {
                QList<QOrganizerItemDetail> details = item.details(name);
                foreach(QOrganizerItemDetail detail, details) {
                    itemToSave.saveDetail(&detail);
                }
            }

            savedToOriginalMap.append(i);
            itemsToSave.append(itemToSave);
        }

        // Now save them
        QMap<int, QOrganizerManager::Error> saveErrors;
        QOrganizerManager::Error saveError = QOrganizerManager::NoError;
        saveItems(&itemsToSave, &saveErrors, &saveError);

        // Now update the passed in arguments, where necessary

        // Update IDs of the items list
        for (int i = 0; i < itemsToSave.count(); i++) {
            (*items)[savedToOriginalMap[i]].setId(itemsToSave[i].id());
        }
        // Populate the errorMap with the errorMap of the attempted save
        QMap<int, QOrganizerManager::Error>::iterator it(saveErrors.begin());
        while (it != saveErrors.end()) {
            if (it.value() != QOrganizerManager::NoError) {
                errorMap->insert(savedToOriginalMap[it.key()], it.value());
            }
            it++;
        }

        return errorMap->isEmpty();
    }
}

/*! \reimp */
QList<QOrganizerItem> QOrganizerManagerEngineV2::itemsForExport(const QDateTime& startDate, const QDateTime& endDate, const QOrganizerItemFilter& filter, const QList<QOrganizerItemSortOrder>& sortOrders, const QOrganizerItemFetchHint& fetchHint, QOrganizerManager::Error* error) const
{
    return QOrganizerManagerEngine::itemsForExport(startDate, endDate, filter, sortOrders, fetchHint, error);
}

/*!
  Returns the list of items with the ids given by \a ids.  There is a one-to-one
  correspondence between the returned items and the supplied \a ids.

  If there is an invalid id in \a ids, then an empty QOrganizerItem will take its place in the
  returned list and an entry will be inserted into \a errorMap.

  The overall operation error will be saved in \a error.

  The \a fetchHint parameter describes the optimization hints that a manager may take.
  If the \a fetchHint is the default constructed hint, all existing details
  in the matching items will be returned.

  If a non-default fetch hint is supplied, and the client wishes to make changes to the items,
  they should ensure that only a detail definition hint is supplied and that when saving it back, a
  definition mask should be used which corresponds to the detail definition hint.  This is to ensure
  that no data is lost by overwriting an existing item with a restricted version of it.

  \sa QOrganizerItemFetchHint
 */
QList<QOrganizerItem> QOrganizerManagerEngineV2::itemsForExport(const QList<QOrganizerItemId> &ids, const QOrganizerItemFetchHint &fetchHint, QMap<int, QOrganizerManager::Error> *errorMap, QOrganizerManager::Error *error) const
{
    QOrganizerItemIdFilter filter;
    filter.setIds(ids);

    QList<QOrganizerItem> unsorted = itemsForExport(QDateTime(), QDateTime(), filter, QOrganizerItemSortOrder(), fetchHint, error);

    // Build an index into the results
    QHash<QOrganizerItemId, int> idMap; // value is index into unsorted
    if (*error == QOrganizerManager::NoError) {
        for (int i = 0; i < unsorted.size(); i++) {
            idMap.insert(unsorted[i].id(), i);
        }
    }

    // Build up the results and errors
    QList<QOrganizerItem> results;
    for (int i = 0; i < ids.count(); i++) {
        QOrganizerItemId id(ids[i]);
        if (!idMap.contains(id)) {
            if (errorMap)
                errorMap->insert(i, QOrganizerManager::DoesNotExistError);
            if (*error == QOrganizerManager::NoError)
                *error = QOrganizerManager::DoesNotExistError;
            results.append(QOrganizerItem());
        } else {
            results.append(unsorted[idMap[id]]);
        }
    }

    return results;
}

/*!
  Updates the given QOrganizerItemFetchByIdRequest \a req with the latest results \a result, and operation error \a error, and map of input index to individual error \a errorMap.
  In addition, the state of the request will be changed to \a newState.

  It then causes the request to emit its resultsAvailable() signal to notify clients of the request progress.

  If the new request state is different from the previous state, the stateChanged() signal will also be emitted from the request.
 */
void QOrganizerManagerEngineV2::updateItemFetchByIdRequest(QOrganizerItemFetchByIdRequest* req, const QList<QOrganizerItem>& result, QOrganizerManager::Error error, const QMap<int, QOrganizerManager::Error>& errorMap, QOrganizerAbstractRequest::State newState)
{
    if (req) {
        QWeakPointer<QOrganizerItemFetchByIdRequest> ireq(req); // Take this in case the first emit deletes us
        QOrganizerItemFetchByIdRequestPrivate* rd = static_cast<QOrganizerItemFetchByIdRequestPrivate*>(ireq.data()->d_ptr);
        QMutexLocker ml(&rd->m_mutex);
        bool emitState = rd->m_state != newState;
        rd->m_items = result;
        rd->m_errors = errorMap;
        rd->m_error = error;
        rd->m_state = newState;
        ml.unlock();
        emit ireq.data()->resultsAvailable();
        if (emitState && ireq)
            emit ireq.data()->stateChanged(newState);
    }
}


#include "moc_qorganizermanagerengine.cpp"

QTM_END_NAMESPACE