controller.cpp 18.1 KB
Newer Older
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
/*
  Copyright (C) 2014 Christian Mollekopf <mollekopf@kolabsys.com>

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License along
  with this program; if not, write to the Free Software Foundation, Inc.,
  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

  As a special exception, permission is given to link this program
  with any edition of Qt, and distribute the resulting executable,
  without including the source code for Qt in the source distribution.
*/
#include "controller.h"

#include <Akonadi/EntityTreeModel>
#include <Akonadi/EntityDisplayAttribute>
#include <Akonadi/CollectionModifyJob>
#include <Akonadi/CollectionFetchJob>
#include <Akonadi/CollectionFetchScope>
#include <Akonadi/AttributeFactory>
#include <KIcon>
#include <KCalCore/Event>
#include <KCalCore/Journal>
#include <KCalCore/Todo>
#include <baloo/pim/collectionquery.h>
#include <akonadi/collectionidentificationattribute.h>

CollectionNode::CollectionNode(ReparentingModel& personModel, const Akonadi::Collection& col)
:   Node(personModel),
    mCollection(col),
    mCheckState(Qt::Unchecked)
{
}

CollectionNode::~CollectionNode()
{

}

bool CollectionNode::operator==(const ReparentingModel::Node &node) const
{
    const CollectionNode *collectionNode = dynamic_cast<const CollectionNode*>(&node);
    if (collectionNode) {
        return (collectionNode->mCollection == mCollection);
    }
    return false;
}

QVariant CollectionNode::data(int role) const
{
    if (role == Qt::DisplayRole) {
        QStringList path;
        Akonadi::Collection c = mCollection;
        while (c.isValid()) {
            path.prepend(c.name());
            c = c.parentCollection();
        }
        return path.join(QLatin1String("/"));
    }
    if (role == Qt::DecorationRole) {
        if (mCollection.hasAttribute<Akonadi::EntityDisplayAttribute>()) {
            return mCollection.attribute<Akonadi::EntityDisplayAttribute>()->icon();
        }
        return QVariant();
    }
    if (role == Qt::CheckStateRole) {
        return mCheckState;
    }
    if (role == Qt::ToolTipRole) {
        return QString(QLatin1String("Collection: ") + mCollection.name() + QString::number(mCollection.id()));
    }
    return QVariant();
}

bool CollectionNode::setData(const QVariant& value, int role)
{
    if (role == Qt::CheckStateRole) {
        mCheckState = static_cast<Qt::CheckState>(value.toInt());
        emitter.emitEnabled(mCheckState == Qt::Checked, mCollection);
        return true;
    }
    return false;
}

bool CollectionNode::isDuplicateOf(const QModelIndex& sourceIndex)
{
    return (sourceIndex.data(Akonadi::EntityTreeModel::CollectionIdRole).value<Akonadi::Collection::Id>() == mCollection.id());
}


PersonNode::PersonNode(ReparentingModel& personModel, const Person& person)
:   Node(personModel),
    mPerson(person),
    mCheckState(Qt::Unchecked)
{

}

PersonNode::~PersonNode()
{

}

bool PersonNode::operator==(const Node &node) const
{
    const PersonNode *personNode = dynamic_cast<const PersonNode*>(&node);
    if (personNode) {
        return (personNode->mPerson.name == mPerson.name);
    }
    return false;
}

void PersonNode::setChecked(bool enabled)
{
    if (enabled) {
        mCheckState = Qt::Checked;
    } else {
        mCheckState = Qt::Unchecked;
    }
}

QVariant PersonNode::data(int role) const
{
    if (role == Qt::DisplayRole) {
        return mPerson.name;
    }
    if (role == Qt::DecorationRole) {
        return KIcon(QLatin1String("meeting-participant"));
    }
    if (role == Qt::CheckStateRole) {
        return mCheckState;
    }
    if (role == Qt::ToolTipRole) {
        return QString(QLatin1String("Person: ") + mPerson.name);
    }
    if (role == PersonRole) {
        return QVariant::fromValue(mPerson);
    }
    return QVariant();
}

bool PersonNode::setData(const QVariant& value, int role)
{
    if (role == Qt::CheckStateRole) {
        mCheckState = static_cast<Qt::CheckState>(value.toInt());
        emitter.emitEnabled(mCheckState == Qt::Checked, mPerson);
        return true;
    }
    return false;
}

bool PersonNode::adopts(const QModelIndex& sourceIndex)
{
    const Akonadi::Collection &parent = sourceIndex.data(Akonadi::EntityTreeModel::ParentCollectionRole).value<Akonadi::Collection>();
    if (parent.id() == mPerson.rootCollection) {
        return true;
    }

    const Akonadi::Collection &col = sourceIndex.data(Akonadi::EntityTreeModel::CollectionRole).value<Akonadi::Collection>();
    // kDebug() << col.displayName();
    //FIXME: we need a way to compare the path we get from LDAP to the folder in akonadi.
    //TODO: get it from the folder attribute
    if ((col.isValid() && mPerson.folderPaths.contains(col.displayName())) || mPerson.collections.contains(col.id())) {
        // kDebug() << "reparenting " << col.displayName() << " to " << mPerson.name;
        return true;
    }
    return false;
}

bool PersonNode::isDuplicateOf(const QModelIndex& sourceIndex)
{
    return (sourceIndex.data(PersonRole).value<Person>().name == mPerson.name);
}

void PersonNodeManager::checkSourceIndex(const QModelIndex &sourceIndex)
{
    const Akonadi::Collection col = sourceIndex.data(Akonadi::EntityTreeModel::CollectionRole).value<Akonadi::Collection>();
    kDebug() << col.displayName() << col.enabled();
    if (col.isValid()) {
        CollectionIdentificationAttribute *attr = col.attribute<CollectionIdentificationAttribute>();
        if (attr && attr->collectionNamespace() == "usertoplevel") {
            kDebug() << "Found user folder, creating person node";
            Person person;
            person.name = col.displayName();
            person.rootCollection = col.id();

            model.addNode(ReparentingModel::Node::Ptr(new PersonNode(model, person)));
        }
    }
}

CollectionSearchJob::CollectionSearchJob(const QString& searchString, QObject* parent)
    : KJob(parent),
    mSearchString(searchString)
{
}

void CollectionSearchJob::start()
{
    Baloo::PIM::CollectionQuery query;
    //We exclude the other users namespace
    query.setNamespace(QStringList() << QLatin1String("shared") << QLatin1String(""));
    query.pathMatches(mSearchString);
    query.setMimetype(QStringList() << QLatin1String("text/calendar"));
    query.setLimit(200);
    Baloo::PIM::ResultIterator it = query.exec();
    Akonadi::Collection::List collections;
    while (it.next()) {
        collections << Akonadi::Collection(it.id());
    }
    kDebug() << "Found collections " << collections.size();
    
    if (collections.isEmpty()) {
        //We didn't find anything
        emitResult();
        return;
    }

    Akonadi::CollectionFetchJob *fetchJob = new Akonadi::CollectionFetchJob(collections, Akonadi::CollectionFetchJob::Base, this);
    fetchJob->fetchScope().setAncestorRetrieval(Akonadi::CollectionFetchScope::All);
    fetchJob->fetchScope().setListFilter(Akonadi::CollectionFetchScope::NoFilter);
    connect(fetchJob, SIGNAL(collectionsReceived(Akonadi::Collection::List)), this, SLOT(onCollectionsReceived(Akonadi::Collection::List)));
    connect(fetchJob, SIGNAL(result(KJob*)), this, SLOT(onCollectionsFetched(KJob*)));
}

void CollectionSearchJob::onCollectionsReceived(const Akonadi::Collection::List &list)
{
    Q_FOREACH(const Akonadi::Collection &col, list) {
        if (col.name().contains(mSearchString)) {
            mMatchingCollections << col;
            Akonadi::Collection ancestor = col.parentCollection();
            while (ancestor.isValid() && (ancestor != Akonadi::Collection::root())) {
                if (!mAncestors.contains(ancestor)) {
                    mAncestors << ancestor;
                }
                ancestor = ancestor.parentCollection();
            }
        }
    }
}

void CollectionSearchJob::onCollectionsFetched(KJob *job)
{
    if (job->error()) {
        kWarning() << job->errorString();
    }
    if (!mAncestors.isEmpty()) {
        Akonadi::CollectionFetchJob *fetchJob = new Akonadi::CollectionFetchJob(mAncestors, Akonadi::CollectionFetchJob::Base, this);
        fetchJob->fetchScope().setListFilter(Akonadi::CollectionFetchScope::NoFilter);
        connect(fetchJob, SIGNAL(result(KJob*)), this, SLOT(onAncestorsFetched(KJob*)));
    } else {
        //We didn't find anything
        emitResult();
    }
}

static Akonadi::Collection replaceParent(Akonadi::Collection col, const Akonadi::Collection::List &ancestors)
{
    if (!col.isValid()) {
        return col;
    }
    const Akonadi::Collection parent = replaceParent(col.parentCollection(), ancestors);
    Q_FOREACH (const Akonadi::Collection &c, ancestors) {
        if (col == c) {
            col = c;
        }
    }
    col.setParentCollection(parent);
    return col;
}

void CollectionSearchJob::onAncestorsFetched(KJob *job)
{
    if (job->error()) {
        kWarning() << job->errorString();
    }
    Akonadi::CollectionFetchJob *fetchJob = static_cast<Akonadi::CollectionFetchJob*>(job);
    Akonadi::Collection::List matchingCollections;
    Q_FOREACH (const Akonadi::Collection &c, mMatchingCollections) {
        //We need to replace the parents with the version that contains the name, so we can display it accordingly
        matchingCollections << replaceParent(c, fetchJob->collections());
    }
    mMatchingCollections = matchingCollections;
    emitResult();
}

Akonadi::Collection::List CollectionSearchJob::matchingCollections() const
{
    return mMatchingCollections;
}


PersonSearchJob::PersonSearchJob(const QString& searchString, QObject* parent)
    : KJob(parent),
    mSearchString(searchString)
{
}

void PersonSearchJob::start()
{
    Baloo::PIM::CollectionQuery query;
    query.setNamespace(QStringList() << QLatin1String("usertoplevel"));
    query.nameMatches(mSearchString);
    query.setLimit(200);
    Baloo::PIM::ResultIterator it = query.exec();
    Akonadi::Collection::List collections;
    while (it.next()) {
        collections << Akonadi::Collection(it.id());
    }
    kDebug() << "Found persons " << collections.size();

    if (collections.isEmpty()) {
        //We didn't find anything
        emitResult();
        return;
    }

    Akonadi::CollectionFetchJob *fetchJob = new Akonadi::CollectionFetchJob(collections, Akonadi::CollectionFetchJob::Base, this);
    fetchJob->fetchScope().setAncestorRetrieval(Akonadi::CollectionFetchScope::All);
    fetchJob->fetchScope().setListFilter(Akonadi::CollectionFetchScope::NoFilter);
    connect(fetchJob, SIGNAL(collectionsReceived(Akonadi::Collection::List)), this, SLOT(onCollectionsReceived(Akonadi::Collection::List)));
    connect(fetchJob, SIGNAL(result(KJob*)), this, SLOT(onCollectionsFetched(KJob*)));
    //TODO query ldap for available persons and their folders.
    //TODO identify imap folders as person folders and list them here (after indexing them in baloo).
    //
    //The IMAP resource should add a "Person" attribute to the collections in the person namespace,
    //the ldap query can then be used to update the name (entitydisplayattribute) for the person.
}

void PersonSearchJob::onCollectionsReceived(const Akonadi::Collection::List &list)
{
    Q_FOREACH(const Akonadi::Collection &col, list) {
        Person person;
        person.name = col.displayName();
        person.rootCollection = col.id();
        mMatches << person;
    }
}

void PersonSearchJob::onCollectionsFetched(KJob *job)
{
    if (job->error()) {
        kWarning() << job->errorString();
    }
    emitResult();
}

QList<Person> PersonSearchJob::matches() const
{
    return mMatches;
}


Controller::Controller(ReparentingModel* personModel, ReparentingModel* searchModel, QObject* parent)
    : QObject(parent),
    mPersonModel(personModel),
    mSearchModel(searchModel),
    mCollectionSearchJob(0),
    mPersonSearchJob(0)
{
    Akonadi::AttributeFactory::registerAttribute<CollectionIdentificationAttribute>();
}

void Controller::setSearchString(const QString &searchString)
{
    if (mCollectionSearchJob) {
        disconnect(mCollectionSearchJob, 0, this, 0);
        mCollectionSearchJob->kill(KJob::Quietly);
        mCollectionSearchJob = 0;
    }
    if (mPersonSearchJob) {
        disconnect(mPersonSearchJob, 0, this, 0);
        mPersonSearchJob->kill(KJob::Quietly);
        mPersonSearchJob = 0;
    }
    //TODO: Delay and abort when results are found
    mSearchModel->clear();
    emit searchIsActive(!searchString.isEmpty());
    if (searchString.size() < 2) {
        return;
    }

    mPersonSearchJob = new PersonSearchJob(searchString, this);
    connect(mPersonSearchJob, SIGNAL(result(KJob*)), this, SLOT(onPersonsFound(KJob*)));
    mPersonSearchJob->start();

    mCollectionSearchJob = new CollectionSearchJob(searchString, this);
    connect(mCollectionSearchJob, SIGNAL(result(KJob*)), this, SLOT(onCollectionsFound(KJob*)));
    mCollectionSearchJob->start();
}

void Controller::onPersonEnabled(bool enabled, const Person& person)
{
    // kDebug() << person.name << enabled;
    if (enabled) {
        PersonNode *personNode = new PersonNode(*mPersonModel, person);
        personNode->setChecked(true);
        mPersonModel->addNode(ReparentingModel::Node::Ptr(personNode));
        Akonadi::Collection rootCollection(person.rootCollection);
        if (rootCollection.isValid()) {
            //Reference the persons collections if available
411
            //We have to include all mimetypes since mimetypes are not available yet (they will be synced once the collectoins are referenced)
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
            Akonadi::CollectionFetchJob *fetchJob = new Akonadi::CollectionFetchJob(rootCollection, Akonadi::CollectionFetchJob::Recursive, this);
            fetchJob->setProperty("enable", enabled);
            fetchJob->fetchScope().setListFilter(Akonadi::CollectionFetchScope::NoFilter);
            connect(fetchJob, SIGNAL(result(KJob*)), this, SLOT(onPersonCollectionsFetched(KJob*)));
        }
    } else {
        //If we accidentally added a person and want to remove it again
        mPersonModel->removeNode(PersonNode(*mPersonModel, person));
        //Dereference subcollections
    }

}

void Controller::onPersonCollectionsFetched(KJob* job)
{
    if (job->error()) {
        kWarning() << "Failed to fetch collections " << job->errorString();
        return;
    }
    const bool enable = job->property("enable").toBool();
    Q_FOREACH(const Akonadi::Collection &col, static_cast<Akonadi::CollectionFetchJob*>(job)->collections()) {
        setCollectionReferenced(enable, col);
    }
}

void Controller::onCollectionsFound(KJob* job)
{
    if (job->error()) {
        kWarning() << job->errorString();
        mCollectionSearchJob = 0;
        return;
    }
    Q_ASSERT(mCollectionSearchJob == static_cast<CollectionSearchJob*>(job));
    Q_FOREACH(const Akonadi::Collection &col, mCollectionSearchJob->matchingCollections()) {
        CollectionNode *collectionNode = new CollectionNode(*mSearchModel, col);
        //toggled by the checkbox, results in collection getting monitored
        connect(&collectionNode->emitter, SIGNAL(enabled(bool, Akonadi::Collection)), this, SLOT(onCollectionEnabled(bool, Akonadi::Collection)));
        mSearchModel->addNode(ReparentingModel::Node::Ptr(collectionNode));
    }
    mCollectionSearchJob = 0;
}

void Controller::onPersonsFound(KJob* job)
{
    if (job->error()) {
        kWarning() << job->errorString();
        mPersonSearchJob = 0;
        return;
    }
    Q_ASSERT(mPersonSearchJob == static_cast<PersonSearchJob*>(job));
    Q_FOREACH(const Person &p, mPersonSearchJob->matches()) {
        PersonNode *personNode = new PersonNode(*mSearchModel, p);
        //toggled by the checkbox, results in person getting added to main model
        connect(&personNode->emitter, SIGNAL(enabled(bool, Person)), this, SLOT(onPersonEnabled(bool, Person)));
        mSearchModel->addNode(ReparentingModel::Node::Ptr(personNode));
    }
    mPersonSearchJob = 0;
}

static Akonadi::EntityTreeModel *findEtm(QAbstractItemModel *model)
{
    QAbstractProxyModel *proxyModel;
    while (model) {
        proxyModel = qobject_cast<QAbstractProxyModel*>(model);
        if (proxyModel && proxyModel->sourceModel()) {
            model = proxyModel->sourceModel();
        } else {
            break;
        }
    }
    return qobject_cast<Akonadi::EntityTreeModel*>(model);
}

void Controller::setCollectionReferenced(bool enabled, const Akonadi::Collection& collection)
{
    kDebug() << collection.displayName() << "do reference " << enabled;
    kDebug() << "current " << collection.referenced();
    Akonadi::EntityTreeModel *etm = findEtm(mPersonModel);
    Q_ASSERT(etm);
    etm->setCollectionReferenced(collection, enabled);
}

void Controller::setCollectionEnabled(bool enabled, const Akonadi::Collection& collection)
{
    kDebug() << collection.displayName() << "do enable " << enabled;
    kDebug() << "current " << collection.enabled();

    Akonadi::Collection modifiedCollection = collection;
    modifiedCollection.setShouldList(Akonadi::Collection::ListDisplay, enabled);
    new Akonadi::CollectionModifyJob(modifiedCollection);
}

void Controller::onCollectionEnabled(bool enabled, const Akonadi::Collection& collection)
{
    setCollectionReferenced(enabled, collection);
}

void Controller::setCollection(const Akonadi::Collection &collection, bool enabled, bool referenced)
{
    Akonadi::EntityTreeModel *etm = findEtm(mPersonModel);
    if (!etm) {
        kWarning() << "Couldn't find etm";
        return;
    }
    kDebug() << collection.displayName() << "do enable " << enabled;
    Akonadi::Collection modifiedCollection = collection;
    modifiedCollection.setShouldList(Akonadi::Collection::ListDisplay, enabled);
    //HACK: We have no way of getting to the correct session as used by the etm,
    //and two concurrent jobs end up overwriting the enabled state of each other.
    etm->setCollectionReferenced(modifiedCollection, referenced);
}

void Controller::setPersonDisabled(const Person &person)
{
    mPersonModel->removeNode(PersonNode(*mPersonModel, person));
}