summaryrefslogtreecommitdiffstats
path: root/plugins/contacts/symbian/contactsmodel/cntmodel/src/rcntmodel.cpp
blob: a820dd9bae8f856d94eb7f15ec91dded5a02d2ac (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
/*
* Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
* Contact: http://www.qt-project.org/legal
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: 
*
*/


/**
 @file
 @internalComponent
 @released
*/

#include <s32mem.h>
#include <cntitem.h>
#include <cntdb.h>
#include <cntfilt.h>

#include "rcntmodel.h"
#include "persistencelayer.h" // for mlplcollection.
#include "ccntnotificationmonitor.h"
#include "ccontactprivate.h" // for mprogresseventhander.
#include "ccntpackager.h"
#include <cntviewstore.h>
#include <cntfield.h>
#include "cntstd.h"
#include <cntdef.h>
#include <cntfldst.h>
#include "cntimagerescaler.h"
#include "cntdbconsts_internal.h"


/** Contacts server version number. */ 
const TInt KCntServerMajorVersionNumber=1;
const TInt KCntServerMinorVersionNumber=1;
const TInt KCntServerBuildVersionNumber=1;

/** Number of attempts to try restart the server after premature termination. */
const TInt KMaxTimesToRestartServer = 3;

/** Maximum number of asynchronous IPC calls. */
const TInt KAsyncMessageSlots=6;


/**
Unlock the last locked contact item on the server.  Used by OpenLX().  If any
method which locks a contact item leaves thenccnt this method is called as the
cleanup stack unwinds, removing the lock for the last locked contact item.

@capability None
*/
void CleanupUnlockRecord(TAny *aSession)
	{
	static_cast<RCntModel*>(aSession)->UnlockLastLockedContact();
	}


/**
Unlock the last locked contact item on the server.  Used by OpenLX().

@capability None
*/
void RCntModel::UnlockLastLockedContact()
	{
	CloseContact(KNullContactId);
	}


/**
Push a Contact item unlock cleanup item on the cleanup stack.
*/
void RCntModel::PushUnlockL() const
	{
	CleanupStack::PushL( TCleanupItem(CleanupUnlockRecord, const_cast<RCntModel *>(this)));
	}


/**
RCntModel constructor.

Member variables must be initialised (zero'd) in the constructor since
RCntModel does not derive from CBase.
*/
RCntModel::RCntModel()
	:
	iDbNotifyMonitor(NULL), 
	iPackager(NULL),
	iConnectionId(0),
	iNoOfSvrStartAttempts(0),
    iRescaler(NULL),
    iServerRunning(EFalse)
	{
	}


/**
Get the Contacts server version number.

@return Contacts server version number.
*/
TVersion RCntModel::Version() const
	{
	return(TVersion(KCntServerMajorVersionNumber,KCntServerMinorVersionNumber,KCntServerBuildVersionNumber));
	}


/** Name of the executable for the Contacts server. */
_LIT(KCntServerExe,"CNTSRV.EXE");
/** Name used to connect a session to the Contacts server. */
_LIT(KCntServerName,"CNTSRV");


/**
Open a Contacts server session.
*/
void RCntModel::ConnectL()
	{
    iServerRunning = EFalse;
	// Assume the server is already running and attempt to create a session
	// with a maximum of KAsyncMessageSlots message slots.
	TInt err = CreateSession(KCntServerName,Version(),KAsyncMessageSlots);
	
	if(err == KErrNotFound) // Server not running?
		{
		// Use the RProcess API to start the server.
		RProcess server;
		User::LeaveIfError(server.Create(KCntServerExe,KNullDesC));
		
		//Enforce server to be at system default priority EPriorityForeground
		//Contact server used to set as EPriorityHigh and this caused client could
		//not get control or responsive until sorting by the idle sorter in remote 
		//view was done.
		server.SetPriority(EPriorityForeground);
		
		// Synchronise with the server.
		TRequestStatus reqStatus;
		server.Rendezvous(reqStatus);
		server.Resume();
		
		// Server will call the reciprocal static synchronisation call.
		User::WaitForRequest(reqStatus);
		server.Close();
		User::LeaveIfError(reqStatus.Int());
		
		// Create the server session.
		User::LeaveIfError(CreateSession(KCntServerName,Version(),KAsyncMessageSlots));
		}
	else
		{
		User::LeaveIfError(err);
		}
	
	// Connection successful
	iServerRunning = ETrue;

	// Create object packer/unpacker if it doesn't already exist.
	if (iPackager == NULL)	
		{
		iPackager = CCntPackager::NewL();
		}
	
	// Each session (client) will be given a unique ID known as the Connection
	// ID.  This ID forms part of the database event notification message.  This
	// ID is created during the connection to the server.
	ConnectionId();
    
    // Create a image rescaler
	if (iRescaler == NULL)
	    {
	    iRescaler = CImageRescaler::NewL();
	    }
	}

	
/**
Close session.
*/
void RCntModel::Close()
	{
	delete iPackager;
	iPackager = NULL;
	delete iDbNotifyMonitor;
	iDbNotifyMonitor = NULL;
	delete iRescaler;
	iRescaler = NULL;
	RHandleBase::Close();
	}


/**
Open a named contact database.

Opens the default contacts database if the default argument is used.  The given
descriptor must not contain more than KCntMaxFilePath characters.

@param aCntFile Filename (in the form drive:database).  Defaults to
KCntDefaultDrive.

@return KErrNone if success, KErrArgument if the given descriptor contains more than the 
        maximum length of 190 characters, otherwise one of the System error codes.

@capability ReadUserData
*/
TInt RCntModel::OpenDatabase(const TDesC& aCntFile) const
    {
    if (!iServerRunning )
        {
        return KErrServerTerminated;
        }
    TInt err = SetFileName(aCntFile);
    if (err == KErrNone)
        {
        TIpcArgs args;
        args.Set(0,&aCntFile);
        err = SendReceive(ECntOpenDataBase, args);
        }

    return err;
    }


/**
Open a named contact database asynchronously.

Opens the default contacts database if the default argument is used.  The given
descriptor must not contain more than KCntMaxFilePath characters.

@param aStatus Asynchronous request object.  Request is completed when database
has been opened.
@param aCntFile Contacts database filename (in the form drive:database).
Defaults to KCntDefaultDrive.

@capability ReadUserData
*/
void RCntModel::OpenDatabaseAsyncL(TRequestStatus& aStatus, const TDesC& aCntFile)
    {
    if (!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
    User::LeaveIfError(SetFileName(aCntFile));

    TIpcArgs args;
    args.Set(0,&aCntFile);
    SendReceive(ECntOpenDataBase, args, aStatus);
    }


/**
Cancel last asynchronous database open request.

@capability None
*/
void RCntModel::CancelAsyncOpen() 
	{
    if (!iServerRunning)
        {
        return;
        }
	SendReceive(ECntCancelAsyncOpenDatabase);		
	}


/**
Handle a premature termination of the contact server process by re-connecting
the session and re-opening the database.

@capability ReadUserData
*/
void RCntModel::HandlePrematureServerTerminationL()
	{
	if (iNoOfSvrStartAttempts > KMaxTimesToRestartServer)
		{
		User::Leave(KErrServerTerminated);
		}
	ConnectL();
	User::LeaveIfError(OpenDatabase(iFileName));
	++iNoOfSvrStartAttempts;
	}

	
/**
Set the database filename. Used to re-open the database if the server is
terminated prematurely.

@param aCntFile Contacts database filename (in the form drive:database).
@return KErrNone if success, KErrArgument if the given descriptor contains more than the 
        maximum length of 190 characters.         
*/
TInt RCntModel::SetFileName(const TDesC& aCntFile) const
    {
    if(aCntFile.Length() > KCntMaxFilePath)
        {
        return KErrArgument;
        }

    iFileName = aCntFile;
    return KErrNone;
    }


/**
Close currently open database.

@capability None
*/
void RCntModel::CloseDatabase() const
	{
    if (!iServerRunning)
        {
        return;
        }
	(void)SendReceive(ECntCloseDataBase);
	}


/**
Get the machine ID. 

Note: This function can leave.

@return Machine ID.

@leave KErrNone The send operation is successful
@leave KErrServerTerminated The server no longer present
@leave KErrServerBusy There are no message slots available
@leave KErrNoMemory There is insufficient memory available


@capability None
*/
TInt64 RCntModel::MachineId() const
	{
    if (!iServerRunning)
        {
        return KErrServerTerminated;
        }
	TIpcArgs args;
	TPckgBuf<TInt64> machineID;
	args.Set(0, &machineID);
	User::LeaveIfError(SendReceive(ECntMachineID, args)); // this can leave
	return machineID();	
	}


/**
Set the machine ID (debug only).

@param aMachineUniqueId New machine ID.

@capability None
*/
void RCntModel::OverrideMachineUniqueId(TInt64 aMachineUniqueId)
	{
    if (!iServerRunning)
        {
        return;
        }
	TIpcArgs args;
	TPckgBuf<TInt64> machineID(aMachineUniqueId);
	args.Set(0, &machineID);
	(void)SendReceive(ECntOverrideMachineID, args);	
	}


/**
Replace a named contact database with an empty one, replacing any database with
the same name.  Replaces the default contacts database if the default argument
is used.  The given descriptor must not contain more than KCntMaxFilePath
characters.

@param aCntFile Contacts database filename (in the form drive:database).
Defaults to KCntDefaultDrive.

@return KErrNone if success, KErrArgument if the given descriptor contains more than the 
        maximum length of 190 characters, KErrInUse if the database is currently open, 
        otherwise one of the System error codes.

@capability WriteUserData
*/
TInt RCntModel::ReplaceDatabase(const TDesC& aCntFile) const
    {
    if (!iServerRunning)
        {
        return KErrServerTerminated;
        }
    TInt err = SetFileName(aCntFile);
    if (err == KErrNone)
        {
        TIpcArgs args;
        args.Set(0,&aCntFile);

        err = SendReceive(ECntReplaceDatabase, args);
        }

    return err;
    }


/**
Returns an array of contact item IDs for all the contact items which may contain
the specified telephone number in a telephone, fax or SMS type field.

@see CContactDatabase::MatchPhoneNumberL() for more details on the match.

@param aNumber Phone number string
@param aMatchLengthFromRight Number of digits from the right of the phone number
to use.  Up to 15 digits can be specified and it is recommended that at least 7
match digits are specified.

@return CContactIdArray of candidate matches.

@capability ReadUserData
*/
CContactIdArray* RCntModel::MatchPhoneNumberL(const TDesC& aNumber, const TInt aMatchLengthFromRight)
	{
    if (!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
    
	TIpcArgs args;
	args.Set(0, &iPackager->GetReceivingBufferL());
	args.Set(1, MLplCollection::EMatchPhoneNos);
	args.Set(2, &aNumber);
	args.Set(3, aMatchLengthFromRight);
	
	TInt newBuffSize = 0;
	User::LeaveIfError(newBuffSize = SendReceive(ECntGetCollection, args));
	
	if (newBuffSize > 0)
		{
		// If the buffer is not large enough resize the packager's internal
		// buffer and make the call again.
		args.Set(0, &iPackager->GetReceivingBufferL(newBuffSize));
		User::LeaveIfError(newBuffSize = SendReceive(ECntGetCollection, args));		
		}
		
	CContactIdArray* idArray = iPackager->UnpackCntIdArrayLC();	
	CleanupStack::Pop(idArray);

	return idArray;
	}
	
	

/**
Create an empty named contact database.

Creates the default contacts database if the default argument is used.  The
given descriptor must not contain more than KCntMaxFilePath characters.

@param aCntFile Contacts database filename (in the form drive:database).
Defaults to KCntDefaultDrive.

@return KErrNone if success, KErrArgument if the given descriptor contains more than the 
        maximum length of 190 characters, KErrAlreadyExists if the database already 
        exists otherwise one of the System error codes.

@capability WriteUserData
*/
TInt RCntModel::CreateDatabase(const TDesC& aCntFile) const
    {
    if (!iServerRunning)
        {
        return KErrServerTerminated;
        }
    
    TInt err = SetFileName(aCntFile);
    if (err == KErrNone)
        {
        TIpcArgs args;
        args.Set(0,&aCntFile);
        err = SendReceive(ECntCreateDatabase, args);
        }
    return err;
    }


/**
Create the system template.

@return KErrNone if success otherwise one of the System error codes.
	
@capability WriteUserData
*/
TInt RCntModel::ReCreateTemplate() const
	{
    if (!iServerRunning)
        {
        return KErrServerTerminated;
        }
	return SendReceive(ECntReCreateTemplate);
	}


/**
Get the database file UID.

@return Pointer to file UID.

@capability None
*/
TPtrC RCntModel::FileUidL() const
	{
    if (!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
    
	TIpcArgs args;
	args.Set(0, &iFileUid);
	User::LeaveIfError (SendReceive(ECntFileUniqueId, args));
    return iFileUid;
	}


/**
Determine if the database is ready.  Ready in this context means that the
database is open and readable/writable (i.e. the state machine is in
CStateWritable).

@capability None

@return ETrue if the database is ready, EFalse if the database is not ready.
*/
TBool RCntModel::DatabaseReadyL() const
    {
    if (!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
    TBool retVal = EFalse;

    // Although the ECntGetDatabaseReady msg. is completed with TBool values,
    // during message processing, it is possible that ServiceError() occurs,
    // causing the message to be completed with negative error codes.
    // LeaveIfError() would protect against such cases.
    User::LeaveIfError(retVal = SendReceive(ECntGetDatabaseReady));

    return retVal;
    }


/**
Tests whether a contact item's hint bit field matches a filter.

@param aBitWiseFilter The filter to compare the item against.  This is a
combination of TContactViewFilter values.
@param aContactId The ID of the item in the database.

@return ETrue if the item is of the correct type for inclusion in the database 
and its hint bit field matches the specified filter, EFalse if either of these
conditions are not met.

@capability None
*/
TBool RCntModel::ContactMatchesHintFieldL(TInt aBitWiseFilter, TContactItemId aContactId)
    {
    if (!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
    
    TIpcArgs args;
    args.Set(0, aBitWiseFilter);
    args.Set(1, aContactId);
    TBool retVal = EFalse;

    // Although the ECntMatchesHintField msg. is completed with TBool values,
    // during message processing, it is possible that ServiceError() occurs,
    // causing the message to be completed with negative error codes.
    // LeaveIfError() would protect against such cases.
    User::LeaveIfError (retVal = SendReceive(ECntMatchesHintField, args));

    return retVal;
    }


/**
Delete a named contact database.

Deletes the default contacts database if the default argument is used.  The
given descriptor must not contain more than KCntMaxFilePath characters.

@param aCntFile Contacts database filename (in the form drive:database).
Defaults to KCntDefaultDrive.

@return KErrNone if success, KErrArgument if the given descriptor contains more 
        than the maximum length of 190 characters, KErrInUse if the database is 
        in use, KErrNotFound if the database does not exist otherwise one of the 
        System error codes.

@capability WriteUserData
*/
TInt RCntModel::DeleteDatabase(const TDesC& aCntFile) const
	{
    if (!iServerRunning)
        {
        return KErrServerTerminated;
        }
    
	if(aCntFile.Length() > KCntMaxFilePath)
		{
		return KErrArgument;
		}
	TIpcArgs args;
	args.Set(0,&aCntFile);
	return SendReceive(ECntDeleteDatabase,args);
	}


/**
Get the name of the default contact database file.

The given descriptor must have room for minimum of KCntMaxFilePath characters.

@param aCntFile Contains the default contact database name on return.

@return KErrNone if success, KErrArgument if the given descriptor contains more 
        than the maximum length of 190 characters, otherwise one of the System 
        error codes.

@capability None
*/
TInt RCntModel::DefaultDatabase(TDes& aCntFile) const
	{
    if (!iServerRunning)
        {
        return KErrServerTerminated;
        }
    
	TIpcArgs args;
	args.Set(0,&aCntFile);
	return SendReceive(ECntGetDefaultDatabaseName,args);
	}


/**
Retrieve the current contact database drive.

@param aDriveUnit Contains the current contact database drive unit on return.

@return KErrNone if success otherwise one of the System error codes.

@capability None
*/
TInt RCntModel::DatabaseDrive(TDriveUnit& aDriveUnit) const
	{
    if (!iServerRunning)
        {
        return KErrServerTerminated;
        }
    
	TInt ret = SendReceive(ECntDatabaseDrive);
	if (ret >= KErrNone)
		{
		aDriveUnit = ret;	
		}
	return ret;
	}


/**
Sets the contact database drive and optionally moves the default contact
database from its current location to the new drive.  This function guarantees
an all or nothing operation.  If the database is not successfully moved, the
drive setting is not updated to reflect the change.

@param aDriveUnit The drive to which to move the contact database.
@param aCopy ETrue moves the existing file to the specified drive.  Deletion of
the source file will fail if it is in use.  EFalse does not move the file.  The
default argument value is ETrue.

@return KErrNone if success, KErrInUse if destination file for copy is open,
KErrNotFound found if source contact database (default) cannot be found,
KErrAlreadyExists if the destination contact database file exists.

@capability WriteUserData
*/
void RCntModel::SetDatabaseDriveL(TDriveUnit aDriveUnit, TBool aCopy)
	{
    if (!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
    
	TIpcArgs args;
	args.Set(0,aDriveUnit);
	args.Set(1,aCopy);
	User::LeaveIfError(SendReceive(ECntSetDatabaseDrive,args));
	}

/** 
Gets the size of the database file in bytes.

@return The size of the contact database in bytes.

@capability None
*/
TInt RCntModel::FileSize() const
	{
    if (!iServerRunning )
        {
        return KErrServerTerminated;
        }
	return SendReceive(ECntFilesSize);	
	}

/**
Determine if the named contact database file exists.

If the aCntFile argument is the default, determines if default contact database
file exists.

@param aCntFile Contacts database filename (in the form drive:database).
@leave KErrArgument if the given descriptor contains more than the maximum length 
       of 190 characters, otherwise one of the System error codes.
@return ETrue if exists, EFalse does not exist. 
@capability None
*/
TBool RCntModel::DatabaseExistsL(const TDesC& aCntFile) const
    {
    if (!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
    
    if(aCntFile.Length() > KCntMaxFilePath)
        {
        User::Leave(KErrArgument);
        }

    TIpcArgs args;
    args.Set(0,&aCntFile);
    TBool ret = EFalse;

    // Although ECntDatabaseExists is normally completed with TBool values,
    // ServiceError() can occur which leads to a negative system error codes
    // being returned.  User::LeaveIfError will allow that to be properly handled.
    User::LeaveIfError(ret = SendReceive(ECntDatabaseExists,args));

    return ret;
    }


/**
List the contact database files for any given drive unit.  Lists all databases
on all drives if aDriveUnit is set to NULL.

@param aDriveUnit The drive unit to search.  Searches all drives if default
argument is used.

@return CDesCArray containing the database list.  Always returns list even if
empty.

@leave KErrNoMemory if not enough free memory, KErrNotReady if drive does not,
otherwise one of the System error codes.

@capability ReadUserData
*/
CDesCArray* RCntModel::ListDatabasesL(TDriveUnit* aDriveUnit) const
	{
    if (!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
    
	// Convert the drive unit to an integer for IPC.  The TDriveUnit constructor
	// does not allow values outside 0 - 25.
	TInt driveNumber;
	(aDriveUnit == NULL) ? (driveNumber = ECntAllDrives) : (driveNumber = *aDriveUnit);

	// Provide a CBufFlat for receiving the list of databases from the server.
	// Format is a (proprietary) serialized CDesCArray.
	const TInt KInitialBufferSize = 200;
	CBufFlat* listBuffer = CBufFlat::NewL(KInitialBufferSize);
	CleanupStack::PushL(listBuffer);
	listBuffer->ExpandL(0,KInitialBufferSize);

	// IPC argument list is:
	// 0 (Return param)	- Address of our receive buffer
	// 1 (Param)		- The drive number 0 - 25 or ECntAllDrives
	// 2 (Return param)	- The size of buffer required for the transfer
	TIpcArgs args;
	TPtr8 ptr(listBuffer->Ptr(0));
	args.Set(0,&ptr);
	args.Set(1,driveNumber);
	TPckgBuf<TInt> size;
	args.Set(2,&size);
	User::LeaveIfError(SendReceive(ECntListDatabases,args));

	// Check if our buffer was large enough by reading returned size argument.
	// The server will not have written any data if our povided buffer was not
	// big enough.
	if(size() > KInitialBufferSize)
		{
		// Not big enough but now we know how big the buffer needs to be.
		// Just allocate buffer again, reset the IPC args and call again.
		CleanupStack::PopAndDestroy(listBuffer);
		listBuffer = CBufFlat::NewL(size());
		CleanupStack::PushL(listBuffer);
		listBuffer->ExpandL(0,size());
		ptr.Set(listBuffer->Ptr(0));
		args.Set(0,&ptr);
		args.Set(1,driveNumber);
		args.Set(2,&size);
		User::LeaveIfError(SendReceive(ECntListDatabases,args));
		}

	// Wrap the buffer in a read stream class to internalize.
	RBufReadStream readStream;
	readStream.Open(*listBuffer);
	CleanupClosePushL(readStream);

	// Number of array elements.
	const TInt count = readStream.ReadUint32L();
	// Use count if it is not zero.
	CDesCArray* list = new(ELeave) CDesCArrayFlat(count ? count : 1);
	CleanupStack::PushL(list);
	for (TInt i=0; i<count; ++i)
		{
		TFileName path;
		TInt length=readStream.ReadInt8L();
		readStream.ReadL(path,length);
		// Add to the list.
		list->AppendL(path);
		}

	CleanupStack::Pop(list);
	CleanupStack::PopAndDestroy(&readStream);
	CleanupStack::PopAndDestroy(listBuffer);
	
	return list;
	}


/**
Add a new contact to the database.

@param aContact The contact to be added to the database.

@capability WriteUserData
*/
TContactItemId RCntModel::CreateContactL(CContactItem& aContact) const
	{
    if (!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
    
    // Process the image field
    if (iRescaler)
        {
        iRescaler->ProcessImageFieldL(aContact);
        }
    
	// Pack the contact into the first IPC argument.
	TIpcArgs args;
	TPtr8 ptr(iPackager->PackL(aContact));
	args.Set(0,&ptr);

	TInt cntId = 0;
	User::LeaveIfError(cntId = SendReceive(ECntItemCreate, args));

	return cntId;
	}


/**
Delete a contact from the database.

@param aCntId The contact to be deleted.
@param aCntEventType The event type to pass on to the observers.
@param aDecAccessCount If ETrue access count should be decremented prior to the
deletion.

@capability WriteUserData
*/
void RCntModel::DeleteContactL(TContactItemId aCntId, TCntSendEventAction aCntEventType, TBool aDecAccessCount) const
	{
    if (!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
	TIpcArgs args(aCntId, aCntEventType, aDecAccessCount);
	User::LeaveIfError(SendReceive(ECntItemDelete, args));
	}

/**
Delete a contact from the database.

@param aCntId The contact to be deleted.
@param aCntEventType The event type to pass on to the observers.
@param aDecAccessCount If ETrue access count should be decremented prior to the
deletion.

@return KErrNone if the function completed successfully, otherwise one of the 
standard error codes.

@capability WriteUserData
*/
TInt RCntModel::DeleteContact(TContactItemId aCntId, TCntSendEventAction aCntEventType, TBool aDecAccessCount) const
	{
    if (!iServerRunning)
        {
        return KErrServerTerminated;
        }
	TIpcArgs args(aCntId, aCntEventType, aDecAccessCount);
	return SendReceive(ECntItemDelete, args);
	}

/** 
Open the database tables.

@capability ReadUserData
*/
void RCntModel::OpenTablesL()
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
	User::LeaveIfError(SendReceive(ECntReOpenDbTables));
	}


/**
Close the database tables.

@capability None
*/
void RCntModel::CloseTablesL()
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
	User::LeaveIfError(SendReceive(ECntCloseDbTables));
	}


/**
Update and unlock an existing contact in the database.

@param aContact The contact to be updated and unlocked
@param aSendChangedEvent If ETrue the changed event should be sent after the
update/unlock.

@capability WriteUserData
*/
void RCntModel::CommitContactL(const CContactItem& aContact, TBool aSendChangedEvent) const
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
    //check what contacts were added/removed to a group
    if (aContact.Type() == KUidContactGroup)
        {
        const CContactGroup& group = static_cast<const CContactGroup&>(aContact);
        if (group.iInitialContactIds != NULL)
            {
            group.iAddedContactIds = CContactIdArray::NewL();
            group.iRemovedContactIds = CContactIdArray::NewL();
            for (int i = 0; i < group.iItems->Count(); i++)
                {
                if (group.iInitialContactIds->Find(group.iItems->operator[](i)) == KErrNotFound)
                    {
                    group.iAddedContactIds->AddL(group.iItems->operator[](i));
                    }
                }
            for (int j = 0; j < group.iInitialContactIds->Count(); j++)
                {
                if (group.iItems->Find(group.iInitialContactIds->operator[](j)) == KErrNotFound)
                    {
                    group.iRemovedContactIds->AddL(group.iInitialContactIds->operator[](j));
                    }
                }           
            }
        }
    
    // Process the image field
    if (iRescaler)
        {
        iRescaler->ProcessImageFieldL(const_cast<CContactItem&>(aContact));
        }
    
	// Pack the contact into the first IPC argument.
	TIpcArgs args; 
	TPtr8 ptr(iPackager->PackL((const_cast<CContactItem&>(aContact))));
	args.Set(0,&ptr);
	
	args.Set(1,aSendChangedEvent);

	User::LeaveIfError(SendReceive(ECntItemCommit, args));
	
    //clear list of contacts added/removed to a group
    if (aContact.Type() == KUidContactGroup)
        {
        const CContactGroup& group = static_cast<const CContactGroup&>(aContact);
        if (group.iAddedContactIds != NULL)
            {
            delete group.iAddedContactIds;
            group.iAddedContactIds = NULL;
            }
        if (group.iRemovedContactIds != NULL)
            {
            delete group.iRemovedContactIds;
            group.iRemovedContactIds = NULL;
            }
        if (group.iInitialContactIds != NULL)
            {
            delete group.iInitialContactIds;
            group.iInitialContactIds = NULL;
            }
        }	
	}


/**
Unpacks a contact item contained within the Packager's internal buffer and
creates a contact item object.  Within the server, the contact item has been
written to the Packager's internal buffer by the RMessage2.

If the buffer size was returned then the buffer was not large enough to hold a
serialised contact item.  The buffer must be expanded to the size returned by
the server (ie aBufferSize) and the read operation performed again. 

@see CCntPackager::SetBufferFromMessageL()
	
@param aBufferSize The new buffer size.
@param aArgs The argument buffer where the serialised contact item is written by
the server.

@return CContactItem unpacked from Packager's internal buffer.

@capability ReadUserData
*/
CContactItem* RCntModel::UnPackContactLC(TInt aBufferSize, TIpcArgs& aArgs) const
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
	if(aBufferSize > 0) // Packager's internal buffer is not large enough.
		{
		// Set new extended receiving buffer.
		aArgs.Set(1, &iPackager->GetReceivingBufferL(aBufferSize));
		// Perform read operation again.
		User::LeaveIfError(SendReceive(ECntItemRead, aArgs));
		}
	return iPackager->UnpackCntItemLC();
	}


/**
Read an existing contact in the database.

@param aCntItemVDef The view definition to use.
@param aCntId Contact ID to read.

@return CContactItem object with contact ID aCntId.
*/
CContactItem* RCntModel::ReadContactL(const CContactItemViewDef* aCntItemVDef, TContactItemId aCntId) const
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
	TIpcArgs args;

	if (aCntItemVDef) 
		{
		iPackager->PackL(*(const_cast<CContactItemViewDef*>(aCntItemVDef)));
		// Indicates that a user ContactItemViewDef is present in first IPC
		// argument.
		args.Set(3,TRUE);
		}
	else
		{
		iPackager->Clear();
		// Indicates that no user ContactItemViewDef is present in first IPC
		// argument.  The default view definition will be used instead.
		args.Set(3,FALSE);
		}

	args.Set(0, &iPackager->GetTransmittingBuffer());
	args.Set(1, &iPackager->GetReceivingBufferL());
	args.Set(2, aCntId);

	TInt newBuffSize = 0;
	User::LeaveIfError(newBuffSize = SendReceive(ECntItemRead, args));
	CContactItem* cntItem = UnPackContactLC(newBuffSize, args);
	CleanupStack::Pop(cntItem);

	return cntItem;
	}
	
	
/**
Open and lock an existing contact in the database.  The contact item lock is
pushed onto the cleanup stack.

@param aCntItemVDef The view definition to use.
@param aCntId Contact ID to read.

@return Opened/locked CContactItem object.
*/
CContactItem* RCntModel::OpenContactLX(const CContactItemViewDef* aCntItemVDef, TContactItemId aCntId) const
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
	TIpcArgs args;
	if (aCntItemVDef) 
		{
		iPackager->PackL(*(const_cast<CContactItemViewDef*>(aCntItemVDef)));
		// Indicates that a user ContactItemViewDef is present in first IPC
		// argument.
		args.Set(3,TRUE);
		}
	else
		{
		iPackager->Clear();
		// Indicates that no user ContactItemViewDef is present in first IPC
		// argument.  The default view definition will be used instead.
		args.Set(3,FALSE);
		}

	args.Set(0, &iPackager->GetTransmittingBuffer());
	args.Set(1, &iPackager->GetReceivingBufferL());
	args.Set(2, aCntId);

	TInt newBuffSize = 0;
	User::LeaveIfError(newBuffSize = SendReceive(ECntItemOpen, args));

	// Push the contact item lock onto the cleanup stack.  If UnPackContactLC()
	// (or any other RCntModel method leaves after this point) then the last
	// contact to be locked will be unlocked (aka closed).  The method returns
	// with the lock remaining on the cleanup stack.
	PushUnlockL(); 

	CContactItem* cntItem = UnPackContactLC(newBuffSize, args);
	
    //save a list of contacts belonging to a group
    if (cntItem->Type() == KUidContactGroup)
        {
        CContactGroup* group = static_cast<CContactGroup*>(cntItem);
        delete group->iInitialContactIds;
        group->iInitialContactIds = NULL;
        group->iInitialContactIds = CContactIdArray::NewL(group->ItemsContained());
        }	
	
	CleanupStack::Pop(cntItem);
	
	return cntItem;		
	}


/**
Close/unLock an existing contact in the database.

@param aCntId The contact ID of the contact to close.

@return ETrue if the contact was opened before and closed after the call,
EFalse if there was no need to close the contact.
*/
TBool RCntModel::CloseContact(TContactItemId aCntId)
	{
    if(!iServerRunning)
        {
        return EFalse;
        }
	TInt res = SendReceive(ECntItemClose, TIpcArgs(aCntId));
	if (res == KErrNone)
		{
		return ETrue;
		}
	return EFalse;
	}


/**
Start a database transaction.
*/
TInt RCntModel::BeginDbTransaction() const
	{
    if(!iServerRunning)
        {
        return KErrServerTerminated;
        }
	return SendReceive(EBeginDbTransaction);
	}

	
/**
Commit a database transaction.
*/
TInt RCntModel::CommitDbTransaction() const
	{
    if(!iServerRunning)
        {
        return KErrServerTerminated;
        }
	return SendReceive(EEndDbTransaction);
	}

/**
Asychrounous commit of a database transaction.

@param aStatus Request status variable that will contain the completion value
*/
void RCntModel::CommitDbTransaction(TRequestStatus*& aStatus) const
    {
    if(!iServerRunning)
        {
        return;
        }
    SendReceive(EEndDbTransaction, *aStatus);
    }
	
/**
Rollback a database transaction.
*/
TInt RCntModel::RollbackDbTransaction() const
	{
    if(!iServerRunning)
        {
        return KErrServerTerminated;
        }
	return SendReceive(ERollbackDbTransaction);
	}


/**
Set the operation timeout value.  This value is the length of time that a
deferred request will remain in the request queue in the State Machine before
being completed with an error code.

@param aMicroSeconds The operation timeout in microseconds.  This timeout will
only be applied to requests sent by clients of this database after this point in
time. 
*/
void RCntModel::SetOperationTimeOutL(const TInt aMicroSeconds) const
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
	TIpcArgs args;
	args.Set(0, aMicroSeconds);
	User::LeaveIfError(SendReceive(ECntOpsTimeOut, args));		
	}

	
/**
Change the existing contact view definition on the server.

@param aView The new contact view defintion.
*/
void RCntModel::SetViewDefinitionL(const CContactViewDef& aView)
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
	TPtr8 ptr(iPackager->PackL(aView));
	User::LeaveIfError(SendReceive(ECntChangeViewDef, TIpcArgs(&ptr)));	
	}


/**
Add a database event observer.

@param aObserver Observer callback inteface used to send database event.
*/
void RCntModel::AddObserverL(MContactDbObserver& aObserver)
	{
	// If this is the first observer to be added then required to create the
	// database event notification monitor (lazy initialisation).
	if (!iDbNotifyMonitor)
		{
		iDbNotifyMonitor = CCntDbNotifyMonitor::NewL(*this);
		}
	iDbNotifyMonitor->AddObserverL(aObserver);
	}

	
/**
Remove a database event observer.

@param aObserver Observer callback inteface to be removed.
*/
void RCntModel::RemoveObserver(const MContactDbObserver& aObserver)
	{
	if (iDbNotifyMonitor)
		{
		iDbNotifyMonitor->RemoveObserver(aObserver);
		// If this is the last observer to be removed then dispose of the
		// database event notification monitor (no longer required).
		if (iDbNotifyMonitor->NumberOfListeners() == 0)
			{
			delete iDbNotifyMonitor;
			iDbNotifyMonitor = NULL;
			}
		}
	}

/**
Add a database event observer.

@param aObserver Observer callback inteface used to send database event.
*/
void RCntModel::AddObserverV2L(MContactDbObserverV2& aObserver)
    {
    // If this is the first observer to be added then required to create the
    // database event notification monitor (lazy initialisation).
    if (!iDbNotifyMonitor)
        {
        iDbNotifyMonitor = CCntDbNotifyMonitor::NewL(*this);
        }
    iDbNotifyMonitor->AddObserverV2L(aObserver);
    }

    
/**
Remove a database event observer.

@param aObserver Observer callback inteface to be removed.
*/
void RCntModel::RemoveObserverV2(const MContactDbObserverV2& aObserver)
    {
    if (iDbNotifyMonitor)
        {
        iDbNotifyMonitor->RemoveObserverV2(aObserver);
        // If this is the last observer to be removed then dispose of the
        // database event notification monitor (no longer required).
        if (iDbNotifyMonitor->NumberOfListeners() == 0)
            {
            delete iDbNotifyMonitor;
            iDbNotifyMonitor = NULL;
            }
        }
    }

/**
Request a database event from the server.

@param aStatus Completed when database event is available.
@param aEvent When aStatus is completed contains the database event.
*/
void RCntModel::StartNotificationTransfer(TRequestStatus& aStatus, TDes8& aEvent, TDes8& aIdArray)
	{	
    if(!iServerRunning)
        {
        return;
        }
	SendReceive(ECntRequestEvent, TIpcArgs(&aEvent, &aIdArray), aStatus);	
	}


/**
End (cancel) request for database event from server.
*/
void RCntModel::EndNotificationTransfer()
	{	
    if(!iServerRunning)
        {
        return;
        }
	SendReceive(ECntCancelEventRequest);	
	}
	
/** 
Sets the ID of the current item and persists it in the database.  The current 
item is provided for use by clients who want to identify one contact item in the
database as the currently selected item.

@param aContactId The ID of the current item. 

@capability WriteUserData
*/
void RCntModel::SetCurrentItem(TContactItemId aContactId) const
	{
    if(!iServerRunning)
        {
        return;
        }
	TIpcArgs args(aContactId);
	(void)SendReceive(ECntSetCurrentItem, args);	
	}

	
/** 
Gets the ID of the current item, as set by SetCurrentItem().  The current item 
ID is initialised to KNullContactId when the database is opened.

@return The ID of the current item. 

@capability None
*/
TContactItemId RCntModel::CurrentItem() const
	{		
    if(!iServerRunning)
        {
        return KNullContactId;
        }
    TContactItemId id = SendReceive(ECntGetCurrentItem);
    if (id < 0)
        {
        return KNullContactId;
        }
    else
        {
        return id;
        }
	}


/** 
When there are multiple contact databases on a device this method can be used to
enquire which database is the current one.

The current database functions are provided as part of current item
functionality.  In order to pass a current item from one contacts model client
to another, the receiving client needs to be using the same database.

The current database is a path and filename, set using SetCurrentDatabase(),
which is persisted by the contacts server.

@deprecated

@param aDatabase The path and filename of the current database.  KNullDesC 
if no current database has been set.

@return KErrNone if success otherwise one of the System error codes. 

@capability None
*/
TInt RCntModel::GetCurrentDatabase(TDes& aDatabase) const
	{
    if(!iServerRunning)
        {
        return KErrServerTerminated;
        }
	TIpcArgs args(&aDatabase);
	return SendReceive(ECntGetCurrentDb, args);
	}


/** 
When there are multiple contact databases on a device this method can be used to
set a database as the current one.

Note: this function simply updates a file name which is stored by the Contacts
server and its use is optional.  It is provided as part of current item
functionality. 

In order to pass a current item from one contacts model client to another, 
the receiving client needs to be using the same database.

@deprecated

@param aDatabase The path and filename of the current database.

@return KErrNone if success otherwise one of the System error codes. 

@capability WriteUserData
*/
TInt RCntModel::SetCurrentDatabase(const TDesC& aDatabase) const
	{
    if(!iServerRunning)
        {
        return KErrServerTerminated;
        }
	TIpcArgs args(&aDatabase);
	return SendReceive(ECntSetCurrentDb, args);
	}


/** 
Returns the ID of the contact item whose telephone number field is mapped to 
the speed dial position specified.

This function is provided so that information may be displayed about a contact
item whose telephone number is being dialled using speed dialling.

The function also retrieves the telephone number stored in the field.

@param aSpeedDialPosition The speed dial position.  This is an integer in the 
range 1 to 9 inclusive.  If outside this range, the function leaves with
KErrArgument.
@param aPhoneNumber On return contains the telephone number which is mapped to
the speed dial position specified.  Returns KNullDesC if the speed dial position
requested has not been set.

@return The ID of the contact item to which the speed dial is mapped. 

@capability ReadUserData
*/
TContactItemId RCntModel::GetSpeedDialFieldL(TInt aSpeedDialPosition, TDes& aPhoneNumber)
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
	__ASSERT_ALWAYS(aSpeedDialPosition >= KCntMinSpeedDialIndex && aSpeedDialPosition <= KCntMaxSpeedDialIndex , User::Leave(KErrArgument));	
	TPckgBuf<TContactItemId> contact(KNullContactId);
	TIpcArgs args(aSpeedDialPosition,&aPhoneNumber);
	return (TContactItemId)SendReceive(ECntGetSpeedDialContactIdAndPhoneNumber, args);
	}

	
/**
Sets a field containing a telephone number as a speed dial field.  The field 
is identified by aFieldIndex within the contact item aItem.  It is assigned a 
speed dial position between 1 and 9 inclusive.

The field's speed dial and user added attributes are set and the appropriate 
UID (KUidSpeedDialXxx) is added to the field's content type.  The changes are 
committed to the database.

Notes:

- If an item's telephone number field has already been assigned to position 
aSpeedDialPosition, that item is updated so that the speed dial attribute 
is removed from its field and the speed dial field type UID is removed from 
the field's content type, before the new speed dial field is set.

- The speed dial attribute can be tested for using the
CContactItemField::IsSpeedDial() method.

- The contact item passed to this function (aItem) must have been obtained using 
one of the variants of CContactDatabase::OpenContactL().  This is because it 
is modified and committed to the database by this function - no further 
commits are necessary.

@param aItem The contact item containing the field to set as a speed dial 
field.
@param aFieldIndex Index of a field in aItem's field set to set as a speed dial
field.
@param aSpeedDialPosition The speed dial position.  This is an integer in the 
range 1 to 9 inclusive.  If outside this range, the function leaves with
KErrArgument. 

@leave KErrDiskFull The disk does not have enough free space to perform the
operation.

@capability ReadUserData
@capability WriteUserData
*/
void RCntModel::SetFieldAsSpeedDialL(TContactItemId aContactId, TInt aFieldIndex, TInt aSpeedDialPosition)
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
	__ASSERT_ALWAYS(aSpeedDialPosition >= KCntMinSpeedDialIndex && aSpeedDialPosition <= KCntMaxSpeedDialIndex , User::Leave(KErrArgument));
	TIpcArgs args(aSpeedDialPosition, aContactId, aFieldIndex);
	User::LeaveIfError(SendReceive(ECntSetSpeedDialIdForPosition, args));
	}


/** 
Removes the mapping between a contact item field and a speed dial position.

Removes the KUidSpeedDialXxx UID from the field's content type, removes the 
field's speed dial attribute and commits the changes to the item.

@param aContactId The ID of the contact item containing the speed dial field.
@param aSpeedDialPosition The speed dial position.  This is an integer in the 
range 1 to 9 inclusive.  If outside this range, the function leaves with
KErrArgument. 

@leave KErrDiskFull The disk does not have enough free space to perform the operation.

@capability ReadUserData
@capability WriteUserData
*/
void RCntModel::RemoveSpeedDialFieldL(TContactItemId aContactId, TInt aSpeedDialPosition)
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
	__ASSERT_ALWAYS(aSpeedDialPosition >= KCntMinSpeedDialIndex && aSpeedDialPosition <= KCntMaxSpeedDialIndex , User::Leave(KErrArgument));
	// Tell the server that this speed dial slot is now free.  Third argument
	// (i.e. field index) is not used.
	TIpcArgs args(aSpeedDialPosition, aContactId, -1);
	User::LeaveIfError(SendReceive(ECntSetSpeedDialIdForPosition, args));		
	}


/**
Returns the ID of the template that should be used with CContactICCEntry items.
If aPhonebookUid is set, the ID of the template belonging to the phonebook with 
TUid aPhonebookUid is returned.

@param aPhonebookUid The phonebook ID with default KNullUid.

@return A template ID.
*/
TContactItemId RCntModel::ICCTemplateIdL(TUid aPhonebookUid)
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
	TIpcArgs args(aPhonebookUid.iUid);
	return SendReceive(ECntICCTemplateId, args);
	}


/**
Returns the ID of the contacts model group which represents the ADN phonebook.

@return ADN phonebook group ID.
*/ 
TContactItemId RCntModel::PhonebookGroupIdL()
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
	return SendReceive(ECntPhonebookGroupId);
	}


/** 
Sets an existing contact item to be the database's current own card.

@param aContact The contact item to set as the database's current own card. 
It must already exist in the database.  It cannot be a group or a template.

@leave KErrNotFound aContact does not exist in the database. 
@leave KErrDiskFull The disk does not have enough free space to perform the
operation.

@capability None
*/
void RCntModel::SetOwnCardL(const CContactItem& aContact)
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
	TIpcArgs args; 
	TPtr8 ptr(iPackager->PackL(aContact));
	args.Set(0,&ptr);
	User::LeaveIfError(SendReceive(ECntSetOwnCard, args));	
	}


/**
Returns the ID of the database's current own card. 

Having obtained this ID, the client may then open the own card in the same 
way as an ordinary contact card (using ReadContactL() or OpenContactL()).

@return The ID of the database's current own card.  KNullContactId if the own 
card has been deleted or has not yet been set.
*/
TContactItemId RCntModel::OwnCard() const
	{
    if(!iServerRunning)
        {
        return KNullContactId;
        }
	return static_cast<TContactItemId>(SendReceive(ECntGetOwnCard));
	}

	
/**
Returns the connection ID of the current client session.

@return Connection ID of the current client session.
*/
TInt RCntModel::ConnectionId() const
	{
    if(!iServerRunning)
        {
        return KErrServerTerminated;
        }
	// If asking for the connection ID the first time, then we ask the server
	// about the session id (lazy initialisation).
	if (!iConnectionId)
		{
		iConnectionId = SendReceive(ECntConnectionId); 	
		}
	return iConnectionId;		
	}


/** 
Debug only.

@capability None
*/
void RCntModel::SetHeapFailure(RHeap::TAllocFail aType, TInt aRate)
	{	
    if(!iServerRunning)
        {
        return;
        }
	TIpcArgs args(aType,aRate);
	SendReceive(ECntSetHeapFailure,args);
	}

	
/** 
Debug only.

@return The heap size usage of the server in debug mode, 0 in release mode.

@capability None
*/
TInt RCntModel::ResourceCount()
	{
    if(!iServerRunning)
        {
        return KErrServerTerminated;
        }
	return(SendReceive(ECntResourceCount));
	}	

	
/**
Returns the ID of the database's preferred template, as set by the method
SetPrefTemplateL().  The preferred template is for clients who may have 
multiple templates but want to identify one as preferred.

@return The ID of the database's current preferred template.  KNullContactId if
not set.
*/
TContactItemId RCntModel::PrefTemplateId() const
	{
    if(!iServerRunning)
        {
        return KNullContactId;
        }
	return(SendReceive(ECntGetPrefTemplateId));	
	}


/** 
Sets the database's preferred template.

The preferred template's ID persists when the database is opened and closed. 
If the preferred template is subsequently deleted, the preferred template 
ID is set to KNullContactId.

@param aContact The contact card template to set as the database's preferred 
template.

@leave KErrNotSupported The item is not a template (i.e. is not of type
KUidContactCardTemplate).
@leave KErrDiskFull The disk does not have enough free space to perform the
operation.

@capability WriteUserData
*/
void RCntModel::SetPrefTemplateL(const TContactItemId aContactId)
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
	TIpcArgs args(aContactId);
	User::LeaveIfError(SendReceive(ECntSetPrefTemplateId, args));
	}

	
/**
Get a list of template IDs from the server.

@return Array of template IDs.
*/
CContactIdArray* RCntModel::FetchTemplateListIdsL()
{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
    
	TIpcArgs args;
	args.Set(0, &iPackager->GetReceivingBufferL());

	TInt newBuffSize;
	User::LeaveIfError(newBuffSize = SendReceive(ECntFetchTemplateIds, args));
	if (newBuffSize > 0)
		{
		args.Set(0, &iPackager->GetReceivingBufferL(newBuffSize));
		User::LeaveIfError(newBuffSize = SendReceive(ECntFetchTemplateIds, args));		
		}

	CContactIdArray* idArray = iPackager->UnpackCntIdArrayLC();	
	CleanupStack::Pop(idArray);

	return idArray;	
}


/**
Get a list of group IDs from the server.

@return Array of group IDs.
*/
CContactIdArray* RCntModel::FetchGroupListIdsL()
{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
    
	TIpcArgs args;
	args.Set(0, &iPackager->GetReceivingBufferL());

	TInt newBuffSize;
	User::LeaveIfError(newBuffSize = SendReceive(ECntFetchGroupIdLists, args));
	if (newBuffSize > 0)
		{
		args.Set(0, &iPackager->GetReceivingBufferL(newBuffSize));
		User::LeaveIfError(newBuffSize = SendReceive(ECntFetchGroupIdLists, args));		
		}

	CContactIdArray* idArray = iPackager->UnpackCntIdArrayLC();	
	CleanupStack::Pop(idArray);

	return idArray;	
}

/**
Get a collection of contact IDs using the specified collection parameters.

@param aCollectionType Type of collection.
@param aTime Used if collection type is "changed since".
@param aGuid Used if collection type is "find GUID".

@return Contact ID array of those contacts which match the specified collection
parameters.
*/
CContactIdArray* RCntModel::CollectionL(TInt aCollectionType, TTime aTime,const TDesC& aGuid)
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
    
	CContactIdArray* idArray = NULL;
	switch(aCollectionType)
	{
	case MLplCollection::EChangedSince :		
		{
		idArray = DoGetCollectionChangedSinceL(aTime);
		}
		break;
	case MLplCollection::EDeleted :
	case MLplCollection::EUnfiled :
		{
		idArray = DoGetCollectionL(aCollectionType);
		}
		break;
	case MLplCollection::EFindGuid :
		{
		idArray = DoGetCollectionGuidL(aGuid);
		}
		break;
	default:
		{
		User::Leave(KErrNotFound);
		}
		break;
	}	
	return idArray;
	}


/**
Get a collection of contact IDs which have changed since the given time.

@param aTime Changed since time.

@return Contact ID array of those contacts which have changed since the given
time.
*/
CContactIdArray* RCntModel::DoGetCollectionChangedSinceL(TTime aTime)
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
    
	TIpcArgs args;
	args.Set(0, &iPackager->GetReceivingBufferL());
	args.Set(1,MLplCollection::EChangedSince);
	TPckgBuf<TTime> pckg(aTime);
	args.Set(2,&pckg);

	TInt newBuffSize;
	User::LeaveIfError(newBuffSize = SendReceive(ECntGetCollection, args));
	if (newBuffSize > 0)
		{
		args.Set(0, &iPackager->GetReceivingBufferL(newBuffSize));
		User::LeaveIfError(newBuffSize = SendReceive(ECntGetCollection, args));		
		}

	CContactIdArray* idArray = iPackager->UnpackCntIdArrayLC();	
	CleanupStack::Pop(idArray);

	return idArray;
	}

	
/**
Get a collection of contact IDs for the given collection type.

@param aCollectionType Collection type.

@return Contact ID array of those contacts which meet the given collection type
criteria.
*/
CContactIdArray* RCntModel::DoGetCollectionL(TInt aCollectionType)
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
    
	TIpcArgs args;
	args.Set(0, &iPackager->GetReceivingBufferL());
	args.Set(1,aCollectionType);

	TInt newBuffSize;
	User::LeaveIfError(newBuffSize = SendReceive(ECntGetCollection, args));
	if (newBuffSize > 0)
		{
		args.Set(0, &iPackager->GetReceivingBufferL(newBuffSize));
		User::LeaveIfError(newBuffSize = SendReceive(ECntGetCollection, args));		
		}

	CContactIdArray* idArray = iPackager->UnpackCntIdArrayLC();	
	CleanupStack::Pop(idArray);

	return idArray;
	}


/**
Get a collection of contact IDs which have the given GUID.  Since GUIDs are
unique (i.e. no two contacts can have the same GUID) there will only ever be
one contact ID in this collection.

@param aGuid Contact GUID.

@return Contact ID array containing the contact with the given GUID.
*/
CContactIdArray* RCntModel::DoGetCollectionGuidL(const TDesC& aGuid)
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
    
	TIpcArgs args;
	args.Set(0, &iPackager->GetReceivingBufferL());
	args.Set(1,MLplCollection::EFindGuid);
	args.Set(2,&aGuid);

	TInt newBuffSize;
	User::LeaveIfError(newBuffSize = SendReceive(ECntGetCollection, args));
	if (newBuffSize > 0)
		{
		args.Set(0, &iPackager->GetReceivingBufferL(newBuffSize));
		User::LeaveIfError(newBuffSize = SendReceive(ECntGetCollection, args));		
		}

	CContactIdArray* idArray = iPackager->UnpackCntIdArrayLC();	
	CleanupStack::Pop(idArray);

	return idArray;
	}


/**
Set the sort preferences in the server.

@param aSortOrder Sort order preferences.
*/
void RCntModel::SetSortPreferenceL(const CArrayFix<CContactDatabase::TSortPref>& aSortOrder)
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
	TPtr8 ptr(iPackager->PackL(aSortOrder));
	TIpcArgs args;
	args.Set(0,&ptr);
	User::LeaveIfError(SendReceive(ECntSetSortPrefs,args));	
	}


/**
Get the sort preferences from the server.

@return Sort order preferences.
*/
CArrayFix<CContactDatabase::TSortPref>* RCntModel::GetSortPreferenceL() const
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
    
	TIpcArgs args;
	args.Set(0, &iPackager->GetReceivingBufferL());

	TInt newBuffSize;
	User::LeaveIfError(newBuffSize = SendReceive(ECntGetSortPrefs, args));
	if (newBuffSize > 0)
		{
		args.Set(0, &iPackager->GetReceivingBufferL(newBuffSize));
		User::LeaveIfError(newBuffSize = SendReceive(ECntGetSortPrefs, args));		
		}

	CArrayFix<CContactDatabase::TSortPref>* prefs = iPackager->UnpackCArrayFixLC();	
	CleanupStack::Pop(prefs);

	return prefs;
	}


/**
Get the number of contacts in the database.

@return Number of contacts in the database if successful, otherwise it leaves.
*/
TInt RCntModel::ContactCountL() const
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
    TInt numContacts = SendReceive( ECntDbContactCount );
    User::LeaveIfError( numContacts );
    return numContacts;
	}

/**
Seek to the given contact ID.

@param aContactId Contact ID to seek to.
@param aId On return the contact ID that the seek found.  This will be the
nearest contact ID if the given aContactID cannot be found.
@param aContactType On return the contact type of the contact that the seek
found.
@param aDeleted On return ETrue if the contact that the seek found is marked as
deleted, EFalse otherwise.

@return ETrue if the seek was successful, EFalse otherwise.
*/
TBool RCntModel::SeekContactL(TContactItemId aContactId,TContactItemId& aId,TUid& aContactType, TBool& aDeleted)
    {
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
    
    TPckgBuf<TInt> id;
    TPckgBuf<TUid> type;
    TPckgBuf<TBool> deleted;
    TIpcArgs args(aContactId,&id,&type,&deleted);
    TInt ret = SendReceive(ECntSeekContactInCollection,args);

    // Although ECntSeekContact/ECntSeekContactInCollection is normally completed
    // with TBool values, ServiceError() can occur which leads to a negative system
    // error codes being returned.  User::LeaveIfError will allow that to be properly
    // handled.
    User::LeaveIfError(ret);

    if(ret)
        {
        aContactType = type();
        aId = id();
        aDeleted = deleted();
        return ETrue;
        }
    else
        {
        return EFalse;
        }
    }


void RCntModel::TextFieldL(TInt aCntItemId,TFieldType aFieldType, TDes& aText)
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
	TPckgBuf<TFieldType> fieldType(aFieldType);
	TIpcArgs args(aCntItemId,&fieldType,&aText);
	User::LeaveIfError(SendReceive(ECntTextField,args));
	}


void RCntModel::ReadContactTextDefL(TContactItemId aContactId, TDes &aResult,const CContactTextDef& aTextDef)
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
	iPackager->PackL( const_cast<CContactTextDef&>(aTextDef));
	TIpcArgs args(&iPackager->GetTransmittingBuffer(), &aResult,aContactId);
	User::LeaveIfError(SendReceive(ECntReadContactTextDef, args));
	}


CContactIdArray* RCntModel::FindL(const TDesC& aText,const CContactItemFieldDef* aFieldDef)
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
    
	TIpcArgs args;

	// Parameter can be NULL so send down an empty descriptor to the server.
	// Server can detect this and pass NULL parameter to the Persistence Layer
	// FindL() method.
	if(aFieldDef != NULL)
		{
		// Packager's sending buffer in slot 1 (contains packed field
		// definition).
		iPackager->PackL(*aFieldDef);
		args.Set(1,&iPackager->GetTransmittingBuffer());
		}
	else
		{
		// Frigged NULL.
		args.Set(1,&KNullDesC);
		}

	// Packager's receiving buffer in slot 0.
	args.Set(0, &iPackager->GetReceivingBufferL());

	// Text in slot 2.
	args.Set(2,&aText);

	// Ensure receiving buffer is big enough.
	TInt newBuffSize;
	User::LeaveIfError(newBuffSize = SendReceive(ECntFind, args));
	if (newBuffSize > 0)
		{
		// Not big enough so resize and call again.
		args.Set(0, &iPackager->GetReceivingBufferL(newBuffSize));
		User::LeaveIfError(newBuffSize = SendReceive(ECntFind, args));
		}

	CContactIdArray* idArray = iPackager->UnpackCntIdArrayLC();	
	CleanupStack::Pop(idArray);

	return idArray;	
	}


void RCntModel::SetDbViewContactType(const TUid aUid)
	{
    if(!iServerRunning)
        {
        return;
        }
	TIpcArgs args(aUid.iUid);
	(void)SendReceive(ECntSetDbViewContactType,args);
	}


TUid RCntModel::GetDbViewContactType() const
	{
    if(!iServerRunning)
        {
        return KNullUid;
        }
	TPckgBuf<TUid> type;
	TIpcArgs args(&type);
	(void)SendReceive(ECntSetDbViewContactType,args);
	return type();	
	}


/**
Initialise the Persistence Layer collection class ready for iterative calls to
the FindAsyncL() method.  This form of initialisation is for an asynchronous
find which uses a text definition and an array of "find words".

@param aWords "Find words" array.
@param aTextDef Text definition to use in find.
*/
void RCntModel::FindAsyncTextDefInitL(const CDesCArray& aWords,CContactTextDef* aTextDef)
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
    
	TIpcArgs args;
	if(aTextDef != NULL)
		{
		// Pack the text definition.
		iPackager->PackL(*aTextDef);
		args.Set(1,&iPackager->GetTransmittingBuffer());
		}
	else
		{
		// No user supplied text definition.
		args.Set(1, &KNullDesC);
		}
	
	// Do the CDesCArray manually as Packager can't do both.
	RBufWriteStream writeStream;
	CBufFlat* buf = CBufFlat::NewL(1 << 8);
	CleanupStack::PushL(buf);

	writeStream.Open(*buf);
	TInt count = aWords.Count();
	writeStream.WriteInt32L(count);	
	TInt length = 0;
	for(TInt i=0; i<count;++i)
		{
		length = aWords[i].Length();
		writeStream.WriteInt32L(length);		
		writeStream.WriteL(aWords[i],length);
		}
	writeStream.CommitL();
	writeStream.Close();

	TPtr8 ptr8(buf->Ptr(0));
	args.Set(0,&ptr8);

	User::LeaveIfError(SendReceive(ECntFindAsyncTextDefInit,args));

	CleanupStack::PopAndDestroy(buf);
	}


/**
Initialise the Persistence Layer collection class ready for iterative calls to
the FindAsyncL() method.  This form of initialisation is for an asynchronous
find which uses text and a field definition.

@param aText Find text.
@param aFieldDef Field definition to use in find.
*/
void RCntModel::FindAsyncInitL(const TDesC& aText,CContactItemFieldDef* aFieldDef)
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
    
	TIpcArgs args;
	args.Set(0,&aText);
	if(aFieldDef != NULL)
		{
		// Pack the field definition.
		iPackager->PackL(*aFieldDef);
		args.Set(1,&iPackager->GetTransmittingBuffer());
		}
	else
		{
		// No user supplied field definition.
		args.Set(1, &KNullDesC);
		}

	User::LeaveIfError(SendReceive(ECntFindAsyncInit,args));
	}


/**
Perform an asynchronous find iteration.  Either the FindAsyncTextDefInitL() or
the FindAsyncInitL() method above must have first been called.

@param aOrigIdArray Set of contacts IDs from previous calls to FindAsyncL().
Will be NULL if this is the first iteration.

@return ETrue if further find iterations are required, EFalse otherwise.
*/
TBool RCntModel::FindAsyncL(CContactIdArray*& aOrigIdArray)
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
    
	TBool moreToGo;
	TPckg<TBool> pckg(moreToGo);
	// Iterations can't fail so expand buffer to 4Kb.  4096 contacts should be
	// enough.  Rather than this brutal approach we could call ContactCountL()
	// and add a contingency in case another client adds some.
	TIpcArgs args(&iPackager->GetReceivingBufferL(4096),&pckg);

	User::LeaveIfError(SendReceive(ECntFindAsync,args));

	CContactIdArray* newIdArray = iPackager->UnpackCntIdArrayLC();	
	if(aOrigIdArray != NULL)
		{
		// Append to the old array if it was not NULL.
		for(TInt i=0;i<newIdArray->Count();++i)
			{
			aOrigIdArray->AddL((*newIdArray)[i]);
			}
		CleanupStack::PopAndDestroy(newIdArray);
		}
	else
		{
		CleanupStack::Pop(newIdArray);
		aOrigIdArray = newIdArray;
		}

	return pckg();
	}


/**
Set the asynchronous activity flag in the server.  Any asynchronous activity
such as asynchronous find or asynchronous sort prevent the database from
being closed and should set this flag.  When all asynchronous activites are
finished this flag should be cleared.

@capability None

@param aAsyncActivity ETrue if at least one asynchronous activity, EFalse if
no asynchronous activities.
*/
void RCntModel::SetAsyncActivityL(TBool aAsyncActivity)
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
	TIpcArgs args;
	args.Set(0,aAsyncActivity);
	User::LeaveIfError(SendReceive(ECntSetAsyncActivity,args));
	}


/**
Filter the database using the given filter.

@param aFilter Filter to use.  On return the contact IDs in this filter will be
augmented with those contact IDs which match the given filter.
*/
void RCntModel::FilterDatabaseL(CCntFilter& aFilter)
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
    
	CContactIdArray* origIdArray = aFilter.iIds;
	aFilter.iIds = NULL;

	TIpcArgs args;
	iPackager->PackL(aFilter);
	args.Set(1,&iPackager->GetTransmittingBuffer());	
	args.Set(0, &iPackager->GetReceivingBufferL());

	TInt newBuffSize(0);
	User::LeaveIfError(newBuffSize = SendReceive(ECntFilterDatabase, args));
	if (newBuffSize > 0)
		{
		// Not big enough so resize and call again.
		args.Set(0, &iPackager->GetReceivingBufferL(newBuffSize));
		User::LeaveIfError(newBuffSize = SendReceive(ECntFilterDatabase, args));
		}
	
	CContactIdArray* newIdArray = iPackager->UnpackCntIdArrayLC();
	if(origIdArray != NULL)
		{
		for(TInt i=0;i<newIdArray->Count();++i)
			{
			origIdArray->AddL((*newIdArray)[i]);
			}
		aFilter.iIds = origIdArray;
		CleanupStack::PopAndDestroy(newIdArray);
		}
	else
		{
		CleanupStack::Pop(newIdArray);
		aFilter.iIds = newIdArray;
		}
	}

	
TInt RCntModel::OpenViewL(const CContactTextDef& aTextDef, const TInt aViewPrefs)
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
    
	TPckgBuf<TInt> viewSessionId;
	iPackager->PackL(const_cast<CContactTextDef&>(aTextDef));
	TIpcArgs args(&iPackager->GetTransmittingBuffer(), aViewPrefs, &viewSessionId);
	
	TInt ret = SendReceive(ECntOpenViewSession,args);
	User::LeaveIfError(ret);
	
	return 	viewSessionId();
	}
	
	
void RCntModel::CloseView(TInt aViewId)
	{
    if(!iServerRunning)
        {
        return;
        }
	TIpcArgs args(aViewId);
	SendReceive(ECntCloseViewSession,args);
	}
	
	
void RCntModel::ChangeSortOrderL(TInt aViewId, const CContactTextDef& aTextDef)
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
    
	// Serialize the text def using packager overload.
	iPackager->PackL( const_cast<CContactTextDef&>(aTextDef));
	

	TIpcArgs args(aViewId, &iPackager->GetTransmittingBuffer());
	TInt ret = SendReceive(ECntViewChangeSortOrderL, args);
	
	User::LeaveIfError(ret);
	}
	
	
void RCntModel::BeginIterateL(TInt aViewId)
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
	TIpcArgs args(aViewId);
	TInt ret = SendReceive(ECntViewBeginIterate,args);
	User::LeaveIfError(ret);
	}
	
	
void RCntModel::EndIterateL(TInt aViewId)
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
	TIpcArgs args(aViewId);
	TInt ret = SendReceive(ECntViewEndIterate,args);
	User::LeaveIfError(ret);
	}
	
	
CViewContact* RCntModel::NextItemL(TInt aViewId, const TInt aViewPrefs)
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
    
	TIpcArgs args(aViewId, aViewPrefs, &iPackager->GetReceivingBufferL());
	TInt size = SendReceive(ECntViewNextItemL, args);

	// KErrNotFound is returned if Persistence Layer view item manager 
	// can't reach end of the contacts.
	if(size == KErrNotFound)
		{
		// Not an error just no match.
		return NULL;
		}

	// Leave on genuine errors.
	User::LeaveIfError(size);

	if(size != 0) // Server session requires larger packager buffer.
		{
		// Increase the buffer size and call again.  Just in case some other
		// client has deleted in between calls do the KErrNotFound check.
		TIpcArgs args(aViewId, aViewPrefs, &iPackager->GetReceivingBufferL(size));
		TInt ret = SendReceive(ECntViewNextItemL, args);
		if(ret == KErrNotFound)
			{
			return NULL;
			}
		// Leave on genuine errors
		User::LeaveIfError(ret);
		}

	// Got it so unpack and return.
	CViewContact* viewContact = iPackager->UnpackViewContactLC();

	CleanupStack::Pop(viewContact);

	return viewContact;
	}

	
CViewContact* RCntModel::ItemAtL(TContactItemId aContactId, TInt aViewId)
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
    
	TIpcArgs args(aContactId, aViewId, &iPackager->GetReceivingBufferL());
	TInt size = SendReceive(ECntItemAtL, args);

	// KErrNotFound is returned if Persistence Layer view item manager cannot 
	// find the view contact by given aContactId.
	if(size == KErrNotFound)
		{
		// Not an error just no match.
		return NULL;
		}

	// Leave on genuine errors.
	User::LeaveIfError(size);

	if(size != 0) // Server session requires larger packager buffer.
		{
		// Increase the buffer size and call again.  Just in case some other
		// client has deleted in between calls do the KErrNotFound check.
		TIpcArgs args(aContactId, aViewId, &iPackager->GetReceivingBufferL(size));
		TInt ret = SendReceive(ECntItemAtL, args);
		if(ret == KErrNotFound)
			{
			return NULL;
			}
		// Leave on genuine errors
		User::LeaveIfError(ret);
		}

	// Got it so unpack and return.
	CViewContact* viewContact = iPackager->UnpackViewContactLC();

	CleanupStack::Pop(viewContact);

	return viewContact;
	}
	

#if defined(_DEBUG)	
void RCntModel::GetDefinitionsOfExistingViewsL(const TDesC& aDbName, RPointerArray<CContactDefaultViewDefinition>& aViewDefs)
	{
    if(!iServerRunning)
        {
        User::Leave(KErrServerTerminated);
        }
    
	RBuf8 buf;
	CleanupClosePushL(buf);
	buf.CreateL(256);
	TIpcArgs args(&aDbName, &buf);

	TInt newBufSize;
	User::LeaveIfError(newBufSize = SendReceive(ECntGetDefinitionsForExistingView, args));
	if (newBufSize > 0)
		{
		buf.ReAllocL(newBufSize);
		args.Set(1, &buf);
		User::LeaveIfError(newBufSize = SendReceive(ECntGetDefinitionsForExistingView, args));		
		}

	RDesReadStream readStream(buf);
	CleanupClosePushL(readStream);
	TInt32 count;
	readStream >> count;
	CContactDefaultViewDefinition* view;
	for (TInt i = 0; i < count; i++)
		{
		view = CContactDefaultViewDefinition::NewLC(readStream);
		aViewDefs.AppendL(view);
		CleanupStack::Pop(view);
		}
		
	CleanupStack::PopAndDestroy(2); // readStream, buf	
	}
#else
void RCntModel::GetDefinitionsOfExistingViewsL(const TDesC& /*aDbName*/, RPointerArray<CContactDefaultViewDefinition>& /*aViewDefs*/)
	{	
	}
#endif // _DEBUG