seasidecache.cpp 121 KB
Newer Older
mvogt's avatar
mvogt committed
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
#include <qtcontacts-extensions.h>
37 38 39 40 41
#include <qtcontacts-extensions_impl.h>
#include <qcontactstatusflags_impl.h>
#include <contactmanagerengine.h>

#include <private/qcontactmanager_p.h>
42

mvogt's avatar
mvogt committed
43 44
#include <QCoreApplication>
#include <QStandardPaths>
45
#include <QDBusConnection>
mvogt's avatar
mvogt committed
46 47 48 49 50 51 52 53 54
#include <QDir>
#include <QEvent>
#include <QFile>

#include <QContactAvatar>
#include <QContactDetailFilter>
#include <QContactDisplayLabel>
#include <QContactEmailAddress>
#include <QContactFavorite>
55
#include <QContactGender>
mvogt's avatar
mvogt committed
56 57 58 59 60 61 62
#include <QContactName>
#include <QContactNickname>
#include <QContactOnlineAccount>
#include <QContactOrganization>
#include <QContactPhoneNumber>
#include <QContactGlobalPresence>
#include <QContactSyncTarget>
63
#include <QContactTimestamp>
mvogt's avatar
mvogt committed
64 65 66 67 68 69 70 71

#include <QVersitContactExporter>
#include <QVersitContactImporter>
#include <QVersitReader>
#include <QVersitWriter>

#include <QtDebug>

72 73
#include <mlocale.h>

74 75 76
#include <mce/dbus-names.h>
#include <mce/mode-names.h>

77
QTVERSIT_USE_NAMESPACE
mvogt's avatar
mvogt committed
78

79
namespace {
mvogt's avatar
mvogt committed
80

81 82
Q_GLOBAL_STATIC(CacheConfiguration, cacheConfig)

83 84
ML10N::MLocale mLocale;

mvogt's avatar
mvogt committed
85
const QString aggregateRelationshipType = QContactRelationship::Aggregates();
86
const QString isNotRelationshipType = QString::fromLatin1("IsNot");
mvogt's avatar
mvogt committed
87

88 89
const QString syncTargetLocal = QLatin1String("local");
const QString syncTargetWasLocal = QLatin1String("was_local");
mvogt's avatar
mvogt committed
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
// 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;
    }
}

152
QString managerName()
mvogt's avatar
mvogt committed
153
{
154
    return QString::fromLatin1("org.nemomobile.contacts.sqlite");
mvogt's avatar
mvogt committed
155 156
}

157 158 159 160 161
QMap<QString, QString> managerParameters()
{
    QMap<QString, QString> rv;
    // Report presence changes independently from other contact changes
    rv.insert(QString::fromLatin1("mergePresenceChanges"), QString::fromLatin1("false"));
162 163 164
    if (!qgetenv("LIBCONTACTS_TEST_MODE").isEmpty()) {
        rv.insert(QString::fromLatin1("autoTest"), QString::fromLatin1("true"));
    }
165 166 167 168
    return rv;
}

Q_GLOBAL_STATIC_WITH_ARGS(QContactManager, manager, (managerName(), managerParameters()))
169

170
typedef QList<QContactDetail::DetailType> DetailList;
171 172

template<typename T>
173
QContactDetail::DetailType detailType()
174 175 176 177
{
    return T::Type;
}

178
QContactDetail::DetailType detailType(const QContactDetail &detail)
179 180 181 182
{
    return detail.type();
}

mvogt's avatar
mvogt committed
183 184 185 186 187 188
template<typename T, typename Filter, typename Field>
void setDetailType(Filter &filter, Field field)
{
    filter.setDetailType(T::Type, field);
}

mvogt's avatar
mvogt committed
189 190 191 192 193 194 195 196 197 198
DetailList detailTypesHint(const QContactFetchHint &hint)
{
    return hint.detailTypesHint();
}

void setDetailTypesHint(QContactFetchHint &hint, const DetailList &types)
{
    hint.setDetailTypesHint(types);
}

199 200 201 202 203 204 205 206 207 208 209 210
QContactFetchHint basicFetchHint()
{
    QContactFetchHint fetchHint;

    // We generally have no use for these things:
    fetchHint.setOptimizationHints(QContactFetchHint::NoRelationships |
                                   QContactFetchHint::NoActionPreferences |
                                   QContactFetchHint::NoBinaryBlobs);

    return fetchHint;
}

211 212 213 214 215
QContactFetchHint presenceFetchHint()
{
    QContactFetchHint fetchHint(basicFetchHint());

    setDetailTypesHint(fetchHint, DetailList() << detailType<QContactPresence>()
216 217
                                               << detailType<QContactGlobalPresence>()
                                               << detailType<QContactOnlineAccount>());
218 219 220 221

    return fetchHint;
}

222
DetailList contactsTableDetails()
223 224
{
    DetailList types;
225 226

    // These details are reported in every query
227 228 229 230
    types << detailType<QContactSyncTarget>() <<
             detailType<QContactName>() <<
             detailType<QContactDisplayLabel>() <<
             detailType<QContactFavorite>() <<
231
             detailType<QContactTimestamp>() <<
232 233 234
             detailType<QContactGender>() <<
             detailType<QContactStatusFlags>();

235 236 237 238 239 240 241 242 243 244
    return types;
}

QContactFetchHint metadataFetchHint(quint32 fetchTypes = 0)
{
    QContactFetchHint fetchHint(basicFetchHint());

    // Include all detail types which come from the main contacts table
    DetailList types(contactsTableDetails());

245 246 247
    // Include nickname, as some contacts have no other name
    types << detailType<QContactNickname>();

248 249 250 251 252 253 254 255 256
    if (fetchTypes & SeasideCache::FetchAccountUri) {
        types << detailType<QContactOnlineAccount>();
    }
    if (fetchTypes & SeasideCache::FetchPhoneNumber) {
        types << detailType<QContactPhoneNumber>();
    }
    if (fetchTypes & SeasideCache::FetchEmailAddress) {
        types << detailType<QContactEmailAddress>();
    }
257 258 259
    if (fetchTypes & SeasideCache::FetchOrganization) {
        types << detailType<QContactOrganization>();
    }
260

mvogt's avatar
mvogt committed
261
    setDetailTypesHint(fetchHint, types);
262 263 264 265 266 267 268 269
    return fetchHint;
}

QContactFetchHint onlineFetchHint(quint32 fetchTypes = 0)
{
    QContactFetchHint fetchHint(metadataFetchHint(fetchTypes));

    // We also need global presence state
mvogt's avatar
mvogt committed
270
    setDetailTypesHint(fetchHint, detailTypesHint(fetchHint) << detailType<QContactGlobalPresence>());
271 272 273 274 275 276 277 278
    return fetchHint;
}

QContactFetchHint favoriteFetchHint(quint32 fetchTypes = 0)
{
    QContactFetchHint fetchHint(onlineFetchHint(fetchTypes));

    // We also need avatar info
mvogt's avatar
mvogt committed
279
    setDetailTypesHint(fetchHint, detailTypesHint(fetchHint) << detailType<QContactAvatar>());
280 281 282
    return fetchHint;
}

283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
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;
}

307 308 309 310 311 312 313 314 315 316 317 318
QContactFilter allFilter()
{
    return QContactFilter();
}

QContactFilter favoriteFilter()
{
    return QContactFavorite::match();
}

QContactFilter onlineFilter()
{
319
    return QContactStatusFlags::matchFlag(QContactStatusFlags::IsOnline);
320 321 322 323
}

QContactFilter aggregateFilter()
{
324 325
    static const QString aggregate(QString::fromLatin1("aggregate"));

326 327
    QContactDetailFilter filter;
    setDetailType<QContactSyncTarget>(filter, QContactSyncTarget::FieldSyncTarget);
328
    filter.setValue(aggregate);
329 330 331 332

    return filter;
}

333 334
typedef QPair<QString, QString> StringPair;

335
QList<StringPair> addressPairs(const QContactPhoneNumber &phoneNumber)
336
{
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
    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;
353 354 355 356 357 358 359 360 361
}

StringPair addressPair(const QContactEmailAddress &emailAddress)
{
    return qMakePair(emailAddress.emailAddress().toLower(), QString());
}

StringPair addressPair(const QContactOnlineAccount &account)
{
362
    StringPair address = qMakePair(account.value<QString>(QContactOnlineAccount__FieldAccountPath), account.accountUri().toLower());
363
    return !address.first.isEmpty() && !address.second.isEmpty() ? address : StringPair();
364 365 366 367
}

bool validAddressPair(const StringPair &address)
{
368
    return (!address.first.isEmpty() || !address.second.isEmpty());
369 370
}

371
bool ignoreContactForDisplayLabelGroups(const QContact &contact)
372 373 374 375 376 377 378 379 380 381 382 383 384
{
    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);
}

385
QList<quint32> internalIds(const QList<QContactId> &ids)
386 387 388 389
{
    QList<quint32> rv;
    rv.reserve(ids.count());

390
    foreach (const QContactId &id, ids) {
391 392 393 394 395 396
        rv.append(SeasideCache::internalId(id));
    }

    return rv;
}

397 398 399 400 401 402 403 404 405 406 407
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;
}

408 409
const int ExactMatch = 100;

410 411 412 413 414 415 416 417 418 419 420 421
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);

422 423
    QString::const_iterator lit, rit;
    bool processDtmf = false;
424
    int matchLength = 0;
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446

    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;
                    }
447
                }
448
                break;
449
            }
450
        }
451 452 453
    } else {
        // Process the DTMF section for a match
        processDtmf = true;
454 455 456 457
    }

    // Have we got a match?
    if ((matchLength >= QtContactsSqliteExtensions::DefaultMaximumPhoneNumberCharacters) ||
458
        processDtmf) {
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
        // 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));
478 479 480
        if (bestMatchLength == ExactMatch) {
            return ExactMatch;
        }
481 482 483 484 485
    }

    return bestMatchLength;
}

486 487 488
}

SeasideCache *SeasideCache::instancePtr = 0;
489 490
int SeasideCache::contactDisplayLabelGroupCount = 0;
QStringList SeasideCache::allContactDisplayLabelGroups = QStringList();
491 492
QTranslator *SeasideCache::engEnTranslator = 0;
QTranslator *SeasideCache::translator = 0;
493

494 495 496 497 498
QContactManager* SeasideCache::manager()
{
    return ::manager();
}

mvogt's avatar
mvogt committed
499 500
SeasideCache* SeasideCache::instance()
{
501 502 503
    if (!instancePtr) {
        instancePtr = new SeasideCache;
    }
mvogt's avatar
mvogt committed
504 505 506
    return instancePtr;
}

507
QContactId SeasideCache::apiId(const QContact &contact)
mvogt's avatar
mvogt committed
508 509 510 511
{
    return contact.id();
}

512
QContactId SeasideCache::apiId(quint32 iid)
mvogt's avatar
mvogt committed
513 514 515 516
{
    return QtContactsSqliteExtensions::apiContactId(iid);
}

517
bool SeasideCache::validId(const QContactId &id)
mvogt's avatar
mvogt committed
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
{
    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()
533
    : m_syncFilter(FilterNone)
mvogt's avatar
mvogt committed
534 535 536
    , m_populated(0)
    , m_cacheIndex(0)
    , m_queryIndex(0)
537 538
    , m_fetchProcessedCount(0)
    , m_fetchByIdProcessedCount(0)
mvogt's avatar
mvogt committed
539
    , m_keepPopulated(false)
540
    , m_populateProgress(Unpopulated)
541
    , m_populating(0)
542
    , m_fetchTypes(0)
543 544
    , m_extraFetchTypes(0)
    , m_dataTypesFetched(0)
mvogt's avatar
mvogt committed
545 546 547
    , m_updatesPending(false)
    , m_refreshRequired(false)
    , m_contactsUpdated(false)
548
    , m_displayOff(false)
mvogt's avatar
mvogt committed
549 550
{
    m_timer.start();
551
    m_fetchPostponed.invalidate();
mvogt's avatar
mvogt committed
552

553 554 555 556
    CacheConfiguration *config(cacheConfig());
    connect(config, SIGNAL(displayLabelOrderChanged(CacheConfiguration::DisplayLabelOrder)),
            this, SLOT(displayLabelOrderChanged(CacheConfiguration::DisplayLabelOrder)));
    connect(config, SIGNAL(sortPropertyChanged(QString)), this, SLOT(sortPropertyChanged(QString)));
mvogt's avatar
mvogt committed
557

558 559 560 561 562 563 564
    // 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";
        }
565 566
    }

567 568
    QContactManager *mgr(manager());

569 570 571 572
    // 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);
573 574 575
    connect(cme, SIGNAL(displayLabelGroupsChanged(QStringList)),
            this, SLOT(displayLabelGroupsChanged(QStringList)));
    displayLabelGroupsChanged(cme->displayLabelGroups());
576

577
    connect(mgr, SIGNAL(dataChanged()), this, SLOT(dataChanged()));
578
    connect(mgr, SIGNAL(contactsAdded(QList<QContactId>)),
mvogt's avatar
mvogt committed
579
            this, SLOT(contactsAdded(QList<QContactId>)));
580
    connect(mgr, SIGNAL(contactsChanged(QList<QContactId>)),
mvogt's avatar
mvogt committed
581
            this, SLOT(contactsChanged(QList<QContactId>)));
582 583
    connect(cme, SIGNAL(contactsPresenceChanged(QList<QContactId>)),
            this, SLOT(contactsPresenceChanged(QList<QContactId>)));
584
    connect(mgr, SIGNAL(contactsRemoved(QList<QContactId>)),
mvogt's avatar
mvogt committed
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
            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)));

609 610 611 612 613 614 615 616
    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);
mvogt's avatar
mvogt committed
617

618
    setSortOrder(sortProperty());
mvogt's avatar
mvogt committed
619 620 621 622 623 624 625 626 627 628
}

SeasideCache::~SeasideCache()
{
    if (instancePtr == this)
        instancePtr = 0;
}

void SeasideCache::checkForExpiry()
{
629
    if (instancePtr->m_users.isEmpty() && !QCoreApplication::closingDown()) {
mvogt's avatar
mvogt committed
630 631 632 633 634 635 636 637 638 639
        bool unused = true;
        for (int i = 0; i < FilterTypesCount; ++i) {
            unused &= instancePtr->m_models[i].isEmpty();
        }
        if (unused) {
            instancePtr->m_expiryTimer.start(30000, instancePtr);
        }
    }
}

640
void SeasideCache::registerModel(ListModel *model, FilterType type, FetchDataType requiredTypes, FetchDataType extraTypes)
mvogt's avatar
mvogt committed
641
{
642 643 644 645 646 647
    // Ensure the cache has been instantiated
    instance();

    instancePtr->m_expiryTimer.stop();
    for (int i = 0; i < FilterTypesCount; ++i)
        instancePtr->m_models[i].removeAll(model);
648

mvogt's avatar
mvogt committed
649
    instancePtr->m_models[type].append(model);
650 651 652 653 654 655

    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;
    }
mvogt's avatar
mvogt committed
656 657 658 659 660 661 662 663 664 665 666 667
}

void SeasideCache::unregisterModel(ListModel *model)
{
    for (int i = 0; i < FilterTypesCount; ++i)
        instancePtr->m_models[i].removeAll(model);

    checkForExpiry();
}

void SeasideCache::registerUser(QObject *user)
{
668 669 670 671
    // Ensure the cache has been instantiated
    instance();

    instancePtr->m_expiryTimer.stop();
mvogt's avatar
mvogt committed
672 673 674 675 676 677 678 679 680 681
    instancePtr->m_users.insert(user);
}

void SeasideCache::unregisterUser(QObject *user)
{
    instancePtr->m_users.remove(user);

    checkForExpiry();
}

682
void SeasideCache::registerDisplayLabelGroupChangeListener(SeasideDisplayLabelGroupChangeListener *listener)
mvogt's avatar
mvogt committed
683
{
684 685 686
    // Ensure the cache has been instantiated
    instance();

687
    instancePtr->m_displayLabelGroupChangeListeners.append(listener);
mvogt's avatar
mvogt committed
688 689
}

690
void SeasideCache::unregisterDisplayLabelGroupChangeListener(SeasideDisplayLabelGroupChangeListener *listener)
mvogt's avatar
mvogt committed
691 692 693
{
    if (!instancePtr)
        return;
694
    instancePtr->m_displayLabelGroupChangeListeners.removeAll(listener);
mvogt's avatar
mvogt committed
695 696
}

697 698
void SeasideCache::registerChangeListener(ChangeListener *listener)
{
699 700 701
    // Ensure the cache has been instantiated
    instance();

702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
    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;

717
    QHash<QContactFetchRequest *, ResolveData>::iterator it = instancePtr->m_resolveAddresses.begin();
718
    while (it != instancePtr->m_resolveAddresses.end()) {
719 720 721
        if (it.value().listener == listener) {
            it.key()->cancel();
            delete it.key();
722 723 724 725 726
            it = instancePtr->m_resolveAddresses.erase(it);
        } else {
            ++it;
        }
    }
727

728 729 730 731
    QList<ResolveData>::iterator it2 = instancePtr->m_unknownAddresses.begin();
    while (it2 != instancePtr->m_unknownAddresses.end()) {
        if (it2->listener == listener) {
            it2 = instancePtr->m_unknownAddresses.erase(it2);
732
        } else {
733
            ++it2;
734 735
        }
    }
736 737 738 739 740 741 742 743 744

    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;
        }
    }
745 746 747 748 749 750 751 752 753

    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;
        }
    }
754 755
}

756
QString SeasideCache::displayLabelGroup(const CacheItem *cacheItem)
mvogt's avatar
mvogt committed
757 758
{
    if (!cacheItem)
759
        return QString();
mvogt's avatar
mvogt committed
760

761
    return cacheItem->displayLabelGroup;
762 763
}

764
QStringList SeasideCache::allDisplayLabelGroups()
mvogt's avatar
mvogt committed
765
{
766 767 768
    // Ensure the cache has been instantiated
    instance();

769
    return allContactDisplayLabelGroups;
mvogt's avatar
mvogt committed
770 771
}

772
QHash<QString, QSet<quint32> > SeasideCache::displayLabelGroupMembers()
mvogt's avatar
mvogt committed
773 774
{
    if (instancePtr)
775
        return instancePtr->m_contactDisplayLabelGroups;
776
    return QHash<QString, QSet<quint32> >();
mvogt's avatar
mvogt committed
777 778 779 780
}

SeasideCache::DisplayLabelOrder SeasideCache::displayLabelOrder()
{
781
    return static_cast<DisplayLabelOrder>(cacheConfig()->displayLabelOrder());
mvogt's avatar
mvogt committed
782 783
}

784 785
QString SeasideCache::sortProperty()
{
786
    return cacheConfig()->sortProperty();
787 788
}

789 790
QString SeasideCache::groupProperty()
{
791
    return cacheConfig()->groupProperty();
792 793
}

mvogt's avatar
mvogt committed
794 795 796 797 798 799
int SeasideCache::contactId(const QContact &contact)
{
    quint32 internal = internalId(contact);
    return static_cast<int>(internal);
}

800
SeasideCache::CacheItem *SeasideCache::itemById(const QContactId &id, bool requireComplete)
mvogt's avatar
mvogt committed
801 802 803 804 805 806 807 808 809 810 811 812 813 814
{
    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]);
815 816 817
        item->iid = iid;
        item->contactState = ContactAbsent;

mvogt's avatar
mvogt committed
818 819 820
        item->contact.setId(id);
    }

821 822
    if (requireComplete) {
        ensureCompletion(item);
mvogt's avatar
mvogt committed
823 824 825 826
    }
    return item;
}

827
SeasideCache::CacheItem *SeasideCache::itemById(int id, bool requireComplete)
mvogt's avatar
mvogt committed
828 829 830 831
{
    if (id != 0) {
        QContactId contactId(apiId(static_cast<quint32>(id)));
        if (!contactId.isNull()) {
832
            return itemById(contactId, requireComplete);
mvogt's avatar
mvogt committed
833 834 835 836 837 838
        }
    }

    return 0;
}

839
SeasideCache::CacheItem *SeasideCache::existingItem(const QContactId &id)
mvogt's avatar
mvogt committed
840
{
841 842
    return existingItem(internalId(id));
}
mvogt's avatar
mvogt committed
843

844 845
SeasideCache::CacheItem *SeasideCache::existingItem(quint32 iid)
{
mvogt's avatar
mvogt committed
846 847 848 849 850 851
    QHash<quint32, CacheItem>::iterator it = instancePtr->m_people.find(iid);
    return it != instancePtr->m_people.end()
            ? &(*it)
            : 0;
}

852
QContact SeasideCache::contactById(const QContactId &id)
mvogt's avatar
mvogt committed
853 854 855 856 857
{
    quint32 iid = internalId(id);
    return instancePtr->m_people.value(iid, CacheItem()).contact;
}

858
void SeasideCache::ensureCompletion(CacheItem *cacheItem)
mvogt's avatar
mvogt committed
859
{
860
    if (cacheItem->contactState < ContactRequested) {
861
        refreshContact(cacheItem);
862 863 864
    }
}

865 866 867 868 869 870 871
void SeasideCache::refreshContact(CacheItem *cacheItem)
{
    cacheItem->contactState = ContactRequested;
    instancePtr->m_changedContacts.append(cacheItem->apiId());
    instancePtr->fetchContacts();
}

872 873
SeasideCache::CacheItem *SeasideCache::itemByPhoneNumber(const QString &number, bool requireComplete)
{
874 875 876
    const QString normalized(normalizePhoneNumber(number));
    if (normalized.isEmpty())
        return 0;
877

878 879 880 881 882
    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;
883 884
        }
    }
885

886 887 888 889 890 891 892 893 894
    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);
mvogt's avatar
mvogt committed
895 896
}

897
SeasideCache::CacheItem *SeasideCache::itemByEmailAddress(const QString &email, bool requireComplete)
mvogt's avatar
mvogt committed
898
{
899 900 901
    if (email.trimmed().isEmpty())
        return 0;

mvogt's avatar
mvogt committed
902 903
    QHash<QString, quint32>::const_iterator it = instancePtr->m_emailAddressIds.find(email.toLower());
    if (it != instancePtr->m_emailAddressIds.end())
904 905
        return itemById(*it, requireComplete);

mvogt's avatar
mvogt committed
906 907 908
    return 0;
}

909 910
SeasideCache::CacheItem *SeasideCache::itemByOnlineAccount(const QString &localUid, const QString &remoteUid, bool requireComplete)
{
911 912 913
    if (localUid.trimmed().isEmpty() || remoteUid.trimmed().isEmpty())
        return 0;

914 915 916 917 918 919 920 921 922 923 924
    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)
{
925 926 927
    // Ensure the cache has been instantiated
    instance();

928 929
    CacheItem *item = itemByPhoneNumber(number, requireComplete);
    if (!item) {
930 931 932 933
        // Don't bother trying to resolve an invalid number
        const QString normalized(normalizePhoneNumber(number));
        if (!normalized.isEmpty()) {
            instancePtr->resolveAddress(listener, QString(), number, requireComplete);
934 935 936 937 938 939 940 941
        } else {
            // Report this address is unknown
            ResolveData data;
            data.second = number;
            data.listener = listener;

            instancePtr->m_unknownResolveAddresses.append(data);
            instancePtr->requestUpdate();
942
        }
943 944
    } else if (requireComplete) {
        ensureCompletion(item);
945 946 947 948 949 950 951
    }

    return item;
}

SeasideCache::CacheItem *SeasideCache::resolveEmailAddress(ResolveListener *listener, const QString &address, bool requireComplete)
{
952 953 954
    // Ensure the cache has been instantiated
    instance();

955 956 957
    CacheItem *item = itemByEmailAddress(address, requireComplete);
    if (!item) {
        instancePtr->resolveAddress(listener, address, QString(), requireComplete);
958 959
    } else if (requireComplete) {
        ensureCompletion(item);
960 961 962 963 964 965
    }
    return item;
}

SeasideCache::CacheItem *SeasideCache::resolveOnlineAccount(ResolveListener *listener, const QString &localUid, const QString &remoteUid, bool requireComplete)
{
966 967 968
    // Ensure the cache has been instantiated
    instance();

969 970 971
    CacheItem *item = itemByOnlineAccount(localUid, remoteUid, requireComplete);
    if (!item) {
        instancePtr->resolveAddress(listener, localUid, remoteUid, requireComplete);
972 973
    } else if (requireComplete) {
        ensureCompletion(item);
974 975 976 977
    }
    return item;
}

978
QContactId SeasideCache::selfContactId()
mvogt's avatar
mvogt committed
979
{
980
    return manager()->selfContactId();
mvogt's avatar
mvogt committed
981 982 983 984
}

void SeasideCache::requestUpdate()
{
985
    if (!m_updatesPending) {
mvogt's avatar
mvogt committed
986
        QCoreApplication::postEvent(this, new QEvent(QEvent::UpdateRequest));
987 988
        m_updatesPending = true;
    }
mvogt's avatar
mvogt committed
989 990 991 992
}

bool SeasideCache::saveContact(const QContact &contact)
{
993
    QContactId id = apiId(contact);
mvogt's avatar
mvogt committed
994 995
    if (validId(id)) {
        instancePtr->m_contactsToSave[id] = contact;
996
        instancePtr->contactDataChanged(internalId(id));
mvogt's avatar
mvogt committed
997 998 999 1000 1001
    } else {
        instancePtr->m_contactsToCreate.append(contact);
    }

    instancePtr->requestUpdate();
1002
    instancePtr->updateSectionBucketIndexCaches();
mvogt's avatar
mvogt committed
1003 1004 1005 1006

    return true;
}

1007
void SeasideCache::contactDataChanged(quint32 iid)
mvogt's avatar
mvogt committed
1008
{
1009 1010 1011
    instancePtr->contactDataChanged(iid, FilterFavorites);
    instancePtr->contactDataChanged(iid, FilterOnline);
    instancePtr->contactDataChanged(iid, FilterAll);
1012
}
mvogt's avatar
mvogt committed
1013

1014
void SeasideCache::contactDataChanged(quint32 iid, FilterType filter)
1015
{
1016
    int row = contactIndex(iid, filter);
1017 1018 1019 1020 1021 1022
    if (row != -1) {
        QList<ListModel *> &models = m_models[filter];
        for (int i = 0; i < models.count(); ++i) {
            models.at(i)->sourceDataChanged(row, row);
        }
    }
mvogt's avatar
mvogt committed
1023 1024
}

1025
bool SeasideCache::removeContact(const QContact &contact)
mvogt's avatar
mvogt committed
1026
{
1027 1028
    return removeContacts(QList<QContact>() << contact);
}
mvogt's avatar
mvogt committed
1029

1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
bool SeasideCache::removeContacts(const QList<QContact> &contacts)
{
    bool allSucceeded = true;
    QSet<QString> modifiedDisplayLabelGroups;
    for (const QContact &contact : contacts) {
        const QContactId id = apiId(contact);
        if (!validId(id)) {
            allSucceeded = false;
            continue;
        }
1040

1041 1042 1043 1044 1045 1046
        instancePtr->m_contactsToRemove.append(id);

        quint32 iid = internalId(id);
        instancePtr->removeContactData(iid, FilterFavorites);
        instancePtr->removeContactData(iid, FilterOnline);
        instancePtr->removeContactData(iid, FilterAll);
mvogt's avatar
mvogt committed
1047

1048 1049 1050 1051 1052 1053
        const QString group(displayLabelGroup(existingItem(iid)));
        instancePtr->removeFromContactDisplayLabelGroup(iid, group, &modifiedDisplayLabelGroups);
    }

    instancePtr->notifyDisplayLabelGroupsChanged(modifiedDisplayLabelGroups);
    instancePtr->updateSectionBucketIndexCaches();
mvogt's avatar
mvogt committed
1054
    instancePtr->requestUpdate();
1055
    return allSucceeded;
mvogt's avatar
mvogt committed
1056 1057
}

1058
void SeasideCache::removeContactData(quint32 iid, FilterType filter)
mvogt's avatar
mvogt committed
1059
{
1060
    int row = contactIndex(iid, filter);
mvogt's avatar
mvogt committed
1061 1062 1063 1064 1065 1066 1067
    if (row == -1)
        return;

    QList<ListModel *> &models = m_models[filter];
    for (int i = 0; i < models.count(); ++i)
        models.at(i)->sourceAboutToRemoveItems(row, row);

1068
    m_contacts[filter].removeAt(row);
mvogt's avatar
mvogt committed
1069 1070 1071 1072 1073

    for (int i = 0; i < models.count(); ++i)
        models.at(i)->sourceItemsRemoved();
}

1074
bool SeasideCache::fetchConstituents(const QContact &contact)
mvogt's avatar
mvogt committed
1075 1076
{
    QContactId personId(contact.id());
1077 1078
    if (!validId(personId))
        return false;
mvogt's avatar
mvogt committed
1079 1080 1081 1082 1083

    if (!instancePtr->m_contactsToFetchConstituents.contains(personId)) {
        instancePtr->m_contactsToFetchConstituents.append(personId);
        instancePtr->requestUpdate();
    }
1084
    return true;
mvogt's avatar
mvogt committed
1085 1086
}

1087
bool SeasideCache::fetchMergeCandidates(const QContact &contact)
mvogt's avatar
mvogt committed
1088 1089
{
    QContactId personId(contact.id());
1090 1091
    if (!validId(personId))
        return false;
mvogt's avatar
mvogt committed
1092 1093 1094 1095 1096

    if (!instancePtr->m_contactsToFetchCandidates.contains(personId)) {
        instancePtr->m_contactsToFetchCandidates.append(personId);
        instancePtr->requestUpdate();
    }
1097
    return true;
mvogt's avatar
mvogt committed
1098 1099
}

1100
const QList<quint32> *SeasideCache::contacts(FilterType type)
mvogt's avatar
mvogt committed
1101 1102 1103 1104 1105 1106 1107 1108 1109
{
    return &instancePtr->m_contacts[type];
}

bool SeasideCache::isPopulated(FilterType filterType)
{
    return instancePtr->m_populated & (1 << filterType);
}

1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
QString SeasideCache::primaryName(const QString &firstName, const QString &lastName)
{
    if (firstName.isEmpty() && lastName.isEmpty()) {
        return QString();
    }

    const bool familyNameFirst(displayLabelOrder() == LastNameFirst ||
                               nameScriptImpliesFamilyFirst(firstName, lastName));
    return familyNameFirst ? lastName : firstName;
}

QString SeasideCache::secondaryName(const QString &firstName, const QString &lastName)
{
    const bool familyNameFirst(displayLabelOrder() == LastNameFirst ||
                               nameScriptImpliesFamilyFirst(firstName, lastName));
    return familyNameFirst ? firstName : lastName;
}

1128 1129 1130 1131 1132 1133 1134 1135 1136
static bool needsSpaceBetweenNames(const QString &first, const QString &second)
{
    if (first.isEmpty() || second.isEmpty()) {
        return false;
    }
    return first[first.length()-1].script() != QChar::Script_Han
            || second[0].script() != QChar::Script_Han;
}

1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
template<typename F1, typename F2>
void updateNameDetail(F1 getter, F2 setter, QContactName *nameDetail, const QString &value)
{
    QString existing((nameDetail->*getter)());
    if (!existing.isEmpty()) {
        existing.append(QChar::fromLatin1(' '));
    }
    (nameDetail->*setter)(existing + value);
}

void SeasideCache::decomposeDisplayLabel(const QString &formattedDisplayLabel, QContactName *nameDetail)
{
1149 1150 1151 1152 1153 1154 1155 1156 1157
    if (!translator) {
        engEnTranslator = new QTranslator(qApp);
        engEnTranslator->load(QString::fromLatin1("libcontacts_eng_en"), QString::fromLatin1("/usr/share/translations"));
        qApp->installTranslator(engEnTranslator);
        translator = new QTranslator(qApp);
        translator->load(QLocale(), QString::fromLatin1("libcontacts"), QString::fromLatin1("-"), QString::fromLatin1("/usr/share/translations"));
        qApp->installTranslator(translator);
    }

1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
    // Try to parse the structure from the formatted name
    // TODO: Use MBreakIterator for localized splitting
    QStringList tokens(formattedDisplayLabel.split(QChar::fromLatin1(' '), QString::SkipEmptyParts));
    if (tokens.count() >= 2) {
        QString format;
        if (tokens.count() == 2) {
            //: Format string for allocating 2 tokens to name parts - 2 characters from the set [FMLPS]
            //% "FL"
            format = qtTrId("libcontacts_name_structure_2_tokens");
        } else if (tokens.count() == 3) {
            //: Format string for allocating 3 tokens to name parts - 3 characters from the set [FMLPS]
            //% "FML"
            format = qtTrId("libcontacts_name_structure_3_tokens");
        } else if (tokens.count() > 3) {
            //: Format string for allocating 4 tokens to name parts - 4 characters from the set [FMLPS]
            //% "FFML"
            format = qtTrId("libcontacts_name_structure_4_tokens");

            // Coalesce the leading tokens together to limit the possibilities
            int excess = tokens.count() - 4;
            if (excess > 0) {
                QString first(tokens.takeFirst());
                while (--excess >= 0) {
                    QString nextNamePart = tokens.takeFirst();
                    first += (needsSpaceBetweenNames(first, nextNamePart) ? QChar::fromLatin1(' ') : QString()) + nextNamePart;
                }
                tokens.prepend(first);
            }
        }

        if (format.length() != tokens.length()) {
            qWarning() << "Invalid structure format for" << tokens.count() << "tokens:" << format;
        } else {
            foreach (const QChar &part, format) {
                const QString token(tokens.takeFirst());
                switch (part.toUpper().toLatin1()) {
                    case 'F': updateNameDetail(&QContactName::firstName, &QContactName::setFirstName, nameDetail, token); break;
                    case 'M': updateNameDetail(&QContactName::middleName, &QContactName::setMiddleName, nameDetail, token); break;
                    case 'L': updateNameDetail(&QContactName::lastName, &QContactName::setLastName, nameDetail, token); break;
                    case 'P': updateNameDetail(&QContactName::prefix, &QContactName::setPrefix, nameDetail, token); break;
                    case 'S': updateNameDetail(&QContactName::suffix, &QContactName::setSuffix, nameDetail, token); break;
                    default:
                        qWarning() << "Invalid structure format character:" << part;
                }
            }
        }
    }
}

mvogt's avatar
mvogt committed
1207 1208 1209 1210 1211 1212 1213
// small helper to avoid inconvenience
QString SeasideCache::generateDisplayLabel(const QContact &contact, DisplayLabelOrder order)
{
    QContactName name = contact.detail<QContactName>();

    QString displayLabel;

1214 1215 1216 1217 1218
    QString nameStr1(name.firstName());
    QString nameStr2(name.lastName());

    const bool familyNameFirst(order == LastNameFirst || nameScriptImpliesFamilyFirst(nameStr1, nameStr2));
    if (familyNameFirst) {
mvogt's avatar
mvogt committed
1219 1220 1221 1222
        nameStr1 = name.lastName();
        nameStr2 = name.firstName();
    }

1223
    if (!nameStr1.isEmpty())
mvogt's avatar
mvogt committed
1224 1225
        displayLabel.append(nameStr1);

1226
    if (!nameStr2.isEmpty()) {
1227
        if (needsSpaceBetweenNames(nameStr1, nameStr2)) {
mvogt's avatar
mvogt committed
1228
            displayLabel.append(" ");
1229
        }
mvogt's avatar
mvogt committed
1230 1231 1232 1233 1234 1235 1236
        displayLabel.append(nameStr2);
    }

    if (!displayLabel.isEmpty()) {
        return displayLabel;
    }

1237
    // Try to generate a label from the contact details, in our preferred order
mvogt's avatar
mvogt committed
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
    displayLabel = generateDisplayLabelFromNonNameDetails(contact);
    if (!displayLabel.isEmpty()) {
        return displayLabel;
    }

    return "(Unnamed)"; // TODO: localisation
}

QString SeasideCache::generateDisplayLabelFromNonNameDetails(const QContact &contact)
{
    foreach (const QContactNickname& nickname, contact.details<QContactNickname>()) {
1249
        if (!nickname.nickname().isEmpty()) {
mvogt's avatar
mvogt committed
1250 1251 1252 1253 1254 1255
            return nickname.nickname();
        }
    }

    foreach (const QContactGlobalPresence& gp, contact.details<QContactGlobalPresence>()) {
        // should only be one of these, but qtct is strange, and doesn't list it as a unique detail in the schema...
1256
        if (!gp.nickname().isEmpty()) {
mvogt's avatar
mvogt committed
1257 1258 1259 1260 1261
            return gp.nickname();
        }
    }

    foreach (const QContactPresence& presence, contact.details<QContactPresence>()) {
1262
        if (!presence.nickname().isEmpty()) {
mvogt's avatar
mvogt committed
1263 1264 1265 1266
            return presence.nickname();
        }
    }

1267 1268 1269 1270 1271 1272
    // If this contact has organization details but no name, it probably represents that organization directly
    QContactOrganization company = contact.detail<QContactOrganization>();
    if (!company.name().isEmpty()) {
        return company.name();
    }

1273 1274 1275 1276 1277 1278 1279
    // If none of the detail fields provides a label, fallback to the backend's label string, in
    // preference to using any of the addressing details directly
    const QString displayLabel = contact.detail<QContactDisplayLabel>().label();
    if (!displayLabel.isEmpty()) {
        return displayLabel;
    }

mvogt's avatar
mvogt committed
1280
    foreach (const QContactOnlineAccount& account, contact.details<QContactOnlineAccount>()) {
1281
        if (!account.accountUri().isEmpty()) {
mvogt's avatar
mvogt committed
1282 1283 1284 1285 1286
            return account.accountUri();
        }
    }

    foreach (const QContactEmailAddress& email, contact.details<QContactEmailAddress>()) {
1287
        if (!email.emailAddress().isEmpty()) {
mvogt's avatar
mvogt committed
1288 1289 1290 1291 1292
            return email.emailAddress();
        }
    }

    foreach (const QContactPhoneNumber& phone, contact.details<QContactPhoneNumber>()) {
1293
        if (!phone.number().isEmpty())
mvogt's avatar
mvogt committed
1294 1295 1296 1297 1298 1299
            return phone.number();
    }

    return QString();
}

1300
static bool avatarUrlWithMetadata(const QContact &contact, QUrl &matchingUrl, const QString &metadataFragment = QString())
1301
{
1302
    static const QString coverMetadata(QString::fromLatin1("cover"));
1303 1304 1305
    static const QString localMetadata(QString::fromLatin1("local"));
    static const QString fileScheme(QString::fromLatin1("file"));

1306
    int fallbackScore = 0;
1307 1308
    QUrl fallbackUrl;

1309
    QList<QContactAvatar> avatarDetails = contact.details<QContactAvatar>();
1310 1311
    for (int i = 0; i < avatarDetails.size(); ++i) {
        const QContactAvatar &av(avatarDetails[i]);
1312 1313 1314 1315

        const QString metadata(av.value(QContactAvatar__FieldAvatarMetadata).toString());
        if (!metadataFragment.isEmpty() && !metadata.startsWith(metadataFragment)) {
            // this avatar doesn't match the metadata requirement.  ignore it.
1316
            continue;
1317 1318 1319 1320 1321 1322
        }

        const QUrl avatarImageUrl = av.imageUrl();

        if (metadata == localMetadata) {
            // We have a local avatar record - use the image it specifies
1323 1324
            matchingUrl = avatarImageUrl;
            return true;
1325
        } else {
1326 1327 1328
            // queue it as fallback if its score is better than the best fallback seen so far.
            // prefer local file system images over remote urls, and prefer normal avatars
            // over "cover" (background image) type avatars.
1329
            const bool remote(!avatarImageUrl.scheme().isEmpty() && avatarImageUrl.scheme() != fileScheme);
1330 1331 1332 1333 1334 1335 1336 1337
            int score = remote ? 3 : 4;
            if (metadata == coverMetadata) {
                score -= 2;
            }

            if (score > fallbackScore) {
                fallbackUrl = avatarImageUrl;
                fallbackScore = score;
1338
            }
1339 1340 1341
        }
    }

1342
    if (!fallbackUrl.isEmpty()) {
1343 1344
        matchingUrl = fallbackUrl;
        return true;
1345 1346 1347
    }

    // no matching avatar image.
1348
    return false;
1349 1350 1351 1352
}

QUrl SeasideCache::filteredAvatarUrl(const QContact &contact, const QStringList &metadataFragments)
{
1353 1354
    QUrl matchingUrl;

1355
    if (metadataFragments.isEmpty()) {
1356 1357 1358
        if (avatarUrlWithMetadata(contact, matchingUrl)) {
            return matchingUrl;
        }
1359 1360 1361
    }

    foreach (const QString &metadataFragment, metadataFragments) {
1362
        if (avatarUrlWithMetadata(contact, matchingUrl, metadataFragment)) {
1363 1364 1365 1366 1367 1368 1369
            return matchingUrl;
        }
    }

    return QUrl();
}

1370
QString SeasideCache::normalizePhoneNumber(const QString &input, bool validate)
1371
{
1372 1373 1374 1375 1376
    QtContactsSqliteExtensions::NormalizePhoneNumberFlags normalizeFlags(QtContactsSqliteExtensions::KeepPhoneNumberDialString);
    if (validate) {
        // If the number if not valid, return empty
        normalizeFlags |= QtContactsSqliteExtensions::ValidatePhoneNumber;
    }
1377 1378 1379 1380

    return QtContactsSqliteExtensions::normalizePhoneNumber(input, normalizeFlags);
}

1381
QString SeasideCache::minimizePhoneNumber(const QString &input, bool validate)
1382 1383
{
    // TODO: use a configuration variable to make this configurable
1384
    const int maxCharacters = QtContactsSqliteExtensions::DefaultMaximumPhoneNumberCharacters;
1385

1386
    QString validated(normalizePhoneNumber(input, validate));
1387
    if (validated.isEmpty())
1388 1389
        return validated;

1390
    return QtContactsSqliteExtensions::minimizePhoneNumber(validated, maxCharacters);
1391 1392
}

mvogt's avatar
mvogt committed
1393 1394 1395 1396 1397 1398
static QContactFilter filterForMergeCandidates(const QContact &contact)
{
    // Find any contacts that we might merge with the supplied contact
    QContactFilter rv;

    QContactName name(contact.detail<QContactName>());
1399 1400
    const QString firstName(name.firstName().trimmed());
    const QString lastName(name.lastName().trimmed());
mvogt's avatar
mvogt committed
1401 1402 1403

    if (firstName.isEmpty() && lastName.isEmpty()) {
        // Use the displayLabel to match with
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
        const QString label(contact.detail<QContactDisplayLabel>().label().trimmed());

        if (!label.isEmpty()) {
            // Partial match to first name
            QContactDetailFilter firstNameFilter;
            setDetailType<QContactName>(firstNameFilter, QContactName::FieldFirstName);
            firstNameFilter.setMatchFlags(QContactFilter::MatchContains | QContactFilter::MatchFixedString);
            firstNameFilter.setValue(label);
            rv = rv | firstNameFilter;

            // Partial match to last name
            QContactDetailFilter lastNameFilter;
            setDetailType<QContactName>(lastNameFilter, QContactName::FieldLastName);
            lastNameFilter.setMatchFlags(QContactFilter::MatchContains | QContactFilter::MatchFixedString);
            lastNameFilter.setValue(label);
            rv = rv | lastNameFilter;

            // Partial match to nickname
            QContactDetailFilter nicknameFilter;
            setDetailType<QContactNickname>(nicknameFilter, QContactNickname::FieldNickname);
            nicknameFilter.setMatchFlags(QContactFilter::MatchContains | QContactFilter::MatchFixedString);
            nicknameFilter.setValue(label);
            rv = rv | nicknameFilter;
        }
mvogt's avatar
mvogt committed
1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442
    } else {
        if (!firstName.isEmpty()) {
            // Partial match to first name
            QContactDetailFilter nameFilter;
            setDetailType<QContactName>(nameFilter, QContactName::FieldFirstName);
            nameFilter.setMatchFlags(QContactFilter::MatchContains | QContactFilter::MatchFixedString);
            nameFilter.setValue(firstName);
            rv = rv | nameFilter;

            // Partial match to first name in the nickname
            QContactDetailFilter nicknameFilter;
            setDetailType<QContactNickname>(nicknameFilter, QContactNickname::FieldNickname);
            nicknameFilter.setMatchFlags(QContactFilter::MatchContains | QContactFilter::MatchFixedString);
            nicknameFilter.setValue(firstName);
            rv = rv | nicknameFilter;
1443 1444 1445 1446 1447 1448 1449 1450 1451

            if (firstName.length() > 3) {
                // Also look for shortened forms of this name, such as 'Timothy' => 'Tim'
                QContactDetailFilter shortFilter;
                setDetailType<QContactName>(shortFilter, QContactName::FieldFirstName);
                shortFilter.setMatchFlags(QContactFilter::MatchStartsWith | QContactFilter::MatchFixedString);
                shortFilter.setValue(firstName.left(3));
                rv = rv | shortFilter;
            }
mvogt's avatar
mvogt committed
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
        }
        if (!lastName.isEmpty()) {
            // Partial match to last name
            QContactDetailFilter nameFilter;
            setDetailType<QContactName>(nameFilter, QContactName::FieldLastName);
            nameFilter.setMatchFlags(QContactFilter::MatchContains | QContactFilter::MatchFixedString);
            nameFilter.setValue(lastName);
            rv = rv | nameFilter;

            // Partial match to last name in the nickname
            QContactDetailFilter nicknameFilter;
            setDetailType<QContactNickname>(nicknameFilter, QContactNickname::FieldNickname);
            nicknameFilter.setMatchFlags(QContactFilter::MatchContains | QContactFilter::MatchFixedString);
            nicknameFilter.setValue(lastName);
            rv = rv | nicknameFilter;
        }
    }

    // Phone number match
1471
    foreach (const QContactPhoneNumber &phoneNumber, contact.details<QContactPhoneNumber>()) {
1472
        const QString number(phoneNumber.number().trimmed());
1473 1474 1475 1476
        if (number.isEmpty())
            continue;

        rv = rv | QContactPhoneNumber::match(number);
mvogt's avatar
mvogt committed
1477 1478 1479 1480
    }

    // Email address match
    foreach (const QContactEmailAddress &emailAddress, contact.details<QContactEmailAddress>()) {
1481
        QString address(emailAddress.emailAddress().trimmed());
mvogt's avatar
mvogt committed
1482 1483 1484
        int index = address.indexOf(QChar::fromLatin1('@'));
        if (index > 0) {
            // Match any address that is the same up to the @ symbol
1485
            address = address.left(index).trimmed();
mvogt's avatar
mvogt committed
1486 1487
        }

1488 1489 1490
        if (address.isEmpty())
            continue;

mvogt's avatar
mvogt committed
1491 1492 1493 1494 1495 1496 1497 1498 1499
        QContactDetailFilter filter;
        setDetailType<QContactEmailAddress>(filter, QContactEmailAddress::FieldEmailAddress);
        filter.setMatchFlags((index > 0 ? QContactFilter::MatchStartsWith : QContactFilter::MatchExactly) | QContactFilter::MatchFixedString);
        filter.setValue(address);
        rv = rv | filter;
    }

    // Account URI match
    foreach (const QContactOnlineAccount &account, contact.details<QContactOnlineAccount>()) {
1500
        QString uri(account.accountUri().trimmed());
mvogt's avatar
mvogt committed
1501 1502 1503
        int index = uri.indexOf(QChar::fromLatin1('@'));
        if (index > 0) {
            // Match any account URI that is the same up to the @ symbol
1504
            uri = uri.left(index).trimmed();
mvogt's avatar
mvogt committed
1505 1506
        }

1507 1508 1509
        if (uri.isEmpty())
            continue;

mvogt's avatar
mvogt committed
1510 1511 1512 1513 1514 1515 1516
        QContactDetailFilter filter;
        setDetailType<QContactOnlineAccount>(filter, QContactOnlineAccount::FieldAccountUri);
        filter.setMatchFlags((index > 0 ? QContactFilter::MatchStartsWith : QContactFilter::MatchExactly) | QContactFilter::MatchFixedString);
        filter.setValue(uri);
        rv = rv | filter;
    }

1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
    // If we know the contact gender rule out mismatches
    QContactGender gender(contact.detail<QContactGender>());
    if (gender.gender() != QContactGender::GenderUnspecified) {
        QContactDetailFilter matchFilter;
        setDetailType<QContactGender>(matchFilter, QContactGender::FieldGender);
        matchFilter.setValue(gender.gender());

        QContactDetailFilter unknownFilter;
        setDetailType<QContactGender>(unknownFilter, QContactGender::FieldGender);
        unknownFilter.setValue(QContactGender::GenderUnspecified);

        rv = rv & (matchFilter | unknownFilter);
    }

mvogt's avatar
mvogt committed
1531
    // Only return aggregate contact IDs
1532
    return rv & aggregateFilter();
mvogt's avatar
mvogt committed
1533 1534
}

1535
void SeasideCache::startRequest(bool *idleProcessing)
mvogt's avatar
mvogt committed
1536
{
1537
    bool requestPending = false;
1538 1539

    // Test these conditions in priority order
1540

1541 1542 1543 1544 1545 1546 1547 1548 1549
    // Start by loading the favorites model, because it's so small and
    // the user is likely to want to interact with it.
    if (m_keepPopulated && (m_populateProgress == Unpopulated)) {
        if (m_fetchRequest.isActive()) {
            requestPending = true;
        } else {
            m_fetchRequest.setFilter(favoriteFilter());
            m_fetchRequest.setFetchHint(favoriteFetchHint(m_fetchTypes));
            m_fetchRequest.setSorting(m_sortOrder);