summaryrefslogtreecommitdiffstats
path: root/src/libraries/qmfclient/qmailmessagelistmodel.cpp
blob: 550e6e22891a7c0610a946f106905b0f387ed0d2 (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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
/****************************************************************************
**
** 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 "qmailmessagelistmodel.h"
#include "qmailnamespace.h"
#include "qmailstore.h"
#include <QtAlgorithms>


class QMailMessageListModelPrivate : public QMailMessageModelImplementation
{
public:
    QMailMessageListModelPrivate(QMailMessageListModel& model,
                                 const QMailMessageKey& key,
                                 const QMailMessageSortKey& sortKey,
                                 bool sychronizeEnabled);
    ~QMailMessageListModelPrivate();

    QMailMessageKey key() const;
    void setKey(const QMailMessageKey& key);

    QMailMessageSortKey sortKey() const;
    void setSortKey(const QMailMessageSortKey& sortKey);

    uint limit() const;
    void setLimit(uint limit);
    int totalCount() const;

    bool isEmpty() const;

    int rowCount(const QModelIndex& idx) const;
    int columnCount(const QModelIndex& idx) const;

    QMailMessageId idFromIndex(const QModelIndex& index) const;
    QModelIndex indexFromId(const QMailMessageId& id) const;

    Qt::CheckState checkState(const QModelIndex &idx) const;
    void setCheckState(const QModelIndex &idx, Qt::CheckState state);

    void reset();

    bool ignoreMailStoreUpdates() const;
    bool setIgnoreMailStoreUpdates(bool ignore);

    bool processMessagesAdded(const QMailMessageIdList &ids);
    bool processMessagesUpdated(const QMailMessageIdList &ids);
    bool processMessagesRemoved(const QMailMessageIdList &ids);

private:
    void init() const;
    
    int indexOf(const QMailMessageId& id) const;

    bool addMessages(const QMailMessageIdList &ids);
    bool appendMessages(const QMailMessageIdList &idsToAppend, const QMailMessageIdList &newIdsList);
    bool updateMessages(const QMailMessageIdList &ids);
    bool removeMessages(const QMailMessageIdList &ids);

    void insertItemAt(int row, const QModelIndex &parentIndex, const QMailMessageId &id);
    void removeItemAt(int row, const QModelIndex &parentIndex);

    QMailMessageListModel &_model;
    QMailMessageKey _key;
    QMailMessageSortKey _sortKey;
    bool _ignoreUpdates;
    mutable QList<QMailMessageId> _idList;
    mutable QMap<QMailMessageId, int> _itemIndex;
    mutable QSet<QMailMessageId> _checkedIds;
    mutable bool _initialised;
    mutable bool _needSynchronize;
    uint _limit;
};


QMailMessageListModelPrivate::QMailMessageListModelPrivate(QMailMessageListModel& model,
                                                           const QMailMessageKey& key,
                                                           const QMailMessageSortKey& sortKey,
                                                           bool ignoreUpdates)
:
    _model(model),
    _key(key),
    _sortKey(sortKey),
    _ignoreUpdates(ignoreUpdates),
    _initialised(false),
    _needSynchronize(true),
    _limit(0)
{
}

QMailMessageListModelPrivate::~QMailMessageListModelPrivate()
{
}

QMailMessageKey QMailMessageListModelPrivate::key() const
{
    return _key; 
}

void QMailMessageListModelPrivate::setKey(const QMailMessageKey& key) 
{
    _key = key;
}

QMailMessageSortKey QMailMessageListModelPrivate::sortKey() const
{
   return _sortKey;
}

void QMailMessageListModelPrivate::setSortKey(const QMailMessageSortKey& sortKey) 
{
    _sortKey = sortKey;
}

uint QMailMessageListModelPrivate::limit() const
{
   return _limit;
}

void QMailMessageListModelPrivate::setLimit(uint limit)
{
    if (_limit != limit) {
        if (limit == 0) {
            // Do full refresh
            _limit = limit;
            _model.fullRefresh(false);
        } else if (_limit > limit) {
            // Limit decreased, remove messages in excess
            _limit = limit;
            QMailMessageIdList idsToRemove = _idList.mid(limit);
            removeMessages(idsToRemove);
        } else {
            _limit = limit;
            QMailMessageIdList idsToAppend;
            QMailMessageIdList newIdsList(QMailStore::instance()->queryMessages(_key, _sortKey, _limit));

            foreach (const QMailMessageId &id, newIdsList) {
                if (!_idList.contains(id)) {
                    idsToAppend.append(id);
                }
            }
            appendMessages(idsToAppend, newIdsList);
        }
    }
}

int QMailMessageListModelPrivate::totalCount() const
{
    if (_limit) {
       return QMailStore::instance()->countMessages(_key);
    } else {
        init();
        return _idList.count();
    }
}

bool QMailMessageListModelPrivate::isEmpty() const
{
    init();

    return _idList.isEmpty();
}

int QMailMessageListModelPrivate::rowCount(const QModelIndex &idx) const
{
    init();

    if (idx.isValid()) {
        // We don't have a hierarchy in this model
        return 0;
    }

    return _idList.count();
}

int QMailMessageListModelPrivate::columnCount(const QModelIndex &idx) const
{
    Q_UNUSED(idx)

    init();

    return 1;
}

QMailMessageId QMailMessageListModelPrivate::idFromIndex(const QModelIndex& index) const
{
    init();

    if (index.isValid()) {
        int row = index.row();
        if ((row >= 0) && (row < _idList.count())) {
            return _idList.at(row);
        }
    }

    return QMailMessageId();
}

QModelIndex QMailMessageListModelPrivate::indexFromId(const QMailMessageId& id) const
{
    init();

    if (id.isValid()) {
        int row = indexOf(id);
        if (row != -1)
            return _model.generateIndex(row, 0, 0);
    }

    return QModelIndex();
}

Qt::CheckState QMailMessageListModelPrivate::checkState(const QModelIndex &idx) const
{
    if (idx.isValid()) {
        int row = idx.row();
        if ((row >= 0) && (row < _idList.count())) {
            return (_checkedIds.contains(_idList.at(row)) ? Qt::Checked : Qt::Unchecked);
        }
    }

    return Qt::Unchecked;
}

void QMailMessageListModelPrivate::setCheckState(const QModelIndex &idx, Qt::CheckState state)
{
    if (idx.isValid()) {
        int row = idx.row();
        if ((row >= 0) && (row < _idList.count())) {
            // No support for partial checking in this model...
            if (state == Qt::Checked) {
                _checkedIds.insert(_idList.at(row));
            } else {
                _checkedIds.remove(_idList.at(row));
            }
        }
    }
}

void QMailMessageListModelPrivate::reset()
{
    _initialised = false;
}

bool QMailMessageListModelPrivate::ignoreMailStoreUpdates() const
{
    return _ignoreUpdates;
}

bool QMailMessageListModelPrivate::setIgnoreMailStoreUpdates(bool ignore)
{
    _ignoreUpdates = ignore;
    return (!_ignoreUpdates && _needSynchronize);
}

bool QMailMessageListModelPrivate::processMessagesAdded(const QMailMessageIdList &ids)
{
    if (ids.empty()) {
        return true;
    }

    if (_ignoreUpdates) {
        // Defer until resynchronised
        _needSynchronize = true;
        return true;
    }

    if (_key.isNonMatching()) {
        // No messages are relevant
        return true;
    }

    init();

    // Find if and where these messages should be added
    if (!addMessages(ids)) {
        return false;
    }

    return true;
}

bool QMailMessageListModelPrivate::addMessages(const QMailMessageIdList &ids)
{
    // Are any of these messages members of our display set?
    // Note - we must only consider messages in the set given by (those we currently know +
    // those we have now been informed of) because the database content may have changed between
    // when this event was recorded and when we're processing the signal.

    QMailMessageKey idKey(QMailMessageKey::id(_idList + ids));
    const QMailMessageIdList newIdsList(QMailStore::instance()->queryMessages(_key & idKey, _sortKey, _limit));

    return appendMessages(ids, newIdsList);
}

bool QMailMessageListModelPrivate::appendMessages(const QMailMessageIdList &idsToAppend, const QMailMessageIdList &newIdsList)
{
    QList<int> insertIndices;
    QMap<QMailMessageId, int> newPositions;

    int index = 0;
    foreach (const QMailMessageId &id, newIdsList) {
        newPositions.insert(id, index);
        ++index;
    }

    QMap<int, QMailMessageId> indexId;
    foreach (const QMailMessageId &id, idsToAppend) {
        int newIndex = -1;
        QMap<QMailMessageId, int>::const_iterator it = newPositions.find(id);
        if (it != newPositions.end()) {
            newIndex = it.value();
        }

        int oldIndex(indexOf(id));
        if (oldIndex == -1) {
            // This message was not previously in our set - add it
            if (newIndex != -1) {
                insertIndices.append(newIndex);
                indexId.insert(newIndex, id);
            }
        }
    }

    std::sort(insertIndices.begin(), insertIndices.end());
    foreach (int index, insertIndices) {
        // Since the list is ordered, if index is bigger than the limit
        // we stop inserting
        if (_limit && index > (int)_limit) {
            break;
        }
        _model.emitBeginInsertRows(QModelIndex(), index, index);
        insertItemAt(index, QModelIndex(), indexId[index]);
        _model.emitEndInsertRows();
    }

    // Check if we passed the model limit, if so remove exceeding messages
    if (_limit && _idList.count() > (int)_limit) {
        QMailMessageIdList idsToRemove = _idList.mid(_limit);
        removeMessages(idsToRemove);
    }
    return true;
}

bool QMailMessageListModelPrivate::processMessagesUpdated(const QMailMessageIdList &ids)
{
    if (_ignoreUpdates) {
        // Defer until resynchronised
        _needSynchronize = true;
        return true;
    }

    if (_key.isNonMatching()) {
        // No messages are relevant
        return true;
    }

    init();

    // Find if and where these messages should be added/removed/updated
    if (!updateMessages(ids)) {
        return false;
    }
    
    return true;
}

bool QMailMessageListModelPrivate::updateMessages(const QMailMessageIdList &ids)
{
    QList<int> insertIndices;
    QList<int> removeIndices;
    QList<int> updateIndices;

    // Find the updated positions for our messages
    QMailMessageKey idKey(QMailMessageKey::id((_idList.toSet() + ids.toSet()).toList()));
    QMailMessageIdList newIds(QMailStore::instance()->queryMessages(_key & idKey, _sortKey, _limit));
    QMap<QMailMessageId, int> newPositions;

    int index = 0;
    foreach (const QMailMessageId &id, newIds) {
        newPositions.insert(id, index);
        ++index;
    }

    QMap<int, QMailMessageId> indexId;
    foreach (const QMailMessageId &id, ids) {
        int newIndex = -1;
        QMap<QMailMessageId, int>::const_iterator it = newPositions.find(id);
        if (it != newPositions.end()) {
            newIndex = it.value();
        }

        int oldIndex(indexOf(id));
        if (oldIndex == -1) {
            // This message was not previously in our set - add it
            if (newIndex != -1) {
                insertIndices.append(newIndex);
                indexId.insert(newIndex, id);
            }
        } else {
            // We already had this message
            if (newIndex == -1) {
                removeIndices.append(oldIndex);
            } else {
                bool reinsert(false);

                // See if this item is still sorted correctly with respect to its neighbours
                if (newIndex >= _idList.count()) {
                    qWarning() << "QMailMessageListModelPrivate::updateMessage index out of bounds" << newIndex << _idList.count();
                } else if (newIndex > 0) {
                    if (newIds.indexOf(_idList.at(newIndex - 1)) > newIndex) {
                        reinsert = true;
                    }
                }

                if (newIndex < _idList.count() - 1) {
                    if (newIds.indexOf(_idList.at(newIndex + 1)) < newIndex) {
                        reinsert = true;
                    }
                }

                if (reinsert) {
                    removeIndices.append(oldIndex);
                    insertIndices.append(newIndex);
                    indexId.insert(newIndex, id);
                } else {
                    // This message is updated but has not changed position
                    updateIndices.append(newIndex);
                }
            }
        }
    }

    // Sort the lists to yield ascending order
    std::sort(removeIndices.begin(), removeIndices.end());
    for (int i = removeIndices.count(); i > 0; --i) {
        int index = removeIndices[i - 1];
        _model.emitBeginRemoveRows(QModelIndex(), index, index);
        removeItemAt(index, QModelIndex());
        _model.emitEndRemoveRows();
    }

    std::sort(insertIndices.begin(), insertIndices.end());
    foreach (int index, insertIndices) {
        // Since the list is ordered, if index is bigger than the limit
        // we stop inserting
        if (_limit && index > (int)_limit) {
            break;
        }
        _model.emitBeginInsertRows(QModelIndex(), index, index);
        insertItemAt(index, QModelIndex(), indexId[index]);
        _model.emitEndInsertRows();
    }

    // Check if we passed the model limit, if so remove exceeding messages
    if (_limit && _idList.count() > (int)_limit) {
        QMailMessageIdList idsToRemove = _idList.mid(_limit);
        removeMessages(idsToRemove);
    }

    std::sort(updateIndices.begin(), updateIndices.end());
    foreach (int index, updateIndices) {
        _model.emitDataChanged(_model.index(index, 0, QModelIndex()), _model.index(index, _model.columnCount() - 1, QModelIndex()));
    }

    return true;
}

bool QMailMessageListModelPrivate::processMessagesRemoved(const QMailMessageIdList &ids)
{
    if (_ignoreUpdates) {
        // Defer until resynchronised
        _needSynchronize = true;
        return true;
    }

    if (_key.isNonMatching()) {
        // No messages are relevant
        return true;
    }

    init();
    
    // Find if and where these messages should be removed from
    if (!removeMessages(ids)) {
        return false;
    }

    return true;
}

bool QMailMessageListModelPrivate::removeMessages(const QMailMessageIdList &ids)
{
    QList<int> removeIndices;
    foreach (const QMailMessageId &id, ids) {
        int index(indexOf(id));
        if (index != -1) {
            removeIndices.append(index);
        }
    }
    
    // Sort the indices to yield ascending order (they must be deleted in descending order!)
    std::sort(removeIndices.begin(), removeIndices.end());

    for (int i = removeIndices.count(); i > 0; --i) {
        int index = removeIndices.at(i - 1);
        _model.emitBeginRemoveRows(QModelIndex(), index, index);
        removeItemAt(index, QModelIndex());
        _model.emitEndRemoveRows();
    }

    return true;
}

void QMailMessageListModelPrivate::insertItemAt(int row, const QModelIndex &parentIndex, const QMailMessageId &id)
{
    _idList.insert(row, id);
    _itemIndex.insert(id, row);

    // Adjust the indices for the items that have been moved
    QList<QMailMessageId>::iterator it = _idList.begin() + (row + 1), end = _idList.end();
    for ( ; it != end; ++it) {
        _itemIndex[*it] += 1;
    }

    Q_UNUSED(parentIndex)
}

void QMailMessageListModelPrivate::removeItemAt(int row, const QModelIndex &parentIndex)
{
    QMailMessageId id(_idList.at(row));
    _checkedIds.remove(id);
    _itemIndex.remove(id);
    _idList.removeAt(row);

    // Adjust the indices for the items that have been moved
    QList<QMailMessageId>::iterator it = _idList.begin() + row, end = _idList.end();
    for ( ; it != end; ++it) {
        _itemIndex[*it] -= 1;
    }

    Q_UNUSED(parentIndex)
}

void QMailMessageListModelPrivate::init() const
{
    if (!_initialised) {
        _idList.clear();
        _itemIndex.clear();
        _checkedIds.clear();

        int index = 0;
        _idList = QMailStore::instance()->queryMessages(_key, _sortKey, _limit);
        foreach (const QMailMessageId &id, _idList) {
            _itemIndex.insert(id, index);
            ++index;
        }

        _initialised = true;
        _needSynchronize = false;
    }
}

int QMailMessageListModelPrivate::indexOf(const QMailMessageId& id) const
{
    QMap<QMailMessageId, int>::const_iterator it = _itemIndex.find(id);
    if (it != _itemIndex.end()) {
        return it.value();
    }

    return -1;
}


/*!
    \class QMailMessageListModel 

    \preliminary
    \ingroup messaginglibrary 
    \brief The QMailMessageListModel class provides access to a list of stored messages. 

    The QMailMessageListModel presents a list of all the messages 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 messages sorted in a particular order.

    The QMailMessageListModel does not represent the hierarchical links between messages 
    implied by conversation threads.  The model flattens the structure of messages such
    that they can be presented as a one-dimensional list.
*/

/*!
    Constructs a QMailMessageListModel with a parent \a parent.

    By default, the model will not match any messages, display messages in
    the order they were submitted, and mail store updates are not ignored.

    \sa setKey(), setSortKey(), setIgnoreMailStoreUpdates()
*/
QMailMessageListModel::QMailMessageListModel(QObject* parent)
    : QMailMessageModelBase(parent),
      d(new QMailMessageListModelPrivate(*this, QMailMessageKey::nonMatchingKey(), QMailMessageSortKey::id(), false))
{
}

/*!
    Deletes the QMailMessageListModel object.
*/
QMailMessageListModel::~QMailMessageListModel()
{
    delete d; d = 0;
}

/*! \reimp */
QModelIndex QMailMessageListModel::index(int row, int column, const QModelIndex &parent) const
{
    return hasIndex(row, column, parent) ? createIndex(row, column) : QModelIndex();
}

/*! \reimp */
QModelIndex QMailMessageListModel::parent(const QModelIndex &idx) const
{
    Q_UNUSED(idx)

    return QModelIndex();
}

/*! \internal */
QModelIndex QMailMessageListModel::generateIndex(int row, int column, void *ptr)
{
    Q_UNUSED(ptr)

    return index(row, column, QModelIndex());
}

/*! \internal */
QMailMessageModelImplementation *QMailMessageListModel::impl()
{
    return d;
}

/*! \internal */
const QMailMessageModelImplementation *QMailMessageListModel::impl() const
{
    return d;
}