summaryrefslogtreecommitdiffstats
path: root/plugins/contacts/symbian/contactsmodel/cntmodel/src/ccontactprivate.cpp
blob: cde9f7a8a0c397929687060cb5c7d8958d54e97c (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
/*
* 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 <cntdb.h>
#include "cntstd.h"
#include "rcntmodel.h"
#include "ccontactprivate.h"
#include "cntviewprivate.h"
#ifdef SYMBIAN_ENABLE_SPLIT_HEADERS
#include "cntdb_internal.h"
#include "cntsyncecom.h"
#endif


const TInt KMaxItemsInTemplateCache = 8; // Maximum number of cached templates.
const TInt KInitialSortArraySize = 20; // Initial size of sort array.


/**
CTextFieldMinimal destructor.
*/
CTextFieldMinimal::~CTextFieldMinimal()
	{
	delete iText;
	}


/**
CTextFieldMinimal second phase constructor.
*/
void CTextFieldMinimal::ConstructL(const TDesC &aText, TContactItemId aId)
	{
	iText=aText.AllocL();
	iId=aId;
	}


/**
CSortArray first phase constructor.
*/
CSortArray::CSortArray()
	:
	iArray(KInitialSortArraySize)
	{
	}


/**
CSortArray destructor.
*/
CSortArray::~CSortArray()
	{
	iArray.ResetAndDestroy();
	iArray.Close();
	}


/**
Create a CTextFieldMinimal object using the given text and Contact ID and append
it to the sort array.

@param aText Text for CTextFieldMinimal object.
@param aId Contact ID for CTextFieldMinimal object.
*/
void CSortArray::AppendL(const TDesC &aText, TContactItemId aId)
	{
	CTextFieldMinimal *tm=new(ELeave) CTextFieldMinimal;
	CleanupStack::PushL(tm);
	tm->ConstructL(aText, aId);
	User::LeaveIfError(iArray.Append(tm));
	CleanupStack::Pop(); // tm
	}


/**
Sort the sort array using the given sort order.

@param aOrder EAsc for ascending order, EDesc for descending order.
*/
void CSortArray::SortL(CContactDatabase::TSortPref::TOrder aOrder)
	{
	// If nothing to sort then return immediately.
	if (iArray.Count()==0)
		{
		return;
		}
		
	// Sort the array in ascending sort order using the default algorithm to
	// compare the elements in the sort array.
	iArray.Sort(TLinearOrder<CTextFieldMinimal>(DefaultAlgorithmToCompareNames));
	
	// If descending sort order then reverse the elements in the sort array.
	if (aOrder==CContactDatabase::TSortPref::EDesc)
		{
		TInt count=Count();
		TInt end=count/2;
		TInt index2=count-1;
		for(TInt index=0;index<end;index++)
			{
			CTextFieldMinimal *tfm=(CTextFieldMinimal *)iArray[index];
			iArray[index]=iArray[index2];
			iArray[index2]=tfm;
			index2--;
			}
		}
	}


/**
Compare the text in the given CTextFieldMinimal objects.

The custom TCollation method is required to ensure that the collated comparison
will not ignore spaces and punctuation (which it does by default).

Mem::CollationMethodByIndex() is an exec call and is hence relatively expensive.
Although it is inefficient to create a collation method each time this method is
called, there is no benefit in storing TCollationMethod as a member of
CSortArray because this method must be static.

@param aName1
@param aName2

@return A positive value if text in aName1 is greater than text in aName2, a
negative value if text in aName1 is less than text in aName2 and zero if the
text in both aName1 and aName2 is the same.
*/
TInt CSortArray::DefaultAlgorithmToCompareNames(const CTextFieldMinimal& aName1, const CTextFieldMinimal& aName2)
	{
	TCollationMethod collateMethod;
	collateMethod = *Mem::CollationMethodByIndex(0);
	collateMethod.iFlags|=TCollationMethod::EIgnoreNone;
	return aName1.iText->CompareC(*aName2.iText,3,&collateMethod);
	}


/**
Get the Contact ID at the given index in the sort array.

@return The Contact ID at the given index.
*/
TContactItemId CSortArray::Id(TInt aIndex) const
	{
	return(((CTextFieldMinimal *)iArray[aIndex])->iId);
	}


/**
Get the text at the given index in the sort array.

@return The text at the given index.
*/
HBufC* CSortArray::Text(TInt aIndex) const
	{
	return(((CTextFieldMinimal *)iArray[aIndex])->iText);
	}


/**
Merge the given sort array with this sort array starting from the given position
in this sort array.

@param aDuplicates The sort array to be merged with this sort array.
@param aStartPos The starting position for the merge in this sort array.
*/
void CSortArray::Merge(CSortArray *aDuplicates,TInt aStartPos)
	{
	TInt numDuplicates=aDuplicates->Count();
	for (TInt loop=0;loop<numDuplicates;loop++)
		{
		const TInt index=aStartPos+loop;
		delete iArray[index];
		iArray[index]=aDuplicates->iArray[0];
		aDuplicates->iArray.Remove(0);
		}
	}


/**
CCntTemplateCache object factory.

@return CCntTemplateCache object.
*/
CCntTemplateCache* CCntTemplateCache::NewL(RCntModel& aCntSvr)
	{
	CCntTemplateCache* templateCache = new(ELeave) CCntTemplateCache(aCntSvr);
	return templateCache;		
	}
	

/**
CCntTemplateCache first phase constructor.

@param aCntSvr Client Contacts Model session object handle.
*/
CCntTemplateCache::CCntTemplateCache(RCntModel& aCntSvr)
	:
	iCache(KMaxItemsInTemplateCache),
	iCntSvr(aCntSvr),
	iTemplateId(KGoldenTemplateId)
	{
	}


/**
CCntTemplateCache destructor.
*/
CCntTemplateCache::~CCntTemplateCache()
	{
	iCache.ResetAndDestroy();
	delete iViewDef;
	delete iSystemTemplate;
	}


/**
Delete an entry from the template cache.

@param aIndex Index of entry in template cache to be deleted.
*/
void CCntTemplateCache::DeleteEntry(TInt aIndex)
	{
	delete iCache [aIndex];
	iCache.Remove(aIndex);
	}


/**
Remove a template from the template cache.

@param aId ID of the template which is to be removed from the template cache.
*/
void CCntTemplateCache::RemoveTemplate(TContactItemId aId)
	{
	for(TInt ii=iCache.Count() - 1; ii >= 0; --ii)
		{
		if (iCache[ii]->Id() == aId)
			{
			DeleteEntry(ii);	
			}
		}
	
	// Are we removing the system template?
	if (iSystemTemplate != NULL && iSystemTemplate->Id() == aId)	
		{
		delete iSystemTemplate;
		iSystemTemplate = NULL;	
		}
	}


/**
Get the system template.  If the system template does not yet exist then
create it (lazy initialisation).

@return CContactItem object reference for the system template.
*/
CContactItem& CCntTemplateCache::SystemTemplateL() 
	{
	if (!iSystemTemplate)
		{
		CContactItemViewDef* matchAll = CContactItemViewDef::NewLC(	CContactItemViewDef::EMaskFields,
																CContactItemViewDef::EIncludeHiddenFields);
		iSystemTemplate = static_cast<CContactItem*>(iCntSvr.ReadContactL(matchAll, KGoldenTemplateId));
		CleanupStack::PopAndDestroy(matchAll);
		}

	return *iSystemTemplate;
	}


/**
Dispose of the system template.  The next time the system template is accessed
via the SystemTemplateL() method it will be fetched from the Server.
*/
void CCntTemplateCache::ResetSystemTemplate()
	{
	delete iSystemTemplate;
	iSystemTemplate = NULL;
	}


/**
Get a template from the template cache with the given ID.

@param Contact item ID of the template.

@return CContactItem object reference for the template.
*/
CContactItem& CCntTemplateCache::TemplateL(TContactItemId aId)
	{
	if (aId == KGoldenTemplateId)
		return SystemTemplateL();
	
	CContactItem *retVal = NULL;
	TInt maxCount 		 = iCache.Count();
	TInt ii				 = maxCount;
	
	// Try to find the template in the cache.
	while(ii) 
		{
		--ii;	
		if (iCache[ii]->Id() == aId)
			{
			retVal = iCache[ii];
			break; // Stop searching
			}
		}
		
	if (!retVal) // Template does not exist in cache.
		{
		// Read the template from the Server.
		CContactItemViewDef* matchAll = CContactItemViewDef::NewLC(	CContactItemViewDef::EMaskFields,
										CContactItemViewDef::EIncludeHiddenFields);
		retVal = iCntSvr.ReadContactL(matchAll, aId);
		CleanupStack::PopAndDestroy(matchAll);
		if (maxCount == KMaxItemsInTemplateCache)
			{
			// Remove the first item from the cache (cache is maintained in
			// using FIFO behaviour i.e. oldest template is removed when cache
			// size is exceeded.
			DeleteEntry(0);
			}
		iCache.Append(retVal);		
		}
		
	return *retVal;
	}


/**
Get the default view definition for the template cache.  If the default view 
definition does not yet exist then create it (lazy initialisation).

@return CContactItemViewDef object reference.

@leave KErrNoMemory Out of memory.
*/
CContactItemViewDef& CCntTemplateCache::DefaultViewDefL()
	{
	if (!iViewDef)
		{
		iViewDef = CContactItemViewDef::NewL(CContactItemViewDef::EIncludeFields, CContactItemViewDef::EIncludeHiddenFields);
		iViewDef->AddL(KUidContactFieldMatchAll);
		}
	return *iViewDef;	
	}

	
/**
Merge the given Contact Item with the template used to create the Contact Item.
If no view definition is supplied then use the default view definition.

@param aContact Contact Item to be merged with template.
@param aViewDef View definition to use.
*/
void CCntTemplateCache::MergeWithTemplateL(CContactItem& aContact, const CContactItemViewDef* aViewDef)
	{
	if (aContact.TemplateRefId()!= KNullContactId && aContact.Type() != KUidContactCardTemplate)
		{
		CContactItemViewDef* viewDef = NULL;
		if(aViewDef == NULL) // Only create a viewDef if none has been given.
			{
			viewDef = &(DefaultViewDefL());
			}
		else 
			{
			viewDef = const_cast<CContactItemViewDef*>(aViewDef);	
			}
	
		// Restore template fields.
		if (aContact.TemplateRefId() != KNullContactId && aContact.Type() != KUidContactCardTemplate)
			{
			// Get the template ID used to create the Contact Item.
			CContactItem* contactTemplate=&(static_cast<CContactTemplate&>(TemplateL(aContact.TemplateRefId())));
			aContact.RestoreTemplateFieldsL(SystemTemplateL().CardFields(), contactTemplate->CardFields(), const_cast<CContactItemViewDef&> (*viewDef));
			}
		}
	else if (aContact.Type()==KUidContactCardTemplate)
		{
		aContact.AddLabelFieldL();
		}
	}


/**
CPrivConverter object factory.

@param aImplementationUid UID of the converter plugin.

@return CPrivConverter object.
*/
CPrivConverter* CPrivConverter::NewL(TUid aImplementationUid)
	{
	CPrivConverter* self=new(ELeave) CPrivConverter;
	CleanupStack::PushL(self);
	CVersitTlsData::VersitTlsDataL();
	self->LoadEComPluginL(aImplementationUid);
	CleanupStack::Pop(self); 
	return self;
	}
/**
CPrivConverter object factory.
Loads PBAP contact converter plug-in.
@param aImplementationUid UID of the converter plugin.
@param aContactFieldFilter Specifies contact fields to be exported.
@param aCallback Callback to client for providing intra-contact properties.
@param aVersion Denotes the vCard version for contact export.
@return CPrivConverter object.
*/
CPrivConverter* CPrivConverter::NewL(TUid aUid, TInt64 aContactFieldFilter, MConverterCallBack* aCallback, TVCardVersion aVersion, TBool aExportTel)
	{
	CPrivConverter* self = new(ELeave) CPrivConverter;
	CleanupStack::PushL(self);
	CVersitTlsData::VersitTlsDataL();
	self->LoadEComPluginL(aUid, aContactFieldFilter, aCallback, aVersion, aExportTel);
	CleanupStack::Pop(self); 
	return self;
	}

TInt64 CPrivConverter::GetPBAPFilter() const
	{
	return iPBAPFilter;
	}

TBool CPrivConverter::GetExportTel() const
	{
	return iExportTel;
	}

TVCardVersion CPrivConverter::GetCurrentVersion() const
	{
	return iVersion;
	}

/**
CPrivConverter destructor.
*/
CPrivConverter::~CPrivConverter()
	{
	delete iConverter;
	CVersitTlsData::CloseVersitTlsData();
	}


/**
Load the ECOM plugin with the given UID.

@param aUid UID of the plugin.
@param aContactFieldFilter Specifies contact fields to be exported.
@param aCallback Callback to client for providing intra-contact properties.
@param aVersion Denotes the vCard version for contact export.
*/
void CPrivConverter::LoadEComPluginL(TUid aUid, TInt64 aContactFieldFilter, MConverterCallBack* aCallback, TVCardVersion aVersion, TBool aExportTel)
	{
	if(IsImplementationAvailableL(aUid))
		{
		iVersion = aVersion;
		iPBAPFilter = aContactFieldFilter;
		iExportTel = aExportTel;
		iConverter = CContactEcomConverter::NewL(aUid, aContactFieldFilter, aCallback, aVersion, aExportTel);
		}
	__ASSERT_DEBUG(ETrue, User::Invariant());
	}

/**
Load the ECOM plugin with the given UID.

@param aUid UID of the plugin.
*/
void CPrivConverter::LoadEComPluginL(TUid aUid)
	{
	if(IsImplementationAvailableL(aUid))
		{
		iVersion = EVCard21;
		iConverter = CContactEcomConverter::NewL(aUid);	
		}
	__ASSERT_DEBUG(ETrue, User::Invariant());
	}

/**
Finds out if implementation for a given plug-in uid is present as part of vCard Interface.

@param aUid UID of the plugin.
@return TBool ETrue if implementation exists.

@leave KErrNoMemory 
@leave KErrNotConnected 
@leave KErrArgument 

*/
TBool CPrivConverter::IsImplementationAvailableL(TUid aUid)
	{
	RImplInfoPtrArray	implInfoArray;
	CleanupResetAndDestroyPushL(implInfoArray);

	REComSession::ListImplementationsL(KUidEcomCntVCardConverterInterface, implInfoArray);

	// Check that aImplementationUid is an implementation of
	// KUidEcomCnVCardConverterInterface by checking it is included in
	// implInfoArray.
	const TInt count = implInfoArray.Count();
	__ASSERT_ALWAYS( count > 0, User::Leave(KErrNotFound));

	TBool isAvailable = EFalse;

	for(TInt i = 0 ; i < count ; ++i)
		{
		if(	aUid == implInfoArray[i]->ImplementationUid())
			{
			switch(aUid.iUid)
				{
				case KUidVCardConvDefaultImpl:
					isAvailable = ETrue;
				break;
				case KUidPBAPVCardConvImpl:
					isAvailable = ETrue;
				break;
				default:
				break;
				}
			break;
			}
		}
	CleanupStack::PopAndDestroy(&implInfoArray);
	
	return isAvailable;
	}

/**
CContactPlugin constructor.
*/
CContactPlugin::CContactPlugin()
	{
	}

/**
CContactPlugin destructor.
*/
CContactPlugin::~CContactPlugin()
	{
	iDll.Close();
	}


/**
Initialise this TSortPref object from the given stream.

@param aStream Stream to read TSortPref object state from.
*/
EXPORT_C void CContactDatabase::TSortPref::InternalizeL(RReadStream& aStream)
	{
	iFieldType.iUid=aStream.ReadInt32L();
	iOrder=STATIC_CAST(CContactDatabase::TSortPref::TOrder,aStream.ReadInt32L());
	}

/**
Store this TSortPref object in the given stream.

@param aStream Stream to write TSortPref object state to.
*/
EXPORT_C void CContactDatabase::TSortPref::ExternalizeL(RWriteStream& aStream) const
	{
	aStream.WriteInt32L(iFieldType.iUid);
	aStream.WriteInt32L(iOrder);
	}


/**
Determine if the asynchronous find is complete.
	
@return ETrue If asynchronous find is complete, EFalse otherwise.
*/
EXPORT_C  TBool CIdleFinder::IsComplete() const
/** Checks whether the contact database search is complete.
@return ETrue if search is complete, otherwise EFalse.  */
	{
	return(iContactDatabase==NULL);
	}


/**
Get and take ownership of the Contact IDs.

@return Array of Contact IDs.
*/
EXPORT_C  CContactIdArray* CIdleFinder::TakeContactIds()
/** Gets an array of contact item IDs where the match is found.
@return Array of contact item IDs.  */
	{
	iOwnsIds=EFalse;
	return(iIdsFound);
	}


/**
Get the last asynchronous find error.

@return The last asynchronous find error.
*/
EXPORT_C  TInt CIdleFinder::Error() const
/** Signals an error while searching the database.
@return The error code, if any error occurs during the search operation.  */
	{
	return iError;
	}


/**
CIdleFinder constructor.
*/
CIdleFinder::CIdleFinder(CContactDatabase &aContactDatabase, const CContactItemFieldDef *aFieldDef, const CContactTextDef* aTextDef, MIdleFindObserver *aObserver)
	:
	CIdle(CActive::EPriorityIdle),
	iContactDatabase(&aContactDatabase),
	iFieldDef(aFieldDef), 
	iTextDef(aTextDef),
	iObserver(aObserver)
	{
	}


/**
CIdleFinder destructor.
*/
CIdleFinder::~CIdleFinder()
	{
	// Only delete the found Contact IDs if ownership has not been taken with
	// a call to TakeContactIds().
	if (iOwnsIds)
		{
		delete iIdsFound;
		}
	delete iFindWords;
	}


void CIdleFinder::DoCancel()
	{
	// Setting to NULL indicates complete.
	iContactDatabase=NULL;
	}


/**
CIdleFinder object factory.  This form of NewL() should be used when performing
an asynchronous find using text and a field definition.

@return CIdleFinder object.
*/
CIdleFinder* CIdleFinder::NewL(CContactDatabase &aContactDatabase, const TDesC& aText, const CContactItemFieldDef *aFieldDef, MIdleFindObserver *aObserver)
	{
	CIdleFinder *finder=new(ELeave) CIdleFinder(aContactDatabase, aFieldDef,NULL,aObserver);
	CleanupStack::PushL(finder);
	finder->ConstructL(&aText,NULL,NULL);
	CleanupStack::Pop(); // finder
	return(finder);
	}


/**
CIdleFinder object factory.  This form of NewL() should be used when performing
an asynchronous find using "find words"/"find words parser" and a text
definition.

@return CIdleFinder object.
*/
CIdleFinder* CIdleFinder::NewL(CContactDatabase &aContactDatabase, const MDesCArray* aFindWords,const CContactTextDef* aTextDef, MIdleFindObserver *aObserver, const TCallBack &aWordParserCallback)
	{
	CIdleFinder *finder=new(ELeave) CIdleFinder(aContactDatabase,NULL,aTextDef,aObserver);
	CleanupStack::PushL(finder);
	finder->ConstructL(NULL,aFindWords,&aWordParserCallback);
	CleanupStack::Pop(); // finder
	return(finder);
	}


/**
Set the CIdle object going.
*/
void CIdleFinder::Start()
	{
	CIdle::Start(TCallBack(CIdleFinder::CallbackL, this));
	}


TInt CIdleFinder::CallbackL(TAny *aSelf)
	{
	return ((CIdleFinder *)aSelf)->doFindL();
	}


TInt CIdleFinder::RunError(TInt aError)
	{
	iError = aError;
	iContactDatabase = NULL;
	if (iObserver)
		{
		iObserver->IdleFindCallback();
		}
	return KErrNone;
	}


/**
CIdle callback method.  Makes an IPC call into the Server to perform a find
iteration.

On return from the find iteration from the Server if "find words" were
specified when initialising the find then the client supplied "find words
parser" is invoked to search the returned Contact IDs.  The search cannot be
performed on the server because it is not possible to provide the client
supplied callback to the server.

@return ETrue if further find iterations are required otherwise EFalse.
*/
TBool CIdleFinder::doFindL()
	{
	iError = KErrNone;
	TBool moreToGo = EFalse;
	iOwnsIds = ETrue;
	
	// Perform a find iteration in the Server.
	TRAP(iError, moreToGo = iContactDatabase->iCntSvr->FindAsyncL(iIdsFound));

	if (iError != KErrNone)
		{
		CContactIdArray* newIdArray = CContactIdArray::NewLC();
		CleanupStack::Pop(newIdArray);
		delete iIdsFound;
		iIdsFound = newIdArray;		
		}
	
	if(iFindWords != NULL)
		{
		// Construct a new Contacts ID array by calling CheckFindL().  This
		// method then calls ScanForMatchL() which calls the client's function
		// pointer (supplied when the find was initialised) for the "find
		// words parser".
		CContactIdArray* newIdArray = CContactIdArray::NewLC();
		for(TInt i=0;i<iIdsFound->Count();++i)
			{
			if(CheckFindL((*iIdsFound)[i]))
				{
				newIdArray->AddL((*iIdsFound)[i]);
				}
			}
		CleanupStack::Pop(newIdArray);

		// Dispose of the existing found Contacts IDs and replace with the fully
		// filtered Contacts IDs.
		delete iIdsFound;
		iIdsFound = newIdArray;
		}
	
	if(!moreToGo)
		{
		// Set to NULL to indicate complete.
		iContactDatabase=NULL;
		}
	
	if (iObserver)
		{
		iObserver->IdleFindCallback();
		}
	
	return moreToGo;
	}


NONSHARABLE_CLASS(TKeyCmpTextLength) : public TKeyArrayFix
	{
public:
	TKeyCmpTextLength();
protected:
	// From TKey.
	virtual TInt Compare(TInt aLeft,TInt aRight) const;
	};


TKeyCmpTextLength::TKeyCmpTextLength()
	:
	// Doesn't matter using ECmpNormal, it's ignored.
	TKeyArrayFix(0,ECmpNormal,0)
	{
	}


/**
Compare the lengths of the words.
*/
TInt TKeyCmpTextLength::Compare(TInt aLeft,TInt aRight) const
	{
	TDesC* left=(*((TDesC**)At(aLeft)));
	TDesC* right=(*((TDesC**)At(aRight)));
	return right->Length()-left->Length();
	}


/**
Initialise and start the asynchronous find.
*/
void CIdleFinder::ConstructL(const TDesC *aText, const MDesCArray* aFindWords, const TCallBack *aWordParserCallback)
	{
	if(aFindWords != NULL) // Find using a CContactTextDef.
		{
		// Construct "find words" from the client supplied aFindWords.
		iFindWords = new (ELeave) CDesCArrayFlat(5);
		for(TInt loop=0;loop<aFindWords->MdcaCount();loop++)
			{
			// Construct iFindWords which contains all the strings in the search
			// surrounded by a *.
			TPtrC findWord(aFindWords->MdcaPoint(loop));
			TKeyCmpTextLength key;
			HBufC* bufPtr=findWord.AllocLC();
			iFindWords->CArrayFixBase::InsertIsqAllowDuplicatesL(&bufPtr,key);
			CleanupStack::Pop(); // bufPtr
			}

		// This is the client supplied "find words parser" callback method.
		iWordParserCallback = *aWordParserCallback;

		// Initialise the asynchronous find in the Server.
		iContactDatabase->iCntSvr->FindAsyncTextDefInitL(*iFindWords,const_cast<CContactTextDef*>(iTextDef));
		}
	else // Find using text and a CContactItemFieldDef.
		{
		// Initialise the asynchronous find in the Server.
		iContactDatabase->iCntSvr->FindAsyncInitL(*aText,const_cast<CContactItemFieldDef*>(iFieldDef));		
		}

	// Start the asynchronous find.
	CActiveScheduler::Add(this);
	Start();
	}


class TFoundMatch
	{
public:
	inline TFoundMatch(TFieldType aFieldType,TInt aPos) : iFieldType(aFieldType),iPos(aPos) {};
	inline TBool operator==(const TFoundMatch &aMatch) const;

private:
	TFieldType iFieldType;
	TInt iPos;
	};


inline TBool TFoundMatch::operator==(const TFoundMatch &aMatch) const
	{
	return(aMatch.iFieldType==iFieldType && aMatch.iPos==iPos);
	}


/**
List of matches.
*/
class CFoundMatches : public CArrayFixFlat<TFoundMatch>
	{
public:
	inline CFoundMatches() : CArrayFixFlat<TFoundMatch>(8) {};
	inline void SetCurrentMatchField(TFieldType aFieldType) {iFieldType=aFieldType;};
	TBool AddMatchL(TInt aPos);

private:
	TFieldType iFieldType;
	};


TBool CFoundMatches::AddMatchL(TInt aPos)
	{
	TFoundMatch newMatch(iFieldType,aPos);
	for(TInt loop=0;loop<Count();loop++)
		{
		if (At(loop)==newMatch)
			{
			return(EFalse);
			}
		}
	AppendL(newMatch);
	return(ETrue);
	}


TBool CIdleFinder::ScanForMatchL(const TDesC &aFieldText,const TDesC &aFindText, CFoundMatches *aFoundMatches) const
	{
	CDesCArray *wordArray=new(ELeave) CDesCArrayFlat(10);
	CleanupStack::PushL(wordArray);

	SFindInTextDefWordParser parser(&aFieldText,wordArray);
	(*iWordParserCallback.iFunction)(&parser);

	TBool matched=EFalse;

	TInt findLen=aFindText.Length();

	for(TInt loop=0;loop<wordArray->Count();loop++)
		{
		TPtrC fieldWord((*wordArray)[loop]);
		if (findLen<=fieldWord.Length() && fieldWord.Left(findLen).CompareF(aFindText)==0)
			{
			if (aFoundMatches->AddMatchL(loop))
				{
				matched=ETrue;
				break;
				}
			}
		}

	CleanupStack::PopAndDestroy(); // wordArray

	return(matched);
	}


/**
Use the client supplied "find words parser" to check for a match of the "find
words" within the text fields in the given Contact Item.

@param aContactID Contact Item to check for match.
*/
TBool CIdleFinder::CheckFindL(TContactItemId aContactId) const
	{
	// If iTextDef is NULL can't check so return EFalse to indicate no match.
	if (!iTextDef)
		{
		return(EFalse);
		}

	// Use ReadMininalContactLC() to read the Contact Item.  We don't need the
	// template and groups data for the find check.
	CContactItem* item = iContactDatabase->ReadMinimalContactLC(aContactId);
	const CContactItemFieldSet& fieldSet = item->CardFields();

	TBool found=ETrue;
	CFoundMatches *foundWords=new(ELeave) CFoundMatches;
	CleanupStack::PushL(foundWords);

	// Iterate through iFindWords.
	for(TInt searchWord=0;found && searchWord<iFindWords->Count();searchWord++)
		{
		const TPtrC findMe((*iFindWords)[searchWord]);
		TBool foundInTextDef=EFalse;
		
		// Iterate through iTextDef field types then fallback field type.
		for(TInt loop=0;!foundInTextDef && loop<=iTextDef->Count();loop++)
			{
			TFieldType fieldType;

			if (loop==iTextDef->Count())
				{
				fieldType=iTextDef->FallbackField();
				}
			else
				{
				fieldType=(*iTextDef)[loop].iFieldType;
				}

			// If field type is KUidContactFieldNone, skip this field.
			if (fieldType==KUidContactFieldNone)
				{
				continue;
				}

			TBuf<KTextFieldMinimalLength> textFieldMin;

			// While that field type is found in the Contact Item field text...
			TInt pos=0;
	        while (pos!=KErrNotFound)
				{
				// Get the field text for this field type.
				pos=fieldSet.FieldText(fieldType,textFieldMin,pos);				
				
				// Scan for match in this field text.
				foundWords->SetCurrentMatchField(fieldType);
				if (ScanForMatchL(textFieldMin,findMe,foundWords))
					{
					foundInTextDef=ETrue;
					break;
					}
				if (pos!=KErrNotFound)
					{
					pos++;
					}
				}
			}

		// If there wasn't a match then set found to EFalse.
		if (!foundInTextDef)
			{
			found=EFalse;
			}
		}

	CleanupStack::PopAndDestroy(2,item); // + foundWords

	return(found);
	}


/**
Reserved (private) virtual function to allow further extension of the
MContactSynchroniser interface without requiring changes to all derived classes.
This can be used to return a pointer to an additional extension class.
*/
EXPORT_C void MContactSynchroniser::MContactSynchroniser_Reserved_1()
	{
	}


EXPORT_C CContactSynchroniser::~CContactSynchroniser()
	{
	REComSession::DestroyedImplementation(iDtor_ID_Key);
	}


/**
Panic the current thread with CNTMODEL as the category
*/
GLDEF_C void Panic(TCntModelPanic aPanic)
	{
	User::Panic(_L("CNTMODEL"),aPanic);
	}


#ifdef __VC32__
extern "C" void __E32Dll(void)
	{
	}
#endif 


/**
 Standard Epoc32 DLL entry point.
*/
#ifndef EKA2
GLDEF_C TInt E32Dll(TInt /*aReason*/)
	{
	return KErrNone;
	}
#endif