This repository has been archived by the owner on Sep 4, 2021. It is now read-only.
/
seasidecache.cpp
3429 lines (2871 loc) · 120 KB
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
/*
* Copyright (C) 2013 Jolla Mobile <andrew.den.exter@jollamobile.com>
*
* You may use this file under the terms of the BSD license as follows:
*
* "Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Nemo Mobile nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
*/
#include "seasidecache.h"
#include "synchronizelists.h"
36
37
38
39
40
#include <qtcontacts-extensions_impl.h>
#include <qcontactstatusflags_impl.h>
#include <contactmanagerengine.h>
#include <private/qcontactmanager_p.h>
41
42
43
#include <QCoreApplication>
#include <QStandardPaths>
44
#include <QDBusConnection>
45
46
47
48
49
50
51
52
53
#include <QDir>
#include <QEvent>
#include <QFile>
#include <QContactAvatar>
#include <QContactDetailFilter>
#include <QContactDisplayLabel>
#include <QContactEmailAddress>
#include <QContactFavorite>
54
#include <QContactGender>
55
56
57
58
59
60
61
#include <QContactName>
#include <QContactNickname>
#include <QContactOnlineAccount>
#include <QContactOrganization>
#include <QContactPhoneNumber>
#include <QContactGlobalPresence>
#include <QContactSyncTarget>
62
#include <QContactTimestamp>
63
64
65
66
67
68
69
70
#include <QVersitContactExporter>
#include <QVersitContactImporter>
#include <QVersitReader>
#include <QVersitWriter>
#include <QtDebug>
71
72
#include <mlocale.h>
73
74
75
#include <mce/dbus-names.h>
#include <mce/mode-names.h>
76
QTVERSIT_USE_NAMESPACE
77
78
namespace {
79
80
81
Q_GLOBAL_STATIC(CacheConfiguration, cacheConfig)
82
83
ML10N::MLocale mLocale;
84
const QString aggregateRelationshipType = QContactRelationship::Aggregates();
85
const QString isNotRelationshipType = QString::fromLatin1("IsNot");
86
87
88
const QString syncTargetLocal = QLatin1String("local");
const QString syncTargetWasLocal = QLatin1String("was_local");
89
90
91
92
93
94
int getContactNameGroupCount()
{
return mLocale.exemplarCharactersIndex().count();
}
95
96
97
98
QStringList getAllContactNameGroups()
{
QStringList groups(mLocale.exemplarCharactersIndex());
groups.append(QString::fromLatin1("#"));
99
100
101
return groups;
}
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
// Find the script that all letters in the name belong to, else yield Unknown
QChar::Script nameScript(const QString &name)
{
QChar::Script script(QChar::Script_Unknown);
if (!name.isEmpty()) {
QString::const_iterator it = name.begin(), end = name.end();
for ( ; it != end; ++it) {
const QChar::Category charCategory((*it).category());
if (charCategory >= QChar::Letter_Uppercase && charCategory <= QChar::Letter_Other) {
const QChar::Script charScript((*it).script());
if (script == QChar::Script_Unknown) {
script = charScript;
} else if (charScript != script) {
return QChar::Script_Unknown;
}
}
}
}
return script;
}
QChar::Script nameScript(const QString &firstName, const QString &lastName)
{
if (firstName.isEmpty()) {
return nameScript(lastName);
} else if (lastName.isEmpty()) {
return nameScript(firstName);
}
QChar::Script firstScript(nameScript(firstName));
if (firstScript != QChar::Script_Unknown) {
QChar::Script lastScript(nameScript(lastName));
if (lastScript == firstScript) {
return lastScript;
}
}
return QChar::Script_Unknown;
}
bool nameScriptImpliesFamilyFirst(const QString &firstName, const QString &lastName)
{
switch (nameScript(firstName, lastName)) {
// These scripts are used by cultures that conform to the family-name-first nameing convention:
case QChar::Script_Han:
case QChar::Script_Lao:
case QChar::Script_Hangul:
case QChar::Script_Khmer:
case QChar::Script_Mongolian:
case QChar::Script_Hiragana:
case QChar::Script_Katakana:
case QChar::Script_Bopomofo:
case QChar::Script_Yi:
return true;
default:
return false;
}
}
163
QString managerName()
164
{
165
return QString::fromLatin1("org.nemomobile.contacts.sqlite");
166
167
}
168
169
170
171
172
QMap<QString, QString> managerParameters()
{
QMap<QString, QString> rv;
// Report presence changes independently from other contact changes
rv.insert(QString::fromLatin1("mergePresenceChanges"), QString::fromLatin1("false"));
173
174
175
if (!qgetenv("LIBCONTACTS_TEST_MODE").isEmpty()) {
rv.insert(QString::fromLatin1("autoTest"), QString::fromLatin1("true"));
}
176
177
178
179
return rv;
}
Q_GLOBAL_STATIC_WITH_ARGS(QContactManager, manager, (managerName(), managerParameters()))
180
181
typedef QList<QContactDetail::DetailType> DetailList;
182
183
template<typename T>
184
QContactDetail::DetailType detailType()
185
186
187
188
{
return T::Type;
}
189
QContactDetail::DetailType detailType(const QContactDetail &detail)
190
191
192
193
{
return detail.type();
}
194
195
196
197
198
199
template<typename T, typename Filter, typename Field>
void setDetailType(Filter &filter, Field field)
{
filter.setDetailType(T::Type, field);
}
200
201
202
203
204
205
206
207
208
209
DetailList detailTypesHint(const QContactFetchHint &hint)
{
return hint.detailTypesHint();
}
void setDetailTypesHint(QContactFetchHint &hint, const DetailList &types)
{
hint.setDetailTypesHint(types);
}
210
211
212
213
214
215
216
217
218
219
220
221
QContactFetchHint basicFetchHint()
{
QContactFetchHint fetchHint;
// We generally have no use for these things:
fetchHint.setOptimizationHints(QContactFetchHint::NoRelationships |
QContactFetchHint::NoActionPreferences |
QContactFetchHint::NoBinaryBlobs);
return fetchHint;
}
222
223
224
225
226
QContactFetchHint presenceFetchHint()
{
QContactFetchHint fetchHint(basicFetchHint());
setDetailTypesHint(fetchHint, DetailList() << detailType<QContactPresence>()
227
228
<< detailType<QContactGlobalPresence>()
<< detailType<QContactOnlineAccount>());
229
230
231
232
return fetchHint;
}
233
DetailList contactsTableDetails()
234
235
{
DetailList types;
236
237
// These details are reported in every query
238
239
240
241
types << detailType<QContactSyncTarget>() <<
detailType<QContactName>() <<
detailType<QContactDisplayLabel>() <<
detailType<QContactFavorite>() <<
242
detailType<QContactTimestamp>() <<
243
244
245
detailType<QContactGender>() <<
detailType<QContactStatusFlags>();
246
247
248
249
250
251
252
253
254
255
return types;
}
QContactFetchHint metadataFetchHint(quint32 fetchTypes = 0)
{
QContactFetchHint fetchHint(basicFetchHint());
// Include all detail types which come from the main contacts table
DetailList types(contactsTableDetails());
256
257
258
// Include nickname, as some contacts have no other name
types << detailType<QContactNickname>();
259
260
261
262
263
264
265
266
267
if (fetchTypes & SeasideCache::FetchAccountUri) {
types << detailType<QContactOnlineAccount>();
}
if (fetchTypes & SeasideCache::FetchPhoneNumber) {
types << detailType<QContactPhoneNumber>();
}
if (fetchTypes & SeasideCache::FetchEmailAddress) {
types << detailType<QContactEmailAddress>();
}
268
269
270
if (fetchTypes & SeasideCache::FetchOrganization) {
types << detailType<QContactOrganization>();
}
271
272
setDetailTypesHint(fetchHint, types);
273
274
275
276
277
278
279
280
return fetchHint;
}
QContactFetchHint onlineFetchHint(quint32 fetchTypes = 0)
{
QContactFetchHint fetchHint(metadataFetchHint(fetchTypes));
// We also need global presence state
281
setDetailTypesHint(fetchHint, detailTypesHint(fetchHint) << detailType<QContactGlobalPresence>());
282
283
284
285
286
287
288
289
return fetchHint;
}
QContactFetchHint favoriteFetchHint(quint32 fetchTypes = 0)
{
QContactFetchHint fetchHint(onlineFetchHint(fetchTypes));
// We also need avatar info
290
setDetailTypesHint(fetchHint, detailTypesHint(fetchHint) << detailType<QContactAvatar>());
291
292
293
return fetchHint;
}
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
QContactFetchHint extendedMetadataFetchHint(quint32 fetchTypes)
{
QContactFetchHint fetchHint(basicFetchHint());
DetailList types;
// Only query for the specific types we need
if (fetchTypes & SeasideCache::FetchAccountUri) {
types << detailType<QContactOnlineAccount>();
}
if (fetchTypes & SeasideCache::FetchPhoneNumber) {
types << detailType<QContactPhoneNumber>();
}
if (fetchTypes & SeasideCache::FetchEmailAddress) {
types << detailType<QContactEmailAddress>();
}
if (fetchTypes & SeasideCache::FetchOrganization) {
types << detailType<QContactOrganization>();
}
setDetailTypesHint(fetchHint, types);
return fetchHint;
}
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
QContactFilter allFilter()
{
return QContactFilter();
}
QContactFilter favoriteFilter()
{
return QContactFavorite::match();
}
QContactFilter nonfavoriteFilter()
{
QContactDetailFilter filter;
setDetailType<QContactFavorite>(filter, QContactFavorite::FieldFavorite);
filter.setMatchFlags(QContactFilter::MatchExactly);
filter.setValue(false);
return filter;
}
QContactFilter onlineFilter()
{
340
return QContactStatusFlags::matchFlag(QContactStatusFlags::IsOnline);
341
342
343
344
}
QContactFilter aggregateFilter()
{
345
346
static const QString aggregate(QString::fromLatin1("aggregate"));
347
348
QContactDetailFilter filter;
setDetailType<QContactSyncTarget>(filter, QContactSyncTarget::FieldSyncTarget);
349
filter.setValue(aggregate);
350
351
352
353
return filter;
}
354
355
typedef QPair<QString, QString> StringPair;
356
QList<StringPair> addressPairs(const QContactPhoneNumber &phoneNumber)
357
{
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
QList<StringPair> rv;
const QString normalized(SeasideCache::normalizePhoneNumber(phoneNumber.number()));
if (!normalized.isEmpty()) {
const QChar plus(QChar::fromLatin1('+'));
if (normalized.startsWith(plus)) {
// Also index the complete form of this number
rv.append(qMakePair(QString(), normalized));
}
// Always index the minimized form of the number
const QString minimized(SeasideCache::minimizePhoneNumber(normalized));
rv.append(qMakePair(QString(), minimized));
}
return rv;
374
375
376
377
378
379
380
381
382
}
StringPair addressPair(const QContactEmailAddress &emailAddress)
{
return qMakePair(emailAddress.emailAddress().toLower(), QString());
}
StringPair addressPair(const QContactOnlineAccount &account)
{
383
StringPair address = qMakePair(account.value<QString>(QContactOnlineAccount__FieldAccountPath), account.accountUri().toLower());
384
return !address.first.isEmpty() && !address.second.isEmpty() ? address : StringPair();
385
386
387
388
}
bool validAddressPair(const StringPair &address)
{
389
return (!address.first.isEmpty() || !address.second.isEmpty());
390
391
}
392
393
394
395
396
397
398
399
400
401
402
403
404
405
bool ignoreContactForNameGroups(const QContact &contact)
{
static const QString aggregate(QString::fromLatin1("aggregate"));
// Don't include the self contact in name groups
if (SeasideCache::apiId(contact) == SeasideCache::selfContactId()) {
return true;
}
// Also ignore non-aggregate contacts
QContactSyncTarget syncTarget = contact.detail<QContactSyncTarget>();
return (syncTarget.syncTarget() != aggregate);
}
406
QList<quint32> internalIds(const QList<QContactId> &ids)
407
408
409
410
{
QList<quint32> rv;
rv.reserve(ids.count());
411
foreach (const QContactId &id, ids) {
412
413
414
415
416
417
rv.append(SeasideCache::internalId(id));
}
return rv;
}
418
419
420
421
422
423
424
425
426
427
428
QString::const_iterator firstDtmfChar(QString::const_iterator it, QString::const_iterator end)
{
static const QString dtmfChars(QString::fromLatin1("pPwWxX#*"));
for ( ; it != end; ++it) {
if (dtmfChars.contains(*it))
return it;
}
return end;
}
429
430
const int ExactMatch = 100;
431
432
433
434
435
436
437
438
439
440
441
442
int matchLength(const QString &lhs, const QString &rhs)
{
if (lhs.isEmpty() || rhs.isEmpty())
return 0;
QString::const_iterator lbegin = lhs.constBegin(), lend = lhs.constEnd();
QString::const_iterator rbegin = rhs.constBegin(), rend = rhs.constEnd();
// Do these numbers contain DTMF elements?
QString::const_iterator ldtmf = firstDtmfChar(lbegin, lend);
QString::const_iterator rdtmf = firstDtmfChar(rbegin, rend);
443
444
QString::const_iterator lit, rit;
bool processDtmf = false;
445
int matchLength = 0;
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
if ((ldtmf != lbegin) && (rdtmf != rbegin)) {
// Start match length calculation at the last non-DTMF digit
lit = ldtmf - 1;
rit = rdtmf - 1;
while (*lit == *rit) {
++matchLength;
--lit;
--rit;
if ((lit == lbegin) || (rit == rbegin)) {
if (*lit == *rit) {
++matchLength;
if ((lit == lbegin) && (rit == rbegin)) {
// We have a complete, exact match - this must be the best match
return ExactMatch;
} else {
// We matched all of one number - continue looking in the DTMF part
processDtmf = true;
}
468
}
469
break;
470
}
471
}
472
473
474
} else {
// Process the DTMF section for a match
processDtmf = true;
475
476
477
478
}
// Have we got a match?
if ((matchLength >= QtContactsSqliteExtensions::DefaultMaximumPhoneNumberCharacters) ||
479
processDtmf) {
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
// See if the match continues into the DTMF area
QString::const_iterator lit = ldtmf;
QString::const_iterator rit = rdtmf;
for ( ; (lit != lend) && (rit != rend); ++lit, ++rit) {
if ((*lit).toLower() != (*rit).toLower())
break;
++matchLength;
}
}
return matchLength;
}
int bestPhoneNumberMatchLength(const QContact &contact, const QString &match)
{
int bestMatchLength = 0;
foreach (const QContactPhoneNumber& phone, contact.details<QContactPhoneNumber>()) {
bestMatchLength = qMax(bestMatchLength, matchLength(SeasideCache::normalizePhoneNumber(phone.number()), match));
499
500
501
if (bestMatchLength == ExactMatch) {
return ExactMatch;
}
502
503
504
505
506
}
return bestMatchLength;
}
507
508
509
}
SeasideCache *SeasideCache::instancePtr = 0;
510
int SeasideCache::contactNameGroupCount = getContactNameGroupCount();
511
QStringList SeasideCache::allContactNameGroups = getAllContactNameGroups();
512
513
QTranslator *SeasideCache::engEnTranslator = 0;
QTranslator *SeasideCache::translator = 0;
514
515
516
517
518
519
QContactManager* SeasideCache::manager()
{
return ::manager();
}
520
521
SeasideCache* SeasideCache::instance()
{
522
523
524
if (!instancePtr) {
instancePtr = new SeasideCache;
}
525
526
527
return instancePtr;
}
528
QContactId SeasideCache::apiId(const QContact &contact)
529
530
531
532
{
return contact.id();
}
533
QContactId SeasideCache::apiId(quint32 iid)
534
535
536
537
{
return QtContactsSqliteExtensions::apiContactId(iid);
}
538
bool SeasideCache::validId(const QContactId &id)
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
{
return !id.isNull();
}
quint32 SeasideCache::internalId(const QContact &contact)
{
return internalId(contact.id());
}
quint32 SeasideCache::internalId(const QContactId &id)
{
return QtContactsSqliteExtensions::internalContactId(id);
}
SeasideCache::SeasideCache()
554
: m_syncFilter(FilterNone)
555
556
557
, m_populated(0)
, m_cacheIndex(0)
, m_queryIndex(0)
558
559
, m_fetchProcessedCount(0)
, m_fetchByIdProcessedCount(0)
560
, m_keepPopulated(false)
561
, m_populateProgress(Unpopulated)
562
, m_populating(0)
563
, m_fetchTypes(0)
564
565
, m_extraFetchTypes(0)
, m_dataTypesFetched(0)
566
567
568
, m_updatesPending(false)
, m_refreshRequired(false)
, m_contactsUpdated(false)
569
, m_displayOff(false)
570
571
{
m_timer.start();
572
m_fetchPostponed.invalidate();
573
574
575
576
577
578
CacheConfiguration *config(cacheConfig());
connect(config, SIGNAL(displayLabelOrderChanged(CacheConfiguration::DisplayLabelOrder)),
this, SLOT(displayLabelOrderChanged(CacheConfiguration::DisplayLabelOrder)));
connect(config, SIGNAL(sortPropertyChanged(QString)), this, SLOT(sortPropertyChanged(QString)));
connect(config, SIGNAL(groupPropertyChanged(QString)), this, SLOT(groupPropertyChanged(QString)));
579
580
581
582
583
584
585
586
// Is this a GUI application? If so, we want to defer some processing when the display is off
if (qApp && qApp->property("applicationDisplayName").isValid()) {
// Only QGuiApplication has this property
if (!QDBusConnection::systemBus().connect(MCE_SERVICE, MCE_SIGNAL_PATH, MCE_SIGNAL_IF,
MCE_DISPLAY_SIG, this, SLOT(displayStatusChanged(QString)))) {
qWarning() << "Unable to connect to MCE displayStatusChanged signal";
}
587
588
}
589
590
QContactManager *mgr(manager());
591
592
593
594
595
// The contactsPresenceChanged signal is not exported by QContactManager, so we
// need to find it from the manager's engine object
typedef QtContactsSqliteExtensions::ContactManagerEngine EngineType;
EngineType *cme = dynamic_cast<EngineType *>(QContactManagerData::managerData(mgr)->m_engine);
596
597
connect(mgr, SIGNAL(dataChanged()), this, SLOT(updateContacts()));
connect(mgr, SIGNAL(contactsAdded(QList<QContactId>)),
598
this, SLOT(contactsAdded(QList<QContactId>)));
599
connect(mgr, SIGNAL(contactsChanged(QList<QContactId>)),
600
this, SLOT(contactsChanged(QList<QContactId>)));
601
602
connect(cme, SIGNAL(contactsPresenceChanged(QList<QContactId>)),
this, SLOT(contactsPresenceChanged(QList<QContactId>)));
603
connect(mgr, SIGNAL(contactsRemoved(QList<QContactId>)),
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
this, SLOT(contactsRemoved(QList<QContactId>)));
connect(&m_fetchRequest, SIGNAL(resultsAvailable()), this, SLOT(contactsAvailable()));
connect(&m_fetchByIdRequest, SIGNAL(resultsAvailable()), this, SLOT(contactsAvailable()));
connect(&m_contactIdRequest, SIGNAL(resultsAvailable()), this, SLOT(contactIdsAvailable()));
connect(&m_relationshipsFetchRequest, SIGNAL(resultsAvailable()), this, SLOT(relationshipsAvailable()));
connect(&m_fetchRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)),
this, SLOT(requestStateChanged(QContactAbstractRequest::State)));
connect(&m_fetchByIdRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)),
this, SLOT(requestStateChanged(QContactAbstractRequest::State)));
connect(&m_contactIdRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)),
this, SLOT(requestStateChanged(QContactAbstractRequest::State)));
connect(&m_relationshipsFetchRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)),
this, SLOT(requestStateChanged(QContactAbstractRequest::State)));
connect(&m_removeRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)),
this, SLOT(requestStateChanged(QContactAbstractRequest::State)));
connect(&m_saveRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)),
this, SLOT(requestStateChanged(QContactAbstractRequest::State)));
connect(&m_relationshipSaveRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)),
this, SLOT(requestStateChanged(QContactAbstractRequest::State)));
connect(&m_relationshipRemoveRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)),
this, SLOT(requestStateChanged(QContactAbstractRequest::State)));
628
629
630
631
632
633
634
635
m_fetchRequest.setManager(mgr);
m_fetchByIdRequest.setManager(mgr);
m_contactIdRequest.setManager(mgr);
m_relationshipsFetchRequest.setManager(mgr);
m_removeRequest.setManager(mgr);
m_saveRequest.setManager(mgr);
m_relationshipSaveRequest.setManager(mgr);
m_relationshipRemoveRequest.setManager(mgr);
636
637
setSortOrder(sortProperty());
638
639
640
641
642
643
644
645
646
647
}
SeasideCache::~SeasideCache()
{
if (instancePtr == this)
instancePtr = 0;
}
void SeasideCache::checkForExpiry()
{
648
if (instancePtr->m_users.isEmpty() && !QCoreApplication::closingDown()) {
649
650
651
652
653
654
655
656
657
658
bool unused = true;
for (int i = 0; i < FilterTypesCount; ++i) {
unused &= instancePtr->m_models[i].isEmpty();
}
if (unused) {
instancePtr->m_expiryTimer.start(30000, instancePtr);
}
}
}
659
void SeasideCache::registerModel(ListModel *model, FilterType type, FetchDataType requiredTypes, FetchDataType extraTypes)
660
{
661
662
663
664
665
666
// Ensure the cache has been instantiated
instance();
instancePtr->m_expiryTimer.stop();
for (int i = 0; i < FilterTypesCount; ++i)
instancePtr->m_models[i].removeAll(model);
667
668
instancePtr->m_models[type].append(model);
669
670
671
672
673
674
instancePtr->keepPopulated(requiredTypes & SeasideCache::FetchTypesMask, extraTypes & SeasideCache::FetchTypesMask);
if (requiredTypes & SeasideCache::FetchTypesMask) {
// If we have filtered models, they will need a contact ID refresh after the cache is populated
instancePtr->m_refreshRequired = true;
}
675
676
677
678
679
680
681
682
683
684
685
686
}
void SeasideCache::unregisterModel(ListModel *model)
{
for (int i = 0; i < FilterTypesCount; ++i)
instancePtr->m_models[i].removeAll(model);
checkForExpiry();
}
void SeasideCache::registerUser(QObject *user)
{
687
688
689
690
// Ensure the cache has been instantiated
instance();
instancePtr->m_expiryTimer.stop();
691
692
693
694
695
696
697
698
699
700
701
702
instancePtr->m_users.insert(user);
}
void SeasideCache::unregisterUser(QObject *user)
{
instancePtr->m_users.remove(user);
checkForExpiry();
}
void SeasideCache::registerNameGroupChangeListener(SeasideNameGroupChangeListener *listener)
{
703
704
705
// Ensure the cache has been instantiated
instance();
706
707
708
709
710
711
712
713
714
715
instancePtr->m_nameGroupChangeListeners.append(listener);
}
void SeasideCache::unregisterNameGroupChangeListener(SeasideNameGroupChangeListener *listener)
{
if (!instancePtr)
return;
instancePtr->m_nameGroupChangeListeners.removeAll(listener);
}
716
717
void SeasideCache::registerChangeListener(ChangeListener *listener)
{
718
719
720
// Ensure the cache has been instantiated
instance();
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
instancePtr->m_changeListeners.append(listener);
}
void SeasideCache::unregisterChangeListener(ChangeListener *listener)
{
if (!instancePtr)
return;
instancePtr->m_changeListeners.removeAll(listener);
}
void SeasideCache::unregisterResolveListener(ResolveListener *listener)
{
if (!instancePtr)
return;
736
QHash<QContactFetchRequest *, ResolveData>::iterator it = instancePtr->m_resolveAddresses.begin();
737
while (it != instancePtr->m_resolveAddresses.end()) {
738
739
740
if (it.value().listener == listener) {
it.key()->cancel();
delete it.key();
741
742
743
744
745
it = instancePtr->m_resolveAddresses.erase(it);
} else {
++it;
}
}
746
747
748
749
750
QList<ResolveData>::iterator it2 = instancePtr->m_unknownAddresses.begin();
while (it2 != instancePtr->m_unknownAddresses.end()) {
if (it2->listener == listener) {
it2 = instancePtr->m_unknownAddresses.erase(it2);
751
} else {
752
++it2;
753
754
}
}
755
756
757
758
759
760
761
762
763
QList<ResolveData>::iterator it3 = instancePtr->m_unknownResolveAddresses.begin();
while (it3 != instancePtr->m_unknownResolveAddresses.end()) {
if (it3->listener == listener) {
it3 = instancePtr->m_unknownResolveAddresses.erase(it3);
} else {
++it3;
}
}
764
765
766
767
768
769
770
771
772
QSet<ResolveData>::iterator it4 = instancePtr->m_pendingResolve.begin();
while (it4 != instancePtr->m_pendingResolve.end()) {
if (it4->listener == listener) {
it4 = instancePtr->m_pendingResolve.erase(it4);
} else {
++it4;
}
}
773
774
}
775
776
void SeasideCache::setNameGrouper(SeasideNameGrouper *grouper)
{
777
778
779
// Ensure the cache has been instantiated
instance();
780
781
instancePtr->m_nameGrouper.reset(grouper);
782
allContactNameGroups = instancePtr->m_nameGrouper->allNameGroups();
783
contactNameGroupCount = allContactNameGroups.count();
784
785
if (!allContactNameGroups.contains(QLatin1String("#")))
allContactNameGroups << QLatin1String("#");
786
787
}
788
QString SeasideCache::nameGroup(const CacheItem *cacheItem)
789
790
{
if (!cacheItem)
791
return QString();
792
793
794
795
return cacheItem->nameGroup;
}
796
QString SeasideCache::determineNameGroup(const CacheItem *cacheItem)
797
798
{
if (!cacheItem)
799
return QString();
800
801
if (!instancePtr->m_nameGrouper.isNull()) {
802
QString group = instancePtr->m_nameGrouper->nameGroupForContact(cacheItem->contact, groupProperty());
803
if (!group.isNull() && allContactNameGroups.contains(group)) {
804
return group;
805
}
806
807
}
808
const QContactName name(cacheItem->contact.detail<QContactName>());
809
const QString nameProperty(groupProperty() == QString::fromLatin1("firstName") ? name.firstName() : name.lastName());
810
811
QString group;
812
if (!nameProperty.isEmpty()) {
813
group = mLocale.indexBucket(nameProperty);
814
} else if (!cacheItem->displayLabel.isEmpty()) {
815
group = mLocale.indexBucket(cacheItem->displayLabel);
816
817
}
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
if (!group.isEmpty()) {
if (!allContactNameGroups.contains(group)) {
// If this group is some kind of digit, group under '#'
if (mLocale.toLatinNumbers(group.mid(0, 1)).at(0).isDigit()) {
group = QString();
}
}
}
if (group.isEmpty()) {
group = QString::fromLatin1("#");
} else if (!allContactNameGroups.contains(group)) {
// Insert before the '#' group, which is always last, and after the pre-defined groups
const int maxIndex = allContactNameGroups.count() - 1;
int index = qMin(contactNameGroupCount, maxIndex);
for ( ; index < maxIndex; ++index) {
if (group < allContactNameGroups.at(index)) {
break;
}
}
allContactNameGroups.insert(index, group);
840
}
841
842
843
844
return group;
}
845
QStringList SeasideCache::allNameGroups()
846
{
847
848
849
// Ensure the cache has been instantiated
instance();
850
851
852
return allContactNameGroups;
}
853
QHash<QString, QSet<quint32> > SeasideCache::nameGroupMembers()
854
855
856
{
if (instancePtr)
return instancePtr->m_contactNameGroups;
857
return QHash<QString, QSet<quint32> >();
858
859
860
861
}
SeasideCache::DisplayLabelOrder SeasideCache::displayLabelOrder()
{
862
return static_cast<DisplayLabelOrder>(cacheConfig()->displayLabelOrder());
863
864
}
865
866
QString SeasideCache::sortProperty()
{
867
return cacheConfig()->sortProperty();
868
869
}
870
871
QString SeasideCache::groupProperty()
{
872
return cacheConfig()->groupProperty();
873
874
}
875
876
877
878
879
880
int SeasideCache::contactId(const QContact &contact)
{
quint32 internal = internalId(contact);
return static_cast<int>(internal);
}
881
SeasideCache::CacheItem *SeasideCache::itemById(const QContactId &id, bool requireComplete)
882
883
884
885
886
887
888
889
890
891
892
893
894
895
{
if (!validId(id))
return 0;
quint32 iid = internalId(id);
CacheItem *item = 0;
QHash<quint32, CacheItem>::iterator it = instancePtr->m_people.find(iid);
if (it != instancePtr->m_people.end()) {
item = &(*it);
} else {
// Insert a new item into the cache if the one doesn't exist.
item = &(instancePtr->m_people[iid]);
896
897
898
item->iid = iid;
item->contactState = ContactAbsent;
899
900
901
item->contact.setId(id);
}
902
903
if (requireComplete) {
ensureCompletion(item);
904
905
906
907
}
return item;
}
908
SeasideCache::CacheItem *SeasideCache::itemById(int id, bool requireComplete)
909
910
911
912
{
if (id != 0) {
QContactId contactId(apiId(static_cast<quint32>(id)));
if (!contactId.isNull()) {
913
return itemById(contactId, requireComplete);
914
915
916
917
918
919
}
}
return 0;
}
920
SeasideCache::CacheItem *SeasideCache::existingItem(const QContactId &id)
921
{
922
923
return existingItem(internalId(id));
}
924
925
926
SeasideCache::CacheItem *SeasideCache::existingItem(quint32 iid)
{
927
928
929
930
931
932
QHash<quint32, CacheItem>::iterator it = instancePtr->m_people.find(iid);
return it != instancePtr->m_people.end()
? &(*it)
: 0;
}
933
QContact SeasideCache::contactById(const QContactId &id)
934
935
936
937
938
{
quint32 iid = internalId(id);
return instancePtr->m_people.value(iid, CacheItem()).contact;
}
939
void SeasideCache::ensureCompletion(CacheItem *cacheItem)
940
{
941
if (cacheItem->contactState < ContactRequested) {
942
refreshContact(cacheItem);
943
944
945
}
}
946
947
948
949
950
951
952
void SeasideCache::refreshContact(CacheItem *cacheItem)
{
cacheItem->contactState = ContactRequested;
instancePtr->m_changedContacts.append(cacheItem->apiId());
instancePtr->fetchContacts();
}
953
954
SeasideCache::CacheItem *SeasideCache::itemByPhoneNumber(const QString &number, bool requireComplete)
{
955
956
957
const QString normalized(normalizePhoneNumber(number));
if (normalized.isEmpty())
return 0;
958
959
960
961
962
963
const QChar plus(QChar::fromLatin1('+'));
if (normalized.startsWith(plus)) {
// See if there is a match for the complete form of this number
if (CacheItem *item = instancePtr->itemMatchingPhoneNumber(normalized, normalized, requireComplete)) {
return item;
964
965
}
}
966
967
968
969
970
971
972
973
974
975
const QString minimized(minimizePhoneNumber(normalized));
if (((instancePtr->m_fetchTypes & SeasideCache::FetchPhoneNumber) == 0) &&
!instancePtr->m_resolvedPhoneNumbers.contains(minimized)) {
// We haven't previously queried this number, so there may be more matches than any
// that we already have cached; return 0 to force a query
return 0;
}
return instancePtr->itemMatchingPhoneNumber(minimized, normalized, requireComplete);
976
977
}
978
SeasideCache::CacheItem *SeasideCache::itemByEmailAddress(const QString &email, bool requireComplete)
979
{
980
981
982
if (email.trimmed().isEmpty())
return 0;
983
984
QHash<QString, quint32>::const_iterator it = instancePtr->m_emailAddressIds.find(email.toLower());
if (it != instancePtr->m_emailAddressIds.end())
985
986
return itemById(*it, requireComplete);
987
988
989
return 0;
}
990
991
SeasideCache::CacheItem *SeasideCache::itemByOnlineAccount(const QString &localUid, const QString &remoteUid, bool requireComplete)
{
992
993
994
if (localUid.trimmed().isEmpty() || remoteUid.trimmed().isEmpty())
return 0;
995
996
997
998
999
1000
QPair<QString, QString> address = qMakePair(localUid, remoteUid.toLower());
QHash<QPair<QString, QString>, quint32>::const_iterator it = instancePtr->m_onlineAccountIds.find(address);
if (it != instancePtr->m_onlineAccountIds.end())
return itemById(*it, requireComplete);