treemodel.cpp 31.9 KB
Newer Older
hjk's avatar
hjk committed
1 2
/****************************************************************************
**
Eike Ziller's avatar
Eike Ziller committed
3 4
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
hjk's avatar
hjk committed
5 6 7 8 9 10 11
**
** This file is part of Qt Creator.
**
** 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
Eike Ziller's avatar
Eike Ziller committed
12 13
** a written agreement between you and The Qt Company.  For licensing terms and
** conditions see http://www.qt.io/terms-conditions.  For further information
Eike Ziller's avatar
Eike Ziller committed
14
** use the contact form at http://www.qt.io/contact-us.
hjk's avatar
hjk committed
15 16 17
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
Eike Ziller's avatar
Eike Ziller committed
18 19 20 21 22 23
** 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.
hjk's avatar
hjk committed
24
**
Eike Ziller's avatar
Eike Ziller committed
25 26
** In addition, as a special exception, The Qt Company gives you certain additional
** rights.  These rights are described in The Qt Company LGPL Exception
hjk's avatar
hjk committed
27 28 29 30 31 32 33
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "treemodel.h"
#include "qtcassert.h"

hjk's avatar
hjk committed
34 35
#include <QStack>
#include <QSize>
hjk's avatar
hjk committed
36

hjk's avatar
hjk committed
37 38
#define USE_MODEL_TEST 0
#define USE_INDEX_CHECKS 0
hjk's avatar
hjk committed
39

hjk's avatar
hjk committed
40
#if USE_INDEX_CHECKS
41 42 43 44 45 46 47 48 49 50 51 52
#define CHECK_INDEX(index) \
    do { \
        if (index.isValid()) { \
            QTC_CHECK(index.model() == this); \
        } else { \
            QTC_CHECK(index.model() == 0); \
        } \
    } while (false)
#else
#define CHECK_INDEX(index)
#endif

hjk's avatar
hjk committed
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
#if USE_MODEL_TEST

namespace  {

class ModelTest : public QObject
{
public:
    ModelTest(QAbstractItemModel *model, QObject *parent = 0);

private:
    void nonDestructiveBasicTest();
    void rowCount();
    void columnCount();
    void hasIndex();
    void index();
    void parent();
    void data();

protected:
    void runAllTests();
    void layoutAboutToBeChanged();
    void layoutChanged();
    void rowsAboutToBeInserted(const QModelIndex &parent, int start, int end);
    void rowsInserted(const QModelIndex & parent, int start, int end);
    void rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end);
    void rowsRemoved(const QModelIndex & parent, int start, int end);

private:
    void checkChildren(const QModelIndex &parent, int currentDepth = 0);

    QAbstractItemModel *model;

    struct Changing
    {
        QModelIndex parent;
        int oldSize;
        QVariant last;
        QVariant next;
    };
    QStack<Changing> insert;
    QStack<Changing> remove;

    bool fetchingMore;

    QList<QPersistentModelIndex> changing;
};

/*!
    Connect to all of the models signals.  Whenever anything happens
    recheck everything.
*/
ModelTest::ModelTest(QAbstractItemModel *_model, QObject *parent) : QObject(parent), model(_model), fetchingMore(false)
{
    Q_ASSERT(model);

    connect(model, &QAbstractItemModel::columnsAboutToBeInserted,
            this, &ModelTest::runAllTests);
    connect(model, &QAbstractItemModel::columnsAboutToBeRemoved,
            this, &ModelTest::runAllTests);
    connect(model, &QAbstractItemModel::columnsInserted,
            this, &ModelTest::runAllTests);
    connect(model, &QAbstractItemModel::columnsRemoved,
            this, &ModelTest::runAllTests);
    connect(model, &QAbstractItemModel::dataChanged,
            this, &ModelTest::runAllTests);
    connect(model, &QAbstractItemModel::headerDataChanged,
            this, &ModelTest::runAllTests);
    connect(model, &QAbstractItemModel::layoutAboutToBeChanged, this, &ModelTest::runAllTests);
    connect(model, &QAbstractItemModel::layoutChanged, this, &ModelTest::runAllTests);
    connect(model, &QAbstractItemModel::modelReset, this, &ModelTest::runAllTests);
    connect(model, &QAbstractItemModel::rowsAboutToBeInserted,
            this, &ModelTest::runAllTests);
    connect(model, &QAbstractItemModel::rowsAboutToBeRemoved,
            this, &ModelTest::runAllTests);
    connect(model, &QAbstractItemModel::rowsInserted,
            this, &ModelTest::runAllTests);
    connect(model, &QAbstractItemModel::rowsRemoved,
            this, &ModelTest::runAllTests);

    // Special checks for inserting/removing
    connect(model, &QAbstractItemModel::layoutAboutToBeChanged,
            this, &ModelTest::layoutAboutToBeChanged);
    connect(model, &QAbstractItemModel::layoutChanged,
            this, &ModelTest::layoutChanged);

    connect(model, &QAbstractItemModel::rowsAboutToBeInserted,
            this, &ModelTest::rowsAboutToBeInserted);
    connect(model, &QAbstractItemModel::rowsAboutToBeRemoved,
            this, &ModelTest::rowsAboutToBeRemoved);
    connect(model, &QAbstractItemModel::rowsInserted,
            this, &ModelTest::rowsInserted);
    connect(model, &QAbstractItemModel::rowsRemoved,
            this, &ModelTest::rowsRemoved);

    runAllTests();
}

void ModelTest::runAllTests()
{
    if (fetchingMore)
        return;
    nonDestructiveBasicTest();
    rowCount();
    columnCount();
    hasIndex();
    index();
    parent();
    data();
}

/*!
    nonDestructiveBasicTest tries to call a number of the basic functions (not all)
    to make sure the model doesn't outright segfault, testing the functions that makes sense.
*/
void ModelTest::nonDestructiveBasicTest()
{
    Q_ASSERT(model->buddy(QModelIndex()) == QModelIndex());
    model->canFetchMore(QModelIndex());
    Q_ASSERT(model->columnCount(QModelIndex()) >= 0);
    Q_ASSERT(model->data(QModelIndex()) == QVariant());
    fetchingMore = true;
    model->fetchMore(QModelIndex());
    fetchingMore = false;
    Qt::ItemFlags flags = model->flags(QModelIndex());
    Q_ASSERT(flags == Qt::ItemIsDropEnabled || flags == 0);
    model->hasChildren(QModelIndex());
    model->hasIndex(0, 0);
    model->headerData(0, Qt::Horizontal);
    model->index(0, 0);
    model->itemData(QModelIndex());
    QVariant cache;
    model->match(QModelIndex(), -1, cache);
    model->mimeTypes();
    QModelIndex m1 = model->parent(QModelIndex());
    QModelIndex m2 = QModelIndex();
    Q_ASSERT(m1 == m2);
    Q_ASSERT(model->parent(QModelIndex()) == QModelIndex());
    Q_ASSERT(model->rowCount() >= 0);
    QVariant variant;
    model->setData(QModelIndex(), variant, -1);
    model->setHeaderData(-1, Qt::Horizontal, QVariant());
    model->setHeaderData(999999, Qt::Horizontal, QVariant());
    QMap<int, QVariant> roles;
    model->sibling(0, 0, QModelIndex());
    model->span(QModelIndex());
    model->supportedDropActions();
}

/*!
    Tests model's implementation of QAbstractItemModel::rowCount() and hasChildren()

    Models that are dynamically populated are not as fully tested here.
 */
void ModelTest::rowCount()
{
    // check top row
    QModelIndex topIndex = model->index(0, 0, QModelIndex());
    int rows = model->rowCount(topIndex);
    Q_ASSERT(rows >= 0);
    if (rows > 0)
        Q_ASSERT(model->hasChildren(topIndex) == true);

    QModelIndex secondLevelIndex = model->index(0, 0, topIndex);
    if (secondLevelIndex.isValid()) { // not the top level
        // check a row count where parent is valid
        rows = model->rowCount(secondLevelIndex);
        Q_ASSERT(rows >= 0);
        if (rows > 0)
            Q_ASSERT(model->hasChildren(secondLevelIndex) == true);
    }

    // The models rowCount() is tested more extensively in checkChildren(),
    // but this catches the big mistakes
}

/*!
    Tests model's implementation of QAbstractItemModel::columnCount() and hasChildren()
 */
void ModelTest::columnCount()
{
    // check top row
    QModelIndex topIndex = model->index(0, 0, QModelIndex());
    Q_ASSERT(model->columnCount(topIndex) >= 0);

    // check a column count where parent is valid
    QModelIndex childIndex = model->index(0, 0, topIndex);
    if (childIndex.isValid())
        Q_ASSERT(model->columnCount(childIndex) >= 0);

    // columnCount() is tested more extensively in checkChildren(),
    // but this catches the big mistakes
}

/*!
    Tests model's implementation of QAbstractItemModel::hasIndex()
 */
void ModelTest::hasIndex()
{
    // Make sure that invalid values returns an invalid index
    Q_ASSERT(model->hasIndex(-2, -2) == false);
    Q_ASSERT(model->hasIndex(-2, 0) == false);
    Q_ASSERT(model->hasIndex(0, -2) == false);

    int rows = model->rowCount();
    int columns = model->columnCount();

    // check out of bounds
    Q_ASSERT(model->hasIndex(rows, columns) == false);
    Q_ASSERT(model->hasIndex(rows + 1, columns + 1) == false);

    if (rows > 0)
        Q_ASSERT(model->hasIndex(0, 0) == true);

    // hasIndex() is tested more extensively in checkChildren(),
    // but this catches the big mistakes
}

/*!
    Tests model's implementation of QAbstractItemModel::index()
 */
void ModelTest::index()
{
    // Make sure that invalid values returns an invalid index
    Q_ASSERT(model->index(-2, -2) == QModelIndex());
    Q_ASSERT(model->index(-2, 0) == QModelIndex());
    Q_ASSERT(model->index(0, -2) == QModelIndex());

    int rows = model->rowCount();
    int columns = model->columnCount();

    if (rows == 0)
        return;

    // Catch off by one errors
    QModelIndex tmp;
    tmp = model->index(rows, columns);
    Q_ASSERT(tmp == QModelIndex());
    tmp = model->index(0, 0);
    Q_ASSERT(tmp.isValid() == true);

    // Make sure that the same index is *always* returned
    QModelIndex a = model->index(0, 0);
    QModelIndex b = model->index(0, 0);
    Q_ASSERT(a == b);

    // index() is tested more extensively in checkChildren(),
    // but this catches the big mistakes
}

/*!
    Tests model's implementation of QAbstractItemModel::parent()
 */
void ModelTest::parent()
{
    // Make sure the model wont crash and will return an invalid QModelIndex
    // when asked for the parent of an invalid index.
    Q_ASSERT(model->parent(QModelIndex()) == QModelIndex());

    if (model->rowCount() == 0)
        return;

    QModelIndex tmp;

    // Column 0                | Column 1    |
    // QModelIndex()           |             |
    //    \- topIndex          | topIndex1   |
    //         \- childIndex   | childIndex1 |

    // Common error test #1, make sure that a top level index has a parent
    // that is a invalid QModelIndex.
    QModelIndex topIndex = model->index(0, 0, QModelIndex());
    tmp = model->parent(topIndex);
    Q_ASSERT(tmp == QModelIndex());

    // Common error test #2, make sure that a second level index has a parent
    // that is the first level index.
    if (model->rowCount(topIndex) > 0) {
        QModelIndex childIndex = model->index(0, 0, topIndex);
        tmp = model->parent(childIndex);
        Q_ASSERT(tmp == topIndex);
    }

    // Common error test #3, the second column should NOT have the same children
    // as the first column in a row.
    // Usually the second column shouldn't have children.
    QModelIndex topIndex1 = model->index(0, 1, QModelIndex());
    if (model->rowCount(topIndex1) > 0) {
        QModelIndex childIndex = model->index(0, 0, topIndex);
        QModelIndex childIndex1 = model->index(0, 0, topIndex1);
        Q_ASSERT(childIndex != childIndex1);
    }

    // Full test, walk n levels deep through the model making sure that all
    // parent's children correctly specify their parent.
    checkChildren(QModelIndex());
}

/*!
    Called from the parent() test.

    A model that returns an index of parent X should also return X when asking
    for the parent of the index.

    This recursive function does pretty extensive testing on the whole model in an
    effort to catch edge cases.

    This function assumes that rowCount(), columnCount() and index() already work.
    If they have a bug it will point it out, but the above tests should have already
    found the basic bugs because it is easier to figure out the problem in
    those tests then this one.
 */
void ModelTest::checkChildren(const QModelIndex &parent, int currentDepth)
{
    QModelIndex tmp;

    // First just try walking back up the tree.
    QModelIndex p = parent;
    while (p.isValid())
        p = p.parent();

    // For models that are dynamically populated
    if (model->canFetchMore(parent)) {
        fetchingMore = true;
        model->fetchMore(parent);
        fetchingMore = false;
    }

    int rows = model->rowCount(parent);
    int columns = model->columnCount(parent);

    if (rows > 0)
        Q_ASSERT(model->hasChildren(parent));

    // Some further testing against rows(), columns(), and hasChildren()
    Q_ASSERT(rows >= 0);
    Q_ASSERT(columns >= 0);
    if (rows > 0)
        Q_ASSERT(model->hasChildren(parent) == true);

    //qDebug() << "parent:" << model->data(parent).toString() << "rows:" << rows
    //         << "columns:" << columns << "parent column:" << parent.column();

    Q_ASSERT(model->hasIndex(rows + 1, 0, parent) == false);
    for (int r = 0; r < rows; ++r) {
        if (model->canFetchMore(parent)) {
            fetchingMore = true;
            model->fetchMore(parent);
            fetchingMore = false;
        }
        Q_ASSERT(model->hasIndex(r, columns + 1, parent) == false);
        for (int c = 0; c < columns; ++c) {
            Q_ASSERT(model->hasIndex(r, c, parent) == true);
            QModelIndex index = model->index(r, c, parent);
            // rowCount() and columnCount() said that it existed...
            Q_ASSERT(index.isValid() == true);

            // index() should always return the same index when called twice in a row
            QModelIndex modifiedIndex = model->index(r, c, parent);
            Q_ASSERT(index == modifiedIndex);

            // Make sure we get the same index if we request it twice in a row
            QModelIndex a = model->index(r, c, parent);
            QModelIndex b = model->index(r, c, parent);
            Q_ASSERT(a == b);

            // Some basic checking on the index that is returned
            Q_ASSERT(index.model() == model);
            Q_ASSERT(index.row() == r);
            Q_ASSERT(index.column() == c);
            // While you can technically return a QVariant usually this is a sign
            // of an bug in data()  Disable if this really is ok in your model.
            //Q_ASSERT(model->data(index, Qt::DisplayRole).isValid() == true);

            // If the next test fails here is some somewhat useful debug you play with.
            /*
            if (model->parent(index) != parent) {
                qDebug() << r << c << currentDepth << model->data(index).toString()
                         << model->data(parent).toString();
                qDebug() << index << parent << model->parent(index);
                // And a view that you can even use to show the model.
                //QTreeView view;
                //view.setModel(model);
                //view.show();
            }*/

            // Check that we can get back our real parent.
            //qDebug() << "TTT 1: " << model->parent(index);
            //qDebug() << "TTT 2: " << parent;
            //qDebug() << "TTT 3: " << index;
            tmp = model->parent(index);
            Q_ASSERT(tmp == parent);

            // recursively go down the children
            if (model->hasChildren(index) && currentDepth < 10 ) {
                //qDebug() << r << c << "has children" << model->rowCount(index);
                checkChildren(index, ++currentDepth);
            }/* else { if (currentDepth >= 10) qDebug() << "checked 10 deep"; };*/

            // make sure that after testing the children that the index doesn't change.
            QModelIndex newerIndex = model->index(r, c, parent);
            Q_ASSERT(index == newerIndex);
        }
    }
}

/*!
    Tests model's implementation of QAbstractItemModel::data()
 */
void ModelTest::data()
{
    // Invalid index should return an invalid qvariant
    Q_ASSERT(!model->data(QModelIndex()).isValid());

    if (model->rowCount() == 0)
        return;

    // A valid index should have a valid QVariant data
    Q_ASSERT(model->index(0, 0).isValid());

    // shouldn't be able to set data on an invalid index
    Q_ASSERT(model->setData(QModelIndex(), QLatin1String("foo"), Qt::DisplayRole) == false);

    // General Purpose roles that should return a QString
    QVariant variant = model->data(model->index(0, 0), Qt::ToolTipRole);
    if (variant.isValid())
        Q_ASSERT(variant.canConvert(QVariant::String));
    variant = model->data(model->index(0, 0), Qt::StatusTipRole);
    if (variant.isValid())
        Q_ASSERT(variant.canConvert(QVariant::String));
    variant = model->data(model->index(0, 0), Qt::WhatsThisRole);
    if (variant.isValid())
        Q_ASSERT(variant.canConvert(QVariant::String));

    // General Purpose roles that should return a QSize
    variant = model->data(model->index(0, 0), Qt::SizeHintRole);
    if (variant.isValid())
        Q_ASSERT(variant.canConvert(QVariant::Size));

    // General Purpose roles that should return a QFont
    QVariant fontVariant = model->data(model->index(0, 0), Qt::FontRole);
    if (fontVariant.isValid())
        Q_ASSERT(fontVariant.canConvert(QVariant::Font));

    // Check that the alignment is one we know about
    QVariant textAlignmentVariant = model->data(model->index(0, 0), Qt::TextAlignmentRole);
    if (textAlignmentVariant.isValid()) {
        int alignment = textAlignmentVariant.toInt();
       Q_ASSERT(alignment == (alignment & (Qt::AlignHorizontal_Mask | Qt::AlignVertical_Mask)));
    }

    // General Purpose roles that should return a QColor
    QVariant colorVariant = model->data(model->index(0, 0), Qt::BackgroundColorRole);
    if (colorVariant.isValid())
        Q_ASSERT(colorVariant.canConvert(QVariant::Color));

    colorVariant = model->data(model->index(0, 0), Qt::TextColorRole);
    if (colorVariant.isValid())
        Q_ASSERT(colorVariant.canConvert(QVariant::Color));

    // Check that the "check state" is one we know about.
    QVariant checkStateVariant = model->data(model->index(0, 0), Qt::CheckStateRole);
    if (checkStateVariant.isValid()) {
        int state = checkStateVariant.toInt();
        Q_ASSERT(state == Qt::Unchecked ||
                 state == Qt::PartiallyChecked ||
                 state == Qt::Checked);
    }
}

/*!
    Store what is about to be inserted to make sure it actually happens

    \sa rowsInserted()
 */
void ModelTest::rowsAboutToBeInserted(const QModelIndex &parent, int start, int end)
{
    Q_UNUSED(end);
    Changing c;
    c.parent = parent;
    c.oldSize = model->rowCount(parent);
    c.last = model->data(model->index(start - 1, 0, parent));
    c.next = model->data(model->index(start, 0, parent));
    insert.push(c);
}

/*!
    Confirm that what was said was going to happen actually did

    \sa rowsAboutToBeInserted()
 */
void ModelTest::rowsInserted(const QModelIndex & parent, int start, int end)
{
    Changing c = insert.pop();
    Q_ASSERT(c.parent == parent);
    Q_ASSERT(c.oldSize + (end - start + 1) == model->rowCount(parent));
    Q_ASSERT(c.last == model->data(model->index(start - 1, 0, c.parent)));
    /*
    if (c.next != model->data(model->index(end + 1, 0, c.parent))) {
        qDebug() << start << end;
        for (int i=0; i < model->rowCount(); ++i)
            qDebug() << model->index(i, 0).data().toString();
        qDebug() << c.next << model->data(model->index(end + 1, 0, c.parent));
    }
    */
    Q_ASSERT(c.next == model->data(model->index(end + 1, 0, c.parent)));
}

void ModelTest::layoutAboutToBeChanged()
{
    for (int i = 0; i < qBound(0, model->rowCount(), 100); ++i)
        changing.append(QPersistentModelIndex(model->index(i, 0)));
}

void ModelTest::layoutChanged()
{
    for (int i = 0; i < changing.count(); ++i) {
        QPersistentModelIndex p = changing[i];
        Q_ASSERT(p == model->index(p.row(), p.column(), p.parent()));
    }
    changing.clear();
}

/*!
    Store what is about to be inserted to make sure it actually happens

    \sa rowsRemoved()
 */
void ModelTest::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
{
    Changing c;
    c.parent = parent;
    c.oldSize = model->rowCount(parent);
    c.last = model->data(model->index(start - 1, 0, parent));
    c.next = model->data(model->index(end + 1, 0, parent));
    remove.push(c);
}

/*!
    Confirm that what was said was going to happen actually did

    \sa rowsAboutToBeRemoved()
 */
void ModelTest::rowsRemoved(const QModelIndex & parent, int start, int end)
{
    Changing c = remove.pop();
    Q_ASSERT(c.parent == parent);
    Q_ASSERT(c.oldSize - (end - start + 1) == model->rowCount(parent));
    Q_ASSERT(c.last == model->data(model->index(start - 1, 0, c.parent)));
    Q_ASSERT(c.next == model->data(model->index(start, 0, c.parent)));
}

} // anon namespace

#endif // ModelTest

hjk's avatar
hjk committed
608 609 610 611 612 613
namespace Utils {

//
// TreeItem
//
TreeItem::TreeItem()
hjk's avatar
hjk committed
614
    : m_parent(0), m_model(0), m_displays(0), m_flags(Qt::ItemIsEnabled|Qt::ItemIsSelectable)
615 616 617
{
}

618
TreeItem::TreeItem(const QStringList &displays, int flags)
hjk's avatar
hjk committed
619
    : m_parent(0), m_model(0), m_displays(new QStringList(displays)), m_flags(flags)
hjk's avatar
hjk committed
620 621 622 623 624
{
}

TreeItem::~TreeItem()
{
hjk's avatar
hjk committed
625 626
    QTC_CHECK(m_parent == 0);
    QTC_CHECK(m_model == 0);
627
    removeChildren();
628
    delete m_displays;
hjk's avatar
hjk committed
629 630 631 632 633
}

TreeItem *TreeItem::child(int pos) const
{
    QTC_ASSERT(pos >= 0, return 0);
hjk's avatar
hjk committed
634
    return pos < m_children.size() ? m_children.at(pos) : 0;
hjk's avatar
hjk committed
635 636 637 638 639 640 641 642 643
}

int TreeItem::rowCount() const
{
    return m_children.size();
}

QVariant TreeItem::data(int column, int role) const
{
644 645
    if (role == Qt::DisplayRole && m_displays && column >= 0 && column < m_displays->size())
        return m_displays->at(column);
hjk's avatar
hjk committed
646 647 648
    return QVariant();
}

649 650 651 652 653 654 655 656
bool TreeItem::setData(int column, const QVariant &data, int role)
{
    Q_UNUSED(column);
    Q_UNUSED(data);
    Q_UNUSED(role);
    return false;
}

hjk's avatar
hjk committed
657 658 659 660 661 662
Qt::ItemFlags TreeItem::flags(int column) const
{
    Q_UNUSED(column);
    return m_flags;
}

663 664 665 666 667
bool TreeItem::hasChildren() const
{
    return canFetchMore() || rowCount() > 0;
}

hjk's avatar
hjk committed
668
bool TreeItem::canFetchMore() const
hjk's avatar
hjk committed
669
{
hjk's avatar
hjk committed
670 671
    return false;
}
hjk's avatar
hjk committed
672

hjk's avatar
hjk committed
673 674 675
void TreeItem::prependChild(TreeItem *item)
{
    insertChild(0, item);
hjk's avatar
hjk committed
676 677 678
}

void TreeItem::appendChild(TreeItem *item)
hjk's avatar
hjk committed
679 680 681 682 683
{
    insertChild(m_children.size(), item);
}

void TreeItem::insertChild(int pos, TreeItem *item)
hjk's avatar
hjk committed
684 685
{
    QTC_CHECK(!item->parent());
hjk's avatar
hjk committed
686
    QTC_ASSERT(0 <= pos && pos <= m_children.size(), return); // '<= size' is intentional.
hjk's avatar
hjk committed
687

hjk's avatar
hjk committed
688
    if (m_model) {
hjk's avatar
hjk committed
689
        QModelIndex idx = index();
hjk's avatar
hjk committed
690
        m_model->beginInsertRows(idx, pos, pos);
hjk's avatar
hjk committed
691
        item->m_parent = this;
692
        item->propagateModel(m_model);
hjk's avatar
hjk committed
693
        m_children.insert(m_children.begin() + pos, item);
hjk's avatar
hjk committed
694 695 696
        m_model->endInsertRows();
    } else {
        item->m_parent = this;
697 698
        if (m_model)
            item->propagateModel(m_model);
hjk's avatar
hjk committed
699
        m_children.insert(m_children.begin() + pos, item);
hjk's avatar
hjk committed
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
    }
}

void TreeItem::removeChildren()
{
    if (rowCount() == 0)
        return;
    if (m_model) {
        QModelIndex idx = index();
        m_model->beginRemoveRows(idx, 0, rowCount() - 1);
        clear();
        m_model->endRemoveRows();
    } else {
        clear();
    }
}

717 718 719 720 721 722 723 724 725 726 727
void TreeItem::sortChildren(const std::function<bool(const TreeItem *, const TreeItem *)> &cmp)
{
    if (m_model) {
        m_model->layoutAboutToBeChanged();
        std::sort(m_children.begin(), m_children.end(), cmp);
        m_model->layoutChanged();
    } else {
        std::sort(m_children.begin(), m_children.end(), cmp);
    }
}

hjk's avatar
hjk committed
728 729 730 731
void TreeItem::update()
{
    if (m_model) {
        QModelIndex idx = index();
732
        m_model->dataChanged(idx.sibling(idx.row(), 0), idx.sibling(idx.row(), m_model->m_columnCount - 1));
hjk's avatar
hjk committed
733 734 735
    }
}

Eike Ziller's avatar
Eike Ziller committed
736 737 738 739 740 741 742 743
void TreeItem::updateColumn(int column)
{
    if (m_model) {
        QModelIndex idx = index();
        m_model->dataChanged(idx.sibling(idx.row(), column), idx.sibling(idx.row(), column));
    }
}

hjk's avatar
hjk committed
744 745 746
TreeItem *TreeItem::firstChild() const
{
    return m_children.isEmpty() ? 0 : m_children.first();
hjk's avatar
hjk committed
747 748
}

749 750 751 752 753 754 755 756 757 758 759 760 761
TreeItem *TreeItem::lastChild() const
{
    return m_children.isEmpty() ? 0 : m_children.last();
}

int TreeItem::level() const
{
    int l = 0;
    for (TreeItem *item = this->parent(); item; item = item->parent())
        ++l;
    return l;
}

hjk's avatar
hjk committed
762 763 764 765 766
void TreeItem::setFlags(Qt::ItemFlags flags)
{
    m_flags = flags;
}

hjk's avatar
hjk committed
767 768 769
QModelIndex TreeItem::index() const
{
    QTC_ASSERT(m_model, return QModelIndex());
hjk's avatar
hjk committed
770
    return m_model->indexForItem(this);
hjk's avatar
hjk committed
771 772
}

773 774 775
void TreeItem::walkTree(TreeItemVisitor *visitor)
{
    if (visitor->preVisit(this)) {
hjk's avatar
hjk committed
776
        ++visitor->m_level;
777 778 779
        visitor->visit(this);
        foreach (TreeItem *item, m_children)
            item->walkTree(visitor);
hjk's avatar
hjk committed
780
        --visitor->m_level;
781
    }
hjk's avatar
hjk committed
782
    visitor->postVisit(this);
783 784 785 786 787 788 789 790 791
}

void TreeItem::walkTree(std::function<void (TreeItem *)> f)
{
    f(this);
    foreach (TreeItem *item, m_children)
        item->walkTree(f);
}

hjk's avatar
hjk committed
792 793 794 795
void TreeItem::clear()
{
    while (m_children.size()) {
        TreeItem *item = m_children.takeLast();
796
        item->m_model = 0;
hjk's avatar
hjk committed
797 798 799 800 801
        item->m_parent = 0;
        delete item;
    }
}

hjk's avatar
hjk committed
802 803 804 805 806 807
void TreeItem::expand()
{
    QTC_ASSERT(m_model, return);
    m_model->requestExpansion(index());
}

808 809 810 811 812 813 814 815 816 817 818
void TreeItem::propagateModel(TreeModel *m)
{
    QTC_ASSERT(m, return);
    QTC_ASSERT(m_model == 0 || m_model == m, return);
    if (m && !m_model) {
        m_model = m;
        foreach (TreeItem *item, m_children)
            item->propagateModel(m);
    }
}

hjk's avatar
hjk committed
819 820 821 822 823 824 825
/*!
    \class Utils::TreeModel

    \brief The TreeModel class is a convienience base class for models
    to use in a QTreeView.
*/

hjk's avatar
hjk committed
826
TreeModel::TreeModel(QObject *parent)
827 828
    : QAbstractItemModel(parent),
      m_root(new TreeItem)
hjk's avatar
hjk committed
829
{
830 831
    m_columnCount = 1;
    m_root->m_model = this;
hjk's avatar
hjk committed
832 833 834
#if USE_MODEL_TEST
    new ModelTest(this, this);
#endif
hjk's avatar
hjk committed
835 836
}

837 838 839 840 841
TreeModel::TreeModel(TreeItem *root, QObject *parent)
    : QAbstractItemModel(parent),
      m_root(root)
{
    m_columnCount = 1;
842
    m_root->propagateModel(this);
843 844
}

hjk's avatar
hjk committed
845 846
TreeModel::~TreeModel()
{
hjk's avatar
hjk committed
847 848 849 850
    QTC_ASSERT(m_root, return);
    QTC_ASSERT(m_root->m_parent == 0, return);
    QTC_ASSERT(m_root->m_model == this, return);
    m_root->m_model = 0;
hjk's avatar
hjk committed
851 852 853 854 855
    delete m_root;
}

QModelIndex TreeModel::parent(const QModelIndex &idx) const
{
856
    CHECK_INDEX(idx);
hjk's avatar
hjk committed
857 858 859
    if (!idx.isValid())
        return QModelIndex();

hjk's avatar
hjk committed
860
    const TreeItem *item = itemForIndex(idx);
861
    QTC_ASSERT(item, return QModelIndex());
hjk's avatar
hjk committed
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
    const TreeItem *parent = item->parent();
    if (!parent || parent == m_root)
        return QModelIndex();

    const TreeItem *grandparent = parent->parent();
    if (!grandparent)
        return QModelIndex();

    for (int i = 0, n = grandparent->rowCount(); i < n; ++i)
        if (grandparent->child(i) == parent)
            return createIndex(i, 0, (void*) parent);

    return QModelIndex();
}

int TreeModel::rowCount(const QModelIndex &idx) const
{
879
    CHECK_INDEX(idx);
hjk's avatar
hjk committed
880 881 882 883
    if (!idx.isValid())
        return m_root->rowCount();
    if (idx.column() > 0)
        return 0;
hjk's avatar
hjk committed
884
    const TreeItem *item = itemForIndex(idx);
885 886
    QTC_ASSERT(item, return 0);
    return item->rowCount();
hjk's avatar
hjk committed
887 888 889 890
}

int TreeModel::columnCount(const QModelIndex &idx) const
{
891
    CHECK_INDEX(idx);
hjk's avatar
hjk committed
892 893
    if (idx.column() > 0)
        return 0;
894
    return m_columnCount;
hjk's avatar
hjk committed
895 896
}

897 898
bool TreeModel::setData(const QModelIndex &idx, const QVariant &data, int role)
{
hjk's avatar
hjk committed
899
    TreeItem *item = itemForIndex(idx);
900 901 902 903 904 905
    bool res = item ? item->setData(idx.column(), data, role) : false;
    if (res)
        emit dataChanged(idx, idx);
    return res;
}

hjk's avatar
hjk committed
906 907
QVariant TreeModel::data(const QModelIndex &idx, int role) const
{
hjk's avatar
hjk committed
908
    TreeItem *item = itemForIndex(idx);
hjk's avatar
hjk committed
909 910 911
    return item ? item->data(idx.column(), role) : QVariant();
}

hjk's avatar
hjk committed
912 913 914
QVariant TreeModel::headerData(int section, Qt::Orientation orientation,
                               int role) const
{
915 916
    if (orientation == Qt::Horizontal && role == Qt::DisplayRole && section < m_header.size())
        return m_header.at(section);
917 918
    if (role == Qt::ToolTipRole && section < m_headerToolTip.size())
        return m_headerToolTip.at(section);
hjk's avatar
hjk committed
919 920 921
    return QVariant();
}

922 923
bool TreeModel::hasChildren(const QModelIndex &idx) const
{
hjk's avatar
hjk committed
924
    TreeItem *item = itemForIndex(idx);
925 926 927
    return !item || item->hasChildren();
}

hjk's avatar
hjk committed
928 929
Qt::ItemFlags TreeModel::flags(const QModelIndex &idx) const
{
hjk's avatar
hjk committed
930 931
    if (!idx.isValid())
        return 0;
hjk's avatar
hjk committed
932
    TreeItem *item = itemForIndex(idx);
hjk's avatar
hjk committed
933 934 935 936
    return item ? item->flags(idx.column())
                : (Qt::ItemIsEnabled|Qt::ItemIsSelectable);
}

hjk's avatar
hjk committed
937 938 939 940
bool TreeModel::canFetchMore(const QModelIndex &idx) const
{
    if (!idx.isValid())
        return false;
hjk's avatar
hjk committed
941
    TreeItem *item = itemForIndex(idx);
hjk's avatar
hjk committed
942 943 944 945 946 947 948
    return item ? item->canFetchMore() : false;
}

void TreeModel::fetchMore(const QModelIndex &idx)
{
    if (!idx.isValid())
        return;
hjk's avatar
hjk committed
949
    TreeItem *item = itemForIndex(idx);
hjk's avatar
hjk committed
950 951 952 953
    if (item)
        item->fetchMore();
}

hjk's avatar
hjk committed
954 955 956 957 958
TreeItem *TreeModel::rootItem() const
{
    return m_root;
}

hjk's avatar
hjk committed
959 960 961 962 963
int TreeModel::topLevelItemCount() const
{
    return m_root->childCount();
}

964 965
void TreeModel::setRootItem(TreeItem *item)
{
966 967 968
    QTC_ASSERT(item, return);
    QTC_ASSERT(item->m_model == 0, return);
    QTC_ASSERT(item->m_parent == 0, return);
hjk's avatar
hjk committed
969 970 971 972 973 974 975
    QTC_CHECK(m_root);
    if (m_root) {
        QTC_CHECK(m_root->m_parent == 0);
        QTC_CHECK(m_root->m_model == this);
        m_root->m_model = 0;
        delete m_root;
    }
976
    m_root = item;
977
    item->propagateModel(this);
978
    emit layoutChanged();
979 980
}

981
void TreeModel::setHeader(const QStringList &displays)
hjk's avatar
hjk committed
982
{
983 984 985 986
    m_header = displays;
    m_columnCount = displays.size();
}

987 988 989 990 991
void TreeModel::setHeaderToolTip(const QStringList &tips)
{
    m_headerToolTip = tips;
}

hjk's avatar
hjk committed
992 993
QModelIndex TreeModel::index(int row, int column, const QModelIndex &parent) const
{
994
    CHECK_INDEX(parent);
hjk's avatar
hjk committed
995 996 997
    if (!hasIndex(row, column, parent))
        return QModelIndex();

hjk's avatar
hjk committed
998
    const TreeItem *item = itemForIndex(parent);
hjk's avatar
hjk committed
999 1000 1001 1002 1003 1004
    QTC_ASSERT(item, return QModelIndex());
    if (row >= item->rowCount())
        return QModelIndex();
    return createIndex(row, column, (void*)(item->child(row)));
}

hjk's avatar
hjk committed
1005
TreeItem *TreeModel::itemForIndex(const QModelIndex &idx) const
hjk's avatar
hjk committed
1006
{
1007
    CHECK_INDEX(idx);
hjk's avatar
hjk committed
1008 1009 1010 1011
    TreeItem *item = idx.isValid() ? static_cast<TreeItem*>(idx.internalPointer()) : m_root;
    QTC_ASSERT(item, return 0);
    QTC_ASSERT(item->m_model == this, return 0);
    return item;
hjk's avatar
hjk committed
1012 1013
}

hjk's avatar
hjk committed
1014
QModelIndex TreeModel::indexForItem(const TreeItem *item) const
hjk's avatar
hjk committed
1015
{
hjk's avatar
hjk committed
1016 1017 1018 1019
    QTC_ASSERT(item, return QModelIndex());
    if (item == m_root)
        return QModelIndex();

hjk's avatar
hjk committed
1020 1021 1022
    TreeItem *p = item->parent();
    QTC_ASSERT(p, return QModelIndex());

hjk's avatar
hjk committed
1023
    TreeItem *mitem = const_cast<TreeItem *>(item);
hjk's avatar
hjk committed
1024
    int row = p->m_children.indexOf(mitem);
hjk's avatar
hjk committed
1025
    return createIndex(row, 0, mitem);
hjk's avatar
hjk committed
1026 1027
}

hjk's avatar
hjk committed
1028 1029 1030 1031
/*!
  Destroys all items in them model except the invisible root item.
*/
void TreeModel::clear()
1032
{
hjk's avatar
hjk committed
1033 1034
    if (m_root)
        m_root->removeChildren();
1035 1036
}

hjk's avatar
hjk committed
1037 1038
/*!
   Removes the specified item from the model.
hjk's avatar
hjk committed
1039

hjk's avatar
hjk committed
1040 1041
   \note The item is not destroyed, ownership is effectively passed to the caller.
   */
hjk's avatar
hjk committed
1042

1043
TreeItem *TreeModel::takeItem(TreeItem *item)
1044
{
hjk's avatar
hjk committed
1045 1046 1047 1048
#if USE_MODEL_TEST
    (void) new ModelTest(this, this);
#endif

1049
    QTC_ASSERT(item, return item);
1050
    TreeItem *parent = item->parent();
1051
    QTC_ASSERT(parent, return item);
1052
    int pos = parent->m_children.indexOf(item);
1053
    QTC_ASSERT(pos != -1, return item);
1054

hjk's avatar
hjk committed
1055
    QModelIndex idx = indexForItem(parent);
1056 1057
    beginRemoveRows(idx, pos, pos);
    item->m_parent = 0;
hjk's avatar
hjk committed
1058
    item->m_model = 0;
1059 1060
    parent->m_children.removeAt(pos);
    endRemoveRows();
1061
    return item;
1062 1063
}

hjk's avatar
hjk committed
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
//
// TreeLevelItems
//

UntypedTreeLevelItems::UntypedTreeLevelItems(TreeItem *item, int level)
    : m_item(item), m_level(level)
{}

UntypedTreeLevelItems::const_iterator::const_iterator(TreeItem *base, int level)
    : m_level(level)
{
    QTC_ASSERT(level > 0, return);
    if (base) {
        // "begin()"
        m_depth = 0;
        // Level x: The item m_item[x] is the m_pos[x]'th child of its
        // parent, out of m_size[x].
        m_pos[0] = 0;
        m_size[0] = 1;
        m_item[0] = base;
        goDown();
    } else {
        // "end()"
        m_depth = -1;
    }
}

UntypedTreeLevelItems::const_iterator UntypedTreeLevelItems::begin() const
{
    return const_iterator(m_item, m_level);
}

UntypedTreeLevelItems::const_iterator UntypedTreeLevelItems::end() const
{
    return const_iterator(0, m_level);
}

hjk's avatar
hjk committed
1101
} // namespace Utils