projectmodels.cpp 26.9 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con committed
2
**
3 4
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
con's avatar
con committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
con's avatar
con committed
7
**
hjk's avatar
hjk committed
8 9 10 11
** 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.
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.
con's avatar
con committed
23
**
hjk's avatar
hjk committed
24
****************************************************************************/
hjk's avatar
hjk committed
25

con's avatar
con committed
26
#include "projectmodels.h"
hjk's avatar
hjk committed
27 28

#include "project.h"
29
#include "projectnodes.h"
dt's avatar
dt committed
30
#include "projectexplorer.h"
31
#include "projecttree.h"
con's avatar
con committed
32 33

#include <coreplugin/fileiconprovider.h>
34
#include <utils/algorithm.h>
35
#include <utils/dropsupport.h>
hjk's avatar
hjk committed
36

37 38 39
#include <QDebug>
#include <QFileInfo>
#include <QFont>
40
#include <QMimeData>
41
#include <QLoggingCategory>
con's avatar
con committed
42

43 44 45
namespace ProjectExplorer {

using namespace Internal;
con's avatar
con committed
46 47

namespace {
hjk's avatar
hjk committed
48 49

// sorting helper function
dt's avatar
dt committed
50

hjk's avatar
hjk committed
51 52
bool sortNodes(Node *n1, Node *n2)
{
53 54 55
    if (n1->priority() > n2->priority())
        return true;
    if (n1->priority() < n2->priority())
hjk's avatar
hjk committed
56
        return false;
con's avatar
con committed
57

58 59 60
    const int displayNameResult = caseFriendlyCompare(n1->displayName(), n2->displayName());
    if (displayNameResult != 0)
        return displayNameResult < 0;
con's avatar
con committed
61

62 63 64 65 66
    const int filePathResult = caseFriendlyCompare(n1->filePath().toString(),
                                 n2->filePath().toString());
    if (filePathResult != 0)
        return filePathResult < 0;
    return n1 < n2; // sort by pointer value
con's avatar
con committed
67 68
}

hjk's avatar
hjk committed
69 70
} // namespace anon

71 72
FlatModel::FlatModel(SessionNode *rootNode, QObject *parent) : QAbstractItemModel(parent),
    m_rootNode(rootNode)
con's avatar
con committed
73
{
74
    ProjectTree *tree = ProjectTree::instance();
con's avatar
con committed
75

76 77
    connect(tree, &ProjectTree::aboutToChangeShowInSimpleTree,
            this, &FlatModel::aboutToShowInSimpleTreeChanged);
78

79 80
    connect(tree, &ProjectTree::showInSimpleTreeChanged,
            this, &FlatModel::showInSimpleTreeChanged);
81

82 83 84 85
    connect(tree, &ProjectTree::foldersAboutToBeAdded,
            this, &FlatModel::foldersAboutToBeAdded);
    connect(tree, &ProjectTree::foldersAdded,
            this, &FlatModel::foldersAdded);
con's avatar
con committed
86

87 88 89 90
    connect(tree, &ProjectTree::foldersAboutToBeRemoved,
            this, &FlatModel::foldersAboutToBeRemoved);
    connect(tree, &ProjectTree::foldersRemoved,
            this, &FlatModel::foldersRemoved);
con's avatar
con committed
91

92 93 94 95
    connect(tree, &ProjectTree::filesAboutToBeAdded,
            this, &FlatModel::filesAboutToBeAdded);
    connect(tree, &ProjectTree::filesAdded,
            this, &FlatModel::filesAdded);
con's avatar
con committed
96

97 98 99 100
    connect(tree, &ProjectTree::filesAboutToBeRemoved,
            this, &FlatModel::filesAboutToBeRemoved);
    connect(tree, &ProjectTree::filesRemoved,
            this, &FlatModel::filesRemoved);
101

102 103 104 105
    connect(tree, &ProjectTree::nodeSortKeyAboutToChange,
            this, &FlatModel::nodeSortKeyAboutToChange);
    connect(tree, &ProjectTree::nodeSortKeyChanged,
            this, &FlatModel::nodeSortKeyChanged);
106

107 108
    connect(tree, &ProjectTree::nodeUpdated,
            this, &FlatModel::nodeUpdated);
con's avatar
con committed
109 110 111 112 113 114 115 116
}

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) {
117
        FolderNode *parentNode = nodeForIndex(parent)->asFolderNode();
dt's avatar
dt committed
118
        Q_ASSERT(parentNode);
con's avatar
con committed
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
        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());
137 138
        if (parentNode)
            return indexForNode(parentNode);
con's avatar
con committed
139 140 141 142 143 144 145 146 147
    }
    return parentIndex;
}

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

    if (Node *node = nodeForIndex(index)) {
148
        FolderNode *folderNode = node->asFolderNode();
con's avatar
con committed
149
        switch (role) {
150 151 152
        case Qt::DisplayRole: {
            QString name = node->displayName();

153
            if (node->nodeType() == NodeType::Project
154
                    && node->parentFolderNode()
155
                    && node->parentFolderNode()->nodeType() == NodeType::Session) {
156
                const QString vcsTopic = static_cast<ProjectNode *>(node)->vcsTopic();
157 158

                if (!vcsTopic.isEmpty())
159
                    name += QLatin1String(" [") + vcsTopic + QLatin1Char(']');
160 161 162 163 164
            }

            result = name;
            break;
        }
con's avatar
con committed
165
        case Qt::EditRole: {
166
            result = node->filePath().fileName();
con's avatar
con committed
167 168 169
            break;
        }
        case Qt::ToolTipRole: {
170
            result = node->tooltip();
con's avatar
con committed
171 172 173 174 175 176
            break;
        }
        case Qt::DecorationRole: {
            if (folderNode)
                result = folderNode->icon();
            else
177
                result = Core::FileIconProvider::icon(node->filePath().toString());
con's avatar
con committed
178 179 180 181 182 183 184 185 186
            break;
        }
        case Qt::FontRole: {
            QFont font;
            if (node == m_startupProject)
                font.setBold(true);
            result = font;
            break;
        }
187
        case Project::FilePathRole: {
188
            result = node->filePath().toString();
con's avatar
con committed
189 190
            break;
        }
191
        case Project::EnabledRole: {
192 193 194
            result = node->isEnabled();
            break;
        }
con's avatar
con committed
195 196 197 198 199 200
        }
    }

    return result;
}

dt's avatar
dt committed
201 202 203 204 205 206 207
Qt::ItemFlags FlatModel::flags(const QModelIndex &index) const
{
    if (!index.isValid())
        return 0;
    // We claim that everything is editable
    // That's slightly wrong
    // We control the only view, and that one does the checks
208
    Qt::ItemFlags f = Qt::ItemIsSelectable|Qt::ItemIsEnabled|Qt::ItemIsDragEnabled;
209
    if (Node *node = nodeForIndex(index)) {
210 211
        if (node == m_rootNode)
            return 0; // no flags for session node...
212
        if (!node->asProjectNode()) {
213
            // either folder or file node
214
            if (node->supportedActions(node).contains(Rename))
215 216 217 218
                f = f | Qt::ItemIsEditable;
        }
    }
    return f;
dt's avatar
dt committed
219 220 221 222 223 224 225 226 227
}

bool FlatModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (!index.isValid())
        return false;
    if (role != Qt::EditRole)
        return false;

228 229
    Node *node = nodeForIndex(index);

230
    Utils::FileName orgFilePath = node->filePath();
231
    Utils::FileName newFilePath = orgFilePath.parentDir().appendPath(value.toString());
232

233
    ProjectExplorerPlugin::renameFile(node, newFilePath.toString());
234
    emit renamed(orgFilePath, newFilePath);
dt's avatar
dt committed
235 236 237
    return true;
}

con's avatar
con committed
238 239 240 241 242 243
int FlatModel::rowCount(const QModelIndex &parent) const
{
    int rows = 0;
    if (!parent.isValid()) {
        rows = 1;
    } else {
244
        FolderNode *folderNode = nodeForIndex(parent)->asFolderNode();
con's avatar
con committed
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
        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;

261
    FolderNode *folderNode = nodeForIndex(parent)->asFolderNode();
con's avatar
con committed
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
    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 {
278
        if (FolderNode *folderNode = nodeForIndex(parent)->asFolderNode())
con's avatar
con committed
279 280 281 282 283 284 285 286
            return !m_childNodes.contains(folderNode);
        else
            return false;
    }
}

void FlatModel::recursiveAddFolderNodes(FolderNode *startNode, QList<Node *> *list, const QSet<Node *> &blackList) const
{
287
    foreach (FolderNode *folderNode, startNode->folderNodes()) {
con's avatar
con committed
288 289 290 291 292 293 294 295 296 297 298
        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 {
299
        foreach (FolderNode *folderNode, startNode->folderNodes()) {
con's avatar
con committed
300 301 302 303 304 305 306 307
            if (folderNode && !blackList.contains(folderNode))
                recursiveAddFolderNodesImpl(folderNode, list, blackList);
        }
    }
}

void FlatModel::recursiveAddFileNodes(FolderNode *startNode, QList<Node *> *list, const QSet<Node *> &blackList) const
{
308
    foreach (FolderNode *subFolderNode, startNode->folderNodes()) {
con's avatar
con committed
309 310 311 312 313 314 315 316 317 318 319
        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
{
320
    qCDebug(logger()) << "    FlatModel::childNodes for " << parentNode->filePath();
con's avatar
con committed
321 322
    QList<Node*> nodeList;

323
    if (parentNode->nodeType() == NodeType::Session) {
324
        auto sessionNode = static_cast<SessionNode*>(parentNode);
con's avatar
con committed
325 326 327 328 329 330 331 332 333
        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());
    }
334
    Utils::sort(nodeList, sortNodes);
335
    qCDebug(logger()) << "      found" << nodeList.size() << "nodes";
con's avatar
con committed
336 337 338 339 340
    return nodeList;
}

void FlatModel::fetchMore(FolderNode *folderNode) const
{
dt's avatar
dt committed
341 342
    Q_ASSERT(folderNode);
    Q_ASSERT(!m_childNodes.contains(folderNode));
con's avatar
con committed
343 344 345 346 347 348 349

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

void FlatModel::fetchMore(const QModelIndex &parent)
{
350
    FolderNode *folderNode = nodeForIndex(parent)->asFolderNode();
dt's avatar
dt committed
351
    Q_ASSERT(folderNode);
con's avatar
con committed
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370

    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()
{
371
    beginResetModel();
con's avatar
con committed
372
    m_childNodes.clear();
373
    endResetModel();
con's avatar
con committed
374 375
}

376 377 378 379 380
Qt::DropActions FlatModel::supportedDragActions() const
{
    return Qt::MoveAction;
}

381 382
QStringList FlatModel::mimeTypes() const
{
383
    return Utils::DropSupport::mimeTypesForFilePaths();
384 385 386 387
}

QMimeData *FlatModel::mimeData(const QModelIndexList &indexes) const
{
388
    auto data = new Utils::DropMimeData;
389 390
    foreach (const QModelIndex &index, indexes) {
        Node *node = nodeForIndex(index);
391
        if (node->asFileNode())
392
            data->addFile(node->filePath().toString());
393
        data->addValue(QVariant::fromValue(node));
394
    }
395
    return data;
396 397
}

398
QModelIndex FlatModel::indexForNode(const Node *node_) const
con's avatar
con committed
399 400 401 402
{
    // We assume that we are only called for nodes that are represented

    // we use non-const pointers internally
403
    auto node = const_cast<Node*>(node_);
con's avatar
con committed
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
    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)
{
428 429
    if (filter == m_filterProjects)
        return;
con's avatar
con committed
430 431 432 433 434 435 436 437 438 439
    m_filterProjects = filter;
    reset();
}

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

440 441 442 443 444 445 446 447 448 449
bool FlatModel::projectFilterEnabled()
{
    return m_filterProjects;
}

bool FlatModel::generatedFilesFilterEnabled()
{
    return m_filterGeneratedFiles;
}

con's avatar
con committed
450 451 452 453
Node *FlatModel::nodeForIndex(const QModelIndex &index) const
{
    if (index.isValid())
        return (Node*)index.internalPointer();
454
    return nullptr;
con's avatar
con committed
455 456 457 458 459 460 461 462 463 464
}

/*
  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)
465
        return nullptr;
con's avatar
con committed
466 467 468 469 470 471 472

    for (FolderNode *folderNode = node;
         folderNode;
         folderNode = folderNode->parentFolderNode()) {
        if (!filter(folderNode))
            return folderNode;
    }
473
    return nullptr;
con's avatar
con committed
474 475 476 477 478
}

bool FlatModel::filter(Node *node) const
{
    bool isHidden = false;
479
    if (FolderNode *folderNode = node->asFolderNode()) {
480
        if (m_filterProjects)
481
            isHidden = !folderNode->showInSimpleTree();
482
    } else if (FileNode *fileNode = node->asFileNode()) {
con's avatar
con committed
483 484 485 486 487 488
        if (m_filterGeneratedFiles)
            isHidden = fileNode->isGenerated();
    }
    return isHidden;
}

489 490 491 492 493 494
const QLoggingCategory &FlatModel::logger()
{
    static QLoggingCategory logger("qtc.projectexplorer.flatmodel");
    return logger;
}

495 496 497 498 499 500 501 502 503 504
bool isSorted(const QList<Node *> &nodes)
{
    int size = nodes.size();
    for (int i = 0; i < size -1; ++i) {
        if (!sortNodes(nodes.at(i), nodes.at(i+1)))
            return false;
    }
    return true;
}

con's avatar
con committed
505 506 507
/// slots and all the fun
void FlatModel::added(FolderNode* parentNode, const QList<Node*> &newNodeList)
{
508
    qCDebug(logger()) << "FlatModel::added" << parentNode->filePath() << newNodeList.size() << "nodes";
con's avatar
con committed
509 510
    QModelIndex parentIndex = indexForNode(parentNode);
    // Old  list
511 512 513 514 515 516

    if (newNodeList.isEmpty()) {
        qCDebug(logger()) << "  newNodeList empty";
        return;
    }

con's avatar
con committed
517
    QHash<FolderNode*, QList<Node*> >::const_iterator it = m_childNodes.constFind(parentNode);
518 519 520 521 522 523 524 525 526
    if (it == m_childNodes.constEnd()) {
        if (!parentIndex.isValid()) {
            qCDebug(logger()) << "  parent not mapped returning";
            return;
        }
        qCDebug(logger()) << "  updated m_childNodes";
        beginInsertRows(parentIndex, 0, newNodeList.size() - 1);
        m_childNodes.insert(parentNode, newNodeList);
        endInsertRows();
con's avatar
con committed
527
        return;
528
    }
con's avatar
con committed
529 530 531 532 533 534
    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();

535 536 537 538 539 540 541 542 543
    Q_ASSERT(isSorted(oldNodeList));
    Q_ASSERT(isSorted(newNodeList));

    QSet<Node *> emptyDifference;
    emptyDifference = oldNodeList.toSet();
    emptyDifference.subtract(newNodeList.toSet());
    if (!emptyDifference.isEmpty()) {
        // This should not happen...
        qDebug() << "FlatModel::added, old Node list should be subset of newNode list, found files in old list which were not part of new list";
544 545
        foreach (Node *n, emptyDifference)
            qDebug()<<n->filePath();
546 547 548
        Q_ASSERT(false);
    }

con's avatar
con committed
549 550 551 552 553 554 555 556 557
    // 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();
558
        qCDebug(logger()) << "  updated m_childNodes";
con's avatar
con committed
559 560 561
        return;
    }

hjk's avatar
hjk committed
562
    while (true) {
con's avatar
con committed
563
        // Skip all that are the same
hjk's avatar
hjk committed
564
        while (*oldIter == *newIter) {
con's avatar
con committed
565 566 567 568 569 570 571 572 573 574
            ++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
575
                    while (startOfBlock != newIter) {
con's avatar
con committed
576 577 578 579 580 581 582 583 584 585 586 587
                        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
588
        while (*oldIter != *newIter)
con's avatar
con committed
589 590 591 592 593 594 595 596
            ++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
597
        while (startOfBlock != newIter) {
con's avatar
con committed
598 599 600 601 602 603 604 605
            oldNodeList.insert(pos, *startOfBlock);
            ++pos;
            ++startOfBlock;
        }
        m_childNodes.insert(parentNode, oldNodeList);
        endInsertRows();
        oldIter = oldNodeList.constBegin() + pos;
    }
606
    qCDebug(logger()) << "  updated m_childNodes";
con's avatar
con committed
607 608 609 610
}

void FlatModel::removed(FolderNode* parentNode, const QList<Node*> &newNodeList)
{
611
    qCDebug(logger()) << "FlatModel::removed" << parentNode->filePath() << newNodeList.size() << "nodes";
con's avatar
con committed
612 613 614
    QModelIndex parentIndex = indexForNode(parentNode);
    // Old  list
    QHash<FolderNode*, QList<Node*> >::const_iterator it = m_childNodes.constFind(parentNode);
615 616
    if (it == m_childNodes.constEnd()) {
        qCDebug(logger()) << "  unmapped node";
con's avatar
con committed
617
        return;
618
    }
619

con's avatar
con committed
620 621 622 623 624
    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();

625 626 627 628 629 630 631 632
    Q_ASSERT(isSorted(newNodeList));

    QSet<Node *> emptyDifference;
    emptyDifference = newNodeList.toSet();
    emptyDifference.subtract(oldNodeList.toSet());
    if (!emptyDifference.isEmpty()) {
        // This should not happen...
        qDebug() << "FlatModel::removed, new Node list should be subset of oldNode list, found files in new list which were not part of old list";
633 634
        foreach (Node *n, emptyDifference)
            qDebug()<<n->filePath();
635 636 637
        Q_ASSERT(false);
    }

con's avatar
con committed
638 639 640 641 642 643 644 645 646
    // 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();
647
        qCDebug(logger()) << "  updated m_childNodes";
con's avatar
con committed
648 649 650
        return;
    }

hjk's avatar
hjk committed
651
    while (true) {
con's avatar
con committed
652
        // Skip all that are the same
hjk's avatar
hjk committed
653
        while (*oldIter == *newIter) {
con's avatar
con committed
654 655 656 657 658 659 660 661 662 663
            ++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
664
                    while (startOfBlock != oldIter) {
con's avatar
con committed
665 666 667 668 669 670 671 672 673 674 675 676
                        ++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
677
        while (*oldIter != *newIter)
con's avatar
con committed
678 679 680 681 682 683 684 685
            ++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
686
        while (startOfBlock != oldIter) {
con's avatar
con committed
687 688 689 690 691 692 693
            ++startOfBlock;
            oldNodeList.removeAt(pos);
        }
        m_childNodes.insert(parentNode, oldNodeList);
        endRemoveRows();
        oldIter = oldNodeList.constBegin() + pos;
    }
694
    qCDebug(logger()) << "  updated m_childNodes";
con's avatar
con committed
695 696
}

697
void FlatModel::aboutToShowInSimpleTreeChanged(FolderNode* node)
698 699 700 701 702 703 704 705 706 707
{
    if (!m_filterProjects)
        return;
    FolderNode *folder = visibleFolderNode(node->parentFolderNode());
    QList<Node *> newNodeList = childNodes(folder, QSet<Node *>() << node);
    removed(folder, newNodeList);

    QList<Node *> staleFolders;
    recursiveAddFolderNodesImpl(node, &staleFolders);
    foreach (Node *n, staleFolders)
708
        if (FolderNode *fn = n->asFolderNode())
709 710 711
            m_childNodes.remove(fn);
}

712
void FlatModel::showInSimpleTreeChanged(FolderNode *node)
713 714 715 716 717 718 719 720 721
{
    if (!m_filterProjects)
        return;
    // we are only interested if we filter
    FolderNode *folder = visibleFolderNode(node->parentFolderNode());
    QList<Node *> newNodeList = childNodes(folder);
    added(folder, newNodeList);
}

con's avatar
con committed
722 723
void FlatModel::foldersAboutToBeAdded(FolderNode *parentFolder, const QList<FolderNode*> &newFolders)
{
724
    qCDebug(logger()) << "FlatModel::foldersAboutToBeAdded";
con's avatar
con committed
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
    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
743
    foreach (FolderNode *node, staleFolders)
con's avatar
con committed
744 745 746 747 748
        blackList.insert(node);

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

749
    removed(folderNode, newNodeList);
con's avatar
con committed
750 751 752 753 754
    removeFromCache(staleFolders);
}

void FlatModel::removeFromCache(QList<FolderNode *> list)
{
hjk's avatar
hjk committed
755
    foreach (FolderNode *fn, list) {
756
        removeFromCache(fn->folderNodes());
con's avatar
con committed
757 758 759 760
        m_childNodes.remove(fn);
    }
}

761 762
void FlatModel::changedSortKey(FolderNode *folderNode, Node *node)
{
763 764 765
    if (!m_childNodes.contains(folderNode))
        return; // The directory was not yet mapped, so there is no need to sort it.

766 767 768 769
    QList<Node *> nodes = m_childNodes.value(folderNode);
    int oldIndex = nodes.indexOf(node);

    nodes.removeAt(oldIndex);
770
    QList<Node *>::iterator newPosIt = std::lower_bound(nodes.begin(), nodes.end(), node, sortNodes);
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
    int newIndex = newPosIt - nodes.begin();

    if (newIndex == oldIndex)
        return;

    nodes.insert(newPosIt, node);

    QModelIndex parentIndex = indexForNode(folderNode);
    if (newIndex > oldIndex)
        ++newIndex; // see QAbstractItemModel::beginMoveRows
    beginMoveRows(parentIndex, oldIndex, oldIndex, parentIndex, newIndex);
    m_childNodes[folderNode] = nodes;
    endMoveRows();
}

con's avatar
con committed
786 787 788 789 790 791 792
void FlatModel::foldersRemoved()
{
    // Do nothing
}

void FlatModel::filesAboutToBeAdded(FolderNode *folder, const QList<FileNode*> &newFiles)
{
793
    qCDebug(logger()) << "FlatModel::filesAboutToBeAdded";
con's avatar
con committed
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
    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;
814
    foreach (Node *node, staleFiles)
con's avatar
con committed
815 816 817 818 819 820 821 822 823 824 825
        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
}
826

827 828 829 830 831 832 833 834 835 836 837
void FlatModel::nodeSortKeyAboutToChange(Node *node)
{
    m_nodeForSortKeyChange = node;
}

void FlatModel::nodeSortKeyChanged()
{
    FolderNode *folderNode = visibleFolderNode(m_nodeForSortKeyChange->parentFolderNode());
    changedSortKey(folderNode, m_nodeForSortKeyChange);
}

838 839 840 841 842 843
void FlatModel::nodeUpdated(Node *node)
{
    QModelIndex idx = indexForNode(node);
    emit dataChanged(idx, idx);
}

844 845 846 847 848 849 850 851 852 853 854
namespace Internal {

int caseFriendlyCompare(const QString &a, const QString &b)
{
    int result = a.compare(b, Qt::CaseInsensitive);
    if (result != 0)
        return result;
    return a.compare(b, Qt::CaseSensitive);
}

}
855 856

} // namespace ProjectExplorer
857