projectmodels.cpp 30.8 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con committed
2
**
Eike Ziller's avatar
Eike Ziller committed
3 4
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://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
Eike Ziller's avatar
Eike Ziller committed
12 13
** a written agreement between you and The Qt Company.  For licensing terms and
** conditions see http://www.qt.io/terms-conditions.  For further information
Eike Ziller's avatar
Eike Ziller committed
14
** use the contact form at http://www.qt.io/contact-us.
15
**
16
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
** Alternatively, this file may be used under the terms of the GNU Lesser
Eike Ziller's avatar
Eike Ziller committed
18 19 20 21 22 23
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
hjk's avatar
hjk committed
24
**
Eike Ziller's avatar
Eike Ziller committed
25 26
** In addition, as a special exception, The Qt Company gives you certain additional
** rights.  These rights are described in The Qt Company LGPL Exception
con's avatar
con committed
27 28
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
29
****************************************************************************/
hjk's avatar
hjk committed
30

con's avatar
con committed
31
#include "projectmodels.h"
hjk's avatar
hjk committed
32 33

#include "project.h"
34
#include "projectnodes.h"
dt's avatar
dt committed
35
#include "projectexplorer.h"
36
#include "projecttree.h"
con's avatar
con committed
37 38

#include <coreplugin/fileiconprovider.h>
39
#include <utils/algorithm.h>
40
#include <utils/dropsupport.h>
hjk's avatar
hjk committed
41

42 43 44
#include <QDebug>
#include <QFileInfo>
#include <QFont>
45
#include <QMimeData>
46
#include <QLoggingCategory>
con's avatar
con committed
47

48 49 50
namespace ProjectExplorer {

using namespace Internal;
con's avatar
con committed
51 52

namespace {
hjk's avatar
hjk committed
53 54

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

hjk's avatar
hjk committed
56 57 58 59 60 61 62 63
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
64 65
    FileNode *file1 = n1->asFileNode();
    FileNode *file2 = n2->asFileNode();
hjk's avatar
hjk committed
66 67
    if (file1 && file1->fileType() == ProjectFileType) {
        if (file2 && file2->fileType() == ProjectFileType) {
68 69
            const QString fileName1 = file1->filePath().fileName();
            const QString fileName2 = file2->filePath().fileName();
hjk's avatar
hjk committed
70

71
            int result = caseFriendlyCompare(fileName1, fileName2);
dt's avatar
dt committed
72
            if (result != 0)
dt's avatar
dt committed
73
                return result < 0;
hjk's avatar
hjk committed
74 75
            else
                return file1 < file2;
con's avatar
con committed
76
        } else {
hjk's avatar
hjk committed
77 78 79
            return true; // project file is before everything else
        }
    } else {
80
        if (file2 && file2->fileType() == ProjectFileType)
hjk's avatar
hjk committed
81 82
            return false;
    }
con's avatar
con committed
83

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

90
            int result = caseFriendlyCompare(project1->displayName(), project2->displayName());
dt's avatar
dt committed
91
            if (result != 0)
dt's avatar
dt committed
92
                return result < 0;
93

94 95
            result = caseFriendlyCompare(project1->filePath().toString(),
                                         project2->filePath().toString());
96 97 98
            if (result != 0)
                return result < 0;
            return project1 < project2; // sort by pointer value
hjk's avatar
hjk committed
99 100 101 102 103 104
        } else {
           return true; // project is before folder & file
       }
    }
    if (n2Type == ProjectNodeType)
        return false;
con's avatar
con committed
105

106 107 108 109 110 111 112 113 114
    if (n1Type == VirtualFolderNodeType) {
        if (n2Type == VirtualFolderNodeType) {
            VirtualFolderNode *folder1 = static_cast<VirtualFolderNode *>(n1);
            VirtualFolderNode *folder2 = static_cast<VirtualFolderNode *>(n2);

            if (folder1->priority() > folder2->priority())
                return true;
            if (folder1->priority() < folder2->priority())
                return false;
115 116
            int result = caseFriendlyCompare(folder1->filePath().toString(),
                                             folder2->filePath().toString());
117 118 119 120 121 122 123 124 125 126 127 128 129
            if (result != 0)
                return result < 0;
            else
                return folder1 < folder2;
        } else {
            return true; // virtual folder is before folder
        }
    }

    if (n2Type == VirtualFolderNodeType)
        return false;


hjk's avatar
hjk committed
130 131 132 133
    if (n1Type == FolderNodeType) {
        if (n2Type == FolderNodeType) {
            FolderNode *folder1 = static_cast<FolderNode*>(n1);
            FolderNode *folder2 = static_cast<FolderNode*>(n2);
con's avatar
con committed
134

135 136
            int result = caseFriendlyCompare(folder1->filePath().toString(),
                                             folder2->filePath().toString());
dt's avatar
dt committed
137
            if (result != 0)
dt's avatar
dt committed
138
                return result < 0;
hjk's avatar
hjk committed
139 140 141 142
            else
                return folder1 < folder2;
        } else {
            return true; // folder is before file
con's avatar
con committed
143
        }
hjk's avatar
hjk committed
144 145 146
    }
    if (n2Type == FolderNodeType)
        return false;
con's avatar
con committed
147

hjk's avatar
hjk committed
148 149
    // must be file nodes
    {
150 151 152 153
        int result = caseFriendlyCompare(n1->displayName(), n2->displayName());
        if (result != 0)
            return result < 0;

154 155
        const QString filePath1 = n1->filePath().toString();
        const QString filePath2 = n2->filePath().toString();
con's avatar
con committed
156

157 158
        const QString fileName1 = n1->filePath().fileName();
        const QString fileName2 = n2->filePath().fileName();
con's avatar
con committed
159

160
        result = caseFriendlyCompare(fileName1, fileName2);
dt's avatar
dt committed
161
        if (result != 0) {
dt's avatar
dt committed
162
            return result < 0; // sort by filename
hjk's avatar
hjk committed
163
        } else {
164
            result = caseFriendlyCompare(filePath1, filePath2);
165
            if (result != 0)
dt's avatar
dt committed
166
                return result < 0; // sort by filepath
167 168 169 170

            if (n1->line() != n2->line())
                return n1->line() < n2->line(); // sort by line numbers
            return n1 < n2; // sort by pointer value
con's avatar
con committed
171 172
        }
    }
hjk's avatar
hjk committed
173
    return false;
con's avatar
con committed
174 175
}

hjk's avatar
hjk committed
176 177
} // namespace anon

con's avatar
con committed
178 179
FlatModel::FlatModel(SessionNode *rootNode, QObject *parent)
        : QAbstractItemModel(parent),
180
          m_filterProjects(false),
con's avatar
con committed
181 182 183 184 185
          m_filterGeneratedFiles(true),
          m_rootNode(rootNode),
          m_startupProject(0),
          m_parentFolderForChange(0)
{
186
    ProjectTree *tree = ProjectTree::instance();
con's avatar
con committed
187

188 189
    connect(tree, &ProjectTree::aboutToChangeShowInSimpleTree,
            this, &FlatModel::aboutToShowInSimpleTreeChanged);
190

191 192
    connect(tree, &ProjectTree::showInSimpleTreeChanged,
            this, &FlatModel::showInSimpleTreeChanged);
193

194 195 196 197
    connect(tree, &ProjectTree::foldersAboutToBeAdded,
            this, &FlatModel::foldersAboutToBeAdded);
    connect(tree, &ProjectTree::foldersAdded,
            this, &FlatModel::foldersAdded);
con's avatar
con committed
198

199 200 201 202
    connect(tree, &ProjectTree::foldersAboutToBeRemoved,
            this, &FlatModel::foldersAboutToBeRemoved);
    connect(tree, &ProjectTree::foldersRemoved,
            this, &FlatModel::foldersRemoved);
con's avatar
con committed
203

204 205 206 207
    connect(tree, &ProjectTree::filesAboutToBeAdded,
            this, &FlatModel::filesAboutToBeAdded);
    connect(tree, &ProjectTree::filesAdded,
            this, &FlatModel::filesAdded);
con's avatar
con committed
208

209 210 211 212
    connect(tree, &ProjectTree::filesAboutToBeRemoved,
            this, &FlatModel::filesAboutToBeRemoved);
    connect(tree, &ProjectTree::filesRemoved,
            this, &FlatModel::filesRemoved);
213

214 215 216 217
    connect(tree, &ProjectTree::nodeSortKeyAboutToChange,
            this, &FlatModel::nodeSortKeyAboutToChange);
    connect(tree, &ProjectTree::nodeSortKeyChanged,
            this, &FlatModel::nodeSortKeyChanged);
218

219 220
    connect(tree, &ProjectTree::nodeUpdated,
            this, &FlatModel::nodeUpdated);
con's avatar
con committed
221 222 223 224 225 226 227 228
}

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) {
229
        FolderNode *parentNode = nodeForIndex(parent)->asFolderNode();
dt's avatar
dt committed
230
        Q_ASSERT(parentNode);
con's avatar
con committed
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
        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());
249 250
        if (parentNode)
            return indexForNode(parentNode);
con's avatar
con committed
251 252 253 254 255 256 257 258 259
    }
    return parentIndex;
}

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

    if (Node *node = nodeForIndex(index)) {
260
        FolderNode *folderNode = node->asFolderNode();
con's avatar
con committed
261
        switch (role) {
262 263 264
        case Qt::DisplayRole: {
            QString name = node->displayName();

265 266
            if (node->nodeType() == ProjectNodeType
                    && node->parentFolderNode()
267
                    && node->parentFolderNode()->nodeType() == SessionNodeType) {
268
                const QString vcsTopic = static_cast<ProjectNode *>(node)->vcsTopic();
269 270

                if (!vcsTopic.isEmpty())
271
                    name += QLatin1String(" [") + vcsTopic + QLatin1Char(']');
272 273 274 275 276
            }

            result = name;
            break;
        }
con's avatar
con committed
277
        case Qt::EditRole: {
278
            result = node->filePath().fileName();
con's avatar
con committed
279 280 281
            break;
        }
        case Qt::ToolTipRole: {
282
            result = node->tooltip();
con's avatar
con committed
283 284 285 286 287 288
            break;
        }
        case Qt::DecorationRole: {
            if (folderNode)
                result = folderNode->icon();
            else
289
                result = Core::FileIconProvider::icon(node->filePath().toString());
con's avatar
con committed
290 291 292 293 294 295 296 297 298
            break;
        }
        case Qt::FontRole: {
            QFont font;
            if (node == m_startupProject)
                font.setBold(true);
            result = font;
            break;
        }
299
        case Project::FilePathRole: {
300
            result = node->filePath().toString();
con's avatar
con committed
301 302
            break;
        }
303
        case Project::EnabledRole: {
304 305 306
            result = node->isEnabled();
            break;
        }
con's avatar
con committed
307 308 309 310 311 312
        }
    }

    return result;
}

dt's avatar
dt committed
313 314 315 316 317 318 319
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
320
    Qt::ItemFlags f = Qt::ItemIsSelectable|Qt::ItemIsEnabled|Qt::ItemIsDragEnabled;
321
    if (Node *node = nodeForIndex(index)) {
322 323
        if (node == m_rootNode)
            return 0; // no flags for session node...
324
        if (!node->asProjectNode()) {
325
            // either folder or file node
326
            if (node->supportedActions(node).contains(Rename))
327 328 329 330
                f = f | Qt::ItemIsEditable;
        }
    }
    return f;
dt's avatar
dt committed
331 332 333 334 335 336 337 338 339
}

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

340 341
    Node *node = nodeForIndex(index);

342
    Utils::FileName orgFilePath = node->filePath();
343
    Utils::FileName newFilePath = orgFilePath.parentDir().appendPath(value.toString());
344

345
    ProjectExplorerPlugin::renameFile(node, newFilePath.toString());
346
    emit renamed(orgFilePath, newFilePath);
dt's avatar
dt committed
347 348 349
    return true;
}

con's avatar
con committed
350 351 352 353 354 355
int FlatModel::rowCount(const QModelIndex &parent) const
{
    int rows = 0;
    if (!parent.isValid()) {
        rows = 1;
    } else {
356
        FolderNode *folderNode = nodeForIndex(parent)->asFolderNode();
con's avatar
con committed
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
        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;

373
    FolderNode *folderNode = nodeForIndex(parent)->asFolderNode();
con's avatar
con committed
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
    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 {
390
        if (FolderNode *folderNode = nodeForIndex(parent)->asFolderNode())
con's avatar
con committed
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
            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
{
432
    qCDebug(logger()) << "    FlatModel::childNodes for " << parentNode->filePath();
con's avatar
con committed
433 434 435 436 437 438 439 440 441 442 443 444 445
    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());
    }
446
    Utils::sort(nodeList, sortNodes);
447
    qCDebug(logger()) << "      found" << nodeList.size() << "nodes";
con's avatar
con committed
448 449 450 451 452
    return nodeList;
}

void FlatModel::fetchMore(FolderNode *folderNode) const
{
dt's avatar
dt committed
453 454
    Q_ASSERT(folderNode);
    Q_ASSERT(!m_childNodes.contains(folderNode));
con's avatar
con committed
455 456 457 458 459 460 461

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

void FlatModel::fetchMore(const QModelIndex &parent)
{
462
    FolderNode *folderNode = nodeForIndex(parent)->asFolderNode();
dt's avatar
dt committed
463
    Q_ASSERT(folderNode);
con's avatar
con committed
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482

    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()
{
483
    beginResetModel();
con's avatar
con committed
484
    m_childNodes.clear();
485
    endResetModel();
con's avatar
con committed
486 487
}

488 489 490 491 492
Qt::DropActions FlatModel::supportedDragActions() const
{
    return Qt::MoveAction;
}

493 494
QStringList FlatModel::mimeTypes() const
{
495
    return Utils::DropSupport::mimeTypesForFilePaths();
496 497 498 499
}

QMimeData *FlatModel::mimeData(const QModelIndexList &indexes) const
{
500
    auto data = new Utils::DropMimeData;
501 502
    foreach (const QModelIndex &index, indexes) {
        Node *node = nodeForIndex(index);
503
        if (node->asFileNode())
504
            data->addFile(node->filePath().toString());
505
        data->addValue(QVariant::fromValue(node));
506
    }
507
    return data;
508 509
}

510
QModelIndex FlatModel::indexForNode(const Node *node_) const
con's avatar
con committed
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
{
    // 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)
{
540 541
    if (filter == m_filterProjects)
        return;
con's avatar
con committed
542 543 544 545 546 547 548 549 550 551
    m_filterProjects = filter;
    reset();
}

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

552 553 554 555 556 557 558 559 560 561
bool FlatModel::projectFilterEnabled()
{
    return m_filterProjects;
}

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

con's avatar
con committed
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
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;
591
    if (FolderNode *folderNode = node->asFolderNode()) {
592
        if (m_filterProjects)
593
            isHidden = !folderNode->showInSimpleTree();
594
    } else if (FileNode *fileNode = node->asFileNode()) {
con's avatar
con committed
595 596 597 598 599 600
        if (m_filterGeneratedFiles)
            isHidden = fileNode->isGenerated();
    }
    return isHidden;
}

601 602 603 604 605 606
const QLoggingCategory &FlatModel::logger()
{
    static QLoggingCategory logger("qtc.projectexplorer.flatmodel");
    return logger;
}

607 608 609 610 611 612 613 614 615 616
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
617 618 619
/// slots and all the fun
void FlatModel::added(FolderNode* parentNode, const QList<Node*> &newNodeList)
{
620
    qCDebug(logger()) << "FlatModel::added" << parentNode->filePath() << newNodeList.size() << "nodes";
con's avatar
con committed
621 622
    QModelIndex parentIndex = indexForNode(parentNode);
    // Old  list
623 624 625 626 627 628

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

con's avatar
con committed
629
    QHash<FolderNode*, QList<Node*> >::const_iterator it = m_childNodes.constFind(parentNode);
630 631 632 633 634 635 636 637 638
    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
639
        return;
640
    }
con's avatar
con committed
641 642 643 644 645 646
    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();

647 648 649 650 651 652 653 654 655
    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";
656 657
        foreach (Node *n, emptyDifference)
            qDebug()<<n->filePath();
658 659 660
        Q_ASSERT(false);
    }

con's avatar
con committed
661 662 663 664 665 666 667 668 669
    // 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();
670
        qCDebug(logger()) << "  updated m_childNodes";
con's avatar
con committed
671 672 673
        return;
    }

hjk's avatar
hjk committed
674
    while (true) {
con's avatar
con committed
675
        // Skip all that are the same
hjk's avatar
hjk committed
676
        while (*oldIter == *newIter) {
con's avatar
con committed
677 678 679 680 681 682 683 684 685 686
            ++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
687
                    while (startOfBlock != newIter) {
con's avatar
con committed
688 689 690 691 692 693 694 695 696 697 698 699
                        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
700
        while (*oldIter != *newIter)
con's avatar
con committed
701 702 703 704 705 706 707 708
            ++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
709
        while (startOfBlock != newIter) {
con's avatar
con committed
710 711 712 713 714 715 716 717
            oldNodeList.insert(pos, *startOfBlock);
            ++pos;
            ++startOfBlock;
        }
        m_childNodes.insert(parentNode, oldNodeList);
        endInsertRows();
        oldIter = oldNodeList.constBegin() + pos;
    }
718
    qCDebug(logger()) << "  updated m_childNodes";
con's avatar
con committed
719 720 721 722
}

void FlatModel::removed(FolderNode* parentNode, const QList<Node*> &newNodeList)
{
723
    qCDebug(logger()) << "FlatModel::removed" << parentNode->filePath() << newNodeList.size() << "nodes";
con's avatar
con committed
724 725 726
    QModelIndex parentIndex = indexForNode(parentNode);
    // Old  list
    QHash<FolderNode*, QList<Node*> >::const_iterator it = m_childNodes.constFind(parentNode);
727 728
    if (it == m_childNodes.constEnd()) {
        qCDebug(logger()) << "  unmapped node";
con's avatar
con committed
729
        return;
730
    }
731

con's avatar
con committed
732 733 734 735 736
    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();

737 738 739 740 741 742 743 744
    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";
745 746
        foreach (Node *n, emptyDifference)
            qDebug()<<n->filePath();
747 748 749
        Q_ASSERT(false);
    }

con's avatar
con committed
750 751 752 753 754 755 756 757 758
    // 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();
759
        qCDebug(logger()) << "  updated m_childNodes";
con's avatar
con committed
760 761 762
        return;
    }

hjk's avatar
hjk committed
763
    while (true) {
con's avatar
con committed
764
        // Skip all that are the same
hjk's avatar
hjk committed
765
        while (*oldIter == *newIter) {
con's avatar
con committed
766 767 768 769 770 771 772 773 774 775
            ++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
776
                    while (startOfBlock != oldIter) {
con's avatar
con committed
777 778 779 780 781 782 783 784 785 786 787 788
                        ++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
789
        while (*oldIter != *newIter)
con's avatar
con committed
790 791 792 793 794 795 796 797
            ++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
798
        while (startOfBlock != oldIter) {
con's avatar
con committed
799 800 801 802 803 804 805
            ++startOfBlock;
            oldNodeList.removeAt(pos);
        }
        m_childNodes.insert(parentNode, oldNodeList);
        endRemoveRows();
        oldIter = oldNodeList.constBegin() + pos;
    }
806
    qCDebug(logger()) << "  updated m_childNodes";
con's avatar
con committed
807 808
}

809
void FlatModel::aboutToShowInSimpleTreeChanged(FolderNode* node)
810 811 812 813 814 815 816 817 818 819
{
    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)
820
        if (FolderNode *fn = n->asFolderNode())
821 822 823
            m_childNodes.remove(fn);
}

824
void FlatModel::showInSimpleTreeChanged(FolderNode *node)
825 826 827 828 829 830 831 832 833
{
    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
834 835
void FlatModel::foldersAboutToBeAdded(FolderNode *parentFolder, const QList<FolderNode*> &newFolders)
{
836
    qCDebug(logger()) << "FlatModel::foldersAboutToBeAdded";
con's avatar
con committed
837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
    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
855
    foreach (FolderNode *node, staleFolders)
con's avatar
con committed
856 857 858 859 860
        blackList.insert(node);

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

861
    removed(folderNode, newNodeList);
con's avatar
con committed
862 863 864 865 866
    removeFromCache(staleFolders);
}

void FlatModel::removeFromCache(QList<FolderNode *> list)
{
hjk's avatar
hjk committed
867
    foreach (FolderNode *fn, list) {
con's avatar
con committed
868 869 870 871 872
        removeFromCache(fn->subFolderNodes());
        m_childNodes.remove(fn);
    }
}

873 874
void FlatModel::changedSortKey(FolderNode *folderNode, Node *node)
{
875 876 877
    if (!m_childNodes.contains(folderNode))
        return; // The directory was not yet mapped, so there is no need to sort it.

878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
    QList<Node *> nodes = m_childNodes.value(folderNode);
    int oldIndex = nodes.indexOf(node);

    nodes.removeAt(oldIndex);
    QList<Node *>::iterator newPosIt = qLowerBound(nodes.begin(), nodes.end(), node, sortNodes);
    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
898 899 900 901 902 903 904
void FlatModel::foldersRemoved()
{
    // Do nothing
}

void FlatModel::filesAboutToBeAdded(FolderNode *folder, const QList<FileNode*> &newFiles)
{
905
    qCDebug(logger()) << "FlatModel::filesAboutToBeAdded";
con's avatar
con committed
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925
    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;
926
    foreach (Node *node, staleFiles)
con's avatar
con committed
927 928 929 930 931 932 933 934 935 936 937
        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
}
938

939 940 941 942 943 944 945 946 947 948 949
void FlatModel::nodeSortKeyAboutToChange(Node *node)
{
    m_nodeForSortKeyChange = node;
}

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

950 951 952 953 954 955
void FlatModel::nodeUpdated(Node *node)
{
    QModelIndex idx = indexForNode(node);
    emit dataChanged(idx, idx);
}

956 957 958 959 960 961 962 963 964 965 966
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);
}

}
967 968

} // namespace ProjectExplorer
969