summaryrefslogtreecommitdiffstats
path: root/src/libraries/qmfclient/qmailthreadlistmodel.cpp
blob: 193ee0d10783845b240f79f8d42a6d3833d56baf (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
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt Messaging Framework.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qmailthreadlistmodel.h"
#include "qmailstore.h"
#include "qmailthread.h"
#include <QCache>

class LessThanFunctorT
{
public:
    LessThanFunctorT(const QMailThreadSortKey& sortKey);
    ~LessThanFunctorT();

    bool operator()(const QMailThreadId& first, const QMailThreadId& second);
    bool invalidatedList() const;

private:
    QMailThreadSortKey mSortKey;
    bool mInvalidatedList;
};

LessThanFunctorT::LessThanFunctorT(const QMailThreadSortKey& sortKey)
:
    mSortKey(sortKey),
    mInvalidatedList(false)
{
}

LessThanFunctorT::~LessThanFunctorT(){}

bool LessThanFunctorT::operator()(const QMailThreadId& first, const QMailThreadId& second)
{
    QMailThreadKey firstKey(QMailThreadKey::id(first));
    QMailThreadKey secondKey(QMailThreadKey::id(second));

    QMailThreadIdList results = QMailStore::instance()->queryThreads(firstKey | secondKey, mSortKey);
    if(results.count() != 2)
    {
        mInvalidatedList = true;
        return false;
    }
    return results.first() == first;
}

bool LessThanFunctorT::invalidatedList() const
{
    return mInvalidatedList;
}


class QMailThreadListModelPrivate
{
public:
    QMailThreadListModelPrivate(const QMailThreadKey& key,
                                const QMailThreadSortKey& sortKey,
                                bool synchronizeEnabled);
    ~QMailThreadListModelPrivate();

    void initialize() const;
    const QMailThreadIdList& ids() const;

    int indexOf(const QMailThreadId& id) const;

    template<typename Comparator>
    QMailThreadIdList::iterator lowerBound(const QMailThreadId& id, Comparator& cmp) const;

public:
    QMailThreadKey key;
    QMailThreadSortKey sortKey;
    bool synchronizeEnabled;
    mutable QMailThreadIdList idList;
    mutable QMailThreadId deletionId;
    mutable bool init;
    mutable bool needSynchronize;
};

QMailThreadListModelPrivate::QMailThreadListModelPrivate(const QMailThreadKey& key,
                                                         const QMailThreadSortKey& sortKey,
                                                         bool synchronizeEnabled)
:
    key(key),
    sortKey(sortKey),
    synchronizeEnabled(synchronizeEnabled),
    init(false),
    needSynchronize(true)
{
}

QMailThreadListModelPrivate::~QMailThreadListModelPrivate()
{
}

void QMailThreadListModelPrivate::initialize() const
{
    idList = QMailStore::instance()->queryThreads(key,sortKey);
    init = true;
    needSynchronize = false;
}

const QMailThreadIdList& QMailThreadListModelPrivate::ids() const
{
    if (!init) {
        initialize();
    }

    return idList;
}

int QMailThreadListModelPrivate::indexOf(const QMailThreadId& id) const
{
    return ids().indexOf(id);
}

template<typename Comparator>
QMailThreadIdList::iterator QMailThreadListModelPrivate::lowerBound(const QMailThreadId& id, Comparator& cmp) const
{
    return qLowerBound(idList.begin(), idList.end(), id, cmp);
}


/*!
  \class QMailThreadListModel

  \preliminary
  \ingroup messaginglibrary
  \brief The QMailThreadListModel class provides access to a list of stored threads.

  The QMailThreadListModel presents a list of all the threads currently stored in
  the message store. By using the setKey() and sortKey() functions it is possible to have the model
  represent specific user filtered subsets of threads sorted in a particular order.

  The QMailThreadListModel is a descendant of QAbstractListModel, so it is suitable for use with
  the Qt View classes such as QListView to visually represent lists of threads.

  The model listens for changes to the underlying storage system and sychronizes its contents based on
  the setSynchronizeEnabled() setting.

  Threads can be extracted from the view with the idFromIndex() function and the resultant id can be
  used to load a thread from the store.

  For filters or sorting not provided by the QMailThreadListModel it is recommended that
  QSortFilterProxyModel is used to wrap the model to provide custom sorting and filtering.

  \sa QMailThread, QSortFilterProxyModel
*/

/*!
  \enum QMailThreadListModel::Roles

  Represents common display roles of a thread. These roles are used to display common thread elements
  in a view and its attached delegates.

  \value ThreadSubjectRole The subject of the thread
  \value ThreadPreviewRole The preview of the thread
  \value ThreadUnreadCountRole The unread count of the thread
  \value ThreadMessageCountRole The message count of the thread
  \value ThreadSendersRole The senders of the thread
  \value ThreadLastDateRole The last date of the thread
  \value ThreadStartedDateRole The start date of the thread
  \value ThreadIdRole The id of the thread
*/

/*!
    Constructs a QMailThreadListModel with a parent \a parent.
    By default, the model will match all threads in the database, and display them in
    the order they were submitted. Synchronization defaults to true.
*/

QMailThreadListModel::QMailThreadListModel(QObject* parent)
:
    QAbstractListModel(parent),
    d(new QMailThreadListModelPrivate(QMailThreadKey(),QMailThreadSortKey(),true))
{
    connect(QMailStore::instance(),
            SIGNAL(threadsAdded(QMailThreadIdList)),
            this,
            SLOT(threadsAdded(QMailThreadIdList)));
    connect(QMailStore::instance(),
            SIGNAL(threadsRemoved(QMailThreadIdList)),
            this,
            SLOT(threadsRemoved(QMailThreadIdList)));
    connect(QMailStore::instance(),
            SIGNAL(threadsUpdated(QMailThreadIdList)),
            this,
            SLOT(threadsUpdated(QMailThreadIdList)));
}

/*!
    Deletes the QMailThreadListModel object.
*/

QMailThreadListModel::~QMailThreadListModel()
{
    delete d; d = 0;
}

/*!
    \reimp
*/

int QMailThreadListModel::rowCount(const QModelIndex& index) const
{
    Q_UNUSED(index);
    return d->ids().count();
}

/*!
    \reimp
*/

QVariant QMailThreadListModel::data(const QModelIndex& index, int role) const
{
    if(!index.isValid())
        return QVariant();

    int offset = index.row();
    QMailThreadId id = d->ids().at(offset);
    if (id == d->deletionId)
        return QVariant();

    QMailThread thread(id);

    switch(role)
    {
    case Qt::DisplayRole:
        return thread.subject();
    case ThreadIdRole:
        return thread.id();
    case ThreadSubjectTextRole:
        return thread.subject();
    case ThreadPreviewTextRole:
        return thread.preview();
    case ThreadUnreadCountRole:
        return thread.unreadCount();
    case ThreadMessageCountRole:
        return thread.messageCount();
    case ThreadSendersRole:
    {
        QStringList senders;
        foreach (const QMailAddress& address, thread.senders()) {
            senders << address.name();
        }
        return senders.join(", ");
    }
    case ThreadLastDateRole:
        return thread.lastDate().toLocalTime();
    case ThreadStartedDateRole:
        return thread.startedDate().toLocalTime();
    }

    return QVariant();
}

/*!
    Returns the QMailThreadKey used to populate the contents of this model.
*/

QMailThreadKey QMailThreadListModel::key() const
{
    return d->key;
}

/*!
    Sets the QMailThreadKey used to populate the contents of the model to \a key.
    If the key is empty, the model is populated with all the threads from the
    database.
*/

void QMailThreadListModel::setKey(const QMailThreadKey& key)
{
    beginResetModel();
    d->key = key;
    d->init = false;
    endResetModel();
}

/*!
    Returns the QMailThreadSortKey used to sort the contents of the model.
*/

QMailThreadSortKey QMailThreadListModel::sortKey() const
{
   return d->sortKey;
}

/*!
    Sets the QMailThreadSortKey used to sort the contents of the model to \a sortKey.
    If the sort key is invalid, no sorting is applied to the model contents and threads
    are displayed in the order in which they were added into the database.
*/

void QMailThreadListModel::setSortKey(const QMailThreadSortKey& sortKey)
{
    beginResetModel();
    d->sortKey = sortKey;
    d->init = false;
    endResetModel();
}

/*! \internal */

void QMailThreadListModel::threadsAdded(const QMailThreadIdList& ids)
{
    d->needSynchronize = true;
    if(!d->synchronizeEnabled)
        return;

    //TODO change this code to use our own searching and insertion routines
    //for more control
    //use id sorted indexes

    if(!d->init)
        d->initialize();

    QMailThreadKey passKey = d->key & QMailThreadKey::id(ids);
    QMailThreadIdList results = QMailStore::instance()->queryThreads(passKey);
    if(results.isEmpty())
        return;

    if(!d->sortKey.isEmpty())
    {
        foreach(const QMailThreadId &id,results)
        {
            LessThanFunctorT lessThan(d->sortKey);

            //if sorting the list fails, then resort to a complete refresh
            if(lessThan.invalidatedList())
                fullRefresh();
            else
            {
                QMailThreadIdList::iterator itr = d->lowerBound(id, lessThan);
                int newIndex = (itr - d->idList.begin());

                beginInsertRows(QModelIndex(),newIndex,newIndex);
                d->idList.insert(itr, id);
                endInsertRows();
            }
        }
    }
    else
    {
        int index = d->idList.count();

        beginInsertRows(QModelIndex(),index,(index + results.count() - 1));
        foreach(const QMailThreadId &id,results)
            d->idList.append(id);
        endInsertRows();
    }
    d->needSynchronize = false;
}

/*! \internal */

void QMailThreadListModel::threadsUpdated(const QMailThreadIdList& ids)
{
    d->needSynchronize = true;
    if(!d->synchronizeEnabled)
        return;

    //TODO change this code to use our own searching and insertion routines
    //for more control
    //use id sorted indexes

    if(!d->init)
        d->initialize();

    QMailThreadKey idKey(QMailThreadKey::id(ids));

    QMailThreadIdList validIds = QMailStore::instance()->queryThreads(idKey & d->key);

    //if the key is empty the id's will be returned valid and invalid
    if(!d->key.isEmpty())
    {
        QMailThreadIdList invalidIds = QMailStore::instance()->queryThreads(idKey & ~d->key);
        foreach(const QMailThreadId &id,invalidIds)
        {
            //get the index
            int index = d->idList.indexOf(id);
            if (index == -1)
                continue;

            d->deletionId = id;
            beginRemoveRows(QModelIndex(),index,index);
            d->idList.removeAt(index);
            endRemoveRows();
            d->deletionId = QMailThreadId();
        }
    }

    LessThanFunctorT lessThan(d->sortKey);

    foreach(const QMailThreadId &id, validIds)
    {
        int index = d->idList.indexOf(id);
        if(index == -1) //insert
        {
            if(lessThan.invalidatedList())
                fullRefresh();
            else
            {
                QMailThreadIdList::iterator itr = d->lowerBound(id, lessThan);
                int newIndex = (itr - d->idList.begin());

                beginInsertRows(QModelIndex(),newIndex,newIndex);
                d->idList.insert(itr, id);
                endInsertRows();
            }
        }
        else //update
        {
            if(lessThan.invalidatedList())
                fullRefresh();
            else
            {
                QMailThreadIdList::iterator itr = d->lowerBound(id, lessThan);
                int newIndex = (itr - d->idList.begin());

                if((newIndex == index) || (newIndex == index + 1))
                {
                    // This item would be inserted either immediately before or after itself
                    QModelIndex modelIndex = createIndex(index,0);
                    emit dataChanged(modelIndex,modelIndex);
                }
                else
                {
                    d->deletionId = id;
                    beginRemoveRows(QModelIndex(),index,index);
                    d->idList.removeAt(index);
                    endRemoveRows();
                    d->deletionId = QMailThreadId();

                    if (newIndex > index)
                        --newIndex;

                    beginInsertRows(QModelIndex(),newIndex,newIndex);
                    d->idList.insert(newIndex, id);
                    endInsertRows();
                }
            }
        }
    }
    d->needSynchronize = false;
}

/*! \internal */

void QMailThreadListModel::threadsRemoved(const QMailThreadIdList& ids)
{
    d->needSynchronize = true;
    if(!d->synchronizeEnabled)
        return;

    if(!d->init)
        d->initialize();

    foreach(const QMailThreadId &id, ids)
    {
        int index = d->indexOf(id);
        if(index == -1)
            continue;

        d->deletionId = id;
        beginRemoveRows(QModelIndex(),index,index);
        d->idList.removeAt(index);
        endRemoveRows();
        d->deletionId = QMailThreadId();
    }
    d->needSynchronize = false;
}

/*!
    Returns the QMailThreadId of the thread represented by the QModelIndex \a index.
    If the index is not valid an invalid QMailThreadId is returned.
*/

QMailThreadId QMailThreadListModel::idFromIndex(const QModelIndex& index) const
{
    if(!index.isValid())
        return QMailThreadId();

    return d->ids().at(index.row());
}

/*!
    Returns the QModelIndex that represents the thread with QMailThreadId \a id.
    If the id is not conatained in this model, an invalid QModelIndex is returned.
*/

QModelIndex QMailThreadListModel::indexFromId(const QMailThreadId& id) const
{
    //if the id does not exist return null
    int index = d->indexOf(id);
    if(index != -1) {
        return createIndex(index,0);
    }

    return QModelIndex();
}

const QMailThreadIdList & QMailThreadListModel::ids() const
{
    return d->ids();
}

/*!
    Returns \c true if the model sychronizes its contents based on thread changes
    in the database, otherwise returns \c false.
*/

bool QMailThreadListModel::synchronizeEnabled() const
{
    return d->synchronizeEnabled;
}

/*!
    Sets wheather the model synchronizes its contents based on thread changes
    in the database to \a val.
*/

void QMailThreadListModel::setSynchronizeEnabled(bool val)
{
    d->synchronizeEnabled = val;
    if(val && d->needSynchronize)
        fullRefresh();
}

/*! \internal */

void QMailThreadListModel::fullRefresh()
{
    beginResetModel();
    d->init = false;
    endResetModel();
    emit modelChanged();
}