treemodel.cpp 31.3 KB
Newer Older
hjk's avatar
hjk committed
1 2
/****************************************************************************
**
3 4
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://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
12 13 14
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
hjk's avatar
hjk committed
15
**
16 17 18 19 20 21 22
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
hjk's avatar
hjk committed
23 24 25 26 27 28
**
****************************************************************************/

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

hjk's avatar
hjk committed
29 30
#include <QStack>
#include <QSize>
hjk's avatar
hjk committed
31

hjk's avatar
hjk committed
32 33
#define USE_MODEL_TEST 0
#define USE_INDEX_CHECKS 0
hjk's avatar
hjk committed
34

hjk's avatar
hjk committed
35
#if USE_INDEX_CHECKS
36 37 38 39 40 41 42 43 44 45 46 47
#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
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
#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
603 604 605 606 607 608
namespace Utils {

//
// TreeItem
//
TreeItem::TreeItem()
hjk's avatar
hjk committed
609
    : m_parent(0), m_model(0), m_flags(Qt::ItemIsEnabled|Qt::ItemIsSelectable)
hjk's avatar
hjk committed
610 611 612 613 614
{
}

TreeItem::~TreeItem()
{
hjk's avatar
hjk committed
615 616
    QTC_CHECK(m_parent == 0);
    QTC_CHECK(m_model == 0);
617
    removeChildren();
hjk's avatar
hjk committed
618 619 620 621 622
}

TreeItem *TreeItem::child(int pos) const
{
    QTC_ASSERT(pos >= 0, return 0);
hjk's avatar
hjk committed
623
    return pos < m_children.size() ? m_children.at(pos) : 0;
hjk's avatar
hjk committed
624 625 626 627 628 629 630 631 632
}

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

QVariant TreeItem::data(int column, int role) const
{
hjk's avatar
hjk committed
633 634
    Q_UNUSED(column);
    Q_UNUSED(role);
hjk's avatar
hjk committed
635 636 637
    return QVariant();
}

638 639 640 641 642 643 644 645
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
646 647 648 649 650 651
Qt::ItemFlags TreeItem::flags(int column) const
{
    Q_UNUSED(column);
    return m_flags;
}

652 653 654 655 656
bool TreeItem::hasChildren() const
{
    return canFetchMore() || rowCount() > 0;
}

hjk's avatar
hjk committed
657
bool TreeItem::canFetchMore() const
hjk's avatar
hjk committed
658
{
hjk's avatar
hjk committed
659 660
    return false;
}
hjk's avatar
hjk committed
661

hjk's avatar
hjk committed
662 663 664
void TreeItem::prependChild(TreeItem *item)
{
    insertChild(0, item);
hjk's avatar
hjk committed
665 666 667
}

void TreeItem::appendChild(TreeItem *item)
hjk's avatar
hjk committed
668 669 670 671 672
{
    insertChild(m_children.size(), item);
}

void TreeItem::insertChild(int pos, TreeItem *item)
hjk's avatar
hjk committed
673
{
674
    QTC_CHECK(!item->model());
hjk's avatar
hjk committed
675
    QTC_CHECK(!item->parent());
hjk's avatar
hjk committed
676
    QTC_ASSERT(0 <= pos && pos <= m_children.size(), return); // '<= size' is intentional.
hjk's avatar
hjk committed
677

hjk's avatar
hjk committed
678
    if (m_model) {
hjk's avatar
hjk committed
679
        QModelIndex idx = index();
hjk's avatar
hjk committed
680
        m_model->beginInsertRows(idx, pos, pos);
hjk's avatar
hjk committed
681
        item->m_parent = this;
682
        item->propagateModel(m_model);
hjk's avatar
hjk committed
683
        m_children.insert(m_children.begin() + pos, item);
hjk's avatar
hjk committed
684 685 686
        m_model->endInsertRows();
    } else {
        item->m_parent = this;
687 688
        if (m_model)
            item->propagateModel(m_model);
hjk's avatar
hjk committed
689
        m_children.insert(m_children.begin() + pos, item);
hjk's avatar
hjk committed
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
    }
}

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();
    }
}

707 708 709
void TreeItem::sortChildren(const std::function<bool(const TreeItem *, const TreeItem *)> &cmp)
{
    if (m_model) {
hjk's avatar
hjk committed
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724
        if (const int n = rowCount()) {
            QVector<TreeItem *> tmp = m_children;
            std::sort(tmp.begin(), tmp.end(), cmp);
            if (tmp == m_children) {
                // Nothing changed.
            } else {
                QModelIndex idx = index();
                m_model->beginRemoveRows(idx, 0, n - 1);
                m_children.clear();
                m_model->endRemoveRows();
                m_model->beginInsertRows(idx, 0, n - 1);
                tmp.swap(m_children);
                m_model->endInsertRows();
            }
        }
725 726 727 728 729
    } else {
        std::sort(m_children.begin(), m_children.end(), cmp);
    }
}

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

Eike Ziller's avatar
Eike Ziller committed
738 739 740 741 742 743 744 745
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
746 747 748
TreeItem *TreeItem::firstChild() const
{
    return m_children.isEmpty() ? 0 : m_children.first();
hjk's avatar
hjk committed
749 750
}

751 752 753 754 755 756 757 758 759 760 761 762 763
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
764 765 766 767 768
void TreeItem::setFlags(Qt::ItemFlags flags)
{
    m_flags = flags;
}

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

hjk's avatar
hjk committed
775 776 777 778
void TreeItem::clear()
{
    while (m_children.size()) {
        TreeItem *item = m_children.takeLast();
779
        item->m_model = 0;
hjk's avatar
hjk committed
780 781 782 783 784
        item->m_parent = 0;
        delete item;
    }
}

hjk's avatar
hjk committed
785 786 787 788 789 790
void TreeItem::expand()
{
    QTC_ASSERT(m_model, return);
    m_model->requestExpansion(index());
}

791 792 793 794 795 796 797 798 799 800 801
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
802 803 804 805 806 807 808
/*!
    \class Utils::TreeModel

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

hjk's avatar
hjk committed
809
TreeModel::TreeModel(QObject *parent)
810 811
    : QAbstractItemModel(parent),
      m_root(new TreeItem)
hjk's avatar
hjk committed
812
{
813 814
    m_columnCount = 1;
    m_root->m_model = this;
hjk's avatar
hjk committed
815 816 817
#if USE_MODEL_TEST
    new ModelTest(this, this);
#endif
hjk's avatar
hjk committed
818 819
}

820 821 822 823 824
TreeModel::TreeModel(TreeItem *root, QObject *parent)
    : QAbstractItemModel(parent),
      m_root(root)
{
    m_columnCount = 1;
825
    m_root->propagateModel(this);
826 827
}

hjk's avatar
hjk committed
828 829
TreeModel::~TreeModel()
{
hjk's avatar
hjk committed
830 831 832 833
    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
834 835 836 837 838
    delete m_root;
}

QModelIndex TreeModel::parent(const QModelIndex &idx) const
{
839
    CHECK_INDEX(idx);
hjk's avatar
hjk committed
840 841 842
    if (!idx.isValid())
        return QModelIndex();

hjk's avatar
hjk committed
843
    const TreeItem *item = itemForIndex(idx);
844
    QTC_ASSERT(item, return QModelIndex());
hjk's avatar
hjk committed
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
    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
{
862
    CHECK_INDEX(idx);
hjk's avatar
hjk committed
863 864 865 866
    if (!idx.isValid())
        return m_root->rowCount();
    if (idx.column() > 0)
        return 0;
hjk's avatar
hjk committed
867
    const TreeItem *item = itemForIndex(idx);
868 869
    QTC_ASSERT(item, return 0);
    return item->rowCount();
hjk's avatar
hjk committed
870 871 872 873
}

int TreeModel::columnCount(const QModelIndex &idx) const
{
874
    CHECK_INDEX(idx);
hjk's avatar
hjk committed
875 876
    if (idx.column() > 0)
        return 0;
877
    return m_columnCount;
hjk's avatar
hjk committed
878 879
}

880 881
bool TreeModel::setData(const QModelIndex &idx, const QVariant &data, int role)
{
hjk's avatar
hjk committed
882
    TreeItem *item = itemForIndex(idx);
883 884 885 886 887 888
    bool res = item ? item->setData(idx.column(), data, role) : false;
    if (res)
        emit dataChanged(idx, idx);
    return res;
}

hjk's avatar
hjk committed
889 890
QVariant TreeModel::data(const QModelIndex &idx, int role) const
{
hjk's avatar
hjk committed
891
    TreeItem *item = itemForIndex(idx);
hjk's avatar
hjk committed
892 893 894
    return item ? item->data(idx.column(), role) : QVariant();
}

hjk's avatar
hjk committed
895 896 897
QVariant TreeModel::headerData(int section, Qt::Orientation orientation,
                               int role) const
{
898 899
    if (orientation == Qt::Horizontal && role == Qt::DisplayRole && section < m_header.size())
        return m_header.at(section);
900 901
    if (role == Qt::ToolTipRole && section < m_headerToolTip.size())
        return m_headerToolTip.at(section);
hjk's avatar
hjk committed
902 903 904
    return QVariant();
}

905 906
bool TreeModel::hasChildren(const QModelIndex &idx) const
{
hjk's avatar
hjk committed
907
    TreeItem *item = itemForIndex(idx);
908 909 910
    return !item || item->hasChildren();
}

hjk's avatar
hjk committed
911 912
Qt::ItemFlags TreeModel::flags(const QModelIndex &idx) const
{
hjk's avatar
hjk committed
913 914
    if (!idx.isValid())
        return 0;
hjk's avatar
hjk committed
915
    TreeItem *item = itemForIndex(idx);
hjk's avatar
hjk committed
916 917 918 919
    return item ? item->flags(idx.column())
                : (Qt::ItemIsEnabled|Qt::ItemIsSelectable);
}

hjk's avatar
hjk committed
920 921 922 923
bool TreeModel::canFetchMore(const QModelIndex &idx) const
{
    if (!idx.isValid())
        return false;
hjk's avatar
hjk committed
924
    TreeItem *item = itemForIndex(idx);
hjk's avatar
hjk committed
925 926 927 928 929 930 931
    return item ? item->canFetchMore() : false;
}

void TreeModel::fetchMore(const QModelIndex &idx)
{
    if (!idx.isValid())
        return;
hjk's avatar
hjk committed
932
    TreeItem *item = itemForIndex(idx);
hjk's avatar
hjk committed
933 934 935 936
    if (item)
        item->fetchMore();
}

hjk's avatar
hjk committed
937 938 939 940 941
TreeItem *TreeModel::rootItem() const
{
    return m_root;
}

hjk's avatar
hjk committed
942 943 944 945 946
int TreeModel::topLevelItemCount() const
{
    return m_root->childCount();
}

947 948
void TreeModel::setRootItem(TreeItem *item)
{
949 950 951
    QTC_ASSERT(item, return);
    QTC_ASSERT(item->m_model == 0, return);
    QTC_ASSERT(item->m_parent == 0, return);
hjk's avatar
hjk committed
952
    QTC_CHECK(m_root);
953 954

    emit layoutAboutToBeChanged();
hjk's avatar
hjk committed
955 956 957
    if (m_root) {
        QTC_CHECK(m_root->m_parent == 0);
        QTC_CHECK(m_root->m_model == this);
958 959 960
        // needs to be done explicitly before setting the model to 0, otherwise it might lead to a
        // crash inside a view or proxy model, especially if there are selected items
        m_root->removeChildren();
hjk's avatar
hjk committed
961 962 963
        m_root->m_model = 0;
        delete m_root;
    }
964
    m_root = item;
965
    item->propagateModel(this);
966
    emit layoutChanged();
967 968
}

969
void TreeModel::setHeader(const QStringList &displays)
hjk's avatar
hjk committed
970
{
971 972 973 974
    m_header = displays;
    m_columnCount = displays.size();
}

975 976 977 978 979
void TreeModel::setHeaderToolTip(const QStringList &tips)
{
    m_headerToolTip = tips;
}

hjk's avatar
hjk committed
980 981
QModelIndex TreeModel::index(int row, int column, const QModelIndex &parent) const
{
982
    CHECK_INDEX(parent);
hjk's avatar
hjk committed
983 984 985
    if (!hasIndex(row, column, parent))
        return QModelIndex();

hjk's avatar
hjk committed
986
    const TreeItem *item = itemForIndex(parent);
hjk's avatar
hjk committed
987 988 989 990 991 992
    QTC_ASSERT(item, return QModelIndex());
    if (row >= item->rowCount())
        return QModelIndex();
    return createIndex(row, column, (void*)(item->child(row)));
}

hjk's avatar
hjk committed
993
TreeItem *TreeModel::itemForIndex(const QModelIndex &idx) const
hjk's avatar
hjk committed
994
{
995
    CHECK_INDEX(idx);
hjk's avatar
hjk committed
996 997 998 999
    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
1000 1001
}

hjk's avatar
hjk committed
1002
QModelIndex TreeModel::indexForItem(const TreeItem *item) const
hjk's avatar
hjk committed
1003
{
hjk's avatar
hjk committed
1004 1005 1006 1007
    QTC_ASSERT(item, return QModelIndex());
    if (item == m_root)
        return QModelIndex();

hjk's avatar
hjk committed
1008 1009 1010
    TreeItem *p = item->parent();
    QTC_ASSERT(p, return QModelIndex());

hjk's avatar
hjk committed
1011
    TreeItem *mitem = const_cast<TreeItem *>(item);
hjk's avatar
hjk committed
1012
    int row = p->m_children.indexOf(mitem);
hjk's avatar
hjk committed
1013
    return createIndex(row, 0, mitem);
hjk's avatar
hjk committed
1014 1015
}

hjk's avatar
hjk committed
1016 1017 1018 1019
/*!
  Destroys all items in them model except the invisible root item.
*/
void TreeModel::clear()
1020
{
hjk's avatar
hjk committed
1021 1022
    if (m_root)
        m_root->removeChildren();
1023 1024
}

hjk's avatar
hjk committed
1025 1026
/*!
   Removes the specified item from the model.
hjk's avatar
hjk committed
1027

hjk's avatar
hjk committed
1028 1029
   \note The item is not destroyed, ownership is effectively passed to the caller.
   */
hjk's avatar
hjk committed
1030

1031
TreeItem *TreeModel::takeItem(TreeItem *item)
1032
{
hjk's avatar
hjk committed
1033 1034 1035 1036
#if USE_MODEL_TEST
    (void) new ModelTest(this, this);
#endif

1037
    QTC_ASSERT(item, return item);
1038
    TreeItem *parent = item->parent();
1039
    QTC_ASSERT(parent, return item);
1040
    int pos = parent->m_children.indexOf(item);
1041
    QTC_ASSERT(pos != -1, return item);
1042

hjk's avatar
hjk committed
1043
    QModelIndex idx = indexForItem(parent);
1044 1045
    beginRemoveRows(idx, pos, pos);
    item->m_parent = 0;
hjk's avatar
hjk committed
1046
    item->m_model = 0;
1047 1048
    parent->m_children.removeAt(pos);
    endRemoveRows();
1049
    return item;
1050 1051
}

1052 1053 1054 1055 1056
void TreeModel::destroyItem(TreeItem *item)
{
    delete takeItem(item);
}

hjk's avatar
hjk committed
1057 1058 1059 1060 1061
StaticTreeItem::StaticTreeItem(const QStringList &displays)
    : m_displays(displays)
{
}

1062 1063 1064 1065 1066
StaticTreeItem::StaticTreeItem(const QString &display)
    : m_displays(display)
{
}

hjk's avatar
hjk committed
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
QVariant StaticTreeItem::data(int column, int role) const
{
    if (role == Qt::DisplayRole && column >= 0 && column < m_displays.size())
        return m_displays.at(column);
    return QVariant();
}

Qt::ItemFlags StaticTreeItem::flags(int column) const
{
    Q_UNUSED(column);
    return Qt::ItemIsEnabled;
}

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