projectmodels.cpp 38.9 KB
Newer Older
con's avatar
con committed
1 2 3 4 5 6 7 8
/***************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact:  Qt Software Information (qt-info@nokia.com)
**
9 10 11
**
** Non-Open Source Usage
**
con's avatar
con committed
12 13 14
** Licensees may use this file in accordance with the Qt Beta Version
** License Agreement, Agreement version 2.2 provided with the Software or,
** alternatively, in accordance with the terms contained in a written
15 16 17 18
** agreement between you and Nokia.
**
** GNU General Public License Usage
**
con's avatar
con committed
19 20 21 22 23 24 25 26 27 28
** Alternatively, this file may be used under the terms of the GNU General
** Public License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the packaging
** of this file.  Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
**
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** In addition, as a special exception, Nokia gives you certain additional
29 30 31 32
** rights. These rights are described in the Nokia Qt GPL Exception
** version 1.2, included in the file GPL_EXCEPTION.txt in this package.
**
***************************************************************************/
hjk's avatar
hjk committed
33

con's avatar
con committed
34
#include "projectmodels.h"
hjk's avatar
hjk committed
35 36

#include "project.h"
con's avatar
con committed
37 38 39
#include "projectexplorerconstants.h"

#include <coreplugin/fileiconprovider.h>
hjk's avatar
hjk committed
40 41 42 43
#include <utils/qtcassert.h>

#include <QtCore/QDebug>
#include <QtCore/QFileInfo>
con's avatar
con committed
44 45 46 47 48

#include <QtGui/QApplication>
#include <QtGui/QIcon>
#include <QtGui/QMessageBox>
#include <QtGui/QSortFilterProxyModel>
hjk's avatar
hjk committed
49
#include <QtGui/QStyle>
con's avatar
con committed
50 51 52 53 54 55

using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
using Core::FileIconProvider;

namespace {
hjk's avatar
hjk committed
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76

// sorting helper function
bool sortNodes(Node *n1, Node *n2)
{
    // Ordering is: project files, project, folder, file

    const NodeType n1Type = n1->nodeType();
    const NodeType n2Type = n2->nodeType();

    // project files
    FileNode *file1 = qobject_cast<FileNode*>(n1);
    FileNode *file2 = qobject_cast<FileNode*>(n2);
    if (file1 && file1->fileType() == ProjectFileType) {
        if (file2 && file2->fileType() == ProjectFileType) {
            const QString fileName1 = QFileInfo(file1->path()).fileName();
            const QString fileName2 = QFileInfo(file2->path()).fileName();

            if (fileName1 != fileName2)
                return fileName1 < fileName2;
            else
                return file1 < file2;
con's avatar
con committed
77
        } else {
hjk's avatar
hjk committed
78 79 80 81 82
            return true; // project file is before everything else
        }
    } else {
        if (file2 && file2->fileType() == ProjectFileType) {
            return false;
con's avatar
con committed
83
        }
hjk's avatar
hjk committed
84
    }
con's avatar
con committed
85

hjk's avatar
hjk committed
86 87 88 89 90
    // projects
    if (n1Type == ProjectNodeType) {
        if (n2Type == ProjectNodeType) {
            ProjectNode *project1 = static_cast<ProjectNode*>(n1);
            ProjectNode *project2 = static_cast<ProjectNode*>(n2);
con's avatar
con committed
91

hjk's avatar
hjk committed
92 93 94 95 96 97 98 99 100 101
            if (project1->name() != project2->name())
                return project1->name() < project2->name(); // sort by name
            else
                return project1 < project2; // sort by pointer value
        } else {
           return true; // project is before folder & file
       }
    }
    if (n2Type == ProjectNodeType)
        return false;
con's avatar
con committed
102

hjk's avatar
hjk committed
103 104 105 106
    if (n1Type == FolderNodeType) {
        if (n2Type == FolderNodeType) {
            FolderNode *folder1 = static_cast<FolderNode*>(n1);
            FolderNode *folder2 = static_cast<FolderNode*>(n2);
con's avatar
con committed
107

hjk's avatar
hjk committed
108 109 110 111 112 113
            if (folder1->name() != folder2->name())
                return folder1->name() < folder2->name();
            else
                return folder1 < folder2;
        } else {
            return true; // folder is before file
con's avatar
con committed
114
        }
hjk's avatar
hjk committed
115 116 117
    }
    if (n2Type == FolderNodeType)
        return false;
con's avatar
con committed
118

hjk's avatar
hjk committed
119 120 121 122
    // must be file nodes
    {
        const QString filePath1 = n1->path();
        const QString filePath2 = n2->path();
con's avatar
con committed
123

hjk's avatar
hjk committed
124 125
        const QString fileName1 = QFileInfo(filePath1).fileName();
        const QString fileName2 = QFileInfo(filePath2).fileName();
con's avatar
con committed
126

hjk's avatar
hjk committed
127 128 129 130 131
        if (fileName1 != fileName2) {
            return fileName1 < fileName2; // sort by file names
        } else {
            if (filePath1 != filePath2) {
                return filePath1 < filePath2; // sort by path names
con's avatar
con committed
132
            } else {
hjk's avatar
hjk committed
133
                return n1 < n2; // sort by pointer value
con's avatar
con committed
134 135 136
            }
        }
    }
hjk's avatar
hjk committed
137
    return false;
con's avatar
con committed
138 139
}

hjk's avatar
hjk committed
140 141
} // namespace anon

con's avatar
con committed
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
/*!
  \class DetailedModel

  A 1:1 mapping of the internal node tree.

  The detailed model shows the complete project file hierarchy and all containing files.
  */

DetailedModel::DetailedModel(SessionNode *rootNode, QObject *parent)
        : QAbstractItemModel(parent),
          m_rootNode(rootNode),
          //m_startupProject(0),
          m_folderToAddTo(0)
{
    NodesWatcher *watcher = new NodesWatcher(this);
    m_rootNode->registerWatcher(watcher);
    connect(watcher, SIGNAL(foldersAboutToBeAdded(FolderNode*, const QList<FolderNode*> &)),
            this, SLOT(foldersAboutToBeAdded(FolderNode*, const QList<FolderNode*> &)));
    connect(watcher, SIGNAL(foldersAdded()),
            this, SLOT(foldersAdded()));
    connect(watcher, SIGNAL(foldersAboutToBeRemoved(FolderNode*, const QList<FolderNode*> &)),
            this, SLOT(foldersAboutToBeRemoved(FolderNode*, const QList<FolderNode*> &)));
    connect(watcher, SIGNAL(filesAboutToBeAdded(FolderNode*, const QList<FileNode*> &)),
            this, SLOT(filesAboutToBeAdded(FolderNode*, const QList<FileNode*> &)));
    connect(watcher, SIGNAL(filesAdded()),
            this, SLOT(filesAdded()));
    connect(watcher, SIGNAL(filesAboutToBeRemoved(FolderNode*, const QList<FileNode*> &)),
            this, SLOT(filesAboutToBeRemoved(FolderNode*, const QList<FileNode*> &)));
}

QModelIndex DetailedModel::index(int row, int column, const QModelIndex &parent) const
{
    QModelIndex result;
    if (!parent.isValid() && row == 0 && column == 0) {
        result = createIndex(0, 0, m_rootNode);
    } else if (column == 0) {
        FolderNode *parentNode = qobject_cast<FolderNode*>(nodeForIndex(parent));
hjk's avatar
hjk committed
179
        QTC_ASSERT(parentNode, return result);
con's avatar
con committed
180 181 182 183 184 185 186 187 188 189 190 191
        result = createIndex(row, 0, m_childNodes.value(parentNode).at(row));
    }
    return result;
}

QModelIndex DetailedModel::parent(const QModelIndex &index) const
{
    QModelIndex parentIndex;

    if (Node *node = nodeForIndex(index)) {
        if (FolderNode *parentFolderNode = node->parentFolderNode()) {
            if (FolderNode *grandParentFolderNode = parentFolderNode->parentFolderNode()) {
hjk's avatar
hjk committed
192
                QTC_ASSERT(m_childNodes.contains(grandParentFolderNode), return parentIndex);
con's avatar
con committed
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
                int row = m_childNodes.value(grandParentFolderNode).indexOf(parentFolderNode);
                parentIndex = createIndex(row, 0, parentFolderNode);
            } else {
                parentIndex = createIndex(0, 0, parentFolderNode);
            }
        }
    }

    return parentIndex;
}

Qt::ItemFlags DetailedModel::flags(const QModelIndex &index) const
{
    Qt::ItemFlags result;
    if (index.isValid()) {
        result = Qt::ItemIsEnabled | Qt::ItemIsSelectable;

        if (Node *node = nodeForIndex(index)) {
            if (node->nodeType() == FileNodeType)
                result |= Qt::ItemIsEditable;
        }
    }
    return result;
}

QVariant DetailedModel::data(const QModelIndex &index, int role) const
{
    QVariant result;

    if (Node *node = nodeForIndex(index)) {
        FolderNode *folderNode = qobject_cast<FolderNode*>(node);
        switch (role) {
        case Qt::DisplayRole:
        case Qt::EditRole: {
            if (folderNode)
                result = folderNode->name();
            else
                result = QFileInfo(node->path()).fileName(); //TODO cache that?
            break;
        }
        case Qt::ToolTipRole: {
            if (folderNode && (folderNode->nodeType() != ProjectNodeType))
                result = tr("%1 of project %2").arg(folderNode->name()).arg(folderNode->projectNode()->name());
            else
                result = node->path();
            break;
        }
        case Qt::DecorationRole: {
            if (folderNode)
                result = folderNode->icon();
            else
                result = FileIconProvider::instance()->icon(QFileInfo(node->path()));
            break;
        }
        case Qt::FontRole: {
            QFont font;
            if (qobject_cast<ProjectNode*>(folderNode)) {
                if (index == this->index(0,0) && m_isStartupProject)
                    font.setBold(true);
            }
            result = font;
            break;
        }
        case ProjectExplorer::Project::FilePathRole: {
            result = node->path();
            break;
        }
        }
    }

    return result;
}

bool DetailedModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    bool result = false;

    if (Node *node = nodeForIndex(index)) {
        FileNode *fileNode = qobject_cast<FileNode*>(node);
        if (fileNode && role == Qt::EditRole && !value.toString().isEmpty()) {
            ProjectNode *projectNode = node->projectNode();
            QString newPath = QFileInfo(fileNode->path()).dir().absoluteFilePath(value.toString());
            if (!projectNode->renameFile(fileNode->fileType(), fileNode->path(), newPath))
                QMessageBox::warning(0, tr("Could not rename file"),
                                     tr("Renaming file %1 to %2 failed.").arg(fileNode->path())
                                                                         .arg(value.toString()));
        }
    }

    return result;
}

int DetailedModel::rowCount(const QModelIndex & parent) const
{
    int count = 0;

    if (!parent.isValid()) { // root item
        count = 1;
    } else {
        // we can be sure that internal cache
        // has been updated by fetchMore()
        FolderNode *folderNode = qobject_cast<FolderNode*>(nodeForIndex(parent));
        if (folderNode && m_childNodes.contains(folderNode))
            count = m_childNodes.value(folderNode).size();
    }
    return count;
}

int DetailedModel::columnCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return 1;
}

bool DetailedModel::hasChildren(const QModelIndex &parent) const
{
    bool hasChilds = false;

    if (!parent.isValid()) {// root index
        hasChilds = true;
    } else {
        if (FolderNode *folderNode = qobject_cast<FolderNode*>(nodeForIndex(parent))) {
            if (m_childNodes.contains(folderNode)) // internal cache
                hasChilds = !m_childNodes.value(folderNode).isEmpty();
            else {
                if (!folderNode->subFolderNodes().isEmpty()
                    || !folderNode->fileNodes().isEmpty()) // underlying data
                    hasChilds = true;
                else {
                    // Make sure add/remove signals are emitted
                    // even for empty nodes (i.e. where canFetchMore
                    // returns false)
                    m_childNodes.insert(folderNode, QList<Node*>());
                }
            }
        }
    }

    return hasChilds;
}

/*!
  Returns true if internal cache has not been built up yet
  */
bool DetailedModel::canFetchMore(const QModelIndex & parent) const
{
    bool canFetch = false;
    if (parent.isValid()) {
        if (FolderNode *folderNode = qobject_cast<FolderNode*>(nodeForIndex(parent))) {
            canFetch = !m_childNodes.contains(folderNode);
        }
    }
    return canFetch;
}

/*!
  Updates internal cache
  */
void DetailedModel::fetchMore(const QModelIndex & parent)
{
    FolderNode *folderNode = qobject_cast<FolderNode*>(nodeForIndex(parent));
hjk's avatar
hjk committed
354 355
    QTC_ASSERT(folderNode, return);
    QTC_ASSERT(!m_childNodes.contains(folderNode), return);
con's avatar
con committed
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370

    m_childNodes.insert(folderNode, childNodeList(folderNode));
}

void DetailedModel::reset()
{
    // todo:How to implement this correctly?????
    m_childNodes.clear();
    QAbstractItemModel::reset();
}

void DetailedModel::foldersAboutToBeAdded(FolderNode *parentFolder,
                           const QList<FolderNode*> &newFolders)
{
    Q_UNUSED(newFolders);
hjk's avatar
hjk committed
371
    QTC_ASSERT(parentFolder, return);
con's avatar
con committed
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388

    if (m_childNodes.contains(parentFolder))
        m_folderToAddTo = parentFolder;
}

void DetailedModel::foldersAdded()
{
    if (m_folderToAddTo) {
        QList<Node*> newChildNodes = childNodeList(m_folderToAddTo);
        addToChildNodes(m_folderToAddTo, newChildNodes);
        m_folderToAddTo = 0;
    }
}

void DetailedModel::foldersAboutToBeRemoved(FolderNode *parentFolder,
                           const QList<FolderNode*> &staleFolders)
{
hjk's avatar
hjk committed
389
    QTC_ASSERT(parentFolder, return);
con's avatar
con committed
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

    if (m_childNodes.contains(parentFolder)) {
        QList<Node*> newChildNodes = m_childNodes.value(parentFolder);
        QList<FolderNode*> nodesToRemove = staleFolders;
        qSort(nodesToRemove.begin(), nodesToRemove.end(), sortNodes);

        QList<Node*>::iterator newListIter = newChildNodes.begin();
        QList<FolderNode*>::const_iterator toRemoveIter = nodesToRemove.constBegin();
        for (; toRemoveIter != nodesToRemove.constEnd(); ++toRemoveIter) {
            while (*newListIter != *toRemoveIter)
                ++newListIter;
            newListIter = newChildNodes.erase(newListIter);
        }

        removeFromChildNodes(parentFolder, newChildNodes);

        // Clear cache for all folders beneath the current folder
        foreach (FolderNode *folder, staleFolders) {
            foreach (FolderNode *subFolder, recursiveSubFolders(folder)) {
                m_childNodes.remove(subFolder);
            }
        }
    }
}

void DetailedModel::filesAboutToBeAdded(FolderNode *parentFolder,
                           const QList<FileNode*> &newFiles)
{
    Q_UNUSED(newFiles);
hjk's avatar
hjk committed
419
    QTC_ASSERT(parentFolder, return);
con's avatar
con committed
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436

    if (m_childNodes.contains(parentFolder))
        m_folderToAddTo = parentFolder;
}

void DetailedModel::filesAdded()
{
    if (m_folderToAddTo) {
        QList<Node*> newChildNodes = childNodeList(m_folderToAddTo);
        addToChildNodes(m_folderToAddTo, newChildNodes);
        m_folderToAddTo = 0;
    }
}

void DetailedModel::filesAboutToBeRemoved(FolderNode *parentFolder,
                           const QList<FileNode*> &staleFiles)
{
hjk's avatar
hjk committed
437
    QTC_ASSERT(parentFolder, return);
con's avatar
con committed
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

    if (m_childNodes.contains(parentFolder)) {
        QList<Node*> newChildNodes = m_childNodes.value(parentFolder);
        QList<FileNode*> nodesToRemove = staleFiles;
        qSort(nodesToRemove.begin(), nodesToRemove.end(), sortNodes);

        QList<Node*>::iterator newListIter = newChildNodes.begin();
        QList<FileNode*>::const_iterator toRemoveIter = nodesToRemove.constBegin();
        for (; toRemoveIter != nodesToRemove.constEnd(); ++toRemoveIter) {
            while (*newListIter != *toRemoveIter)
                ++newListIter;
            newListIter = newChildNodes.erase(newListIter);
        }

        removeFromChildNodes(parentFolder, newChildNodes);
    }
}

Node *DetailedModel::nodeForIndex(const QModelIndex &index) const
{
    return (Node*)index.internalPointer();
}

/*!
  Returns the index corresponding to a node.
 */
QModelIndex DetailedModel::indexForNode(const Node *node)
{
    if (!node)
        return QModelIndex();

    if (FolderNode *parentFolder = node->parentFolderNode()) {
        // iterate recursively
        QModelIndex parentIndex = indexForNode(parentFolder);

        // update internal cache
        if (canFetchMore(parentIndex))
            fetchMore(parentIndex);
hjk's avatar
hjk committed
476
        QTC_ASSERT(m_childNodes.contains(parentFolder), return QModelIndex());
con's avatar
con committed
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

        int row = m_childNodes.value(parentFolder).indexOf(const_cast<Node*>(node));
        if (row >= 0)
            return index(row, 0, parentIndex);
        else
            return QModelIndex();
    } else {
        // root node
        return index(0, 0);
    }
}

QList<Node*> DetailedModel::childNodeList(FolderNode *folderNode) const
{
    QList<FolderNode*> folderNodes = folderNode->subFolderNodes();
    QList<FileNode*> fileNodes = folderNode->fileNodes();

    QList<Node*> nodes;
    foreach (FolderNode *folderNode, folderNodes)
        nodes << folderNode;
    foreach (FileNode *fileNode, fileNodes)
        nodes << fileNode;

    qSort(nodes.begin(), nodes.end(), sortNodes);

    return nodes;
}

void DetailedModel::addToChildNodes(FolderNode *parentFolder, QList<Node*> newChildNodes)
{
    QList<Node*> childNodes = m_childNodes.value(parentFolder);
    QModelIndex parentIndex = indexForNode(parentFolder);
hjk's avatar
hjk committed
509
    QTC_ASSERT(parentIndex.isValid(), return);
con's avatar
con committed
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

    // position -> nodes, with positions in decreasing order
    QList<QPair<int, QList<Node*> > > insertions;

    // add nodes that should be added at the end or in between
    int newIndex = newChildNodes.size() - 1;
    for (int oldIndex = childNodes.size() - 1;
         oldIndex >= 0; --oldIndex, --newIndex) {
        QList<Node*> nodesPerIndex;
        Node* oldNode = childNodes.at(oldIndex);
        while (newChildNodes.at(newIndex) != oldNode) {
            nodesPerIndex.append(newChildNodes.at(newIndex));
            --newIndex;
        }
        if (!nodesPerIndex.isEmpty())
            insertions.append(QPair<int, QList<Node*> >(oldIndex + 1, nodesPerIndex));
    }
    { // add nodes that should be added to the beginning
        QList<Node*> insertAtStart;
        while (newIndex >= 0) {
            insertAtStart.append(newChildNodes.at(newIndex--));
        }
        if (!insertAtStart.isEmpty())
            insertions.append(QPair<int, QList<Node*> >(0, insertAtStart));
    }

    for (QList<QPair<int, QList<Node*> > >::const_iterator iter = insertions.constBegin();
         iter != insertions.constEnd(); ++iter) {

        const int key = iter->first;
        const QList<Node*> nodesToInsert = iter->second;

        beginInsertRows(parentIndex, key, key + nodesToInsert.size() - 1);

        // update internal cache
        for (QList<Node*>::const_iterator nodeIterator = nodesToInsert.constBegin();
             nodeIterator != nodesToInsert.constEnd(); ++nodeIterator)
            childNodes.insert(key, *nodeIterator);
        m_childNodes.insert(parentFolder, childNodes);

        endInsertRows();
    }

hjk's avatar
hjk committed
553
    QTC_ASSERT(childNodes == newChildNodes, /**/);
con's avatar
con committed
554 555 556 557 558 559
}

void DetailedModel::removeFromChildNodes(FolderNode *parentFolder, QList<Node*> newChildNodes)
{
    QList<Node*> childNodes = m_childNodes.value(parentFolder);
    QModelIndex parentIndex = indexForNode(parentFolder);
hjk's avatar
hjk committed
560
    QTC_ASSERT(parentIndex.isValid(), return);
con's avatar
con committed
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

    // position -> nodes, with positions in decreasing order
    QList<QPair<int, QList<Node*> > > deletions;

    // add nodes that should be removed at the end or in between
    int oldIndex = childNodes.size() - 1;
    for (int newIndex = newChildNodes.size() - 1;
         newIndex >= 0; --oldIndex, --newIndex) {
        QList<Node*> nodesPerIndex;
        Node* newNode = newChildNodes.at(newIndex);
        while (childNodes.at(oldIndex) != newNode) {
            nodesPerIndex.append(childNodes.at(oldIndex));
            --oldIndex;
        }
        if (!nodesPerIndex.isEmpty())
            deletions.append(QPair<int, QList<Node*> >(oldIndex + 1, nodesPerIndex));
    }
    { // add nodes that should be removed to the beginning
        QList<Node*> deleteAtStart;
        while (oldIndex >= 0) {
            deleteAtStart.append(childNodes.at(oldIndex--));
        }
        if (!deleteAtStart.isEmpty())
            deletions.append(QPair<int, QList<Node*> >(0, deleteAtStart));
    }

    for (QList<QPair<int, QList<Node*> > >::const_iterator iter = deletions.constBegin();
         iter != deletions.constEnd(); ++iter) {

        const int key = iter->first;
        const QList<Node*> nodes = iter->second;

        beginRemoveRows(parentIndex, key, key + nodes.size() - 1);

        // update internal cache
        for (int i = nodes.size(); i > 0; --i)
            childNodes.removeAt(key);
        m_childNodes.insert(parentFolder, childNodes);

        endRemoveRows();
    }

hjk's avatar
hjk committed
603
    QTC_ASSERT(childNodes == newChildNodes, /**/);
con's avatar
con committed
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
}

QList<FolderNode*> DetailedModel::recursiveSubFolders(FolderNode *parentFolder)
{
    QList<FolderNode*> subFolders;
    foreach (FolderNode *subFolder, parentFolder->subFolderNodes()) {
        subFolders.append(subFolder);
        subFolders != recursiveSubFolders(subFolder);
    }
    return subFolders;
}


/*!
  \class FlatModel

  The flat model shows only application/library projects.


  Shows all application/library projects directly unter the root project
  This results in a "flattened" view (max 3 hierachies).
  */

FlatModel::FlatModel(SessionNode *rootNode, QObject *parent)
        : QAbstractItemModel(parent),
629
          m_filterProjects(false),
con's avatar
con committed
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
          m_filterGeneratedFiles(true),
          m_rootNode(rootNode),
          m_startupProject(0),
          m_parentFolderForChange(0)
{
    NodesWatcher *watcher = new NodesWatcher(this);
    m_rootNode->registerWatcher(watcher);

    connect(watcher, SIGNAL(foldersAboutToBeAdded(FolderNode *, const QList<FolderNode*> &)),
            this, SLOT(foldersAboutToBeAdded(FolderNode *, const QList<FolderNode*> &)));
    connect(watcher, SIGNAL(foldersAdded()),
            this, SLOT(foldersAdded()));

    connect(watcher, SIGNAL(foldersAboutToBeRemoved(FolderNode *, const QList<FolderNode*> &)),
            this, SLOT(foldersAboutToBeRemoved(FolderNode *, const QList<FolderNode*> &)));
    connect(watcher, SIGNAL(foldersRemoved()),
            this, SLOT(foldersRemoved()));

    connect(watcher, SIGNAL(filesAboutToBeAdded(FolderNode *,const QList<FileNode*> &)),
            this, SLOT(filesAboutToBeAdded(FolderNode *, const QList<FileNode *> &)));
    connect(watcher, SIGNAL(filesAdded()),
            this, SLOT(filesAdded()));

    connect(watcher, SIGNAL(filesAboutToBeRemoved(FolderNode *, const QList<FileNode*> &)),
            this, SLOT(filesAboutToBeRemoved(FolderNode *, const QList<FileNode*> &)));
    connect(watcher, SIGNAL(filesRemoved()),
            this, SLOT(filesRemoved()));
}

QModelIndex FlatModel::index(int row, int column, const QModelIndex &parent) const
{
    QModelIndex result;
    if (!parent.isValid() && row == 0 && column == 0) { // session
        result = createIndex(0, 0, m_rootNode);
    } else if (parent.isValid() && column == 0) {
        FolderNode *parentNode = qobject_cast<FolderNode*>(nodeForIndex(parent));
hjk's avatar
hjk committed
666
        QTC_ASSERT(parentNode, return QModelIndex());
con's avatar
con committed
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
        QHash<FolderNode*, QList<Node*> >::const_iterator it = m_childNodes.constFind(parentNode);
        if (it == m_childNodes.constEnd()) {
            fetchMore(parentNode);
            it = m_childNodes.constFind(parentNode);
        }

        if (row < it.value().size())
            result = createIndex(row, 0, it.value().at(row));
    }
//    qDebug() << "index of " << row << column << parent.data(Project::FilePathRole) << " is " << result.data(Project::FilePathRole);
    return result;
}

QModelIndex FlatModel::parent(const QModelIndex &idx) const
{
    QModelIndex parentIndex;
    if (Node *node = nodeForIndex(idx)) {
        FolderNode *parentNode = visibleFolderNode(node->parentFolderNode());
        if (parentNode) {
            FolderNode *grandParentNode = visibleFolderNode(parentNode->parentFolderNode());
            if (grandParentNode) {
                QHash<FolderNode*, QList<Node*> >::const_iterator it = m_childNodes.constFind(grandParentNode);
                if (it == m_childNodes.constEnd()) {
                    fetchMore(grandParentNode);
                    it = m_childNodes.constFind(grandParentNode);
                }
hjk's avatar
hjk committed
693
                QTC_ASSERT(it != m_childNodes.constEnd(), return QModelIndex());
con's avatar
con committed
694
                const int row = it.value().indexOf(parentNode);
hjk's avatar
hjk committed
695
                QTC_ASSERT(row >= 0, return QModelIndex());
con's avatar
con committed
696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 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 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 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 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 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
                parentIndex = createIndex(row, 0, parentNode);
            } else {
                // top level node, parent is session
                parentIndex = index(0, 0, QModelIndex());
            }
        }
    }

//    qDebug() << "parent of " << idx.data(Project::FilePathRole) << " is " << parentIndex.data(Project::FilePathRole);

    return parentIndex;
}

QVariant FlatModel::data(const QModelIndex &index, int role) const
{
    QVariant result;

    if (Node *node = nodeForIndex(index)) {
        FolderNode *folderNode = qobject_cast<FolderNode*>(node);
        switch (role) {
        case Qt::DisplayRole:
        case Qt::EditRole: {
            if (folderNode)
                result = folderNode->name();
            else
                result = QFileInfo(node->path()).fileName(); //TODO cache that?
            break;
        }
        case Qt::ToolTipRole: {
            result = node->path();
            break;
        }
        case Qt::DecorationRole: {
            if (folderNode)
                result = folderNode->icon();
            else
                result = FileIconProvider::instance()->icon(QFileInfo(node->path()));
            break;
        }
        case Qt::FontRole: {
            QFont font;
            if (node == m_startupProject)
                font.setBold(true);
            result = font;
            break;
        }
        case ProjectExplorer::Project::FilePathRole: {
            result = node->path();
            break;
        }
        }
    }

    return result;
}

int FlatModel::rowCount(const QModelIndex &parent) const
{
    int rows = 0;
    if (!parent.isValid()) {
        rows = 1;
    } else {
        FolderNode *folderNode = qobject_cast<FolderNode*>(nodeForIndex(parent));
        if (folderNode && m_childNodes.contains(folderNode))
            rows = m_childNodes.value(folderNode).size();
    }
    return rows;
}

int FlatModel::columnCount(const QModelIndex &/*parent*/) const
{
    return 1;
}

bool FlatModel::hasChildren(const QModelIndex &parent) const
{
    if (!parent.isValid())
        return true;

    FolderNode *folderNode = qobject_cast<FolderNode*>(nodeForIndex(parent));
    if (!folderNode)
        return false;

    QHash<FolderNode*, QList<Node*> >::const_iterator it = m_childNodes.constFind(folderNode);
    if (it == m_childNodes.constEnd()) {
        fetchMore(folderNode);
        it = m_childNodes.constFind(folderNode);
    }
    return !it.value().isEmpty();
}

bool FlatModel::canFetchMore(const QModelIndex & parent) const
{
    if (!parent.isValid()) {
        return false;
    } else {
        if (FolderNode *folderNode = qobject_cast<FolderNode*>(nodeForIndex(parent)))
            return !m_childNodes.contains(folderNode);
        else
            return false;
    }
}

void FlatModel::recursiveAddFolderNodes(FolderNode *startNode, QList<Node *> *list, const QSet<Node *> &blackList) const
{
    foreach (FolderNode *folderNode, startNode->subFolderNodes()) {
        if (folderNode && !blackList.contains(folderNode))
            recursiveAddFolderNodesImpl(folderNode, list, blackList);
    }
}

void FlatModel::recursiveAddFolderNodesImpl(FolderNode *startNode, QList<Node *> *list, const QSet<Node *> &blackList) const
{
    if (!filter(startNode)) {
        if (!blackList.contains(startNode))
            list->append(startNode);
    } else {
        foreach (FolderNode *folderNode, startNode->subFolderNodes()) {
            if (folderNode && !blackList.contains(folderNode))
                recursiveAddFolderNodesImpl(folderNode, list, blackList);
        }
    }
}

void FlatModel::recursiveAddFileNodes(FolderNode *startNode, QList<Node *> *list, const QSet<Node *> &blackList) const
{
    foreach (FolderNode *subFolderNode, startNode->subFolderNodes()) {
        if (!blackList.contains(subFolderNode))
            recursiveAddFileNodes(subFolderNode, list, blackList);
    }
    foreach (Node *node, startNode->fileNodes()) {
        if (!blackList.contains(node) && !filter(node))
            list->append(node);
    }
}

QList<Node*> FlatModel::childNodes(FolderNode *parentNode, const QSet<Node*> &blackList) const
{
    QList<Node*> nodeList;

    if (parentNode->nodeType() == SessionNodeType) {
        SessionNode *sessionNode = static_cast<SessionNode*>(parentNode);
        QList<ProjectNode*> projectList = sessionNode->projectNodes();
        for (int i = 0; i < projectList.size(); ++i) {
            if (!blackList.contains(projectList.at(i)))
                nodeList << projectList.at(i);
        }
    } else {
        recursiveAddFolderNodes(parentNode, &nodeList, blackList);
        recursiveAddFileNodes(parentNode, &nodeList, blackList + nodeList.toSet());
    }
    qSort(nodeList.begin(), nodeList.end(), sortNodes);
    return nodeList;
}

void FlatModel::fetchMore(FolderNode *folderNode) const
{
hjk's avatar
hjk committed
853 854
    QTC_ASSERT(folderNode, return);
    QTC_ASSERT(!m_childNodes.contains(folderNode), return);
con's avatar
con committed
855 856 857 858 859 860 861 862

    QList<Node*> nodeList = childNodes(folderNode);
    m_childNodes.insert(folderNode, nodeList);
}

void FlatModel::fetchMore(const QModelIndex &parent)
{
    FolderNode *folderNode = qobject_cast<FolderNode*>(nodeForIndex(parent));
hjk's avatar
hjk committed
863
    QTC_ASSERT(folderNode, return);
con's avatar
con committed
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 914 915 916

    fetchMore(folderNode);
}

void FlatModel::setStartupProject(ProjectNode *projectNode)
{
    if (m_startupProject != projectNode) {
        QModelIndex oldIndex = (m_startupProject ? indexForNode(m_startupProject) : QModelIndex());
        QModelIndex newIndex = (projectNode ? indexForNode(projectNode) : QModelIndex());
        m_startupProject = projectNode;
        if (oldIndex.isValid())
            emit dataChanged(oldIndex, oldIndex);
        if (newIndex.isValid())
            emit dataChanged(newIndex, newIndex);
    }
}

void FlatModel::reset()
{
    m_childNodes.clear();
    QAbstractItemModel::reset();
}

QModelIndex FlatModel::indexForNode(const Node *node_)
{
    // We assume that we are only called for nodes that are represented

    // we use non-const pointers internally
    Node *node = const_cast<Node*>(node_);
    if (!node)
        return QModelIndex();

    if (node == m_rootNode)
        return createIndex(0, 0, m_rootNode);

    FolderNode *parentNode = visibleFolderNode(node->parentFolderNode());

    // Do we have the parent mapped?
    QHash<FolderNode*, QList<Node*> >::const_iterator it = m_childNodes.constFind(parentNode);
    if (it == m_childNodes.constEnd()) {
        fetchMore(parentNode);
        it = m_childNodes.constFind(parentNode);
    }
    if (it != m_childNodes.constEnd()) {
        const int row = it.value().indexOf(node);
        if (row != -1)
            return createIndex(row, 0, node);
    }
    return QModelIndex();
}

void FlatModel::setProjectFilterEnabled(bool filter)
{
917 918
    if (filter == m_filterProjects)
        return;
con's avatar
con committed
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 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
    m_filterProjects = filter;
    reset();
}

void FlatModel::setGeneratedFilesFilterEnabled(bool filter)
{
    m_filterGeneratedFiles = filter;
    reset();
}

Node *FlatModel::nodeForIndex(const QModelIndex &index) const
{
    if (index.isValid())
        return (Node*)index.internalPointer();
    return 0;
}

/*
  Returns the first folder node in the ancestors
  for the given node that is not filtered
  out by the Flat Model.
*/
FolderNode *FlatModel::visibleFolderNode(FolderNode *node) const
{
    if (!node)
        return 0;

    for (FolderNode *folderNode = node;
         folderNode;
         folderNode = folderNode->parentFolderNode()) {
        if (!filter(folderNode))
            return folderNode;
    }
    return 0;
}

bool FlatModel::filter(Node *node) const
{
    bool isHidden = false;
    if (ProjectNode *projectNode = qobject_cast<ProjectNode*>(node)) {
        if (m_filterProjects && projectNode->parentFolderNode() != m_rootNode)
            isHidden = !projectNode->hasTargets();
    }
    if (FileNode *fileNode = qobject_cast<FileNode*>(node)) {
        if (m_filterGeneratedFiles)
            isHidden = fileNode->isGenerated();
    }

    return isHidden;
}

/// slots and all the fun
void FlatModel::added(FolderNode* parentNode, const QList<Node*> &newNodeList)
{
    QModelIndex parentIndex = indexForNode(parentNode);
    // Old  list
    QHash<FolderNode*, QList<Node*> >::const_iterator it = m_childNodes.constFind(parentNode);
    if (it == m_childNodes.constEnd())
        return;
    QList<Node *> oldNodeList = it.value();

    // Compare lists and emit signals, and modify m_childNodes on the fly
    QList<Node *>::const_iterator oldIter = oldNodeList.constBegin();
    QList<Node *>::const_iterator newIter = newNodeList.constBegin();

    // optimization, check for old list is empty
    if (oldIter == oldNodeList.constEnd()) {
        // New Node List is empty, nothing added which intrest us
        if (newIter == newNodeList.constEnd())
            return;
        // So all we need to do is easy
        beginInsertRows(parentIndex, 0, newNodeList.size() - 1);
        m_childNodes.insert(parentNode, newNodeList);
        endInsertRows();
        return;
    }

hjk's avatar
hjk committed
996
    while (true) {
con's avatar
con committed
997
        // Skip all that are the same
hjk's avatar
hjk committed
998
        while (*oldIter == *newIter) {
con's avatar
con committed
999 1000 1001 1002 1003 1004 1005 1006 1007 1008
            ++oldIter;
            ++newIter;
            if (oldIter == oldNodeList.constEnd()) {
                // At end of oldNodeList, sweep up rest of newNodeList
                QList<Node *>::const_iterator startOfBlock = newIter;
                newIter = newNodeList.constEnd();
                int pos = oldIter - oldNodeList.constBegin();
                int count = newIter - startOfBlock;
                if (count > 0) {
                    beginInsertRows(parentIndex, pos, pos+count-1);
hjk's avatar
hjk committed
1009
                    while (startOfBlock != newIter) {
con's avatar
con committed
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
                        oldNodeList.insert(pos, *startOfBlock);
                        ++pos;
                        ++startOfBlock;
                    }
                    m_childNodes.insert(parentNode, oldNodeList);
                    endInsertRows();
                }
                return; // Done with the lists, leave the function
            }
        }

        QList<Node *>::const_iterator startOfBlock = newIter;
hjk's avatar
hjk committed
1022
        while (*oldIter != *newIter)
con's avatar
con committed
1023 1024 1025 1026 1027 1028 1029 1030
            ++newIter;
        // startOfBlock is the first that was diffrent
        // newIter points to the new position of oldIter
        // newIter - startOfBlock is number of new items
        // oldIter is the position where those are...
        int pos = oldIter - oldNodeList.constBegin();
        int count = newIter - startOfBlock;
        beginInsertRows(parentIndex, pos, pos + count - 1);
hjk's avatar
hjk committed
1031
        while (startOfBlock != newIter) {
con's avatar
con committed
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
            oldNodeList.insert(pos, *startOfBlock);
            ++pos;
            ++startOfBlock;
        }
        m_childNodes.insert(parentNode, oldNodeList);
        endInsertRows();
        oldIter = oldNodeList.constBegin() + pos;
    }
}

void FlatModel::removed(FolderNode* parentNode, const QList<Node*> &newNodeList)
{
    QModelIndex parentIndex = indexForNode(parentNode);
    // Old  list
    QHash<FolderNode*, QList<Node*> >::const_iterator it = m_childNodes.constFind(parentNode);
    if (it == m_childNodes.constEnd())
        return;
    QList<Node *> oldNodeList = it.value();
    // Compare lists and emit signals, and modify m_childNodes on the fly
    QList<Node *>::const_iterator oldIter = oldNodeList.constBegin();
    QList<Node *>::const_iterator newIter = newNodeList.constBegin();

    // optimization, check for new list is empty
    if (newIter == newNodeList.constEnd()) {
        // New Node List is empty, everything removed
        if (oldIter == oldNodeList.constEnd())
            return;
        // So all we need to do is easy
        beginRemoveRows(parentIndex, 0, oldNodeList.size() - 1);
        m_childNodes.insert(parentNode, newNodeList);
        endRemoveRows();
        return;
    }

hjk's avatar
hjk committed
1066
    while (true) {
con's avatar
con committed
1067
        // Skip all that are the same
hjk's avatar
hjk committed
1068
        while (*oldIter == *newIter) {
con's avatar
con committed
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
            ++oldIter;
            ++newIter;
            if (newIter == newNodeList.constEnd()) {
                // At end of newNodeList, sweep up rest of oldNodeList
                QList<Node *>::const_iterator startOfBlock = oldIter;
                oldIter = oldNodeList.constEnd();
                int pos = startOfBlock - oldNodeList.constBegin();
                int count = oldIter - startOfBlock;
                if (count > 0) {
                    beginRemoveRows(parentIndex, pos, pos+count-1);
hjk's avatar
hjk committed
1079
                    while (startOfBlock != oldIter) {
con's avatar
con committed
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
                        ++startOfBlock;
                        oldNodeList.removeAt(pos);
                    }

                    m_childNodes.insert(parentNode, oldNodeList);
                    endRemoveRows();
                }
                return; // Done with the lists, leave the function
            }
        }

        QList<Node *>::const_iterator startOfBlock = oldIter;
hjk's avatar
hjk committed
1092
        while (*oldIter != *newIter)
con's avatar
con committed
1093 1094 1095 1096 1097 1098 1099 1100
            ++oldIter;
        // startOfBlock is the first that was diffrent
        // oldIter points to the new position of newIter
        // oldIter - startOfBlock is number of new items
        // newIter is the position where those are...
        int pos = startOfBlock - oldNodeList.constBegin();
        int count = oldIter - startOfBlock;
        beginRemoveRows(parentIndex, pos, pos + count - 1);
hjk's avatar
hjk committed
1101
        while (startOfBlock != oldIter) {
con's avatar
con committed
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
            ++startOfBlock;
            oldNodeList.removeAt(pos);
        }
        m_childNodes.insert(parentNode, oldNodeList);
        endRemoveRows();
        oldIter = oldNodeList.constBegin() + pos;
    }
}

void FlatModel::foldersAboutToBeAdded(FolderNode *parentFolder, const QList<FolderNode*> &newFolders)
{
    Q_UNUSED(newFolders)
    m_parentFolderForChange = parentFolder;
}

void FlatModel::foldersAdded()
{
    // First found out what the folder is that we are adding the files to
    FolderNode *folderNode = visibleFolderNode(m_parentFolderForChange);

    // Now get the new list for that folder
    QList<Node *> newNodeList = childNodes(folderNode);

    added(folderNode, newNodeList);
}

void FlatModel::foldersAboutToBeRemoved(FolderNode *parentFolder, const QList<FolderNode*> &staleFolders)
{
    QSet<Node *> blackList;
hjk's avatar
hjk committed
1131
    foreach (FolderNode *node, staleFolders)
con's avatar
con committed
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
        blackList.insert(node);

    FolderNode *folderNode = visibleFolderNode(parentFolder);
    QList<Node *> newNodeList = childNodes(folderNode, blackList);

    removed(parentFolder, newNodeList);
    removeFromCache(staleFolders);
}

void FlatModel::removeFromCache(QList<FolderNode *> list)
{
hjk's avatar
hjk committed
1143
    foreach (FolderNode *fn, list) {
con's avatar
con committed
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
        removeFromCache(fn->subFolderNodes());
        m_childNodes.remove(fn);
    }
}

void FlatModel::foldersRemoved()
{
    // Do nothing
}

void FlatModel::filesAboutToBeAdded(FolderNode *folder, const QList<FileNode*> &newFiles)
{
    Q_UNUSED(newFiles)
    m_parentFolderForChange = folder;
}

void FlatModel::filesAdded()
{
    // First find out what the folder is that we are adding the files to
    FolderNode *folderNode = visibleFolderNode(m_parentFolderForChange);

    // Now get the new List for that folder
    QList<Node *> newNodeList = childNodes(folderNode);
    added(folderNode, newNodeList);
}

void FlatModel::filesAboutToBeRemoved(FolderNode *folder, const QList<FileNode*> &staleFiles)
{
    // First found out what the folder (that is the project) is that we are adding the files to
    FolderNode *folderNode = visibleFolderNode(folder);

    QSet<Node *> blackList;
hjk's avatar
hjk committed
1176
    foreach(Node *node, staleFiles)
con's avatar
con committed
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
        blackList.insert(node);

    // Now get the new List for that folder
    QList<Node *> newNodeList = childNodes(folderNode, blackList);
    removed(folderNode, newNodeList);
}

void FlatModel::filesRemoved()
{
    // Do nothing
}