This repository has been archived by the owner on Sep 4, 2021. It is now read-only.
/
seasidecache.cpp
3190 lines (2663 loc) · 110 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
ML10N::MLocale mLocale;
82
const QString aggregateRelationshipType = QContactRelationship::Aggregates();
83
84
85
const QString syncTargetLocal = QLatin1String("local");
const QString syncTargetWasLocal = QLatin1String("was_local");
86
87
88
89
90
91
int getContactNameGroupCount()
{
return mLocale.exemplarCharactersIndex().count();
}
92
93
94
95
QStringList getAllContactNameGroups()
{
QStringList groups(mLocale.exemplarCharactersIndex());
groups.append(QString::fromLatin1("#"));
96
97
98
return groups;
}
99
QString managerName()
100
{
101
return QString::fromLatin1("org.nemomobile.contacts.sqlite");
102
103
}
104
105
106
107
108
109
110
111
112
QMap<QString, QString> managerParameters()
{
QMap<QString, QString> rv;
// Report presence changes independently from other contact changes
rv.insert(QString::fromLatin1("mergePresenceChanges"), QString::fromLatin1("false"));
return rv;
}
Q_GLOBAL_STATIC_WITH_ARGS(QContactManager, manager, (managerName(), managerParameters()))
113
114
typedef QList<QContactDetail::DetailType> DetailList;
115
116
template<typename T>
117
QContactDetail::DetailType detailType()
118
119
120
121
{
return T::Type;
}
122
QContactDetail::DetailType detailType(const QContactDetail &detail)
123
124
125
126
{
return detail.type();
}
127
128
129
130
131
132
template<typename T, typename Filter, typename Field>
void setDetailType(Filter &filter, Field field)
{
filter.setDetailType(T::Type, field);
}
133
134
135
136
137
138
139
140
141
142
DetailList detailTypesHint(const QContactFetchHint &hint)
{
return hint.detailTypesHint();
}
void setDetailTypesHint(QContactFetchHint &hint, const DetailList &types)
{
hint.setDetailTypesHint(types);
}
143
144
145
146
147
148
149
150
151
152
153
154
QContactFetchHint basicFetchHint()
{
QContactFetchHint fetchHint;
// We generally have no use for these things:
fetchHint.setOptimizationHints(QContactFetchHint::NoRelationships |
QContactFetchHint::NoActionPreferences |
QContactFetchHint::NoBinaryBlobs);
return fetchHint;
}
155
156
157
158
159
160
161
162
163
164
QContactFetchHint presenceFetchHint()
{
QContactFetchHint fetchHint(basicFetchHint());
setDetailTypesHint(fetchHint, DetailList() << detailType<QContactPresence>()
<< detailType<QContactGlobalPresence>());
return fetchHint;
}
165
DetailList contactsTableDetails()
166
167
{
DetailList types;
168
169
// These details are reported in every query
170
171
172
173
types << detailType<QContactSyncTarget>() <<
detailType<QContactName>() <<
detailType<QContactDisplayLabel>() <<
detailType<QContactFavorite>() <<
174
detailType<QContactTimestamp>() <<
175
176
177
detailType<QContactGender>() <<
detailType<QContactStatusFlags>();
178
179
180
181
182
183
184
185
186
187
return types;
}
QContactFetchHint metadataFetchHint(quint32 fetchTypes = 0)
{
QContactFetchHint fetchHint(basicFetchHint());
// Include all detail types which come from the main contacts table
DetailList types(contactsTableDetails());
188
189
190
// Include nickname, as some contacts have no other name
types << detailType<QContactNickname>();
191
192
193
194
195
196
197
198
199
if (fetchTypes & SeasideCache::FetchAccountUri) {
types << detailType<QContactOnlineAccount>();
}
if (fetchTypes & SeasideCache::FetchPhoneNumber) {
types << detailType<QContactPhoneNumber>();
}
if (fetchTypes & SeasideCache::FetchEmailAddress) {
types << detailType<QContactEmailAddress>();
}
200
201
202
if (fetchTypes & SeasideCache::FetchOrganization) {
types << detailType<QContactOrganization>();
}
203
204
setDetailTypesHint(fetchHint, types);
205
206
207
208
209
210
211
212
return fetchHint;
}
QContactFetchHint onlineFetchHint(quint32 fetchTypes = 0)
{
QContactFetchHint fetchHint(metadataFetchHint(fetchTypes));
// We also need global presence state
213
setDetailTypesHint(fetchHint, detailTypesHint(fetchHint) << detailType<QContactGlobalPresence>());
214
215
216
217
218
219
220
221
return fetchHint;
}
QContactFetchHint favoriteFetchHint(quint32 fetchTypes = 0)
{
QContactFetchHint fetchHint(onlineFetchHint(fetchTypes));
// We also need avatar info
222
setDetailTypesHint(fetchHint, detailTypesHint(fetchHint) << detailType<QContactAvatar>());
223
224
225
return fetchHint;
}
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
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;
}
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
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()
{
272
return QContactStatusFlags::matchFlag(QContactStatusFlags::IsOnline);
273
274
275
276
}
QContactFilter aggregateFilter()
{
277
278
static const QString aggregate(QString::fromLatin1("aggregate"));
279
280
QContactDetailFilter filter;
setDetailType<QContactSyncTarget>(filter, QContactSyncTarget::FieldSyncTarget);
281
filter.setValue(aggregate);
282
283
284
285
return filter;
}
286
287
typedef QPair<QString, QString> StringPair;
288
QList<StringPair> addressPairs(const QContactPhoneNumber &phoneNumber)
289
{
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
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;
306
307
308
309
310
311
312
313
314
}
StringPair addressPair(const QContactEmailAddress &emailAddress)
{
return qMakePair(emailAddress.emailAddress().toLower(), QString());
}
StringPair addressPair(const QContactOnlineAccount &account)
{
315
StringPair address = qMakePair(account.value<QString>(QContactOnlineAccount__FieldAccountPath), account.accountUri().toLower());
316
return !address.first.isEmpty() && !address.second.isEmpty() ? address : StringPair();
317
318
319
320
}
bool validAddressPair(const StringPair &address)
{
321
return (!address.first.isEmpty() || !address.second.isEmpty());
322
323
}
324
325
326
327
328
329
330
331
332
333
334
335
336
337
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);
}
338
QList<quint32> internalIds(const QList<QContactId> &ids)
339
340
341
342
{
QList<quint32> rv;
rv.reserve(ids.count());
343
foreach (const QContactId &id, ids) {
344
345
346
347
348
349
rv.append(SeasideCache::internalId(id));
}
return rv;
}
350
351
352
353
354
355
356
357
358
359
360
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;
}
361
362
const int ExactMatch = 100;
363
364
365
366
367
368
369
370
371
372
373
374
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);
375
376
QString::const_iterator lit, rit;
bool processDtmf = false;
377
int matchLength = 0;
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
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;
}
400
}
401
break;
402
}
403
}
404
405
406
} else {
// Process the DTMF section for a match
processDtmf = true;
407
408
409
410
}
// Have we got a match?
if ((matchLength >= QtContactsSqliteExtensions::DefaultMaximumPhoneNumberCharacters) ||
411
processDtmf) {
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
// 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));
431
432
433
if (bestMatchLength == ExactMatch) {
return ExactMatch;
}
434
435
436
437
438
}
return bestMatchLength;
}
439
440
441
}
SeasideCache *SeasideCache::instancePtr = 0;
442
int SeasideCache::contactNameGroupCount = getContactNameGroupCount();
443
QStringList SeasideCache::allContactNameGroups = getAllContactNameGroups();
444
445
446
447
448
449
QContactManager* SeasideCache::manager()
{
return ::manager();
}
450
451
452
453
454
SeasideCache* SeasideCache::instance()
{
return instancePtr;
}
455
QContactId SeasideCache::apiId(const QContact &contact)
456
457
458
459
{
return contact.id();
}
460
QContactId SeasideCache::apiId(quint32 iid)
461
462
463
464
{
return QtContactsSqliteExtensions::apiContactId(iid);
}
465
bool SeasideCache::validId(const QContactId &id)
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
{
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()
481
: m_syncFilter(FilterNone)
482
483
#ifdef HAS_MLITE
, m_displayLabelOrderConf(QLatin1String("/org/nemomobile/contacts/display_label_order"))
484
, m_sortPropertyConf(QLatin1String("/org/nemomobile/contacts/sort_property"))
485
, m_groupPropertyConf(QLatin1String("/org/nemomobile/contacts/group_property"))
486
487
488
489
#endif
, m_populated(0)
, m_cacheIndex(0)
, m_queryIndex(0)
490
491
, m_fetchProcessedCount(0)
, m_fetchByIdProcessedCount(0)
492
, m_displayLabelOrder(FirstNameFirst)
493
, m_sortProperty(QString::fromLatin1("firstName"))
494
, m_groupProperty(QString::fromLatin1("firstName"))
495
, m_keepPopulated(false)
496
497
, m_populateProgress(Unpopulated)
, m_fetchTypes(0)
498
499
, m_extraFetchTypes(0)
, m_dataTypesFetched(0)
500
501
502
, m_updatesPending(false)
, m_refreshRequired(false)
, m_contactsUpdated(false)
503
, m_displayOff(false)
504
, m_activeResolve(0)
505
506
507
508
509
{
Q_ASSERT(!instancePtr);
instancePtr = this;
m_timer.start();
510
m_fetchPostponed.invalidate();
511
512
513
514
515
516
#ifdef HAS_MLITE
connect(&m_displayLabelOrderConf, SIGNAL(valueChanged()), this, SLOT(displayLabelOrderChanged()));
QVariant displayLabelOrder = m_displayLabelOrderConf.value();
if (displayLabelOrder.isValid())
m_displayLabelOrder = static_cast<DisplayLabelOrder>(displayLabelOrder.toInt());
517
518
519
520
521
connect(&m_sortPropertyConf, SIGNAL(valueChanged()), this, SLOT(sortPropertyChanged()));
QVariant sortPropertyConf = m_sortPropertyConf.value();
if (sortPropertyConf.isValid())
m_sortProperty = sortPropertyConf.toString();
522
523
524
525
526
connect(&m_groupPropertyConf, SIGNAL(valueChanged()), this, SLOT(groupPropertyChanged()));
QVariant groupPropertyConf = m_groupPropertyConf.value();
if (groupPropertyConf.isValid())
m_groupProperty = groupPropertyConf.toString();
527
528
#endif
529
530
531
532
533
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";
}
534
535
QContactManager *mgr(manager());
536
537
538
539
540
// 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);
541
542
connect(mgr, SIGNAL(dataChanged()), this, SLOT(updateContacts()));
connect(mgr, SIGNAL(contactsAdded(QList<QContactId>)),
543
this, SLOT(contactsAdded(QList<QContactId>)));
544
connect(mgr, SIGNAL(contactsChanged(QList<QContactId>)),
545
this, SLOT(contactsChanged(QList<QContactId>)));
546
547
connect(cme, SIGNAL(contactsPresenceChanged(QList<QContactId>)),
this, SLOT(contactsPresenceChanged(QList<QContactId>)));
548
connect(mgr, SIGNAL(contactsRemoved(QList<QContactId>)),
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
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)));
573
574
575
576
577
578
579
580
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);
581
582
setSortOrder(m_sortProperty);
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
}
SeasideCache::~SeasideCache()
{
if (instancePtr == this)
instancePtr = 0;
}
void SeasideCache::checkForExpiry()
{
if (instancePtr->m_users.isEmpty()) {
bool unused = true;
for (int i = 0; i < FilterTypesCount; ++i) {
unused &= instancePtr->m_models[i].isEmpty();
}
if (unused) {
instancePtr->m_expiryTimer.start(30000, instancePtr);
}
}
}
604
void SeasideCache::registerModel(ListModel *model, FilterType type, FetchDataType requiredTypes, FetchDataType extraTypes)
605
606
607
608
609
610
611
612
{
if (!instancePtr) {
new SeasideCache;
} else {
instancePtr->m_expiryTimer.stop();
for (int i = 0; i < FilterTypesCount; ++i)
instancePtr->m_models[i].removeAll(model);
}
613
614
instancePtr->m_models[type].append(model);
615
616
617
618
619
620
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;
}
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
}
void SeasideCache::unregisterModel(ListModel *model)
{
for (int i = 0; i < FilterTypesCount; ++i)
instancePtr->m_models[i].removeAll(model);
checkForExpiry();
}
void SeasideCache::registerUser(QObject *user)
{
if (!instancePtr) {
new SeasideCache;
} else {
instancePtr->m_expiryTimer.stop();
}
instancePtr->m_users.insert(user);
}
void SeasideCache::unregisterUser(QObject *user)
{
instancePtr->m_users.remove(user);
checkForExpiry();
}
void SeasideCache::registerNameGroupChangeListener(SeasideNameGroupChangeListener *listener)
{
if (!instancePtr)
new SeasideCache;
instancePtr->m_nameGroupChangeListeners.append(listener);
}
void SeasideCache::unregisterNameGroupChangeListener(SeasideNameGroupChangeListener *listener)
{
if (!instancePtr)
return;
instancePtr->m_nameGroupChangeListeners.removeAll(listener);
}
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
void SeasideCache::registerChangeListener(ChangeListener *listener)
{
if (!instancePtr)
new SeasideCache;
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;
// We might have outstanding resolve requests for this listener
if (instancePtr->m_activeResolve && (instancePtr->m_activeResolve->listener == listener)) {
instancePtr->m_activeResolve = 0;
}
QList<ResolveData>::iterator it = instancePtr->m_resolveAddresses.begin();
687
while (it != instancePtr->m_resolveAddresses.end()) {
688
689
690
691
692
693
if (it->listener == listener) {
it = instancePtr->m_resolveAddresses.erase(it);
} else {
++it;
}
}
694
695
696
697
698
699
700
701
702
it = instancePtr->m_unknownAddresses.begin();
while (it != instancePtr->m_unknownAddresses.end()) {
if (it->listener == listener) {
it = instancePtr->m_unknownAddresses.erase(it);
} else {
++it;
}
}
703
704
}
705
706
707
708
709
710
void SeasideCache::setNameGrouper(SeasideNameGrouper *grouper)
{
if (!instancePtr)
new SeasideCache;
instancePtr->m_nameGrouper.reset(grouper);
711
allContactNameGroups = instancePtr->m_nameGrouper->allNameGroups();
712
contactNameGroupCount = allContactNameGroups.count();
713
714
if (!allContactNameGroups.contains(QLatin1String("#")))
allContactNameGroups << QLatin1String("#");
715
716
}
717
QString SeasideCache::nameGroup(const CacheItem *cacheItem)
718
719
{
if (!cacheItem)
720
return QString();
721
722
723
724
return cacheItem->nameGroup;
}
725
QString SeasideCache::determineNameGroup(const CacheItem *cacheItem)
726
727
{
if (!cacheItem)
728
return QString();
729
730
if (!instancePtr->m_nameGrouper.isNull()) {
731
QString group = instancePtr->m_nameGrouper->nameGroupForContact(cacheItem->contact, instancePtr->m_groupProperty);
732
if (!group.isNull() && allContactNameGroups.contains(group)) {
733
return group;
734
}
735
736
}
737
const QContactName name(cacheItem->contact.detail<QContactName>());
738
const QString nameProperty(instancePtr->m_groupProperty == QString::fromLatin1("firstName") ? name.firstName() : name.lastName());
739
740
QString group;
741
if (!nameProperty.isEmpty()) {
742
group = mLocale.indexBucket(nameProperty);
743
} else if (!cacheItem->displayLabel.isEmpty()) {
744
group = mLocale.indexBucket(cacheItem->displayLabel);
745
746
}
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
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);
769
}
770
771
772
773
return group;
}
774
QStringList SeasideCache::allNameGroups()
775
{
776
777
if (!instancePtr)
new SeasideCache;
778
779
780
return allContactNameGroups;
}
781
QHash<QString, QSet<quint32> > SeasideCache::nameGroupMembers()
782
783
784
{
if (instancePtr)
return instancePtr->m_contactNameGroups;
785
return QHash<QString, QSet<quint32> >();
786
787
788
789
790
791
792
}
SeasideCache::DisplayLabelOrder SeasideCache::displayLabelOrder()
{
return instancePtr->m_displayLabelOrder;
}
793
794
795
796
797
QString SeasideCache::sortProperty()
{
return instancePtr->m_sortProperty;
}
798
799
800
801
802
QString SeasideCache::groupProperty()
{
return instancePtr->m_groupProperty;
}
803
804
805
806
807
808
int SeasideCache::contactId(const QContact &contact)
{
quint32 internal = internalId(contact);
return static_cast<int>(internal);
}
809
SeasideCache::CacheItem *SeasideCache::itemById(const QContactId &id, bool requireComplete)
810
811
812
813
814
815
816
817
818
819
820
821
822
823
{
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]);
824
825
826
item->iid = iid;
item->contactState = ContactAbsent;
827
828
829
item->contact.setId(id);
}
830
831
if (requireComplete) {
ensureCompletion(item);
832
833
834
835
}
return item;
}
836
SeasideCache::CacheItem *SeasideCache::itemById(int id, bool requireComplete)
837
838
839
840
{
if (id != 0) {
QContactId contactId(apiId(static_cast<quint32>(id)));
if (!contactId.isNull()) {
841
return itemById(contactId, requireComplete);
842
843
844
845
846
847
}
}
return 0;
}
848
SeasideCache::CacheItem *SeasideCache::existingItem(const QContactId &id)
849
{
850
851
return existingItem(internalId(id));
}
852
853
854
SeasideCache::CacheItem *SeasideCache::existingItem(quint32 iid)
{
855
856
857
858
859
860
QHash<quint32, CacheItem>::iterator it = instancePtr->m_people.find(iid);
return it != instancePtr->m_people.end()
? &(*it)
: 0;
}
861
QContact SeasideCache::contactById(const QContactId &id)
862
863
864
865
866
{
quint32 iid = internalId(id);
return instancePtr->m_people.value(iid, CacheItem()).contact;
}
867
void SeasideCache::ensureCompletion(CacheItem *cacheItem)
868
{
869
if (cacheItem->contactState < ContactRequested) {
870
refreshContact(cacheItem);
871
872
873
}
}
874
875
876
877
878
879
880
void SeasideCache::refreshContact(CacheItem *cacheItem)
{
cacheItem->contactState = ContactRequested;
instancePtr->m_changedContacts.append(cacheItem->apiId());
instancePtr->fetchContacts();
}
881
882
SeasideCache::CacheItem *SeasideCache::itemByPhoneNumber(const QString &number, bool requireComplete)
{
883
884
885
const QString normalized(normalizePhoneNumber(number));
if (normalized.isEmpty())
return 0;
886
887
888
889
890
891
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;
892
893
}
}
894
895
896
897
898
899
900
901
902
903
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);
904
905
}
906
SeasideCache::CacheItem *SeasideCache::itemByEmailAddress(const QString &email, bool requireComplete)
907
{
908
909
910
if (email.trimmed().isEmpty())
return 0;
911
912
QHash<QString, quint32>::const_iterator it = instancePtr->m_emailAddressIds.find(email.toLower());
if (it != instancePtr->m_emailAddressIds.end())
913
914
return itemById(*it, requireComplete);
915
916
917
return 0;
}
918
919
SeasideCache::CacheItem *SeasideCache::itemByOnlineAccount(const QString &localUid, const QString &remoteUid, bool requireComplete)
{
920
921
922
if (localUid.trimmed().isEmpty() || remoteUid.trimmed().isEmpty())
return 0;
923
924
925
926
927
928
929
930
931
932
933
934
935
936
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);
return 0;
}
SeasideCache::CacheItem *SeasideCache::resolvePhoneNumber(ResolveListener *listener, const QString &number, bool requireComplete)
{
CacheItem *item = itemByPhoneNumber(number, requireComplete);
if (!item) {
instancePtr->resolveAddress(listener, QString(), number, requireComplete);
937
938
} else if (requireComplete) {
ensureCompletion(item);
939
940
941
942
943
944
945
946
947
948
}
return item;
}
SeasideCache::CacheItem *SeasideCache::resolveEmailAddress(ResolveListener *listener, const QString &address, bool requireComplete)
{
CacheItem *item = itemByEmailAddress(address, requireComplete);
if (!item) {
instancePtr->resolveAddress(listener, address, QString(), requireComplete);
949
950
} else if (requireComplete) {
ensureCompletion(item);
951
952
953
954
955
956
957
958
959
}
return item;
}
SeasideCache::CacheItem *SeasideCache::resolveOnlineAccount(ResolveListener *listener, const QString &localUid, const QString &remoteUid, bool requireComplete)
{
CacheItem *item = itemByOnlineAccount(localUid, remoteUid, requireComplete);
if (!item) {
instancePtr->resolveAddress(listener, localUid, remoteUid, requireComplete);
960
961
} else if (requireComplete) {
ensureCompletion(item);
962
963
964
965
}
return item;
}
966
QContactId SeasideCache::selfContactId()
967
{
968
return manager()->selfContactId();
969
970
971
972
}
void SeasideCache::requestUpdate()
{
973
if (!m_updatesPending) {
974
QCoreApplication::postEvent(this, new QEvent(QEvent::UpdateRequest));
975
976
m_updatesPending = true;
}
977
978
979
980
}
bool SeasideCache::saveContact(const QContact &contact)
{
981
QContactId id = apiId(contact);
982
983
if (validId(id)) {
instancePtr->m_contactsToSave[id] = contact;
984
instancePtr->contactDataChanged(internalId(id));
985
986
987
988
989
990
991
992
993
} else {
instancePtr->m_contactsToCreate.append(contact);
}
instancePtr->requestUpdate();
return true;
}
994
void SeasideCache::contactDataChanged(quint32 iid)
995
{
996
997
998
instancePtr->contactDataChanged(iid, FilterFavorites);
instancePtr->contactDataChanged(iid, FilterOnline);
instancePtr->contactDataChanged(iid, FilterAll);
999
}
1000