summaryrefslogtreecommitdiffstats
path: root/src/contacts/qcontactmanagerenginev2wrapper_p.cpp
blob: 210738ff1fcd80e7bd6a0ff3e348641ac6590664 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qcontact_p.h"
#include "qcontactmanagerenginev2wrapper_p.h"
#include "qcontactlocalidfilter.h"
#include "qcontactabstractrequest_p.h"
#include "qcontactfetchbyidrequest.h"
#include <QDebug>

QTM_USE_NAMESPACE

QContactManagerEngineV2Wrapper::QContactManagerEngineV2Wrapper(QContactManagerEngine *wrappee)
    : m_engine(wrappee)
{
    Q_ASSERT(wrappee);
}

QContactManagerEngineV2Wrapper::~QContactManagerEngineV2Wrapper()
{
    delete m_engine;
}

void QContactManagerEngineV2Wrapper::requestDestroyed(QContactAbstractRequest* req)
{
    RequestController* controller = m_controllerForRequest.value(req);

    if (controller) {
        // If we own it, just delete the controller (and ignore any subrequests' signals from now on)
        delete controller;
        m_controllerForRequest.insert(req, 0);
    } else {
        m_engine->requestDestroyed(req);
    }
}

bool QContactManagerEngineV2Wrapper::startRequest(QContactAbstractRequest* req)
{
    if ((req->type() == QContactAbstractRequest::ContactSaveRequest
            && !static_cast<QContactSaveRequest*>(req)->definitionMask().isEmpty())
        || (req->type() == QContactAbstractRequest::ContactFetchByIdRequest)) {
        RequestController* controller;
        if (req->type() == QContactAbstractRequest::ContactFetchByIdRequest)
            controller = new FetchByIdRequestController(m_engine);
        else
            controller = new PartialSaveRequestController(m_engine, this);
        controller->setRequest(req);
        connect(controller, SIGNAL(stateChanged(QContactAbstractRequest::State)),
                this, SLOT(requestStateChanged(QContactAbstractRequest::State)),
                Qt::QueuedConnection);
        m_controllerForRequest.insert(req, controller);
        if (controller->start()) {
            updateRequestState(req, QContactAbstractRequest::ActiveState);
            return true;
        } else {
            return false;
        }
    }

    // Otherwise, pass it on
    return m_engine->startRequest(req);
}

/* A slot connected to the stateChanged signal of a controller object.  It is signaled by the
   controller to indicate that one of the client's requests has an updated state. */
void QContactManagerEngineV2Wrapper::requestStateChanged(QContactAbstractRequest::State state)
{
    RequestController* controller = qobject_cast<RequestController*>(sender());
    Q_ASSERT(controller);
    QContactAbstractRequest* request = controller->request();

    if (state == QContactAbstractRequest::FinishedState) {
        delete controller;
        if (request) { // It's possible the request was deleted by the sender.
            // Keep the key in m_controllerForRequest but point it to null to indicate a defunct
            // controller
            m_controllerForRequest.insert(request, 0);
        }
    } else {
        updateRequestState(request, state);
    }

}

/* \reimp */
bool QContactManagerEngineV2Wrapper::cancelRequest(QContactAbstractRequest* req)
{
    if (m_controllerForRequest.contains(req)) {
        RequestController* controller = m_controllerForRequest.value(req);
        if (controller) {
            // If we own it and it hasn't already been deleted,
            // just delete the controller (and ignore any subrequests' signals from now on)
            delete controller;
            m_controllerForRequest.insert(req, 0);
        }
        return true;
    } else {
        return m_engine->cancelRequest(req);
    }
}

/* \reimp */
bool QContactManagerEngineV2Wrapper::waitForRequestFinished(QContactAbstractRequest* req, int msecs)
{
    if (m_controllerForRequest.contains(req)) {
        RequestController* controller = m_controllerForRequest.value(req);
        if (controller) {
            if (controller->waitForFinished(msecs)) {
                updateRequestState(req, QContactAbstractRequest::FinishedState);
                return true;
            } else {
                return false;
            }
        } else {
            // A request with a null controller means it has already finished
            return true;
        }
    } else {
        return m_engine->waitForRequestFinished(req, msecs);
    }

}

/* A static helper to twiddle with \a request's privates, setting its engine to \a engine. */
void QContactManagerEngineV2Wrapper::setEngineOfRequest(QContactAbstractRequest* request,
                                                        QContactManagerEngine* engine)
{
    request->d_ptr->m_engine = engine;
}


// General RequestController stuff
/* A single RequestController is associated with a single client QContactAbstractRequest.  It
   manages the sub-requests that need to be sent to the real engine and controls the asynchronous
   flow between start() and one or more handleUpdatedSubRequest() calls that might follow.
   waitForFinished() can also be called on a controller, which synchronously performs the rest of
   the necessary sub-requests.
 */

/* A slot connected the stateChanged signal of a sub request */
void RequestController::handleUpdatedSubRequest(QContactAbstractRequest::State state)
{
    QObject* caller = sender();
    QContactAbstractRequest* subRequest = qobject_cast<QContactAbstractRequest*>(caller);
    if (subRequest) {
        if (state == QContactAbstractRequest::FinishedState) {
            // It's possibly already finished if waitForFinished has previously been called
            if (!isFinished())
                handleFinishedSubRequest(subRequest);
        } else {
            // XXX maybe Canceled should be handled
        }
    }
}

/* This function handles the rest of the program flow in a synchronous way. */
bool RequestController::waitForFinished(int msecs)
{
    // If the current request is active, it must be a ContactFetchRequest.  We just need to
    // wait for it to finish, then finalize the post-processing.
    if (m_currentSubRequest.isNull()) {
        return false;
    }
    while (!isFinished()) {
        QContactAbstractRequest* const activeSubRequest = m_currentSubRequest.data();
        if (!m_currentSubRequest->waitForFinished(msecs))
            return false;
        // Handler not yet called due to some event loop used by the engine on waiting?
        if (activeSubRequest == m_currentSubRequest.data()) {
            handleFinishedSubRequest(activeSubRequest);
        }
    }
    return true;
}

// FetchByIdRequestController stuff
/* A FetchByIdRequestController is a RequestController for QContactFetchByIdRequests */
bool FetchByIdRequestController::start()
{
    // Our strategy is to translate it to a ContactFetchRequest.  Later when it finishes, we can
    // fiddle with the results to get it in the right format.
    Q_ASSERT(m_request);
    QContactFetchByIdRequest* originalRequest = static_cast<QContactFetchByIdRequest*>(m_request.data());
    QContactFetchRequest* qcfr = new QContactFetchRequest;
    QContactLocalIdFilter lif;
    lif.setIds(originalRequest->localIds());
    qcfr->setFilter(lif);
    qcfr->setFetchHint(originalRequest->fetchHint());
    // normally, you'd set the manager, but in this case, we only have a bare engine:
    QContactManagerEngineV2Wrapper::setEngineOfRequest(qcfr, m_engine);
    m_currentSubRequest.reset(qcfr);
    connect(qcfr, SIGNAL(stateChanged(QContactAbstractRequest::State)),
            this, SLOT(handleUpdatedSubRequest(QContactAbstractRequest::State)),
            Qt::QueuedConnection);
    return qcfr->start();
}

/* One of our subrequests has finished.  Go to the next step. */
void FetchByIdRequestController::handleFinishedSubRequest(QContactAbstractRequest* subReq)
{
    // For a FetchByIdRequest, we know that the only subrequest is a QContactFetchRequest.
    // The next step is simply to take the results and reformat it.
    // Take the results:
    QContactFetchRequest* qcfr = qobject_cast<QContactFetchRequest*>(subReq);
    QList<QContact> contacts = qcfr->contacts();
    QContactManager::Error error = qcfr->error();

    // Build an index into the results
    QHash<QContactLocalId, int> idMap; // value is index into unsorted
    if (error == QContactManager::NoError) {
        for (int i = 0; i < contacts.size(); i++) {
            idMap.insert(contacts[i].localId(), i);
        }
    }

    // Find the order in which the results should be presented
    QContactFetchByIdRequest* request = static_cast<QContactFetchByIdRequest*>(m_request.data());
    QList<QContactLocalId> ids(request->localIds());

    // Build up the results and errors
    QList<QContact> results;
    QMap<int, QContactManager::Error> errorMap;
    for (int i = 0; i < ids.count(); i++) {
        QContactLocalId id(ids[i]);
        if (!idMap.contains(id)) {
            errorMap.insert(i, QContactManager::DoesNotExistError);
            if (error == QContactManager::NoError)
                error = QContactManager::DoesNotExistError;
            results.append(QContact());
        } else {
            results.append(contacts[idMap[id]]);
        }
    }

    // Free the subrequest, to mark that this handler has been run
    m_currentSubRequest.reset();

    // Update the request object
    QContactManagerEngineV2Wrapper::updateContactFetchByIdRequest(
            request,
            results,
            error,
            errorMap,
            QContactAbstractRequest::FinishedState);
    finish();
}


// PartialSaveRequestController stuff
/* A PartialSaveRequestController is a RequestController for QContactSaveRequests with definition mask */
bool PartialSaveRequestController::start()
{
    // The first step is to fetch the existing contacts.
    QList<QContactLocalId> existingContactIds;
    QList<int> newContactIndices;

    // First, remove the contacts that aren't from this manager
    QList<QContact> contacts(request()->contacts());
    // Try to figure out which of our arguments are new contacts
    for(int i = 0; i < contacts.count(); i++) {
        // See if there's a contactId that's not from this manager
        const QContact c = contacts.at(i);
        if (c.id().managerUri() == m_engine->managerUri()) {
            if (c.localId() != 0) {
                m_existingIdMap.insert(i, existingContactIds.count());
                existingContactIds.append(c.localId());
            } else {
                // Strange. it's just a new contact (with a managerUri set?)
                newContactIndices.append(i);
            }
        } else if (!c.id().managerUri().isEmpty() || c.localId() != 0) {
            // Hmm, error (wrong manager)
            m_errorMap.insert(i, QContactManager::DoesNotExistError);
        } else {
            newContactIndices.append(i);
        }
    }

    if (!existingContactIds.isEmpty()) {
        // Now do the fetch and wait for the result in handleFinishedSubRequest
        QContactFetchByIdRequest* cfbir = new QContactFetchByIdRequest;
        cfbir->setLocalIds(existingContactIds);
        // normally, you'd set the manager, but in this case, we only have a bare engine:
        QContactManagerEngineV2Wrapper::setEngineOfRequest(cfbir, m_v2wrapper);
        m_currentSubRequest.reset(cfbir);
        connect(cfbir, SIGNAL(stateChanged(QContactAbstractRequest::State)),
                this, SLOT(handleUpdatedSubRequest(QContactAbstractRequest::State)),
                Qt::QueuedConnection);
        return cfbir->start();
    } else {
        // Special case for the case where every contact is new - we don't need to bother fetching
        // any existing contacts - just prune them down to the mask and do the save request.
        QList<QContact> contactsToSave;
        QSet<QString> mask(request()->definitionMask().toSet());
        for (int i = 0; i < newContactIndices.count(); i++) {
            QContact contactToSave;
            partiallyCopyDetails(&contactToSave, contacts[newContactIndices[i]], mask);
            m_savedToOriginalMap.append(i);
            contactsToSave.append(contactToSave);
        }
        QContactSaveRequest* csr = new QContactSaveRequest;
        csr->setContacts(contactsToSave);
        // normally, you'd set the manager, but in this case, we only have a bare engine:
        QContactManagerEngineV2Wrapper::setEngineOfRequest(csr, m_engine);
        m_currentSubRequest.reset(csr);
        connect(csr, SIGNAL(stateChanged(QContactAbstractRequest::State)),
                this, SLOT(handleUpdatedSubRequest(QContactAbstractRequest::State)),
                Qt::QueuedConnection);
        return csr->start();
    }
}

/* One of our subrequests has finished.  Go to the next step. */
void PartialSaveRequestController::handleFinishedSubRequest(QContactAbstractRequest* subReq)
{
    if (subReq->type() == QContactAbstractRequest::ContactFetchByIdRequest) {
        QContactFetchByIdRequest* cfbir = qobject_cast<QContactFetchByIdRequest*>(subReq);
        QList<QContact> contactsToSave;
        QMap<int, QContactManager::Error> fetchErrors(cfbir->errorMap());
        QList<QContact> existingContacts(cfbir->contacts());
        QList<QContact> contacts(request()->contacts());
        QSet<QString> mask(request()->definitionMask().toSet());
        for (int i = 0; i < contacts.count(); i++) {
            // See if this is an existing contact or a new one
            const int fetchedIdx = m_existingIdMap.value(i, -1);
            QContact contactToSave;
            if (fetchedIdx >= 0) {
                // See if we had an error
                if (fetchErrors[fetchedIdx] != QContactManager::NoError) {
                    m_errorMap.insert(i, fetchErrors[fetchedIdx]);
                    continue;
                }

                // Existing contact we should have fetched
                contactToSave = existingContacts.at(fetchedIdx);

                QSharedDataPointer<QContactData>& cd = QContactData::contactData(contactToSave);
                cd->removeOnly(mask);
            } else if (m_errorMap.contains(i)) {
                // A bad argument.  Leave it out of the contactsToSave list
                continue;
            } // else new contact

            partiallyCopyDetails(&contactToSave, contacts.at(i), mask);
            m_savedToOriginalMap.append(i);
            contactsToSave.append(contactToSave);
        }

        // Now do the fetch and wait for the result
        QContactSaveRequest* csr = new QContactSaveRequest;
        csr->setContacts(contactsToSave);
        // normally, you'd set the manager, but in this case, we only have a bare engine:
        QContactManagerEngineV2Wrapper::setEngineOfRequest(csr, m_engine);
        m_currentSubRequest.reset(csr);
        connect(csr, SIGNAL(stateChanged(QContactAbstractRequest::State)),
                this, SLOT(handleUpdatedSubRequest(QContactAbstractRequest::State)),
                Qt::QueuedConnection);
        csr->start(); // TODO what if this fails?
    } else if (subReq->type() == QContactAbstractRequest::ContactSaveRequest) {
        QContactSaveRequest* csr = qobject_cast<QContactSaveRequest*>(subReq);
        QList<QContact> savedContacts(csr->contacts());
        QMap<int, QContactManager::Error> saveErrors(csr->errorMap());
        QList<QContact> contacts(request()->contacts());
        for (int i = 0; i < savedContacts.count(); i++) {
            contacts[m_savedToOriginalMap[i]].setId(savedContacts[i].id());
        }
        // Populate the m_errorMap with the m_errorMap of the attempted save
        QMap<int, QContactManager::Error>::ConstIterator it(saveErrors.constBegin());
        while (it != saveErrors.constEnd()) {
            m_errorMap.insert(m_savedToOriginalMap[it.key()], it.value());
            it++;
        }
        // Get last error (m_errorMap being a QMap is sorted by index, so just pick it)
        QContactManager::Error error = QContactManager::NoError;
        it = m_errorMap.constEnd();
        if (it != m_errorMap.constBegin()) {
            --it;
            error = it.value();
        }

        // Update the request object
        QContactManagerEngine::updateContactSaveRequest(
                request(),
                contacts,
                error,
                m_errorMap,
                QContactAbstractRequest::FinishedState);
        finish();
    } else {
        Q_ASSERT(false);
    }
}

/* Copy details specified in \a mask from contact \a from to contact \a to */
void PartialSaveRequestController::partiallyCopyDetails(QContact* to, const QContact& from,
                                                        const QSet<QString>& mask) {
    // Perhaps this could do this directly rather than through saveDetail
    // but that would duplicate the checks for display label etc
    foreach (const QString& name, mask) {
        QList<QContactDetail> details = from.details(name);
        foreach(QContactDetail detail, details) {
            to->saveDetail(&detail);
        }
    }
}