model.cpp 190 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
/******************************************************************************
 *
 *  Copyright 2008 Szymon Tomasz Stefanek <pragma@kvirc.net>
 *
 *  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.
 *
 *******************************************************************************/

//
// This class is a rather huge monster. It's something that resembles a QAbstractItemModel
// (because it has to provide the interface for a QTreeView) but isn't entirely one
// (for optimization reasons). It basically manages a tree of items of two types:
// GroupHeaderItem and MessageItem. Be sure to read the docs for ViewItemJob.
//
// A huge credit here goes to Till Adam which seems to have written most
// (if not all) of the original KMail threading code. The KMHeaders implementation,
// the documentation and his clever ideas were my starting points and essential tools.
// This is why I'm adding his copyright entry (copied from headeritem.cpp) here even if
// he didn't write a byte in this file until now :)
//
//                                       Szymon Tomasz Stefanek, 03 Aug 2008 04:50 (am)
//
// This class contains ideas from:
//
//   kmheaders.cpp / kmheaders.h, headeritem.cpp / headeritem.h
//   Copyright: (c) 2004 Till Adam < adam at kde dot org >
//
#include <config-messagelist.h>
#include "core/model.h"
#include "core/model_p.h"
#include "core/view.h"
#include "core/filter.h"
#include "core/groupheaderitem.h"
#include "core/item_p.h"
#include "core/messageitem.h"
#include "core/modelinvariantrowmapper.h"
#include "core/storagemodelbase.h"
#include "core/theme.h"
#include "core/delegate.h"
#include "core/manager.h"
#include "core/messageitemsetmanager.h"
#include "messagelist_debug.h"

#include <item.h>
#include <Akonadi/KMime/MessageStatus>
#include <AkonadiCore/Item>
#include "MessageCore/StringUtil"

#include <KLocalizedString>

#include <QApplication>
#include <QTimer>
#include <QDateTime>
#include <QScrollBar>
#include <QIcon>
#include <QLocale>
69
#include <QElapsedTimer>
70

71 72
#include <algorithm>

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
namespace MessageList
{

namespace Core
{

Q_GLOBAL_STATIC(QTimer, _k_heartBeatTimer)

/**
 * A job in a "View Fill" or "View Cleanup" or "View Update" task.
 *
 * For a "View Fill" task a job is a set of messages
 * that are contiguous in the storage. The set is expressed as a range
 * of row indexes. The task "sweeps" the storage in the specified
 * range, creates the appropriate Item instances and places them
 * in the right position in the tree.
 *
 * The idea is that in a single instance and for the same StorageModel
 * the jobs should never "cover" the same message twice. This assertion
 * is enforced all around this source file.
 *
 * For a "View Cleanup" task the job is a list of ModelInvariantIndex
 * objects (that are in fact MessageItem objects) that need to be removed
 * from the view.
 *
 * For a "View Update" task the job is a list of ModelInvariantIndex
 * objects (that are in fact MessageItem objects) that need to be updated.
 *
 * The interesting fact is that all the tasks need
 * very similar operations to be performed on the message tree.
 *
 * For a "View Fill" we have 5 passes.
 *
 * Pass 1 scans the underlying storage, creates the MessageItem objects
 * (which are subclasses of ModelInvariantIndex) and retrieves invariant
 * storage indexes for them. It also builds threading caches and
 * attempts to do some "easy" threading. If it succeeds in threading
 * and some conditions apply then it also attaches the items to the view.
 * Any unattached message is placed in a list.
 *
 * Pass 2 scans the list of messages that haven't been attached in
 * the first pass and performs perfect and reference based threading.
 * Since grouping of messages may depend on the "shape" of the thread
 * then certain threads aren't attacched to the view yet.
 * Unassigned messages get stuffed into a list waiting for Pass3
 * or directly to a list waiting for Pass4 (that is, Pass3 may be skipped
 * if there is no hope to find an imperfect parent by subject based threading).
 *
 * Pass 3 scans the list of messages that haven't been attached in
 * the first and second passes and performs subject based threading.
 * Since grouping of messages may depend on the "shape" of the thread
 * then certain threads aren't attacched to the view yet.
 * Anything unattached gets stuffed into the list waiting for Pass4.
 *
 * Pass 4 scans the unattached threads and puts them in the appropriate
 * groups. After this pass nothing is unattached.
 *
 * Pass 5 eventually re-sorts the groups and removes the empty ones.
 *
 * For a "View Cleanup" we still have 5 passes.
 *
 * Pass 1 scans the list of invalidated ModelInvariantIndex-es, casts
 * them to MessageItem objects and detaches them from the view.
 * The orphan children of the destroyed items get stuffed in the list
 * of unassigned messages that has been used also in the "View Fill" task above.
 *
 * Pass 2, 3, 4 and 5: same as "View Fill", just operating on the "orphaned"
 * messages that need to be reattached to the view.
 *
 * For a "View Update" we still have 5 passes.
 *
 * Pass 1 scans the list of ModelInvariantIndex-es that need an update, casts
 * them to MessageItem objects and handles the updates from storage.
 * The updates may cause a regrouping so items might be stuffed in one
 * of the lists for pass 4 or 5.
 *
 * Pass 2, 3 and 4 are simply empty.
 *
 * Pass 5: same as "View Fill", just operating on groups that require updates
 * after the messages have been moved in pass 1.
 *
 * That's why we in fact have Pass1Fill, Pass1Cleanup, Pass1Update, Pass2, Pass3, Pass4 and Pass5 below.
 * Pass1Fill, Pass1Cleanup and Pass1Update are exclusive and all of them proceed with Pass2 when finished.
 */
class ViewItemJob
{
public:
    enum Pass {
        Pass1Fill    = 0,     ///< Build threading caches, *TRY* to do some threading, try to attach something to the view
        Pass1Cleanup = 1,     ///< Kill messages, build list of orphans
        Pass1Update  = 2,     ///< Update messages
        Pass2        = 3,     ///< Thread everything by using caches, try to attach more to the view
        Pass3        = 4,     ///< Do more threading (this time try to guess), try to attach more to the view
        Pass4        = 5,     ///< Attach anything is still unattacched
        Pass5        = 6,     ///< Eventually Re-sort group headers and remove the empty ones
        LastIndex    = 7      ///< Keep this at the end, needed to get the size of the enum
    };
private:
    // Data for "View Fill" jobs
    int mStartIndex;        ///< The first index (in the underlying storage) of this job
    int mCurrentIndex;      ///< The current index (in the underlying storage) of this job
    int mEndIndex;          ///< The last index (in the underlying storage) of this job

    // Data for "View Cleanup" jobs
    QList< ModelInvariantIndex * > *mInvariantIndexList;  ///< Owned list of shallow pointers

    // Common data

    // The maximum time that we can spend "at once" inside viewItemJobStep() (milliseconds)
    // The bigger this value, the larger chunks of work we do at once and less the time
    // we loose in "breaking and resuming" the job. On the other side large values tend
    // to make the view less responsive up to a "freeze" perception if this value is larger
    // than 2000.
    int mChunkTimeout;

    // The interval between two fillView steps. The larger the interval, the more interactivity
    // we have. The shorter the interval the more work we get done per second.
    int mIdleInterval;

    // The minimum number of messages we process in every viewItemJobStep() call
    // The larger this value the less time we loose in checking the timeout every N messages.
    // On the other side, making this very large may make the view less responsive
    // if we're processing very few messages at a time and very high values (say > 10000) may
    // eventually make our job unbreakable until the end.
    int mMessageCheckCount;
    Pass mCurrentPass;

    // If this parameter is true then this job uses a "disconnected" UI.
    // It's FAR faster since we don't need to call beginInsertRows()/endInsertRows()
    // and we simply Q_EMIT a layoutChanged() at the end. It can be done only as the first
    // job though: subsequent jobs can't use layoutChanged() as it looses the expanded
    // state of items.
    bool mDisconnectUI;
public:
    /**
    * Creates a "View Fill" operation job
    */
    ViewItemJob(int startIndex, int endIndex, int chunkTimeout, int idleInterval, int messageCheckCount, bool disconnectUI = false)
        : mStartIndex(startIndex), mCurrentIndex(startIndex), mEndIndex(endIndex),
Laurent Montel's avatar
Laurent Montel committed
212
          mInvariantIndexList(nullptr),
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
          mChunkTimeout(chunkTimeout), mIdleInterval(idleInterval),
          mMessageCheckCount(messageCheckCount), mCurrentPass(Pass1Fill),
          mDisconnectUI(disconnectUI) {}

    /**
    * Creates a "View Cleanup" or "View Update" operation job
    */
    ViewItemJob(Pass pass, QList< ModelInvariantIndex * > *invariantIndexList, int chunkTimeout, int idleInterval, int messageCheckCount)
        : mStartIndex(0), mCurrentIndex(0), mEndIndex(invariantIndexList->count() - 1),
          mInvariantIndexList(invariantIndexList),
          mChunkTimeout(chunkTimeout), mIdleInterval(idleInterval),
          mMessageCheckCount(messageCheckCount), mCurrentPass(pass),
          mDisconnectUI(false) {}

    ~ViewItemJob()
    {
        delete mInvariantIndexList;
    }
public:
    int startIndex() const
    {
        return mStartIndex;
    }
    void setStartIndex(int startIndex)
    {
        mStartIndex = startIndex;
        mCurrentIndex = startIndex;
    }
    int currentIndex() const
    {
        return mCurrentIndex;
    }
    void setCurrentIndex(int currentIndex)
    {
        mCurrentIndex = currentIndex;
    }
    int endIndex() const
    {
        return mEndIndex;
    }
    void setEndIndex(int endIndex)
    {
        mEndIndex = endIndex;
    }
    Pass currentPass() const
    {
        return mCurrentPass;
    }
    void setCurrentPass(Pass pass)
    {
        mCurrentPass = pass;
    }
    int idleInterval() const
    {
        return mIdleInterval;
    }
    int chunkTimeout() const
    {
        return mChunkTimeout;
    }
    int messageCheckCount() const
    {
        return mMessageCheckCount;
    }
    QList< ModelInvariantIndex * > *invariantIndexList() const
    {
        return mInvariantIndexList;
    }
    bool disconnectUI() const
    {
        return mDisconnectUI;
    }
};

} // namespace Core

} // namespace MessageList

using namespace MessageList::Core;

Model::Model(View *pParent)
    : QAbstractItemModel(pParent), d(new ModelPrivate(this))
{
    d->mRecursionCounterForReset = 0;
Laurent Montel's avatar
Laurent Montel committed
297
    d->mStorageModel = nullptr;
298
    d->mView = pParent;
Laurent Montel's avatar
Laurent Montel committed
299 300 301 302 303
    d->mAggregation = nullptr;
    d->mTheme = nullptr;
    d->mSortOrder = nullptr;
    d->mFilter = nullptr;
    d->mPersistentSetManager = nullptr;
304
    d->mInLengthyJobBatch = false;
Laurent Montel's avatar
Laurent Montel committed
305
    d->mLastSelectedMessageInFolder = nullptr;
306 307 308
    d->mLoading = false;

    d->mRootItem = new Item(Item::InvisibleRoot);
Laurent Montel's avatar
Laurent Montel committed
309
    d->mRootItem->setViewable(nullptr, true);
310 311 312 313

    d->mFillStepTimer.setSingleShot(true);
    d->mInvariantRowMapper = new ModelInvariantRowMapper();
    d->mModelForItemFunctions = this;
314
    connect(&d->mFillStepTimer, &QTimer::timeout,
Laurent Montel's avatar
Laurent Montel committed
315 316 317
    this, [this]() {
        d->viewItemJobStep();
    });
318 319 320 321 322 323 324 325 326 327 328 329 330

    d->mCachedTodayLabel = i18n("Today");
    d->mCachedYesterdayLabel = i18n("Yesterday");
    d->mCachedUnknownLabel = i18nc("Unknown date",
                                   "Unknown");
    d->mCachedLastWeekLabel = i18n("Last Week");
    d->mCachedTwoWeeksAgoLabel = i18n("Two Weeks Ago");
    d->mCachedThreeWeeksAgoLabel = i18n("Three Weeks Ago");
    d->mCachedFourWeeksAgoLabel = i18n("Four Weeks Ago");
    d->mCachedFiveWeeksAgoLabel = i18n("Five Weeks Ago");

    d->mCachedWatchedOrIgnoredStatusBits = Akonadi::MessageStatus::statusIgnored().toQInt32() | Akonadi::MessageStatus::statusWatched().toQInt32();

331
    connect(_k_heartBeatTimer(), &QTimer::timeout,
Laurent Montel's avatar
Laurent Montel committed
332 333 334
    this, [this]() {
        d->checkIfDateChanged();
    });
335 336 337 338 339 340 341 342

    if (!_k_heartBeatTimer->isActive()) {   // First model starts it
        _k_heartBeatTimer->start(60000);   // 1 minute
    }
}

Model::~Model()
{
Laurent Montel's avatar
Laurent Montel committed
343
    setStorageModel(nullptr);
344 345

    d->clearJobList();
Laurent Montel's avatar
Laurent Montel committed
346 347
    d->mOldestItem = nullptr;
    d->mNewestItem = nullptr;
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
    d->clearUnassignedMessageLists();
    d->clearOrphanChildrenHash();
    d->clearThreadingCacheMessageSubjectMD5ToMessageItem();
    delete d->mPersistentSetManager;
    // Delete the invariant row mapper before removing the items.
    // It's faster since the items will not need to call the invariant
    delete d->mInvariantRowMapper;
    delete d->mRootItem;

    delete d;
}

void Model::setAggregation(const Aggregation *aggregation)
{
    d->mAggregation = aggregation;
    d->mView->setRootIsDecorated((d->mAggregation->grouping() == Aggregation::NoGrouping) &&
                                 (d->mAggregation->threading() != Aggregation::NoThreading));
}

void Model::setTheme(const Theme *theme)
{
    d->mTheme = theme;
}

void Model::setSortOrder(const SortOrder *sortOrder)
{
    d->mSortOrder = sortOrder;
}

const SortOrder *Model::sortOrder() const
{
    return d->mSortOrder;
}

void Model::setFilter(const Filter *filter)
{
    d->mFilter = filter;

    if (d->mFilter) {
Laurent Montel's avatar
Laurent Montel committed
387 388 389
        connect(d->mFilter, &Filter::finished, this, [this]() {
            d->slotApplyFilter();
        });
390 391 392 393 394 395 396
    }

    d->slotApplyFilter();
}

void ModelPrivate::slotApplyFilter()
{
Daniel Vrátil's avatar
Daniel Vrátil committed
397
    auto childList = mRootItem->childItems();
398 399 400 401 402 403 404
    if (!childList) {
        return;
    }

    QModelIndex idx; // invalid

    QApplication::setOverrideCursor(Qt::WaitCursor);
Daniel Vrátil's avatar
Daniel Vrátil committed
405 406
    for (const auto child : qAsConst(*childList)) {
        applyFilterToSubtree(child, idx);
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
    }

    QApplication::restoreOverrideCursor();
}

bool ModelPrivate::applyFilterToSubtree(Item *item, const QModelIndex &parentIndex)
{
    // This function applies the current filter (eventually empty)
    // to a message tree starting at "item".

    if (!mModelForItemFunctions) {
        qCWarning(MESSAGELIST_LOG) << "Cannot apply filter, the UI must be not disconnected.";
        return true;
    }
    Q_ASSERT(item);                      // the item must obviously be valid
    Q_ASSERT(item->isViewable());        // the item must be viewable

    // Apply to children first

Daniel Vrátil's avatar
Daniel Vrátil committed
426
    auto childList = item->childItems();
427 428 429 430 431 432

    bool childrenMatch = false;

    QModelIndex thisIndex = q->index(item, 0);

    if (childList) {
Daniel Vrátil's avatar
Daniel Vrátil committed
433 434
        for (const auto child : qAsConst(*childList)) {
            if (applyFilterToSubtree(child, thisIndex)) {
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
                childrenMatch = true;
            }
        }
    }

    if (!mFilter) { // empty filter always matches (but does not expand items)
        mView->setRowHidden(thisIndex.row(), parentIndex, false);
        return true;
    }

    if (childrenMatch) {
        mView->setRowHidden(thisIndex.row(), parentIndex, false);

        if (!mView->isExpanded(thisIndex)) {
            mView->expand(thisIndex);
        }
        return true;
    }

    if (item->type() == Item::Message) {
        if (mFilter->match((MessageItem *)item)) {
            mView->setRowHidden(thisIndex.row(), parentIndex, false);
            return true;
        }
    } // else this is a group header and it never explicitly matches

    // filter doesn't match, hide the item
    mView->setRowHidden(thisIndex.row(), parentIndex, true);

    return false;
}

int Model::columnCount(const QModelIndex &parent) const
{
    if (!d->mTheme) {
        return 0;
    }
    if (parent.column() > 0) {
        return 0;
    }
    return d->mTheme->columns().count();
}

QVariant Model::data(const QModelIndex &index, int role) const
{
    /// this is called only when Akonadi is using the selectionmodel
    ///  for item actions. since akonadi uses the ETM ItemRoles, and the
    ///  messagelist uses its own internal roles, here we respond
    ///  to the ETM ones.

Daniel Vrátil's avatar
Daniel Vrátil committed
485
    auto item = static_cast<Item *>(index.internalPointer());
486 487 488 489 490

    switch (role) {
    /// taken from entitytreemodel.h
    case Qt::UserRole + 1: //EntityTreeModel::ItemIdRole
        if (item->type() == MessageList::Core::Item::Message) {
Daniel Vrátil's avatar
Daniel Vrátil committed
491
            auto mItem = static_cast<MessageItem *>(item);
492 493 494 495 496 497 498
            return QVariant::fromValue(mItem->akonadiItem().id());
        } else {
            return QVariant();
        }
        break;
    case Qt::UserRole + 2: //EntityTreeModel::ItemRole
        if (item->type() == MessageList::Core::Item::Message) {
Daniel Vrátil's avatar
Daniel Vrátil committed
499
            auto mItem = static_cast<MessageItem *>(item);
500 501 502 503 504 505 506 507 508 509 510 511 512 513
            return QVariant::fromValue(mItem->akonadiItem());
        } else {
            return QVariant();
        }
        break;
    case Qt::UserRole + 3: //EntityTreeModel::MimeTypeRole
        if (item->type() == MessageList::Core::Item::Message) {
            return QStringLiteral("message/rfc822");
        } else {
            return QVariant();
        }
        break;
    case Qt::AccessibleTextRole:
        if (item->type() == MessageList::Core::Item::Message) {
Daniel Vrátil's avatar
Daniel Vrátil committed
514
            auto mItem = static_cast<MessageItem *>(item);
515 516 517 518 519
            return mItem->accessibleText(d->mTheme, index.column());
        } else if (item->type() == MessageList::Core::Item::GroupHeader) {
            if (index.column() > 0) {
                return QString();
            }
Daniel Vrátil's avatar
Daniel Vrátil committed
520
            auto hItem = static_cast<GroupHeaderItem *>(item);
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
            return hItem->label();
        }
        return QString();
        break;
    default:
        return QVariant();
    }
}

QVariant Model::headerData(int section, Qt::Orientation, int role) const
{
    if (!d->mTheme) {
        return QVariant();
    }

Daniel Vrátil's avatar
Daniel Vrátil committed
536
    auto column = d->mTheme->column(section);
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
    if (!column) {
        return QVariant();
    }

    if (d->mStorageModel && column->isSenderOrReceiver() &&
            (role == Qt::DisplayRole)) {
        if (d->mStorageModelContainsOutboundMessages) {
            return QVariant(i18n("Receiver"));
        }
        return QVariant(i18n("Sender"));
    }

    const bool columnPixmapEmpty(column->pixmapName().isEmpty());
    if ((role == Qt::DisplayRole) && columnPixmapEmpty) {
        return QVariant(column->label());
    } else if ((role == Qt::ToolTipRole) && !columnPixmapEmpty) {
        return QVariant(column->label());
    } else if ((role == Qt::DecorationRole) && !columnPixmapEmpty) {
        return QVariant(QIcon::fromTheme(column->pixmapName()));
    }

    return QVariant();
}

QModelIndex Model::index(Item *item, int column) const
{
    if (!d->mModelForItemFunctions) {
        return QModelIndex();    // called with disconnected UI: the item isn't known on the Qt side, yet
    }

    if (!item) {
        return QModelIndex();
    }
    // FIXME: This function is a bottleneck (the caching in indexOfChildItem only works 30% of the time)
Daniel Vrátil's avatar
Daniel Vrátil committed
571
    auto par = item->parent();
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
    if (!par) {
        if (item != d->mRootItem) {
            item->dump(QString());
        }
        return QModelIndex();
    }

    const int index = par->indexOfChildItem(item);
    if (index < 0) {
        return QModelIndex();    // BUG
    }
    return createIndex(index, column, item);
}

QModelIndex Model::index(int row, int column, const QModelIndex &parent) const
{
    if (!d->mModelForItemFunctions) {
        return QModelIndex();    // called with disconnected UI: the item isn't known on the Qt side, yet
    }

#ifdef READD_THIS_IF_YOU_WANT_TO_PASS_MODEL_TEST
    if (column < 0) {
        return QModelIndex();    // senseless column (we could optimize by skipping this check but ModelTest from trolltech is pedantic)
    }
#endif

    const Item *item;
    if (parent.isValid()) {
Daniel Vrátil's avatar
Daniel Vrátil committed
600
        item = static_cast<const Item *>(parent.internalPointer());
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
        if (!item) {
            return QModelIndex();    // should never happen
        }
    } else {
        item = d->mRootItem;
    }

    if (parent.column() > 0) {
        return QModelIndex();    // parent column is not 0: shouldn't have children (as per Qt documentation)
    }

    Item *child = item->childItem(row);
    if (!child) {
        return QModelIndex();    // no such row in parent
    }
    return createIndex(row, column, child);
}

QModelIndex Model::parent(const QModelIndex &modelIndex) const
{
    Q_ASSERT(d->mModelForItemFunctions);   // should be never called with disconnected UI

    if (!modelIndex.isValid()) {
        return QModelIndex();    // should never happen
    }
Daniel Vrátil's avatar
Daniel Vrátil committed
626
    auto item = static_cast<Item *>(modelIndex.internalPointer());
627 628 629
    if (!item) {
        return QModelIndex();
    }
Daniel Vrátil's avatar
Daniel Vrátil committed
630
    auto par = item->parent();
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
    if (!par) {
        return QModelIndex();    // should never happen
    }
    //return index( par, modelIndex.column() );
    return index(par, 0);   // parents are always in column 0 (as per Qt documentation)
}

int Model::rowCount(const QModelIndex &parent) const
{
    if (!d->mModelForItemFunctions) {
        return 0;    // called with disconnected UI
    }

    const Item *item;
    if (parent.isValid()) {
Daniel Vrátil's avatar
Daniel Vrátil committed
646
        item = static_cast<const Item *>(parent.internalPointer());
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 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
        if (!item) {
            return 0;    // should never happen
        }
    } else {
        item = d->mRootItem;
    }

    if (!item->isViewable()) {
        return 0;
    }

    return item->childItemCount();
}

class RecursionPreventer
{
public:
    RecursionPreventer(int &counter)
        : mCounter(counter)
    {
        mCounter++;
    }
    ~RecursionPreventer()
    {
        mCounter--;
    }
    bool isRecursive() const
    {
        return mCounter > 1;
    }

private:
    int &mCounter;
};

StorageModel *Model::storageModel() const
{
    return d->mStorageModel;
}

void ModelPrivate::clear()
{
    if (mFillStepTimer.isActive()) {
        mFillStepTimer.stop();
    }

    // Kill pre-selection at this stage
    mPreSelectionMode = PreSelectNone;
Laurent Montel's avatar
Laurent Montel committed
695 696 697
    mLastSelectedMessageInFolder = nullptr;
    mOldestItem = nullptr;
    mNewestItem = nullptr;
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714

    // Reset the row mapper before removing items
    // This is faster since the items don't need to access the mapper.
    mInvariantRowMapper->modelReset();

    clearJobList();
    clearUnassignedMessageLists();
    clearOrphanChildrenHash();
    mGroupHeaderItemHash.clear();
    mGroupHeadersThatNeedUpdate.clear();
    mThreadingCacheMessageIdMD5ToMessageItem.clear();
    mThreadingCacheMessageInReplyToIdMD5ToMessageItem.clear();
    clearThreadingCacheMessageSubjectMD5ToMessageItem();
    mViewItemJobStepChunkTimeout = 100;
    mViewItemJobStepIdleInterval = 10;
    mViewItemJobStepMessageCheckCount = 10;
    delete mPersistentSetManager;
Laurent Montel's avatar
Laurent Montel committed
715 716
    mPersistentSetManager = nullptr;
    mCurrentItemToRestoreAfterViewItemJobStep = nullptr;
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742

    mTodayDate = QDate::currentDate();

    // FIXME: CLEAR THE FILTER HERE AS WE CAN'T APPLY IT WITH UI DISCONNECTED!

    mRootItem->killAllChildItems();

    q->reset();
    //Q_EMIT headerDataChanged();

    mView->modelHasBeenReset();
    mView->selectionModel()->clearSelection();
}

void Model::setStorageModel(StorageModel *storageModel, PreSelectionMode preSelectionMode)
{
    // Prevent a case of recursion when opening a folder that has a message and the folder was
    // never opened before.
    RecursionPreventer preventer(d->mRecursionCounterForReset);
    if (preventer.isRecursive()) {
        return;
    }

    d->clear();

    if (d->mStorageModel) {
743 744
        // Disconnect all signals from old storageModel
        std::for_each(d->mStorageModelConnections.cbegin(), d->mStorageModelConnections.cend(),
Laurent Montel's avatar
Laurent Montel committed
745
                      [](const QMetaObject::Connection & c) -> bool { return QObject::disconnect(c); });
746
        d->mStorageModelConnections.clear();
747 748
    }

749
    const bool isReload = (d->mStorageModel == storageModel);
750 751 752 753 754 755 756 757 758
    d->mStorageModel = storageModel;

    if (!d->mStorageModel) {
        return;    // no folder: nothing to fill
    }

    // Sometimes the folders need to be resurrected...
    d->mStorageModel->prepareForScan();

759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
    // Save threading cache of the previous folder, but only if the cache was
    // enabled and a different folder is being loaded - reload of the same folder
    // means change in aggregation in which case we will have to re-build the
    // cache so there's no point saving the current threading cache.
    if (d->mThreadingCache.isEnabled() && !isReload) {
        d->mThreadingCache.save();
    } else {
        if (isReload) {
            qCDebug(MESSAGELIST_LOG) << "Identical folder reloaded, not saving old threading cache";
        } else {
            qCDebug(MESSAGELIST_LOG) << "Threading disabled in previous folder, not saving threading cache";
        }
    }
    // Load threading cache for the new folder, but only if threading is enabled,
    // otherwise we would just be caching a flat list.
    if (d->mAggregation->threading() != Aggregation::NoThreading) {
        d->mThreadingCache.setEnabled(true);
        d->mThreadingCache.load(d->mStorageModel->id(), d->mAggregation);
    } else {
        // No threading, no cache - don't even bother inserting entries into the
        // cache or trying to look them up there
        d->mThreadingCache.setEnabled(false);
        qCDebug(MESSAGELIST_LOG) << "Threading disabled in folder" << d->mStorageModel->id() << ", not using threading cache";
    }

784 785 786
    d->mPreSelectionMode = preSelectionMode;
    d->mStorageModelContainsOutboundMessages = d->mStorageModel->containsOutboundMessages();

787 788
    d->mStorageModelConnections = {
        connect(d->mStorageModel, &StorageModel::rowsInserted,
Laurent Montel's avatar
Laurent Montel committed
789 790 791 792
        this, [this](const QModelIndex & parent, int first, int last)
        {
            d->slotStorageModelRowsInserted(parent, first, last);
        }),
793
        connect(d->mStorageModel, &StorageModel::rowsRemoved,
Laurent Montel's avatar
Laurent Montel committed
794 795 796 797
        this, [this](const QModelIndex & parent, int first, int last)
        {
            d->slotStorageModelRowsRemoved(parent, first, last);
        }),
798
        connect(d->mStorageModel, &StorageModel::layoutChanged,
Laurent Montel's avatar
Laurent Montel committed
799 800 801 802
        this, [this]()
        {
            d->slotStorageModelLayoutChanged();
        }),
803
        connect(d->mStorageModel, &StorageModel::modelReset,
Laurent Montel's avatar
Laurent Montel committed
804 805 806 807
        this, [this]()
        {
            d->slotStorageModelLayoutChanged();
        }),
808
        connect(d->mStorageModel, &StorageModel::dataChanged,
Laurent Montel's avatar
Laurent Montel committed
809 810 811 812
        this, [this](const QModelIndex & topLeft, const QModelIndex & bottomRight)
        {
            d->slotStorageModelDataChanged(topLeft, bottomRight);
        }),
813
        connect(d->mStorageModel, &StorageModel::headerDataChanged,
Laurent Montel's avatar
Laurent Montel committed
814 815 816 817
        this, [this](Qt::Orientation orientation, int first, int last)
        {
            d->slotStorageModelHeaderDataChanged(orientation, first, last);
        })
818
    };
819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913

    if (d->mStorageModel->rowCount() == 0) {
        return;    // folder empty: nothing to fill
    }

    // Here we use different strategies based on user preference and the folder size.
    // The knobs we can tune are:
    //
    // - The number of jobs used to scan the whole folder and their order
    //
    //   There are basically two approaches to this. One is the "single big job"
    //   approach. It scans the folder from the beginning to the end in a single job
    //   entry. The job passes are done only once. It's advantage is that it's simplier
    //   and it's less likely to generate imperfect parent threadings. The bad
    //   side is that since the folders are "sort of" date ordered then the most interesting
    //   messages show up at the end of the work. Not nice for large folders.
    //   The other approach uses two jobs. This is a bit slower but smarter strategy.
    //   First we scan the latest 1000 messages and *then* take care of the older ones.
    //   This will show up the most interesting messages almost immediately. (Well...
    //   All this assuming that the underlying storage always appends the newly arrived messages)
    //   The strategy is slower since it  generates some imperfect parent threadings which must be
    //   adjusted by the second job. For instance, in my kernel mailing list folder this "smart" approach
    //   generates about 150 additional imperfectly threaded children... but the "today"
    //   messages show up almost immediately. The two-chunk job also makes computing
    //   the percentage user feedback a little harder and might break some optimization
    //   in the insertions (we're able to optimize appends and prepends but a chunked
    //   job is likely to split our work at a boundary where messages are always inserted
    //   in the middle of the list).
    //
    // - The maximum time to spend inside a single job step
    //
    //   The larger this time, the greater the number of messages per second that this
    //   engine can process but also greater time with frozen UI -> less interactivity.
    //   Reasonable values start at 50 msecs. Values larger than 300 msecs are very likely
    //   to be percieved by the user as UI non-reactivity.
    //
    // - The number of messages processed in each job step subchunk.
    //
    //   A job subchunk is processed without checking the maximum time above. This means
    //   that each job step will process at least the number of messages specified by this value.
    //   Very low values mean that we respect the maximum time very carefully but we also
    //   waste time to check if we ran out of time :)
    //   Very high values are likely to cause the engine to not respect the maximum step time.
    //   Reasonable values go from 5 to 100.
    //
    // - The "idle" time between two steps
    //
    //   The lower this time, the greater the number of messages per second that this
    //   engine can process but also lower time for the UI to process events -> less interactivity.
    //   A value of 0 here means that Qt will trigger the timer as soon as it has some
    //   idle time to spend. UI events will be still processed but slowdowns are possible.
    //   0 is reasonable though. Values larger than 200 will tend to make the total job
    //   completion times high.
    //

    // If we have no filter it seems that we can apply a huge optimization.
    // We disconnect the UI for the first huge filling job. This allows us
    // to save the extremely expensive beginInsertRows()/endInsertRows() calls
    // and call a single layoutChanged() at the end. This slows down a lot item
    // expansion. But on the other side if only few items need to be expanded
    // then this strategy is better. If filtering is enabled then this strategy
    // isn't applicable (because filtering requires interaction with the UI
    // while the data is loading).

    // So...

    // For the very first small chunk it's ok to work with disconnected UI as long
    // as we have no filter. The first small chunk is always 1000 messages, so
    // even if all of them are expanded, it's still somewhat acceptable.
    bool canDoFirstSmallChunkWithDisconnectedUI = !d->mFilter;

    // Larger works need a bigger condition: few messages must be expanded in the end.
    bool canDoJobWithDisconnectedUI =
        // we have no filter
        !d->mFilter &&
        (
            // we do no threading at all
            (d->mAggregation->threading() == Aggregation::NoThreading) ||
            // or we never expand threads
            (d->mAggregation->threadExpandPolicy() == Aggregation::NeverExpandThreads) ||
            // or we expand threads but we'll be going to expand really only a few
            (
                // so we don't expand them all
                (d->mAggregation->threadExpandPolicy() != Aggregation::AlwaysExpandThreads) &&
                // and we'd expand only a few in fact
                (d->mStorageModel->initialUnreadRowCountGuess() < 1000)
            )
        );

    switch (d->mAggregation->fillViewStrategy()) {
    case Aggregation::FavorInteractivity:
        // favor interactivity
        if ((!canDoJobWithDisconnectedUI) && (d->mStorageModel->rowCount() > 3000)) {     // empiric value
            // First a small job with the most recent messages. Large chunk, small (but non zero) idle interval
            // and a larger number of messages to process at once.
Daniel Vrátil's avatar
Daniel Vrátil committed
914 915
            auto job1 = new ViewItemJob(d->mStorageModel->rowCount() - 1000, d->mStorageModel->rowCount() - 1,
                                        200, 20, 100, canDoFirstSmallChunkWithDisconnectedUI);
916 917 918
            d->mViewItemJobs.append(job1);
            // Then a larger job with older messages. Small chunk, bigger idle interval, small number of messages to
            // process at once.
Daniel Vrátil's avatar
Daniel Vrátil committed
919
            auto job2 = new ViewItemJob(0, d->mStorageModel->rowCount() - 1001, 100, 50, 10, false);
920 921 922 923 924 925 926 927
            d->mViewItemJobs.append(job2);

            // We could even extremize this by splitting the folder in several
            // chunks and scanning them from the newest to the oldest... but the overhead
            // due to imperfectly threaded children would be probably too big.
        } else {
            // small folder or can be done with disconnected UI: single chunk work.
            // Lag the CPU a bit more but not too much to destroy even the earliest interactivity.
Daniel Vrátil's avatar
Daniel Vrátil committed
928
            auto job = new ViewItemJob(0, d->mStorageModel->rowCount() - 1, 150, 30, 30, canDoJobWithDisconnectedUI);
929 930 931 932 933 934 935
            d->mViewItemJobs.append(job);
        }
        break;
    case Aggregation::FavorSpeed:
        // More batchy jobs, still interactive to a certain degree
        if ((!canDoJobWithDisconnectedUI) && (d->mStorageModel->rowCount() > 3000)) {     // empiric value
            // large folder, but favor speed
Daniel Vrátil's avatar
Daniel Vrátil committed
936 937
            auto job1 = new ViewItemJob(d->mStorageModel->rowCount() - 1000, d->mStorageModel->rowCount() - 1,
                                        250, 0, 100, canDoFirstSmallChunkWithDisconnectedUI);
938
            d->mViewItemJobs.append(job1);
Daniel Vrátil's avatar
Daniel Vrátil committed
939
            auto job2 = new ViewItemJob(0, d->mStorageModel->rowCount() - 1001, 200, 0, 10, false);
940 941 942 943
            d->mViewItemJobs.append(job2);
        } else {
            // small folder or can be done with disconnected UI and favor speed: single chunk work.
            // Lag the CPU more, get more work done
Daniel Vrátil's avatar
Daniel Vrátil committed
944
            auto job = new ViewItemJob(0, d->mStorageModel->rowCount() - 1, 250, 0, 100, canDoJobWithDisconnectedUI);
945 946 947 948 949
            d->mViewItemJobs.append(job);
        }
        break;
    case Aggregation::BatchNoInteractivity: {
        // one large job, never interrupt, block UI
Daniel Vrátil's avatar
Daniel Vrátil committed
950
        auto job = new ViewItemJob(0, d->mStorageModel->rowCount() - 1, 60000, 0, 100000, canDoJobWithDisconnectedUI);
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
        d->mViewItemJobs.append(job);
    }
    break;
    default:
        qCWarning(MESSAGELIST_LOG) << "Unrecognized fill view strategy";
        Q_ASSERT(false);
        break;
    }

    d->mLoading = true;

    d->viewItemJobStep();
}

void ModelPrivate::checkIfDateChanged()
{
    // This function is called by MessageList::Core::Manager once in a while (every 1 minute or sth).
    // It is used to check if the current date has changed (with respect to mTodayDate).
    //
    // Our message items cache the formatted dates (as formatting them
    // on the fly would be too expensive). We also cache the labels of the groups which often display dates.
    // When the date changes we would need to fix all these strings.
    //
    // A dedicated algorithm to refresh the labels of the items would be either too complex
    // or would block on large trees. Fixing the labels of the groups is also quite hard...
    //
    // So to keep the things simple we just reload the view.

    if (!mStorageModel) {
        return;    // nothing to do
    }

    if (mLoading) {
        return;    // not now
    }

    if (!mViewItemJobs.isEmpty()) {
        return;    // not now
    }

    if (mTodayDate == QDate::currentDate()) {
        return;    // date not changed
    }

    // date changed, reload the view (and try to preserve the current selection)
    q->setStorageModel(mStorageModel, PreSelectLastSelected);
}

void Model::setPreSelectionMode(PreSelectionMode preSelect)
{
    d->mPreSelectionMode = preSelect;
Laurent Montel's avatar
Laurent Montel committed
1002
    d->mLastSelectedMessageInFolder = nullptr;
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
}

//
// The "view fill" algorithm implemented in the functions below is quite smart but also quite complex.
// It's governed by the following goals:
//
// - Be flexible: allow different configurations from "unsorted flat list" to a "grouped and threaded
//     list with different sorting algorightms applied to each aggregation level"
// - Be reasonably fast
// - Be non blocking: UI shouldn't freeze while the algorithm is running
// - Be interruptible: user must be able to abort the execution and just switch to another folder in the middle
//

void ModelPrivate::clearUnassignedMessageLists()
{
    // This is a bit tricky...
    // The three unassigned message lists contain messages that have been created
    // but not yet attached to the view. There may be two major cases for a message:
    // - it has no parent -> it must be deleted and it will delete its children too
    // - it has a parent -> it must NOT be deleted since it will be deleted by its parent.

    // Sometimes the things get a little complicated since in Pass2 and Pass3
    // we have transitional states in that the MessageItem object can be in two of these lists.

    // WARNING: This function does NOT fixup mNewestItem and mOldestItem. If one of these
    // two messages is in the lists below, it's deleted and the member becomes a dangling pointer.
    // The caller must ensure that both mNewestItem and mOldestItem are set to 0
    // and this is enforced in the assert below to avoid errors. This basically means
    // that this function should be called only when the storage model changes or
    // when the model is destroyed.
Laurent Montel's avatar
Laurent Montel committed
1033
    Q_ASSERT((mOldestItem == nullptr) && (mNewestItem == nullptr));
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044

    if (!mUnassignedMessageListForPass2.isEmpty()) {
        // We're actually in Pass1* or Pass2: everything is mUnassignedMessageListForPass2
        // Something may *also* be in mUnassignedMessageListForPass3 and mUnassignedMessageListForPass4
        // but that are duplicates for sure.

        // We can't just sweep the list and delete parentless items since each delete
        // could kill children which are somewhere AFTER in the list: accessing the children
        // would then lead to a SIGSEGV. We first sweep the list gathering parentless
        // items and *then* delete them without accessing the parented ones.

Daniel Vrátil's avatar
Daniel Vrátil committed
1045 1046 1047 1048
        QList<MessageItem*> parentless;
        for (const auto mi : qAsConst(mUnassignedMessageListForPass2)) {
            if (!mi->parent()) {
                parentless.append(mi);
1049 1050 1051
            }
        }

Daniel Vrátil's avatar
Daniel Vrátil committed
1052 1053
        for (const auto mi : qAsConst(parentless)) {
            delete mi;
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
        }

        mUnassignedMessageListForPass2.clear();
        // Any message these list contain was also in mUnassignedMessageListForPass2
        mUnassignedMessageListForPass3.clear();
        mUnassignedMessageListForPass4.clear();
        return;
    }

    // mUnassignedMessageListForPass2 is empty

    if (!mUnassignedMessageListForPass3.isEmpty()) {
        // We're actually at the very end of Pass2 or inside Pass3
        // Pass2 pushes stuff in mUnassignedMessageListForPass3 *or* mUnassignedMessageListForPass4
        // Pass3 pushes stuff from mUnassignedMessageListForPass3 to mUnassignedMessageListForPass4
        // So if we're in Pass2 then the two lists contain distinct messages but if we're in Pass3
        // then the two lists may contain the same messages.

        if (!mUnassignedMessageListForPass4.isEmpty()) {
            // We're actually in Pass3: the messiest one.

Daniel Vrátil's avatar
Daniel Vrátil committed
1075 1076 1077 1078
            QSet<MessageItem *> itemsToDelete;
            for (const auto mi : qAsConst(mUnassignedMessageListForPass3)) {
                if (!mi->parent()) {
                    itemsToDelete.insert(mi);
1079 1080
                }
            }
Daniel Vrátil's avatar
Daniel Vrátil committed
1081 1082 1083
            for (const auto mi : qAsConst(mUnassignedMessageListForPass4)) {
                if (!mi->parent()) {
                    itemsToDelete.insert(mi);
1084 1085
                }
            }
Daniel Vrátil's avatar
Daniel Vrátil committed
1086 1087
            for (const auto mi : qAsConst(itemsToDelete)) {
                delete mi;
1088 1089 1090 1091 1092 1093 1094 1095 1096
            }

            mUnassignedMessageListForPass3.clear();
            mUnassignedMessageListForPass4.clear();
            return;
        }

        // mUnassignedMessageListForPass4 is empty so we must be at the end of a very special kind of Pass2
        // We have the same problem as in mUnassignedMessageListForPass2.
Daniel Vrátil's avatar
Daniel Vrátil committed
1097 1098 1099 1100
        QList<MessageItem *> parentless;
        for (const auto mi : qAsConst(mUnassignedMessageListForPass3)) {
            if (!mi->parent()) {
                parentless.append(mi);
1101 1102
            }
        }
Daniel Vrátil's avatar
Daniel Vrátil committed
1103 1104
        for (const auto mi : qAsConst(parentless)) {
            delete mi;
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
        }

        mUnassignedMessageListForPass3.clear();
        return;
    }

    // mUnassignedMessageListForPass3 is empty
    if (!mUnassignedMessageListForPass4.isEmpty()) {
        // we're in Pass4.. this is easy.

        // We have the same problem as in mUnassignedMessageListForPass2.
Daniel Vrátil's avatar
Daniel Vrátil committed
1116 1117 1118 1119
        QList<MessageItem *> parentless;
        for (const auto mi : qAsConst(mUnassignedMessageListForPass4)) {
            if (!mi->parent()) {
                parentless.append(mi);
1120 1121
            }
        }
Daniel Vrátil's avatar
Daniel Vrátil committed
1122 1123
        for (const auto mi : qAsConst(parentless)) {
            delete mi;
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
        }

        mUnassignedMessageListForPass4.clear();
        return;
    }
}

void ModelPrivate::clearThreadingCacheMessageSubjectMD5ToMessageItem()
{
    qDeleteAll(mThreadingCacheMessageSubjectMD5ToMessageItem);
    mThreadingCacheMessageSubjectMD5ToMessageItem.clear();
}

void ModelPrivate::clearOrphanChildrenHash()
{
Daniel Vrátil's avatar
Daniel Vrátil committed
1139
    qDeleteAll(mOrphanChildrenHash);
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
    mOrphanChildrenHash.clear();
}

void ModelPrivate::clearJobList()
{
    if (mViewItemJobs.isEmpty()) {
        return;
    }

    if (mInLengthyJobBatch) {
        mInLengthyJobBatch = false;
        mView->modelJobBatchTerminated();
    }

Daniel Vrátil's avatar
Daniel Vrátil committed
1154
    qDeleteAll(mViewItemJobs);
1155 1156 1157 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 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
    mViewItemJobs.clear();

    mModelForItemFunctions = q; // make sure it's true, as there remains no job with disconnected UI
}

void ModelPrivate::attachGroup(GroupHeaderItem *ghi)
{
    if (ghi->parent()) {
        if (
            ((ghi)->childItemCount() > 0) &&     // has children
            (ghi)->isViewable() &&   // is actually attached to the viewable root
            mModelForItemFunctions && // the UI is not disconnected
            mView->isExpanded(q->index(ghi, 0))     // is actually expanded
        ) {
            saveExpandedStateOfSubtree(ghi);
        }

        // FIXME: This *WILL* break selection and current index... :/

        ghi->parent()->takeChildItem(mModelForItemFunctions, ghi);
    }

    ghi->setParent(mRootItem);

    // I'm using a macro since it does really improve readability.
    // I'm NOT using a helper function since gcc will refuse to inline some of
    // the calls because they make this function grow too much.
#define INSERT_GROUP_WITH_COMPARATOR( _ItemComparator ) \
    switch( mSortOrder->groupSortDirection() ) \
    { \
    case SortOrder::Ascending: \
        mRootItem->d_ptr->insertChildItem< _ItemComparator, true >( mModelForItemFunctions, ghi ); \
        break; \
    case SortOrder::Descending: \
        mRootItem->d_ptr->insertChildItem< _ItemComparator, false >( mModelForItemFunctions, ghi ); \
        break; \
    default: /* should never happen... */ \
        mRootItem->appendChildItem( mModelForItemFunctions, ghi ); \
        break; \
    }

    switch (mSortOrder->groupSorting()) {
    case SortOrder::SortGroupsByDateTime:
        INSERT_GROUP_WITH_COMPARATOR(ItemDateComparator)
        break;
    case SortOrder::SortGroupsByDateTimeOfMostRecent:
        INSERT_GROUP_WITH_COMPARATOR(ItemMaxDateComparator)
        break;
    case SortOrder::SortGroupsBySenderOrReceiver:
        INSERT_GROUP_WITH_COMPARATOR(ItemSenderOrReceiverComparator)
        break;
    case SortOrder::SortGroupsBySender:
        INSERT_GROUP_WITH_COMPARATOR(ItemSenderComparator)
        break;
    case SortOrder::SortGroupsByReceiver:
        INSERT_GROUP_WITH_COMPARATOR(ItemReceiverComparator)
        break;
    case SortOrder::NoGroupSorting:
        mRootItem->appendChildItem(mModelForItemFunctions, ghi);
        break;
    default: // should never happen
        mRootItem->appendChildItem(mModelForItemFunctions, ghi);
        break;
    }

    if (ghi->initialExpandStatus() == Item::ExpandNeeded)   // this actually is a "non viewable expanded state"
        if (ghi->childItemCount() > 0)
            if (mModelForItemFunctions) { // the UI is not disconnected
                syncExpandedStateOfSubtree(ghi);
            }

    // A group header is always viewable, when attached: apply the filter, if we have it.
    if (mFilter) {
        Q_ASSERT(mModelForItemFunctions);   // UI must be NOT disconnected
        // apply the filter to subtree
        applyFilterToSubtree(ghi, QModelIndex());
    }
}

void ModelPrivate::saveExpandedStateOfSubtree(Item *root)
{
    Q_ASSERT(mModelForItemFunctions);   // UI must be NOT disconnected here
    Q_ASSERT(root);

    root->setInitialExpandStatus(Item::ExpandNeeded);

Daniel Vrátil's avatar
Daniel Vrátil committed
1241
    auto children = root->childItems();
1242 1243 1244
    if (!children) {
        return;
    }
Daniel Vrátil's avatar
Daniel Vrátil committed
1245 1246 1247 1248 1249 1250
    for (const auto mi : qAsConst(*children)) {
        if (mi->childItemCount() > 0 &&     // has children
            mi->isViewable() &&   // is actually attached to the viewable root
            mView->isExpanded(q->index(mi, 0)))    // is actually expanded
        {
            saveExpandedStateOfSubtree(mi);
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
        }
    }
}

void ModelPrivate::syncExpandedStateOfSubtree(Item *root)
{
    Q_ASSERT(mModelForItemFunctions);   // UI must be NOT disconnected here

    // WE ASSUME that:
    // - the item is viewable
    // - its initialExpandStatus() is Item::ExpandNeeded
    // - it has at least one children (well.. this is not a strict requirement, but it's a waste of resources to expand items that don't have children)

    QModelIndex idx = q->index(root, 0);

    //if ( !mView->isExpanded( idx ) ) // this is O(logN!) in Qt.... very ugly... but it should never happen here
    mView->expand(idx);   // sync the real state in the view
    root->setInitialExpandStatus(Item::ExpandExecuted);

Daniel Vrátil's avatar
Daniel Vrátil committed
1270
    auto children = root->childItems();
1271 1272 1273 1274
    if (!children) {
        return;
    }

Daniel Vrátil's avatar
Daniel Vrátil committed
1275 1276 1277 1278
    for (const auto mi : qAsConst(*children)) {
        if (mi->initialExpandStatus() == Item::ExpandNeeded) {
            if (mi->childItemCount() > 0) {
                syncExpandedStateOfSubtree(mi);
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
            }
        }
    }
}

void ModelPrivate::attachMessageToGroupHeader(MessageItem *mi)
{
    QString groupLabel;
    time_t date;

    // compute the group header label and the date
    switch (mAggregation->grouping()) {
    case Aggregation::GroupByDate:
    case Aggregation::GroupByDateRange: {
        if (mAggregation->threadLeader() == Aggregation::MostRecentMessage) {
            date = mi->maxDate();
        } else {
            date = mi->date();
        }

        QDateTime dt;
        dt.setTime_t(date);
        QDate dDate = dt.date();
        int daysAgo = -1;
        const int daysInWeek = 7;
        if (dDate.isValid() && mTodayDate.isValid()) {
            daysAgo = dDate.daysTo(mTodayDate);
        }

        if ((daysAgo < 0) ||    // In the future
                (static_cast< uint >(date) == static_cast< uint >(-1))) {      // Invalid
            groupLabel = mCachedUnknownLabel;
        } else if (daysAgo == 0) { // Today
            groupLabel = mCachedTodayLabel;
        } else if (daysAgo == 1) { // Yesterday
            groupLabel = mCachedYesterdayLabel;
        } else if (daysAgo > 1 && daysAgo < daysInWeek) {   // Within last seven days
1316 1317 1318 1319 1320
            auto dayName = mCachedDayNameLabel.find(dDate.dayOfWeek()); // non-const call, but non-shared container
            if (dayName == mCachedDayNameLabel.end()) {
                dayName = mCachedDayNameLabel.insert(dDate.dayOfWeek(), QLocale::system().standaloneDayName(dDate.dayOfWeek()));
            }
            groupLabel = *dayName;
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
        } else if (mAggregation->grouping() == Aggregation::GroupByDate) {   // GroupByDate seven days or more ago
            groupLabel = QLocale::system().toString(dDate, QLocale::ShortFormat);
        } else if (dDate.month() == mTodayDate.month() &&       // GroupByDateRange within this month
                   dDate.year() == mTodayDate.year()) {
            int startOfWeekDaysAgo = (daysInWeek + mTodayDate.dayOfWeek() - QLocale().firstDayOfWeek()) % daysInWeek;
            int weeksAgo = ((daysAgo - startOfWeekDaysAgo) / daysInWeek) + 1;
            switch (weeksAgo) {
            case 0: // This week
                groupLabel = QLocale::system().standaloneDayName(dDate.dayOfWeek());
                break;
            case 1: // 1 week ago
                groupLabel = mCachedLastWeekLabel;
                break;
            case 2:
                groupLabel = mCachedTwoWeeksAgoLabel;
                break;
            case 3:
                groupLabel = mCachedThreeWeeksAgoLabel;
                break;
            case 4:
                groupLabel = mCachedFourWeeksAgoLabel;
                break;
            case 5:
                groupLabel = mCachedFiveWeeksAgoLabel;
                break;
            default: // should never happen
                groupLabel = mCachedUnknownLabel;
            }
        } else if (dDate.year() == mTodayDate.year()) {       // GroupByDateRange within this year
1350 1351 1352 1353 1354
            auto monthName = mCachedMonthNameLabel.find(dDate.month()); // non-const call, but non-shared container
            if (monthName == mCachedMonthNameLabel.end()) {
                monthName = mCachedMonthNameLabel.insert(dDate.month(), QLocale::system().standaloneMonthName(dDate.month()));
            }
            groupLabel = *monthName;
1355
        } else { // GroupByDateRange in previous years
1356 1357 1358 1359 1360
            auto monthName = mCachedMonthNameLabel.find(dDate.month()); // non-const call, but non-shared container
            if (monthName == mCachedMonthNameLabel.end()) {
                monthName = mCachedMonthNameLabel.insert(dDate.month(), QLocale::system().standaloneMonthName(dDate.month()));
            }
            groupLabel = i18nc("Message Aggregation Group Header: Month name and Year number", "%1 %2", *monthName,
1361 1362 1363 1364 1365 1366 1367
                               QLocale::system().toString(dDate, QLatin1Literal("yyyy")));
        }
        break;
    }

    case Aggregation::GroupBySenderOrReceiver:
        date = mi->date();
1368
        groupLabel = mi->displaySenderOrReceiver();
1369 1370 1371 1372
        break;

    case Aggregation::GroupBySender:
        date = mi->date();
1373
        groupLabel = mi->displaySender();
1374 1375 1376 1377
        break;

    case Aggregation::GroupByReceiver:
        date = mi->date();
1378
        groupLabel = mi->displayReceiver();
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
        break;

    case Aggregation::NoGrouping:
        // append directly to root
        attachMessageToParent(mRootItem, mi);
        return;

    default:
        // should never happen
        attachMessageToParent(mRootItem, mi);
        return;
    }

    GroupHeaderItem *ghi;

Laurent Montel's avatar
Laurent Montel committed
1394
    ghi = mGroupHeaderItemHash.value(groupLabel, nullptr);
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
    if (!ghi) {
        // not found

        ghi = new GroupHeaderItem(groupLabel);
        ghi->initialSetup(date, mi->size(), mi->sender(), mi->receiver(), mi->useReceiver());

        switch (mAggregation->groupExpandPolicy()) {
        case Aggregation::NeverExpandGroups:
            // nothing to do
            break;
        case Aggregation::AlwaysExpandGroups:
            // expand always
            ghi->setInitialExpandStatus(Item::ExpandNeeded);
            break;
        case Aggregation::ExpandRecentGroups:
            // expand only if "close" to today
            if (mViewItemJobStepStartTime > ghi->date()) {
                if ((mViewItemJobStepStartTime - ghi->date()) < (3600 * 72)) {
                    ghi->setInitialExpandStatus(Item::ExpandNeeded);
                }
            } else {
                if ((ghi->date() - mViewItemJobStepStartTime) < (3600 * 72)) {
                    ghi->setInitialExpandStatus(Item::ExpandNeeded);
                }
            }
            break;
        default:
            // b0rken
            break;
        }

        attachMessageToParent(ghi, mi);

        attachGroup(ghi);   // this will expand the group if required

        mGroupHeaderItemHash.insert(groupLabel, ghi);
    } else {
        // the group was already there (certainly viewable)

        // This function may be also called to re-group a message.
        // That is, to eventually find a new group for a message that has changed
        // its properties (but was already attacched to a group).
        // So it may happen that we find out that in fact re-grouping wasn't really
        // needed because the message is already in the correct group.
        if (mi->parent() == ghi) {
            return;    // nothing to be done
        }

        attachMessageToParent(ghi, mi);
    }
1445 1446

    // Remember this message as a thread leader
Laurent Montel's avatar
Laurent Montel committed
1447
    mThreadingCache.updateParent(mi, nullptr);
1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477
}

MessageItem *ModelPrivate::findMessageParent(MessageItem *mi)
{
    Q_ASSERT(mAggregation->threading() != Aggregation::NoThreading);   // caller must take care of this

    // This function attempts to find a thread parent for the item "mi"
    // which actually may already have a children subtree.

    // Forged or plain broken message trees are dangerous here.
    // For example, a message tree with circular references like
    //
    //        Message mi, Id=1, In-Reply-To=2
    //          Message childOfMi, Id=2, In-Reply-To=1
    //
    // is perfectly possible and will cause us to find childOfMi
    // as parent of mi. This will then create a loop in the message tree
    // (which will then no longer be a tree in fact) and cause us to freeze
    // once we attempt to climb the parents. We need to take care of that.

    bool bMessageWasThreadable = false;
    MessageItem *pParent;

    // First of all try to find a "perfect parent", that is the message for that
    // we have the ID in the "In-Reply-To" field. This is actually done by using
    // MD5 caches of the message ids because of speed. Collisions are very unlikely.

    QByteArray md5 = mi->inReplyToIdMD5();
    if (!md5.isEmpty()) {
        // have an In-Reply-To field MD5
Laurent Montel's avatar
Laurent Montel committed
1478
        pParent = mThreadingCacheMessageIdMD5ToMessageItem.value(md5, nullptr);
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
        if (pParent) {
            // Take care of circular references
            if (
                (mi == pParent) ||                // self referencing message
                (
                    (mi->childItemCount() > 0) &&   // mi already has children, this is fast to determine
                    pParent->hasAncestor(mi)        // pParent is in the mi's children tree
                )
            ) {
                qCWarning(MESSAGELIST_LOG) << "Circular In-Reply-To reference loop detected in the message tree";
                mi->setThreadingStatus(MessageItem::NonThreadable);
Laurent Montel's avatar
Laurent Montel committed
1490
                return nullptr; // broken message: throw it away
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501
            }
            mi->setThreadingStatus(MessageItem::PerfectParentFound);
            return pParent; // got a perfect parent for this message
        }

        // got no perfect parent
        bMessageWasThreadable = true; // but the message was threadable
    }

    if (mAggregation->threading() == Aggregation::PerfectOnly) {
        mi->setThreadingStatus(bMessageWasThreadable ? MessageItem::ParentMissing : MessageItem::NonThreadable);
Laurent Montel's avatar
Laurent Montel committed
1502
        return nullptr; // we're doing only perfect parent matches
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
    }

    // Try to use the "References" field. In fact we have the MD5 of the
    // (n-1)th entry in References.
    //
    // Original rationale from KMHeaders:
    //
    // If we don't have a replyToId, or if we have one and the
    // corresponding message is not in this folder, as happens
    // if you keep your outgoing messages in an OUTBOX, for
    // example, try the list of references, because the second
    // to last will likely be in this folder. replyToAuxIdMD5
    // contains the second to last one.

    md5 = mi->referencesIdMD5();
    if (!md5.isEmpty()) {
Laurent Montel's avatar
Laurent Montel committed
1519
        pParent = mThreadingCacheMessageIdMD5ToMessageItem.value(md5, nullptr);
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
        if (pParent) {
            // Take care of circular references
            if (
                (mi == pParent) ||                // self referencing message
                (
                    (mi->childItemCount() > 0) &&   // mi already has children, this is fast to determine
                    pParent->hasAncestor(mi)        // pParent is in the mi's children tree
                )
            ) {
                qCWarning(MESSAGELIST_LOG) << "Circular reference loop detected in the message tree";
                mi->setThreadingStatus(MessageItem::NonThreadable);
Laurent Montel's avatar
Laurent Montel committed
1531
                return nullptr; // broken message: throw it away
1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
            }
            mi->setThreadingStatus(MessageItem::ImperfectParentFound);
            return pParent; // got an imperfect parent for this message
        }

        // got no imperfect parent
        bMessageWasThreadable = true; // but the message was threadable
    }

    if (mAggregation->threading() == Aggregation::PerfectAndReferences) {
        mi->setThreadingStatus(bMessageWasThreadable ? MessageItem::ParentMissing : MessageItem::NonThreadable);
Laurent Montel's avatar
Laurent Montel committed
1543
        return nullptr; // we're doing only perfect parent matches
1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554
    }

    Q_ASSERT(mAggregation->threading() == Aggregation::PerfectReferencesAndSubject);

    // We are supposed to do subject based threading but we can't do it now.
    // This is because the subject based threading *may* be wrong and waste
    // time by creating circular references (that we'd need to detect and fix).
    // We first try the perfect and references based threading on all the messages
    // and then run subject based threading only on the remaining ones.

    mi->setThreadingStatus((bMessageWasThreadable || mi->subjectIsPrefixed()) ? MessageItem::ParentMissing : MessageItem::NonThreadable);
Laurent Montel's avatar
Laurent Montel committed
1555
    return nullptr;
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
}

// Subject threading cache stuff

#if 0
// Debug helpers
void dump_iterator_and_list(QList< MessageItem * >::Iterator &iter, QList< MessageItem * > *list)
{
    qCDebug(MESSAGELIST_LOG) << "Threading cache part dump";
    if (iter == list->end()) {
        qCDebug(MESSAGELIST_LOG) << "Iterator pointing to end of the list";
    } else {
        qCDebug(MESSAGELIST_LOG) << "Iterator pointing to " << *iter << " subject [" << (*iter)->subject() << "] date [" << (*iter)->date() << "]";
    }

    for (QList< MessageItem * >::Iterator it = list->begin(); it != list->end(); ++it) {
        qCDebug(MESSAGELIST_LOG) << "List element " << *it << " subject [" << (*it)->subject() << "] date [" << (*it)->date() << "]";
    }

    qCDebug(MESSAGELIST_LOG) << "End of threading cache part dump";
}

void dump_list(QList< MessageItem * > *list)
{
    qCDebug(MESSAGELIST_LOG) << "Threading cache part dump";

    for (QList< MessageItem * >::Iterator it = list->begin(); it != list->end(); ++it) {
        qCDebug(MESSAGELIST_LOG) << "List element " << *it << " subject [" << (*it)->subject() << "] date [" << (*it)->date() << "]";
    }

    qCDebug(MESSAGELIST_LOG) << "End of threading cache part dump";
}
#endif // debug helpers

// a helper class used in a qLowerBound() call below
class MessageLessThanByDate
{
public:
    inline bool operator()(const MessageItem *mi1, const MessageItem *mi2) const
    {
        if (mi1->date() < mi2->date()) { // likely
            return true;
        }
        if (mi1->date() > mi2->date()) { // likely
            return false;
        }
        // dates are equal, compare by pointer
        return mi1 < mi2;
    }
};

void ModelPrivate::addMessageToSubjectBasedThreadingCache(MessageItem *mi)
{
    // Messages in this cache are sorted by date, and if dates are equal then they are sorted by pointer value.
    // Sorting by date is used to optimize the parent lookup in guessMessageParent() below.

    // WARNING: If the message date changes for some reason (like in the "update" step)
    //          then the cache may become unsorted. For this reason the message about to
    //          be changed must be first removed from the cache and then reinserted.

    // Lookup the list of messages with the same stripped subject
Daniel Vrátil's avatar
Daniel Vrátil committed
1617
    auto messagesWithTheSameStrippedSubject = mThreadingCacheMessageSubjectMD5ToMessageItem.value(mi->strippedSubjectMD5(), nullptr);
1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630

    if (!messagesWithTheSameStrippedSubject) {
        // Not there yet: create it and append.
        messagesWithTheSameStrippedSubject = new QList< MessageItem * >();
        mThreadingCacheMessageSubjectMD5ToMessageItem.insert(mi->strippedSubjectMD5(), messagesWithTheSameStrippedSubject);
        messagesWithTheSameStrippedSubject->append(mi);
        return;
    }

    // Found: assert that we have no duplicates in the cache.
    Q_ASSERT(!messagesWithTheSameStrippedSubject->contains(mi));

    // Ordered insert: first by date then by pointer value.
Daniel Vrátil's avatar
Daniel Vrátil committed
1631
    auto it = qLowerBound(messagesWithTheSameStrippedSubject->begin(), messagesWithTheSameStrippedSubject->end(), mi, MessageLessThanByDate());
1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642
    messagesWithTheSameStrippedSubject->insert(it, mi);
}

void ModelPrivate::removeMessageFromSubjectBasedThreadingCache(MessageItem *mi)
{
    // We assume that the caller knows what he is doing and the message is actually in the cache.
    // If the message isn't in the cache then we should be called at all.
    //
    // The game is called "performance"

    // Grab the list of all the messages with the same stripped subject (all potential parents)
Daniel Vrátil's avatar
Daniel Vrátil committed
1643
    auto messagesWithTheSameStrippedSubject = mThreadingCacheMessageSubjectMD5ToMessageItem.value(mi->strippedSubjectMD5(), nullptr);
1644 1645 1646 1647 1648

    // We assume that the message is there so the list must be non null.
    Q_ASSERT(messagesWithTheSameStrippedSubject);

    // The cache *MUST* be ordered first by date then by pointer value
Daniel Vrátil's avatar
Daniel Vrátil committed
1649
    auto it = qLowerBound(messagesWithTheSameStrippedSubject->begin(), messagesWithTheSameStrippedSubject->end(), mi, MessageLessThanByDate());
1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682

    // The binary based search must have found a message
    Q_ASSERT(it != messagesWithTheSameStrippedSubject->end());

    // and it must have found exactly the message requested
    Q_ASSERT(*it == mi);

    // Kill it
    messagesWithTheSameStrippedSubject->erase(it);

    // And kill the list if it was the last one
    if (messagesWithTheSameStrippedSubject->isEmpty()) {
        mThreadingCacheMessageSubjectMD5ToMessageItem.remove(mi->strippedSubjectMD5());
        delete messagesWithTheSameStrippedSubject;
    }
}

MessageItem *ModelPrivate::guessMessageParent(MessageItem *mi)
{
    // This function implements subject based threading
    // It attempts to guess a thread parent for the item "mi"
    // which actually may already have a children subtree.

    // We have all the problems of findMessageParent() plus the fact that
    // we're actually guessing (and often we may be *wrong*).

    Q_ASSERT(mAggregation->threading() == Aggregation::PerfectReferencesAndSubject);   // caller must take care of this
    Q_ASSERT(mi->subjectIsPrefixed());   // caller must take care of this
    Q_ASSERT(mi->threadingStatus() == MessageItem::ParentMissing);

    // Do subject based threading
    const QByteArray md5 = mi->strippedSubjectMD5();
    if (!md5.isEmpty()) {
Daniel Vrátil's avatar
Daniel Vrátil committed
1683
        auto messagesWithTheSameStrippedSubject = mThreadingCacheMessageSubjectMD5ToMessageItem.value(md5, nullptr);
1684 1685 1686 1687 1688 1689 1690

        if (messagesWithTheSameStrippedSubject) {
            Q_ASSERT(messagesWithTheSameStrippedSubject->count() > 0);

            // Need to find the message with the maximum date lower than the one of this message

            time_t maxTime = (time_t)0;
Laurent Montel's avatar
Laurent Montel committed
1691
            MessageItem *pParent = nullptr;
1692 1693 1694 1695 1696 1697 1698

            // Here'we re really guessing so circular references are possible
            // even on perfectly valid trees. This is why we don't consider it
            // an error but just continue searching.

            // FIXME: This might be speed up with an initial binary search (?)
            // ANSWER: No. We can't rely on date order (as it can be updated on the fly...)
Daniel Vrátil's avatar
Daniel Vrátil committed
1699 1700
            for (const auto it : qAsConst(*messagesWithTheSameStrippedSubject)) {
                int delta = mi->date() - it->date();
1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721

                // We don't take into account messages with a delta smaller than 120.
                // Assuming that our date() values are correct (that is, they take into
                // account timezones etc..) then one usually needs more than 120 seconds
                // to answer to a message. Better safe than sorry.

                // This check also includes negative deltas so messages later than mi aren't considered

                if (delta < 120) {
                    break;    // The list is ordered by date (ascending) so we can stop searching here
                }

                // About the "magic" 3628899 value here comes a Till's comment from the original KMHeaders:
                //
                //   "Parents more than six weeks older than the message are not accepted. The reasoning being
                //   that if a new message with the same subject turns up after such a long time, the chances
                //   that it is still part of the same thread are slim. The value of six weeks is chosen as a
                //   result of a poll conducted on kde-devel, so it's probably bogus. :)"

                if (delta < 3628899) {
                    // Compute the closest.
Daniel Vrátil's avatar
Daniel Vrátil committed
1722
                    if ((maxTime < it->date())) {
1723 1724
                        // This algorithm *can* be (and often is) wrong.
                        // Take care of circular threading which is really possible at this level.
Daniel Vrátil's avatar
Daniel Vrátil committed
1725
                        // If mi contains "it" inside its children subtree then we have
1726 1727
                        // found such a circular threading problem.

Daniel Vrátil's avatar
Daniel Vrátil committed
1728
                        // Note that here we can't have it == mi because of the delta >= 120 check above.
1729

Daniel Vrátil's avatar
Daniel Vrátil committed
1730 1731 1732
                        if ((mi->childItemCount() == 0) || !it->hasAncestor(mi)) {
                            maxTime = it->date();
                            pParent = it;
1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744
                        }
                    }
                }
            }

            if (pParent) {
                mi->setThreadingStatus(MessageItem::ImperfectParentFound);
                return pParent; // got an imperfect parent for this message
            }
        }
    }

Laurent Montel's avatar
Laurent Montel committed
1745
    return nullptr;
1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993