summaryrefslogtreecommitdiffstats
path: root/plugins/contacts/symbian/contactsmodel/cntview/localview.cpp
blob: a128b6f9b9822b06e051c484a4a2c8da4b1aee4e (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
/*
* 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: 
*
*/

#include <phbksync.h>
#include "CNTSTD.H"
#include <cntviewbase.h>
#include <cntitem.h>
#include "cntviewprivate.h"
#include <cntviewsortplugin.h>
#include "persistencelayer.h"
#include "cviewiterator.h"
#ifdef SYMBIAN_ENABLE_SPLIT_HEADERS
#include <cntviewsortpluginbase.h>
#endif
//uncomment to test
//#define __PROFILE_SORT__

//uncomment for commonly required debug printing
//#define __VERBOSE_DEBUG__

extern void DebugLogNotification(const TDesC& aMethod, const TContactDbObserverEvent &aEvent);

//
// CContactLocalView.
//

// CIdle Callback function's return values: 0 - finished, 1 - call again
// (CIdle is used to Insert & Sort contacts one at a time into the view)

const TInt    KSortFinished = 0;
const TInt    KSortCallAgain = 1;

// Tunable constants
// These seem to be useful values for memory allocations with RPointerArray
const TInt    KContactsArrayGranularity = 100;
const TInt    KUnsortedArrayGranularity = 16;
// Number of Contacts to process per invocation of the Sorter
// Local Views can't do much whilst sorting, but we want to allow other
// Active Objects in the thread to run.
const TInt    KNumberOfContactsPerChunk = 50;

CContactLocalView::CContactLocalView(const CContactDatabase& aDb,TContactViewPreferences aContactTypes, MLplPersistenceLayerFactory* aFactory) 
: CContactViewBase(aDb), 
iFactory(aFactory),
iContacts(KContactsArrayGranularity), 
iUnSortedContacts(KUnsortedArrayGranularity),
iViewPreferences(aContactTypes)
/**
@internalComponent
*/
    {
    }

EXPORT_C CContactLocalView::CContactLocalView(const CContactDatabase& aDb,TContactViewPreferences aContactTypes) 
: CContactViewBase(aDb), iContacts(KContactsArrayGranularity), iUnSortedContacts(KUnsortedArrayGranularity),
iViewPreferences(aContactTypes)
/** Protected C++ constructor.

Called by NewL().

@param aDb The underlying database that contains the contact items.
@param aContactTypes Specifies which types of contact items should be included 
in the view and the behaviour for items that do not have content in any of 
the fields specified in the sort order. */
    {
    }

EXPORT_C CContactLocalView::~CContactLocalView()
/** Destructor.

Deletes all resources owned by the object, and removes itself as the contact 
database observer. */
    {
#ifdef CONTACTS_API_PROFILING
    TContactsApiProfile::CntViewMethodLog(TContactsApiProfile::ECntVwClassLocalView, TContactsApiProfile::ECntViewDestructor);
#endif
    delete iTextDef;
    delete iAsyncSorter;
    iContacts.ResetAndDestroy();
    iUnSortedContacts.ResetAndDestroy();
    iOutstandingEvents.Close();
    iSortOrder.Close();

    if (&iDb != NULL)
        {
        const_cast<CContactDatabase&>(iDb).RemoveObserver(*this);
        }
    delete iViewIterator;
    }

EXPORT_C CContactLocalView* CContactLocalView::NewL(MContactViewObserver& aObserver,const CContactDatabase& aDb,
                                                    const RContactViewSortOrder& aSortOrder,TContactViewPreferences aContactTypes)
/** Allocates and constructs the local view object.

The view is sorted according to the sort order and view preferences specified, 
using a low priority idle time active object. The specified view observer 
is notified when the view is sorted and ready for use.

@param aObserver An observer that receives notifications when this view is 
ready for use and when changes take place in it. The observer receives a TContactViewEvent::EReady 
event when the view is ready. Any attempt to use the view before this notification will Leave with KErrNotReady
@param aDb The underlying database that contains the contact items. The view 
observes the database, so that it handles change events sent from the database.
@param aSortOrder Specifies the fields to use to sort the items in the view.
@param aContactTypes Specifies which types of contact items should be included 
in the view and the behaviour for items that do not have content in any of 
the fields specified in the sort order.
@return The newly constructed local view object. */
    {
#ifdef CONTACTS_API_PROFILING
    TContactsApiProfile::CntViewMethodLog(TContactsApiProfile::ECntVwClassLocalView, TContactsApiProfile::ECntViewApiNewL, aSortOrder, aContactTypes);
#endif
    CContactLocalView* self=new(ELeave) CContactLocalView(aDb,aContactTypes);
    CleanupStack::PushL(self);
    self->ConstructL(aObserver,aSortOrder);
    CleanupStack::Pop(self); 
    return self;
    }

EXPORT_C void CContactLocalView::ConstructL(MContactViewObserver& aObserver,const RContactViewSortOrder& aSortOrder)
/** Protected second phase constructor.

The view is sorted according to the sort order and view preferences specified, 
using a low priority idle time active object. The specified view observer 
is notified when the view is sorted and ready for use.

Called by NewL().

@param aObserver An observer that receives notifications when this view is 
ready for use and when changes take place in it. The observer receives a TContactViewEvent::EReady 
event when the view is ready. Any attempt to use the view before this notification will Leave with KErrNotReady.
@param aSortOrder Specifies the fields to use to sort the items in the view. */
    {
    // call new ConstructL
    ConstructL(aObserver, aSortOrder, EFalse, KNullDesC8);
    }

EXPORT_C CContactLocalView* CContactLocalView::NewL(MContactViewObserver& aObserver,const CContactDatabase& aDb,
                                                    const RContactViewSortOrder& aSortOrder,TContactViewPreferences aContactTypes,
                                                    const TDesC8& aSortPluginName)
/** Allocates and constructs the local view object.

The view is sorted according to the sort order and view preferences specified, 
using a low priority idle time active object. The specified view observer 
is notified when the view is sorted and ready for use.

@param aObserver An observer that receives notifications when this view is 
ready for use and when changes take place in it. The observer receives a TContactViewEvent::EReady 
event when the view is ready. Any attempt to use the view before this notification will Leave with KErrNotReady
@param aDb The underlying database that contains the contact items. The view 
observes the database, so that it handles change events sent from the database.
@param aSortOrder Specifies the fields to use to sort the items in the view.
@param aContactTypes Specifies which types of contact items should be included 
in the view and the behaviour for items that do not have content in any of 
the fields specified in the sort order.
@param aSortPluginName Specifies a plug-in that will be used to compare view contacts
when the the view is sorted. This name is used by ECOM to select the plugin, and is matched
with the "default_data" of all ECOM plugins that support the required interface.
@return The newly constructed local view object. */
    {
#ifdef CONTACTS_API_PROFILING
    TContactsApiProfile::CntViewMethodLog(TContactsApiProfile::ECntVwClassLocalView, TContactsApiProfile::ECntViewApiNewL, aSortOrder, aContactTypes, aSortPluginName);
#endif
    CContactLocalView* self=new(ELeave) CContactLocalView(aDb,aContactTypes);
    CleanupStack::PushL(self);
    self->ConstructL(aObserver, aSortOrder, ETrue, aSortPluginName);
    CleanupStack::Pop(self); 
    return self;
    }

/** CContactLocalView contructor, used in the server
@internalTechnology 
 */
EXPORT_C CContactLocalView* CContactLocalView::NewL(MContactViewObserver& aObserver,const CContactDatabase& aDb,const RContactViewSortOrder& aSortOrder,TContactViewPreferences aContactTypes,
        MLplPersistenceLayerFactory* aFactory,const TDesC8& aSortPluginName)
    {
    CContactLocalView* self=new(ELeave) CContactLocalView(aDb,aContactTypes,aFactory);
    CleanupStack::PushL(self);
    self->ConstructL(aObserver, aSortOrder, ETrue, aSortPluginName);
    CleanupStack::Pop(self); 
    return self;
    }

void CContactLocalView::ConstructL(MContactViewObserver& aObserver,const RContactViewSortOrder& aSortOrder,
                                   TBool aUseNamedPlugin, const TDesC8& aSortPluginName)
/** Protected second phase constructor.

The view is sorted according to the sort order and view preferences specified, 
using a low priority idle time active object. The specified view observer 
is notified when the view is sorted and ready for use.

Called by NewL().

@internalComponent
@param aObserver An observer that receives notifications when this view is 
ready for use and when changes take place in it. The observer receives a TContactViewEvent::EReady 
event when the view is ready. Any attempt to use the view before this notification will Leave with KErrNotReady.
@param aSortOrder Specifies the fields to use to sort the items in the view. 
@param aUseNamedPlugin A flag indicates whether the aSortPluginName parameter is valid.
@param aSortPluginName Specifies a plug-in that will be used to compare view contacts
when the the view is sorted. This name is used by ECOM to select the plugin, and is matched
with the "default_data" of all ECOM plugins that support the required interface.
*/
    {
    CContactViewBase::ConstructL();
    if(iFactory == NULL)
        {
        iFactory = const_cast<CContactDatabase&>(iDb).FactoryL();
        }
    iAsyncSorter = CIdleContactSorter::NewL(*this, *iFactory);

    OpenL(aObserver);
    if (aUseNamedPlugin)
        {
        // find and load Sort plug-in
        if (aSortPluginName.Length())
            {
            TUid sortPluginUid = FindSortPluginImplL (aSortPluginName);
            LoadViewSortPluginL(sortPluginUid, iViewPreferences);
            }
        }
    else
        {
        // find and load default Sort plug-in (if any)
        TUid sortPluginUid = FindDefaultViewSortPluginImplL();
        if (sortPluginUid != KNullUid)
            {
            LoadViewSortPluginL(sortPluginUid, iViewPreferences);
            }
        }
    // initialise for sort, and start if the database is ready
    InitialiseSortL(aSortOrder, EFalse);
    if (&iDb != NULL)
        {
        const_cast<CContactDatabase&>(iDb).AddObserverL(*this);
        }
    }


EXPORT_C const RContactViewSortOrder& CContactLocalView::SortOrder() const
/** Gets the sort order, as set during construction.

@return The sort order. */
    {
#ifdef CONTACTS_API_PROFILING
    TContactsApiProfile::CntViewMethodLog(TContactsApiProfile::ECntVwClassLocalView, TContactsApiProfile::ECntViewApiSortOrder);
#endif
    return iSortOrder;
    }

TContactItemId CContactLocalView::AtL(TInt aIndex) const
/** Returns the ID of the contact item at a specified index into the view.

@param aIndex An index into the view.
@leave KErrNotFound The index is out of bounds.
@return The ID of the contact item at the specified index.
@leave KErrNotReady The view is not ready for use.  */
    {
#ifdef CONTACTS_API_PROFILING
    TContactsApiProfile::CntViewMethodLog(TContactsApiProfile::ECntVwClassLocalView, TContactsApiProfile::ECntViewApiAtL, aIndex);
#endif
    const CViewContact& contact = ContactAtL(aIndex);
    return contact.Id();
    }

const CViewContact& CContactLocalView::ContactAtL(TInt aIndex) const
/** Returns the contact item at a specified index into the view.

@param aIndex An index into the view.
@leave KErrNotFound The index is out of bounds.
@leave KErrNotReady The view is not ready for use.
@return The contact item at the specified index. */
    {
#ifdef CONTACTS_API_PROFILING
    TContactsApiProfile::CntViewMethodLog(TContactsApiProfile::ECntVwClassLocalView, TContactsApiProfile::ECntViewApiContactAtL, aIndex);
#endif
    // state cannot be EInitializing or ENotReady
    if( iState != EReady )
        {
        User::Leave(KErrNotReady);
        }

    TInt offsetIndex=aIndex;
    const TInt unsortedCount=iUnSortedContacts.Count();
    const TInt sortedCount=iContacts.Count();
    if(offsetIndex >= (unsortedCount+sortedCount))
        {
        //Out of Bounds.
        User::Leave(KErrNotFound);
        }

    if(unsortedCount>0)
        {
        if(iViewPreferences & EUnSortedAtBeginning)
            {
            if(aIndex<unsortedCount)
                {
                //contact in unsorted array
                return *iUnSortedContacts[aIndex];
                }
            else
                {
                //contact in sorted array
                offsetIndex-=unsortedCount;
                }
            }
        else if ((iViewPreferences & EUnSortedAtEnd) && (aIndex>=sortedCount))
            {
            offsetIndex-=sortedCount;
            return *iUnSortedContacts[offsetIndex];
            }

        }
    return *iContacts[offsetIndex];
    }

TInt CContactLocalView::CountL() const
/** Gets the total number of contact items in the view.

@return The number of contact items in the view. This includes both sorted 
and unsorted items.
@leave KErrNotReady The view is not ready for use. */
    {
#ifdef CONTACTS_API_PROFILING
    TContactsApiProfile::CntViewMethodLog(TContactsApiProfile::ECntVwClassLocalView, TContactsApiProfile::ECntViewApiCountL);
#endif
    // state cannot be EInitializing or ENotReady
    if( iState != EReady )
        {
        User::Leave(KErrNotReady);
        }
    
    TInt count(iUnSortedContacts.Count());
    count+=iContacts.Count();
    return count;
    }

TInt CContactLocalView::FindL(TContactItemId aId) const
/** Searches for a contact item in the view with the specified ID.

@param aId The ID of the contact item to search for.
@return If found, the index into the view of the matching item. Otherwise, 
KErrNotFound.
@leave KErrNotReady The view is not ready for use.  */
    {
#ifdef CONTACTS_API_PROFILING
    TContactsApiProfile::CntViewMethodLog(TContactsApiProfile::ECntVwClassLocalView, TContactsApiProfile::ECntViewApiFindL, aId);
#endif
    // state cannot be EInitializing or ENotReady
    if( iState != EReady )
        {
        User::Leave(KErrNotReady);
        }

    TInt index=KErrNotFound;
    CViewContact* contact = CViewContact::NewLC(aId);
    const TInt unSortedCount=iUnSortedContacts.Count();
    // first look in unsorted contacts
    if(unSortedCount > 0)
        {
        // contact may be in the unsorted array
        index = iUnSortedContacts.Find(contact,TIdentityRelation<CViewContact>(IdsMatch));

        if ((index != KErrNotFound) && (iViewPreferences & EUnSortedAtEnd))
            {
            // account for sorted array size
            index = index + iContacts.Count();
            }
        }

    // if not found try sorted contacts
    if (index == KErrNotFound)
        {
        //contact may be in the sorted array
        index = iContacts.Find(contact,TIdentityRelation<CViewContact>(IdsMatch));

        if ((index != KErrNotFound) && (iViewPreferences & EUnSortedAtBeginning))
            {
            // account for unsorted array size
            index = index + unSortedCount;
            }
        }

    CleanupStack::PopAndDestroy(contact);
    return index;
    }

HBufC* CContactLocalView::AllFieldsLC(TInt aIndex,const TDesC& aSeparator) const
/** Gets a descriptor containing the contents of all fields specified in the view's 
sort order for an item in the view.

The field separator is used to separate the contents of each field. It is 
not appended to the last field.

@param aIndex The index of the contact item into the view.
@param aSeparator The string to use to separate the fields.
@return Pointer to the contact item descriptor. */
    {
#ifdef CONTACTS_API_PROFILING
    TContactsApiProfile::CntViewMethodLog(TContactsApiProfile::ECntVwClassLocalView, TContactsApiProfile::ECntViewApiAllFieldsLC, aIndex);
#endif

    if( iState != EReady )
        {
        User::Leave(KErrNotReady);
        }

    TInt offsetIndex=aIndex;
    const TInt unSortedCount=iUnSortedContacts.Count();
    if(unSortedCount>0)
        {
        if(iViewPreferences & EUnSortedAtBeginning)
            {
            if(aIndex<unSortedCount)
                {
                //contact in unsorted array
                return FieldsWithSeparatorLC(iUnSortedContacts,aIndex,aSeparator);
                }
            else
                {
                //contact in sorted array
                offsetIndex-=unSortedCount;
                }
            }
        else if(iViewPreferences & EUnSortedAtEnd)
            {
            const TInt sortedCount=iContacts.Count();
            if(aIndex>=sortedCount)
                {
                offsetIndex-=sortedCount;
                return FieldsWithSeparatorLC(iUnSortedContacts,offsetIndex,aSeparator);
                }
            }
        }
    return FieldsWithSeparatorLC(iContacts,offsetIndex,aSeparator);
    }

EXPORT_C void CContactLocalView::SortL(const RContactViewSortOrder& aSortOrder)
/** Sorts the view using the specified sort order, using a low priority idle time 
active object.

This function is called during view construction and on receipt of certain 
change events from the underlying database.

@param aSortOrder Specifies the fields to use to sort the items in the view. */
    {
#ifdef CONTACTS_API_PROFILING
    TContactsApiProfile::CntViewMethodLog(TContactsApiProfile::ECntVwClassLocalView, TContactsApiProfile::ECntViewApiSortL);
#endif
    // re-initialise sort, and try to start it
    InitialiseSortL(aSortOrder, ETrue);
    }


/*
 Start first sort of view, or restart after SortL() API has changed the order.
 */
void CContactLocalView::InitialiseSortL(const RContactViewSortOrder& aSortOrder, TBool aChangingSortOrder)
    {
    if (aChangingSortOrder)
        {
        if (&iDb != NULL)
            {
            if (!iDb.DatabaseReadyL())
                {
                User::Leave(KErrNotReady);
                }
            }
        }

    // copy new sort order
    TRAPD(sortStartError, iSortOrder.CopyL(aSortOrder));
    
    if (sortStartError)
        {
        // ensure Db Recover (close then open tables) cannot push view to EReady
        iExtension->iError = sortStartError;
        User::Leave(sortStartError);
        }

    // New sort order for Sort Plugin
    CViewContactSortPlugin* sortPluginImpl = SortPluginImpl();
    if (sortPluginImpl)
        {
        sortPluginImpl->SetSortOrderL(aSortOrder);
        }

    // View can Sort only if database is 'ready'.
    if (&iDb != NULL)
        {
        if (!iDb.DatabaseReadyL())
            {
            return;
            }
        }

    // database is ready for reading - so start the Sort
    SortL();
    }


/**
Safe resort of view after Recover, Backup/Restore, etc...

@internalComponent
@released
*/
void CContactLocalView::SafeResort( )
    {
    TInt sortError( KErrNone );
    
    // Database tables are closed across backup or restore so we may need to
    // re-open view iterator here.
    if ( iViewIterator == NULL )
        {
        const TContactViewPreferences viewPrefs = iAsyncSorter->SortViewPreferences( );
        TRAP(sortError, // codescanner::trapeleave: CViewIterator hasn't NewL function and ignore the medium issue.
            if( iFactory == NULL )
                {
                iFactory = const_cast<CContactDatabase&>( iDb ).FactoryL( );
                }
            MLplViewIteratorManager& manager = iFactory->GetViewIteratorManagerL( );
            iViewIterator = new (ELeave) CViewIterator( manager,*iTextDef,viewPrefs );
            ) // TRAP
        }

    if ( !sortError )
        {
        TRAP( sortError, SortL( ) );
        }

    // notify any error
    if ( sortError )
        {
        NotifySortError( sortError );
        }
    }


/**
@internalComponent
@released
*/
void CContactLocalView::SortL()
    {
    // Initialisation for each explicitly requested sort
    // Construct a text def to read out the required fields from the db.
    CContactTextDef* textDef=CContactTextDef::NewLC();
    TInt sortOrderCount=iSortOrder.Count();

    for (TInt sortIndex=0;sortIndex<sortOrderCount;sortIndex++)
        {
        textDef->AppendL(TContactTextDefItem(iSortOrder[sortIndex]));
        }
    CleanupStack::Pop(); // textDef.
    delete iTextDef;
    iTextDef=textDef;

    // NB ResetSortL() requires iTextDef to be initialised

    // initialisation for each pass (of the insert sort) through the db
    // (2 passes may be required if the SIM card starts locked and is then unlocked)
    // (such a 2nd pass is kicked off by CIdleContactSorter)
    ResetSortL();

    // Delete existing sort if present.
    iAsyncSorter->Stop();

    iContacts.ResetAndDestroy();
    iUnSortedContacts.ResetAndDestroy();

#ifdef __PROFILE_SORT__
    RDebug::Print(_L("[CNTMODEL] CntModel View, , %u, %u, Starting sort\n"), 
        static_cast<TUint>(RProcess().Id()), 
        static_cast<TUint>(RThread().Id()));

    // 3 timers: 1st for read/Append; 2nd for Sort, 3rd for Compare
    RDebug::ProfileReset(1,3);
    RDebug::ProfileStart(1);
#endif

    // reset sort error
    iExtension->iError = KErrNone;

    // Kick off idler.
    iAsyncSorter->Start();
    }

void CContactLocalView::ResetSortL()
/**
 * Setup for a fresh pass through the Contacts database table
 *
 * (Code was in SortL)
 */
    {
    delete iViewIterator;
    iViewIterator = NULL;
    }

EXPORT_C TInt CContactLocalView::InsertL(TContactItemId aId)
/** Inserts a contact item into the view, maintaining the view's sort order.

For the item to be inserted, it must exist in the underlying database, and 
it must be of the correct type according to the view preferences.

This function is called when a contact item or group is added to or changed 
in the underlying database.

@param aId The ID of a contact item that exists in the underlying database.
@return The index at which the item was inserted into the view, or KErrNotFound 
if the contact item was not found in the underlying database, or it already 
exists in the view. */
    {
    TInt index=KErrNotFound;
#if defined(__VERBOSE_DEBUG__)
    RDebug::Print(_L("[CNTMODEL] CContactLocalView{ViewPrefs = 0x%08X}::InsertL into view Contact Id %i\r\n"), 
        iViewPreferences, aId);
#endif
    TContactViewPreferences view = iViewPreferences;
    if(!iAsyncSorter->InsertViewPreferences(view))
        {
        return KErrNotFound;
        }
    if(iFactory == NULL)
        {
        iFactory = const_cast<CContactDatabase&>(iDb).FactoryL();
        }
    MLplViewIteratorManager& manager = iFactory->GetViewIteratorManagerL();
    CViewIterator* iter = new (ELeave) CViewIterator(manager,*iTextDef,view);
    CleanupStack::PushL(iter);
    CViewContact* contact = iter->ItemAtL(aId);
    CleanupStack::PopAndDestroy(iter);    
    if(contact != NULL && ContactCorrectType(contact->ContactTypeUid(),view))
        {
        CleanupStack::PushL(contact);
        if(IsContactSortable(*contact, iViewPreferences))
            {
            //Contact has normal fields and can be added to the standard sorted array                
#if defined(__VERBOSE_DEBUG__)
                RDebug::Print(_L("[CNTMODEL] > > > > > View Insert into RPointerArray [Count = %i]\r\n"), iContacts.Count());
#endif
                
            // Insert using Sort Plugin compare method, and get new index
            User::LeaveIfError(InsertContactInView(iContacts, contact, EFalse, &index));
            CleanupStack::Pop(contact);
            if (iViewPreferences & EUnSortedAtBeginning)
                {
                index += iUnSortedContacts.Count();
                }
            }
        else if (iViewPreferences & (EUnSortedAtBeginning | EUnSortedAtEnd))
            {
            // unsortable contacts go at the end or beginning
            // we want this to be stable (e.g. when ICC becomes unlocked)
            User::LeaveIfError(InsertContactInView(iUnSortedContacts, contact, ETrue, &index));
            CleanupStack::Pop(contact);
            // calc new index
            if (iViewPreferences & EUnSortedAtEnd)
                {
                index += iContacts.Count();
                }
            }
        else // EIgnoreUnSorted
            {
            CleanupStack::PopAndDestroy(contact);
            }
        }
    else if(contact)
        {
        delete contact;
        }

    return index;
    }

EXPORT_C TInt CContactLocalView::RemoveL(TContactItemId aId)
/** Removes a contact item from the view.

This function is called when a contact item or group is deleted from or changed 
in the underlying database.

@param aId The ID of the contact item to remove from the view.
@return The index of the removed item into the view's list of sorted or unsorted 
contact items, or KErrNotFound if the item was not found in the view. */
    {
    CViewContact* contact = CViewContact::NewLC(aId);
    TInt index=KErrNotFound;
    index=iContacts.Find(contact,TIdentityRelation<CViewContact>(IdsMatch));
    if (index!=KErrNotFound)
        {
        CViewContact* temp= iContacts[index];
        iContacts.Remove(index);
        delete temp;
        if (iViewPreferences & EUnSortedAtBeginning)
            {
            index+=iUnSortedContacts.Count();
            }
        }
    else
        {
        if(iUnSortedContacts.Count()>0)
            {
            index=iUnSortedContacts.Find(contact,TIdentityRelation<CViewContact>(IdsMatch));
            if (index!=KErrNotFound)
                {
                CViewContact* temp= iUnSortedContacts[index];
                iUnSortedContacts.Remove(index);
                delete temp;
                if (iViewPreferences & EUnSortedAtEnd)
                    {
                    index+=iContacts.Count();
                    }
                // NB - If EIgnoreUnsorted, then this clause would not be running,
                // as the contact would never be added to the view.
                }
            }
        }
    CleanupStack::PopAndDestroy(contact);
    return index;
    }

EXPORT_C void CContactLocalView::CContactLocalView_Reserved_1()
    {
    }

EXPORT_C void CContactLocalView::CContactLocalView_Reserved_2()
    {
    }

void CContactLocalView::HandleDatabaseEventL(TContactDbObserverEvent aEvent)
    {
    // handle Backup / Restore notifications before checking View State
    switch (aEvent.iType)
        {
        case EContactDbObserverEventBackupBeginning:
        case EContactDbObserverEventRestoreBeginning:
#if defined(__VERBOSE_DEBUG__)
            RDebug::Print(_L("[CNTMODEL] CContactLocalView{ViewPrefs = 0x%08X}::HandleDatabaseEventL -> Backup/Restore Beginning, state = %i\r\n"), 
                iViewPreferences, iState);
#endif
            if (iState == EReady)
                {
                SetState(ENotReady);
                }
            else
                {
                // stop sorting
                iAsyncSorter->Stop();
                }
            ResetSortL();
            return;

        case EContactDbObserverEventBackupRestoreCompleted:
#if defined(__VERBOSE_DEBUG__)
            RDebug::Print(_L("[CNTMODEL] CContactLocalView{ViewPrefs = 0x%08X}::HandleDatabaseEventL -> Backup/Restore Completed, state = %i, old sort error %i\r\n"), 
                iViewPreferences, iState, iExtension->iError);
#endif
            if (iState == ENotReady && iExtension->iError == KErrNone)
                {
                // view was ready before tables were closed
                SetState(EReady);
                }
            else // view was Initializing (sorting) before tables were closed
                {
                // re-read database and sort
                SafeResort();
                }
            return;

        default:
            // other events dealt with below
            break;
        }


    if (iState!=EReady)
        {
        // The tables have been closed so the the sort must be cancelled.
        if (aEvent.iType == EContactDbObserverEventTablesClosed)
            {
            iAsyncSorter->Stop();
            }

        if (iAsyncSorter->QueueViewEvents())
            {
                   
#if defined(__VERBOSE_DEBUG__)
            DebugLogNotification(_L("[CNTMODEL] . . . . . Queueing Database Event "), aEvent);
#endif
            iOutstandingEvents.AppendL(aEvent);
            // The view state is set to ENotReady when a recovery takes place, and also when the tables
            // are closed, so set ready here.
            if (iState==ENotReady && (aEvent.iType==EContactDbObserverEventRecover || aEvent.iType==EContactDbObserverEventTablesOpened))
                {
                SetState(EReady);
                }
            // view was Initializing (sorting) before recovery or compression started!    
            if (iState==EInitializing && (aEvent.iType==EContactDbObserverEventRecover || aEvent.iType==EContactDbObserverEventCompress))
                {
                // re-read database and sort
                SafeResort();
                }
            }
            
            
#if defined(__VERBOSE_DEBUG__)
        else
            {
            DebugLogNotification(_L("[CNTMODEL] . . . . . Discarding Database Event "), aEvent);
            }
#endif
        }
    else
        {
        TContactViewEvent event;
        event.iInt = KErrNone;
        switch(aEvent.iType)
            {
            case EContactDbObserverEventGroupChanged:
                {
                //Groups are a special case the base view may not contain the group
                //but a sub view may be such a group and need to know its changed
                //Local views can contain groups so this case carries on to the next so no break;
                event.iEventType=TContactViewEvent::EGroupChanged;
                event.iContactId=aEvent.iContactId;
                NotifyObservers(event);
                }
            case EContactDbObserverEventContactChanged:
            case EContactDbObserverEventOwnCardChanged:
                {// Remove from old position, and notify.
                TRAPD(err,event.iInt=RemoveL(aEvent.iContactId));

                if (err == KErrNone && event.iInt != KErrNotFound)
                    {
                    event.iEventType=TContactViewEvent::EItemRemoved;
                    event.iContactId=aEvent.iContactId;
                    NotifyObservers(event);
                    }
                
                // Insert at new position, and notify.
                event.iInt=InsertL(aEvent.iContactId);
                if (event.iInt != KErrNotFound)
                    {
                    event.iEventType=TContactViewEvent::EItemAdded;
                    event.iContactId=aEvent.iContactId;
                    NotifyObservers(event);
                    }
                break;
                }
            case EContactDbObserverEventContactAdded:
            case EContactDbObserverEventGroupAdded:
#if defined(__VERBOSE_DEBUG__)
            DebugLogNotification(_L("[CNTMODEL] DatabaseEvent -> Contact/Group Added"), aEvent);
#endif
                event.iInt=InsertL(aEvent.iContactId);
                if (event.iInt != KErrNotFound)
                    {
                    event.iEventType=TContactViewEvent::EItemAdded;
                    event.iContactId=aEvent.iContactId;
                    NotifyObservers(event);
                    }
                break;
            case EContactDbObserverEventContactDeleted:
                if(aEvent.iContactId == KNullContactId)// KNullContactId indicates a bulk delete 
                    {
                    SetState(EInitializing); // Use initializing state to avoid ESortOrderChanged event being sent to observers.
                    SafeResort();
                    }
                else
                    {
                    event.iInt=RemoveL(aEvent.iContactId);
                    if (event.iInt != KErrNotFound)
                        {
                        event.iEventType=TContactViewEvent::EItemRemoved;
                        event.iContactId=aEvent.iContactId;
                        NotifyObservers(event);
                        }
                    }
                break;
            case EContactDbObserverEventGroupDeleted:
            case EContactDbObserverEventOwnCardDeleted:
                event.iInt=RemoveL(aEvent.iContactId);
                if (event.iInt != KErrNotFound)
                    {
                    event.iEventType=TContactViewEvent::EItemRemoved;
                    event.iContactId=aEvent.iContactId;
                    NotifyObservers(event);
                    }
                break;
            case EContactDbObserverEventUnknownChanges:
            case EContactDbObserverEventCurrentDatabaseChanged:
                SetState(EInitializing); // Use initializing state to avoid ESortOrderChanged event being sent to observers.
                SafeResort();
                break;
            case EContactDbObserverEventSortOrderChanged: // event is not currently used
                SetState(ENotReady);
                SafeResort();
                break;
            case EContactDbObserverEventTablesClosed:
                if (iState == EReady)
                    {
                    SetState(ENotReady);
                    }
                break;
            case EContactDbObserverEventTablesOpened:
                // re-read database and sort
                SafeResort();
                break;

            case EContactDbObserverEventNull:
            case EContactDbObserverEventUnused:
            case EContactDbObserverEventRecover:
            case EContactDbObserverEventCompress:
            case EContactDbObserverEventRollback:
            case EContactDbObserverEventTemplateChanged:
            case EContactDbObserverEventTemplateDeleted:
            case EContactDbObserverEventTemplateAdded:
            case EContactDbObserverEventCurrentItemDeleted:
            case EContactDbObserverEventCurrentItemChanged:
            case EContactDbObserverEventPreferredTemplateChanged:
            case EContactDbObserverEventSpeedDialsChanged:
            case EContactDbObserverEventRestoreBadDatabase:
                break;

            // these events should not come here, but be dealt with at the top of HandleDatabaseEventL
            case EContactDbObserverEventBackupBeginning:
            case EContactDbObserverEventRestoreBeginning:
            case EContactDbObserverEventBackupRestoreCompleted:
                break;
                
            default:
                ASSERT(EFalse);
            }
        }
    }

TInt CContactLocalView::SortCallBack()
    {
    TInt ret=KErrNotFound;
    TRAPD(err, ret = DoReadIncrementL());

#if defined(__VERBOSE_DEBUG__)
    if (err)
        {
        RDebug::Print(_L("[CNTMODEL] CContactLocalView{ViewPrefs = 0x%08X} . . . DoReadIncrementL ERROR %i\r\n"),
            iViewPreferences, err);
        }
    else
        {
        RDebug::Print(_L("[CNTMODEL] CContactLocalView{ViewPrefs = 0x%08X} . . . DoReadIncrementL returned %i\r\n"),
            iViewPreferences, ret);
        }
#endif

    if(err!=KErrNone)
        {
        ret=err;
        }
    if (ret<0)
        {
        // There was an error, so notify observers and stop any further callbacks.
        NotifySortError(ret);
        return KSortFinished;
        }
    if (ret==0)
        {
        //Read Has Finished.
#ifdef __PROFILE_SORT__
        RDebug::ProfileEnd(1);

        RDebug::ProfileStart(2);
#endif

        // is there a View Sort ECOM plug-in present?
        CViewContactSortPlugin*    sortPluginImpl = SortPluginImpl();

        if (sortPluginImpl)
            {
            // prepare View Sort plug-in
            ret = sortPluginImpl->SortStart(CViewContactSortPlugin::ESortStartFull, iContacts.Count());

            if (ret < 0)
                {
                return ret;
                }
            }

        // customised array sort implementation
        TRAP(err, ContactsArraySortL());

        //Sort Has Finished.
        if (sortPluginImpl)
            {
            sortPluginImpl->SortCompleted();
            }


#ifdef __PROFILE_SORT__

        RDebug::ProfileEnd(2);
        TProfile profile[3];
        RDebug::ProfileResult(profile,1,3);

        RDebug::Print(_L("[CNTMODEL] CntModel View, , %u, %u, Finished sort total, %u us\n"), 
            static_cast<TUint>(RProcess().Id()), static_cast<TUint>(RThread().Id()),
            profile[1].iTime + profile[0].iTime);

        RDebug::Print(_L("[CNTMODEL] CntModel View, , , , Data Read time, %u us\n"), profile[0].iTime);
        RDebug::Print(_L("[CNTMODEL] CntModel View, , , , Data Sort time, %u us\n"), profile[1].iTime);
        RDebug::Print(_L("[CNTMODEL] CntModel View, , , , Compare time, %u us\n"), profile[2].iTime);

#endif

        // sort finished, change state, allow for 2nd pass for ICC entries
        TInt result = iAsyncSorter->SortComplete();

        if (iState != EInitializing)
            {
            //The view has just been re-sorted notifiy observers ESortOrderChanged
            iState = EReady;
            NotifyObservers(TContactViewEvent(TContactViewEvent::ESortOrderChanged));
            HandleOutstandingEvents();
            return result;
            }
        // Sorted for the first time, notifiy ready
        SetState(EReady);
        return result;
        }
    // There's more reading to be done, so request another callback.
    return KSortCallAgain;
    }

TInt CContactLocalView::DoReadIncrementL()
    {
#if defined(__VERBOSE_DEBUG__)
    RDebug::Print(_L("[CNTMODEL] CContactLocalView{ViewPrefs = 0x%08X}::DoReadIncrement()"), iViewPreferences);
#endif

    // what contacts are we adding to the View?
    const TContactViewPreferences viewPrefs = iAsyncSorter->SortViewPreferences();

    if(iViewIterator == NULL)
        {
        if(iFactory == NULL)
            {
            iFactory = const_cast<CContactDatabase&>(iDb).FactoryL();
            }
        MLplViewIteratorManager& manager = iFactory->GetViewIteratorManagerL();
        iViewIterator = new (ELeave) CViewIterator(manager,*iTextDef,viewPrefs);
        iViewIterator->GoFirstL();
        }
    TInt i(0);
    // process a chunk of contacts
    CViewContact* contact;
    for(;i<KNumberOfContactsPerChunk;++i)
        {
        contact = iViewIterator->NextItemL();
        if(contact == NULL)
            {
            break; // No more contacts so quick exit
            }
        else if(!ContactCorrectType(contact->ContactTypeUid(),viewPrefs))
            {
            delete contact;
            }
        else
            {
            CleanupStack::PushL(contact);
            if(IsContactSortable(*contact,iViewPreferences))
                {
                iContacts.AppendL(contact);
                CleanupStack::Pop(contact);
                }
            else if(iViewPreferences & (EUnSortedAtBeginning | EUnSortedAtEnd))
                {
                // unsortable contacts go at the end or beginning
                iUnSortedContacts.AppendL(contact);
                CleanupStack::Pop(contact);
                }
            else
                {
                CleanupStack::PopAndDestroy(contact);
                }
            }
        }
    if(i== KNumberOfContactsPerChunk)
        {
        // Loop did not break so more contacts
        return ETrue;
        }
    else
        {
        // Loop break so no more contacts
        return EFalse;
        }
    }

void CContactLocalView::ContactsArraySortL()
    {

    // HeapSort (stolen from RPointerArrayBase)
    TInt ss = iContacts.Count();
    if (ss>1)
        {
        TInt sh = ss>>1;
        FOREVER
            {
            CViewContact* si;
            if (sh!=0)
                {
                // make heap
                --sh;
                si = iContacts[sh];
                }
            else
                {
                // sort heap
                --ss;
                si = iContacts[ss];
                iContacts[ss] = iContacts[0];
                if (ss==1)
                    {
                    iContacts[0] = si;
                    break;
                    }
                }

            // sift down
            TInt ii = sh;
            TInt jj = sh;
            FOREVER
                {
                jj = (jj+1)<<1;
                if (jj>=ss || CompareContactsAndIdsL(*iContacts[jj-1],*iContacts[jj])>0 )
                    --jj;
                if (jj>=ss || CompareContactsAndIdsL(*iContacts[jj],*si)<=0 )
                    break;
                iContacts[ii] = iContacts[jj];
                ii = jj;
                }
            iContacts[ii]=si;
            }
        }

    }


/**
@internalComponent
*/
void CContactLocalView::SetState(TState aState)
    {
    switch (iState)
        {
        case EInitializing:
        case ENotReady:
            ASSERT(aState==EReady);
            iState=EReady;
            NotifyObservers(TContactViewEvent(TContactViewEvent::EReady));
            HandleOutstandingEvents();
            break;
        case EReady:
            ASSERT(aState==ENotReady || aState==EInitializing);
            // ensure sort error is reset
            iExtension->iError = KErrNone;
            iState=aState;
            NotifyObservers(TContactViewEvent(TContactViewEvent::EUnavailable));
            break;
        default:
            ASSERT(EFalse);
        }
    }


void CContactLocalView::HandleOutstandingEventL()
    {
    TContactDbObserverEvent event = iOutstandingEvents[0];
    iOutstandingEvents.Remove(0);
    HandleDatabaseEventL(event);
    }

void CContactLocalView::HandleOutstandingEvents()
    {
    while (iOutstandingEvents.Count() > 0)
        {
        // loop through as many events as possible in the one Trap harness
        TRAP_IGNORE(HandleOutstandingEventL());
        // if HandleDatabaseEventL left we must remove the event
        }
    }

TContactViewPreferences CContactLocalView::ContactViewPreferences()
/** Gets the view preferences, as set during construction.

@return The view preferences. */
    {
    return iViewPreferences;
    }

const RContactViewSortOrder& CContactLocalView::SortOrderL() const
/** Gets the sort order, as set during construction.

This function cannot leave.

@return The sort order. */
    {
    return iSortOrder;
    }

/*
 * Notify observers that view construction failed.
 * The error is stored so that if another client tries to open the view
 * they will receive the same error.
 * @param aError Leave code from CIdleContactSorter::RunL
 */
void CContactLocalView::NotifySortError(TInt aError)
    {
    iExtension->iError = aError;
    NotifyObservers(TContactViewEvent(TContactViewEvent::ESortError, aError));
    }

/*
 * This is a reserved virtual exported function that is used for BC proofing 
 * against present and future additions of new exported virtual functions.
 @return Any return values of the helper methods called from this function or NULL.
*/
EXPORT_C TAny* CContactLocalView::CContactViewBase_Reserved_1(TFunction aFunction,TAny* aParams)
    {
    return CContactViewBase::CContactViewBase_Reserved_1(aFunction,aParams);
    }


/*
 * Factory constructor.
 * @since 7.0
 * @param aView Reference to CContactLocalView object
 */
CIdleContactSorter* CIdleContactSorter::NewL(CContactLocalView& aView, MLplPersistenceLayerFactory& aFactory)
    {
    CIdleContactSorter* self = new (ELeave) CIdleContactSorter(aView, aFactory);
    CleanupStack::PushL(self);
    self->ConstructL();
    CleanupStack::Pop(self);
    return self;
    }

/* Destructor */
CIdleContactSorter::~CIdleContactSorter()
    {
    Cancel();

    if (iPhbkSyncWatcher)
        {
        iPhbkSyncWatcher->RemovePhbkObserver(*this);
        ReleasePhbkSyncWatcher();
        }
    }

/* Cancel any active requests to the phonebook synchroniser */
void CIdleContactSorter::DoCancel()
    {
    // Nothing to do.
    }

/** 
 * Uses a simple state machine, initial iSortState is set by Start() to either
 * EInsertSortFinal or EWaitingForInitialICCReady
 *
 * Either Insert Sort all or part of the requested view.
 * (CIdle::RunL calls back to the Insert Sort code.)
 *    State
 *    EInsertContactsOnlyIccLocked          insert Contacts only (in a mixed view)
 *        goes to EContactsReadyWaitICCUnlock
 *    EInsertSortFinal                    insert all Contacts & ICC entries, or
 *        goes to ESortDone               add ICC entries to mixed view
 *                                        (iSortView specifies which)
 * Or wait for Phonebook Synchroniser to either finish or fail
 *    (failure other than SIM Locked causes a Sort Error) 
 *    State
 *    EWaitingForInitialICCReady          the view has nothing in: Phonebook
 *        goes to EInsertSortFinal        Synchronised allows full view to be available;
 *        or EInsertContactsOnlyIccLocked SIM Locked allows a view without ICC entries to 
 *                                        accessible
 *    EContactsReadyWaitICCUnlock         SIM was previously found to be locked, if/when
 *        goes to EInsertSortFinal        Phonebook Synchroniser completes we can merge in
 *                                        requested ICC entries
 *
 * The check whether the phonebook synchroniser is in a cache-valid state:-
 *
 * This check is done by making a async request to be completed when the 
 * phbksync cache state has changed, checking the current cache state and 
 * if the cache is valid already cancelling the request.
 * (The cancelled request will complete, causing RunL to run again.)
 * If there was a phbksync error check the error code, if it is not due to the
 * SIM card being locked then Leave.
 */
void CIdleContactSorter::RunL()
    {
#if defined(__VERBOSE_DEBUG__)
    RDebug::Print(_L("[CNTMODEL] CIdleContactSorter{RequestedView = 0x%08X, SortView = 0x%08X}::RunL()\r\n"),
        iRequestedView, iSortView);
    TSorterState oldSortState = iSortState;        // for debug messages only
#endif

    User::LeaveIfError(iStatus.Int());

    // either sort or wait for ICC ready / phonebook synch state change
    switch (iSortState)
        {
        // states that are sorting all or part of view
    case EInsertSortFinal:                // full insert sort or Phonebook Synched so add ICC entries
    case EInsertContactsOnlyIccLocked:    // insert Contacts for now, then wait for SIM to be unlocked
        // do slice of full / Contacts only /ICC only insert sort
        if (iView.SortCallBack() == KSortCallAgain)
            { // CAsyncOneShot::Call()
            Call();
            }
        break;

        // states that are waiting for a phonebook sync event
    case EWaitingForInitialICCReady:    // ICC entries in view, waiting for Phonebook Synch state change
        // ICC entries are included in view:
        if (iPhbkSyncWatcher->PhonebooksReady() > 0)
            {
            // ICC sync complete - can immediately sort everything
            ChangeSortState(EInsertSortFinal);
            }
        else if (iPhbkSyncWatcher->PhonebooksWaiting() > 0)
            {
            // SIM card is locked and, this is the first time we've seen this

            // Insert Contacts (if wanted) into View now
            // Afterwards we will wait again for SIM to unlock & Phonebook Synch to complete
            if(iRequestedView & EICCEntriesAndContacts)
                {
                // insert/sort view, but without the requested ICC entries
                iSortView = static_cast<TContactViewPreferences>(iSortView & ~EICCEntriesAndContacts);
                ChangeSortState(EInsertContactsOnlyIccLocked);
                }
            else 
                {
                // only ICC entries were wanted in the first place
                // so make the (empty) View Ready
                const_cast<CContactLocalView&>(iView).SetState(CContactLocalView::EReady);
                // now wait for SIM to unlock & Phonebook Synch to complete
                ChangeSortState(EContactsReadyWaitICCUnlock);
                }
            }
        else
            {
            // synchronisation finished with an error?
            User::LeaveIfError(iPhbkSyncWatcher->PhonebookSyncError());
            }

        // otherwise wait for a Phonebook Synch event
        break;

    case EContactsReadyWaitICCUnlock:    // when SIM is unlocked add ICC Entries to this view
        // ICC entries are included in view:
        if (iPhbkSyncWatcher->PhonebooksReady() > 0)
            {
            // ICC sync complete - can sort everything
            ChangeSortState(EInsertSortFinal);

            // add requested ICC entries into the sorted view
            iSortView = STATIC_CAST(TContactViewPreferences, (iSortView & ~EContactsOnly) | EICCEntriesOnly);
            const_cast<CContactLocalView&>(iView).SetState(CContactLocalView::ENotReady);

            // another pass through contacts database is needed
            // ResetSortL should not Leave (especially as it must have worked previously)
            const_cast<CContactLocalView&>(iView).ResetSortL();
            }

        // otherwise wait for a Phonebook Synch event
        break;

    case ESortAllDone: // shouldn't have come back here
    default:
        Panic(ECntPanicViewSorterStateMachine);
        break;
        }

#if defined(__VERBOSE_DEBUG__)
    if (oldSortState != iSortState)
        {
        switch (iSortState)
            {
            case EInsertSortFinal:
                RDebug::Print(_L("[CNTMODEL] {RequestedView = 0x%08X} * * * new Sort State = EInsertSortFinal, SortView = 0x%08X\r\n"),
                    iRequestedView, iSortView);
                break;
            case EInsertContactsOnlyIccLocked:
                RDebug::Print(_L("[CNTMODEL] {RequestedView = 0x%08X} * * * new Sort State = EInsertContactsOnlyIccLocked, SortView = 0x%08X\r\n"),
                    iRequestedView, iSortView);
                break;
            case EWaitingForInitialICCReady:
                RDebug::Print(_L("[CNTMODEL] {RequestedView = 0x%08X} * * * new Sort State = EWaitingForInitialICCReady\r\n"),
                    iRequestedView);
                break;
            case EContactsReadyWaitICCUnlock:
                RDebug::Print(_L("[CNTMODEL] {RequestedView = 0x%08X} * * * new Sort State = EContactsReadyWaitICCUnlock, SortView = 0x%08X\r\n"),
                    iRequestedView, iSortView);
                break;
            case ESortAllDone:
                RDebug::Print(_L("[CNTMODEL] {RequestedView = 0x%08X} * * * new Sort State = ESortAllDone\r\n"), iRequestedView);
                break;
            }
        }
    RDebug::Print(_L("[CNTMODEL] [Unsorted Contacts = %i, Sorted Contacts = %i, IsActive = %i]\r\n"),
    const_cast<CContactLocalView&>(iView).iUnSortedContacts.Count(),
    const_cast<CContactLocalView&>(iView).iContacts.Count(),
    IsActive());
#endif

    }


void CIdleContactSorter::ChangeSortState(TSorterState aNewSortState)
    {
#if defined(__VERBOSE_DEBUG__)
    RDebug::Print(_L("[CNTMODEL] CIdleContactSorter{RequestedView = 0x%08X, SortView = 0x%08X}::ChangeSortState(%i)\r\n"),
        iRequestedView, iSortView, static_cast<TInt>(aNewSortState));
#endif
    // new state
    iSortState = aNewSortState;
    // make the active object to run, CAsyncOneShot::Call()
    Call();
    }


/* 
 * Handle any leave during CIdleContactSorter::RunL. 
 * The local view is informed of that the view construction failed.
 * It will broadcast an ESortError view event to all clients of this view.
 * 
 * @param aError Leave code from RunL
 */
TInt CIdleContactSorter::RunError(TInt aError)
    {
#if defined(__VERBOSE_DEBUG__)
    RDebug::Print(_L("[CNTMODEL] CIdleContactSorter{RequestedView = 0x%08X, SortView = 0x%08X}::RunError(error = %i)\r\n"),
        iRequestedView, iSortView, aError);
#endif
    if ((aError != KErrCancel) && (iSortState != ESortAllDone))
        {
        const_cast<CContactLocalView&>(iView).NotifySortError(aError);
        iSortState = ESortAllDone;
        }
    return KErrNone;
    }


TInt CIdleContactSorter::SortComplete()
/**
 * Sort or partial sort completed, decide if there is more to do:
 * EInsertSortFinal -> ESortAllDone
 * EInsertContactsOnlyIccLocked -> EContactsReadyWaitICCUnlock (wait for SIM to become unlocked)
 *
 * return KSortCallAgain if there is more work to do, KSortFinished otherwise
 */
    {
    if(iSortState == EInsertContactsOnlyIccLocked)
        {
        // we are now waiting for phbksync, so that we can add ICC entries
        iSortState = EContactsReadyWaitICCUnlock;
#if defined(__VERBOSE_DEBUG__)
        RDebug::Print(_L("[CNTMODEL] * * * * * SortComplete: New Sort State = EContactsReadyWaitICCUnlock\r\n"));
#endif
        // CIdleContactSorter has more to do
        return KSortCallAgain;
        }

    // CIdleContactSorter all done
    iSortState = ESortAllDone;
#if defined(__VERBOSE_DEBUG__)
    RDebug::Print(_L("[CNTMODEL] * * * * * SortComplete: New Sort State = ESortAllDone\r\n"));
#endif
    return KSortFinished;
    }

/*
 Initialise Idle Contact Sorter for a new sort

 Re-init iSortView - the view filter for the Insert Sort
 Decide the initial iSortState for RunL:
   Contacts only view -> EInsertSortFinal
   ICC entries included -> EWaitingForInitialICCReady
 */
 void CIdleContactSorter::Start()
    {
    // initially we will try to insert sort everything requested
    iSortView = iRequestedView;

    if (iPhbkSyncWatcher)
        {
        // ICC entries included in view, must wait for Phonebook Synch
        iSortState = EWaitingForInitialICCReady;
        }
    else
        {
        // Only Contacts wanted in view, we can Sort straight away
        iSortState = EInsertSortFinal;
        }

#if defined(__VERBOSE_DEBUG__)
    RDebug::Print(
        (iSortState == EInsertSortFinal) ? 
            _L("[CNTMODEL] CIdleContactSorter{RequestedView = 0x%08X}::Start() Sort State = EInsertSortFinal\r\n") :
            _L("[CNTMODEL] CIdleContactSorter{RequestedView = 0x%08X}::Start() Sort State = EWaitingForInitialICCReady\r\n"),
        iRequestedView);
#endif

    // set Active for the first time, CAsyncOneShot::Call()
    Call();
    }


/*
 Stop any sort that is already in progress
 */
void CIdleContactSorter::Stop()
    {
    if (iSortState != ESortAllDone)
        {
        // stop sorting
        iSortState = ESortAllDone;
        Cancel();
        }
    }


/* 
 * Second phase construction.
 * Copy the View's requested preferences, get link to ICC phonebook watcher
 */
void CIdleContactSorter::ConstructL()
    {
    iRequestedView = CONST_CAST(CContactLocalView&,iView).ContactViewPreferences();

    // is ICC phonebook sync expected?
    if (iRequestedView & (EICCEntriesOnly | EICCEntriesAndContacts))
        {
        iPhbkSyncWatcher = GetPhbkSyncWatcherL();

        // observe ICC sync events
        iPhbkSyncWatcher->AddPhbkObserverL(*this);
        }
    }

 /*
 Utility method to return a reference to the ICC synchroniser watcher.
 Always returns a pointer to the real phonebook synchroniser plugin.
 It is assumed that Phonebook synchronising server never creates the view,
 so the deadlock in not possible and the dummy plugin is not required.

 @internalTechnology
 @leave KErrNotSupported if contact synchroniser plug-in cannot be found
 @leave KErrNoMemory if not enough memory
 @return Pointer to CContactPhbkSyncWatcher instance.
 */
CContactPhbkSyncWatcher* CIdleContactSorter::GetPhbkSyncWatcherL()
    {
    if (!iPhbkSyncWatcher)
        {
        iPhbkSyncWatcher = CContactPhbkSyncWatcher::NewL(iFactory.GetContactSynchroniserL(KMaxTUint32)); //Always use the Contact Synchroniser
        }
    return iPhbkSyncWatcher;
    }


void CIdleContactSorter::ReleasePhbkSyncWatcher()
    {
    if (iPhbkSyncWatcher)
        {
        if (iPhbkSyncWatcher->ObserverCount() == 0)
            {
            delete iPhbkSyncWatcher;
            iPhbkSyncWatcher = NULL;
            }
        }
    }


/* Constructor */
  CIdleContactSorter::CIdleContactSorter(CContactLocalView& aView, MLplPersistenceLayerFactory& aFactory) 
  : CAsyncOneShot(CActive::EPriorityLow), iView(aView), iFactory(aFactory)
    {
    }

/* 
 * Determines whether view events should be queued.
 *
 * View events are only queued when the ICC has been synchronised. This prevents
 * duplicate contacts in an ICC view because add events are not queued until the 
 * SIM is fully synchronised. 
 * 
 * See LUD-5EBHZF "ICC contacts view broadcasts add item events after view is 
 * ready" for more detail.
 * 
 * @return ETrue, if view events should be queued. EFalse, otherwise
 */
TBool CIdleContactSorter::QueueViewEvents() const
    {
    // Initial wait for phonebook synch (i.e. waiting for ICC ready or locked) ?
    if(iSortState == EWaitingForInitialICCReady)
        {
        return EFalse;
        }
    return ETrue;
    }

TContactViewPreferences CIdleContactSorter::SortViewPreferences() const
/**
 * Current View Preferences for insert sort in to View
 *
 * May be a subset of the requested View.
 * If the SIM card is locked this will initially be a View without ICC entries.
 * If the SIM becomes unlocked a second pass then picks out ICC entries only.
 *
 */
    {
    return iSortView;
    }


TBool CIdleContactSorter::InsertViewPreferences(TContactViewPreferences &aInsertView) const
/**
 * Modifies View Preferences for inserting into View
 *
 * May be a subset of the requested View:
 * If a Mixed (Contacts & ICC view) is requested and the Phonebook Synch has NOT
 * completed then only Contacts entries are added to the view. When the PhoneBook Synch 
 * completes all ICC entries will at the same time.
 *
 */
    {
    TBool okayToInsert = ETrue;

    switch (iSortState)
        {
    case EInsertSortFinal:                // full insert sort or Phonebook Synched so add ICC entries
    case ESortAllDone:
        // view is finished or finishing, can Insert any contact
        break;

    case EInsertContactsOnlyIccLocked:    // insert Contacts for now, then wait for SIM to be unlocked
        // only Contacts can be inserted now, no ICC entries
        aInsertView = iSortView;
        break;

    case EWaitingForInitialICCReady:    // ICC entries in view, waiting for Phonebook Synch state change
        // Waiting for initial ICC Synch result, insert nothing
        okayToInsert = EFalse;
        break;

    case EContactsReadyWaitICCUnlock:    // when SIM is unlocked add ICC Entries to this view
        if (aInsertView & EICCEntriesOnly)
            {
            okayToInsert = EFalse;        // can't insert ICC entries yet
            }
        else
            {
            aInsertView = iSortView;    // only Insert Contacts
            }
        break;
        }

    return okayToInsert;
    }

TBool CContactLocalView::ContactCorrectType(TUid aType,TContactViewPreferences aTypeToInclude)
    {
    TBool correctType = EFalse;

    if (aType == KUidContactCard)
        {
        if (!(aTypeToInclude & (EGroupsOnly | EICCEntriesOnly)))
            {
            correctType = ETrue;
            }
        }
    else if (aType == KUidContactOwnCard)
        {
        if (!(aTypeToInclude & (EGroupsOnly | EICCEntriesOnly | EContactCardsOnly)))
            {
            correctType = ETrue;
            }
        }
    else if (aType==KUidContactGroup)
        {
        if (aTypeToInclude & (EGroupsOnly | EContactAndGroups))
            {
            correctType = ETrue;
            }
        }
    else if (aType == KUidContactICCEntry)
        {
        if (aTypeToInclude & (EICCEntriesOnly | EICCEntriesAndContacts))
            {
            correctType = ETrue;
            }
        }

    return correctType;
    }

void CIdleContactSorter::ContactPhbkSyncEventHandler(TPhonebookState aPhbkState)
    {
#if defined(__VERBOSE_DEBUG__)
    RDebug::Print(_L("[CNTMODEL] CIdleContactSorter{RequestedView = 0x%08X, SortView = 0x%08X}::ContactPhbkSyncEventHandler\r\n"),
        iRequestedView, iSortView);
#endif
    switch (aPhbkState)
        {
        case EIccPhbkNotSynchronised:
            /* Initial state, or ICC card has 'gone away' (e.g. ICC is resetting). */
            // no action - may want to act on this in future
            break;

        case EIccPhbkSynchronised:    // ICC Phonebook has completed synchronisation.

        case EIccWaitForPhbkToBeReady:    // Sync failed due to ICC being locked or not ready.

        case EIccPhbkSyncError:        //    Sync with Phbk Server failed.

#if defined(__VERBOSE_DEBUG__)
            RDebug::Print(aPhbkState == EIccPhbkSynchronised ? _L("[CNTMODEL]     state = ICC phonebook synchronised)\r\n") :
                aPhbkState == EIccWaitForPhbkToBeReady ? _L("    state = ICC phonebook Locked)\r\n") :
                 _L("    state = ICC phonebook Sync Error)\r\n"));
#endif
            // in a sorting state where we care?
            if ((iSortState == EWaitingForInitialICCReady) || (iSortState == EContactsReadyWaitICCUnlock))
                {
                // let state machine in RunL() deal with the event
                if (!IsActive())
                    { // CAsyncOneShot::Call()
                    Call();
                    }
                }
            break;
        }
    }