projectmodels.cpp 12.4 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"
32
#include "session.h"
con's avatar
con committed
33 34

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

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

44 45
using namespace Utils;

46 47 48
namespace ProjectExplorer {

using namespace Internal;
con's avatar
con committed
49

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

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

61 62 63 64 65
    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
66 67
}

68 69 70 71
static bool sortWrapperNodes(const WrapperNode *w1, const WrapperNode *w2)
{
    return sortNodes(w1->m_node, w2->m_node);
}
hjk's avatar
hjk committed
72

73
FlatModel::FlatModel(QObject *parent)
hjk's avatar
hjk committed
74
    : TreeModel<WrapperNode, WrapperNode>(new WrapperNode(nullptr), parent)
con's avatar
con committed
75
{
76
    ProjectTree *tree = ProjectTree::instance();
77
    connect(tree, &ProjectTree::subtreeChanged, this, &FlatModel::updateSubtree);
con's avatar
con committed
78

79
    SessionManager *sm = SessionManager::instance();
80 81
    connect(sm, &SessionManager::projectRemoved, this, &FlatModel::handleProjectRemoved);
    connect(sm, &SessionManager::aboutToLoadSession, this, &FlatModel::loadExpandData);
82 83
    connect(sm, &SessionManager::aboutToSaveSession, this, &FlatModel::saveExpandData);
    connect(sm, &SessionManager::projectAdded, this, &FlatModel::handleProjectAdded);
84
    connect(sm, &SessionManager::startupProjectChanged, this, [this] { layoutChanged(); });
85
    rebuildModel();
con's avatar
con committed
86 87 88 89 90 91 92
}

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

    if (Node *node = nodeForIndex(index)) {
93
        FolderNode *folderNode = node->asFolderNode();
con's avatar
con committed
94
        switch (role) {
95
        case Qt::DisplayRole: {
hjk's avatar
hjk committed
96
            result = node->displayName();
97 98
            break;
        }
con's avatar
con committed
99
        case Qt::EditRole: {
100
            result = node->filePath().fileName();
con's avatar
con committed
101 102 103
            break;
        }
        case Qt::ToolTipRole: {
104
            result = node->tooltip();
con's avatar
con committed
105 106 107
            break;
        }
        case Qt::DecorationRole: {
108
            if (folderNode) {
con's avatar
con committed
109
                result = folderNode->icon();
110 111 112 113 114
                if (ContainerNode *containerNode = folderNode->asContainerNode()) {
                    if (ProjectNode *projectNode = containerNode->rootProjectNode())
                        result = projectNode->icon();
                }
            } else {
115
                result = Core::FileIconProvider::icon(node->filePath().toString());
116
            }
con's avatar
con committed
117 118 119 120
            break;
        }
        case Qt::FontRole: {
            QFont font;
121
            if (Project *project = SessionManager::startupProject()) {
hjk's avatar
hjk committed
122
                if (node == project->containerNode())
123 124
                    font.setBold(true);
            }
con's avatar
con committed
125 126 127
            result = font;
            break;
        }
128
        case Project::FilePathRole: {
129
            result = node->filePath().toString();
con's avatar
con committed
130 131
            break;
        }
132
        case Project::EnabledRole: {
133 134 135
            result = node->isEnabled();
            break;
        }
con's avatar
con committed
136 137 138 139 140 141
        }
    }

    return result;
}

dt's avatar
dt committed
142 143 144 145 146 147 148
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
149
    Qt::ItemFlags f = Qt::ItemIsSelectable|Qt::ItemIsEnabled|Qt::ItemIsDragEnabled;
150
    if (Node *node = nodeForIndex(index)) {
151
        if (!node->asProjectNode()) {
152
            // either folder or file node
153
            if (node->supportsAction(Rename, node))
154 155 156 157
                f = f | Qt::ItemIsEditable;
        }
    }
    return f;
dt's avatar
dt committed
158 159 160 161 162 163 164 165 166
}

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

167
    Node *node = nodeForIndex(index);
168
    QTC_ASSERT(node, return false);
169

170
    Utils::FileName orgFilePath = node->filePath();
171
    Utils::FileName newFilePath = orgFilePath.parentDir().appendPath(value.toString());
172

173
    ProjectExplorerPlugin::renameFile(node, newFilePath.toString());
174
    emit renamed(orgFilePath, newFilePath);
dt's avatar
dt committed
175 176 177
    return true;
}

178
void FlatModel::addOrRebuildProjectModel(Project *project)
con's avatar
con committed
179
{
180 181 182 183 184 185 186
    WrapperNode *container = nodeForProject(project);
    if (container) {
        container->removeChildren();
    } else {
        container = new WrapperNode(project->containerNode());
        rootItem()->appendChild(container);
    }
hjk's avatar
hjk committed
187

188
    QSet<Node *> seen;
con's avatar
con committed
189

190 191 192 193 194 195
    if (ProjectNode *projectNode = project->rootProjectNode()) {
        addFolderNode(container, projectNode, &seen);
    } else {
        FileNode *projectFileNode = new FileNode(project->projectFilePath(), FileType::Project, false);
        seen.insert(projectFileNode);
        container->appendChild(new WrapperNode(projectFileNode));
con's avatar
con committed
196 197
    }

198
    container->forAllChildren([this](WrapperNode *node) {
hjk's avatar
hjk committed
199 200 201 202 203 204 205
        if (node->m_node) {
            const QString path = node->m_node->filePath().toString();
            const QString displayName = node->m_node->displayName();
            ExpandData ed(path, displayName);
            if (m_toExpand.contains(ed))
                emit requestExpansion(node->index());
        } else {
206
            emit requestExpansion(node->index());
hjk's avatar
hjk committed
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

    const QString path = container->m_node->filePath().toString();
    const QString displayName = container->m_node->displayName();
    ExpandData ed(path, displayName);
    if (m_toExpand.contains(ed))
        emit requestExpansion(container->index());
}

void FlatModel::updateSubtree(FolderNode *node)
{
    // FIXME: This is still excessive, should be limited to the affected subtree.
    while (FolderNode *parent = node->parentFolderNode())
        node = parent;
    if (ContainerNode *container = node->asContainerNode())
        addOrRebuildProjectModel(container->project());
}

void FlatModel::rebuildModel()
{
    QList<Project *> projects = SessionManager::projects();
    QTC_CHECK(projects.size() == rootItem()->childCount());

    Utils::sort(projects, [](Project *p1, Project *p2) {
        const int displayNameResult = caseFriendlyCompare(p1->displayName(), p2->displayName());
        if (displayNameResult != 0)
            return displayNameResult < 0;
        return p1 < p2; // sort by pointer value
    });

    for (Project *project : projects)
        addOrRebuildProjectModel(project);
con's avatar
con committed
240 241
}

242
void FlatModel::onCollapsed(const QModelIndex &idx)
con's avatar
con committed
243
{
244
    m_toExpand.remove(expandDataForNode(nodeForIndex(idx)));
con's avatar
con committed
245 246
}

247
void FlatModel::onExpanded(const QModelIndex &idx)
con's avatar
con committed
248
{
249
    m_toExpand.insert(expandDataForNode(nodeForIndex(idx)));
con's avatar
con committed
250 251
}

252
ExpandData FlatModel::expandDataForNode(const Node *node) const
con's avatar
con committed
253
{
254 255 256 257
    QTC_ASSERT(node, return ExpandData());
    const QString path = node->filePath().toString();
    const QString displayName = node->displayName();
    return ExpandData(path, displayName);
con's avatar
con committed
258 259
}

260
void FlatModel::handleProjectAdded(Project *project)
con's avatar
con committed
261
{
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
    addOrRebuildProjectModel(project);
}

void FlatModel::handleProjectRemoved(Project *project)
{
    destroyItem(nodeForProject(project));
}

WrapperNode *FlatModel::nodeForProject(Project *project)
{
    QTC_ASSERT(project, return nullptr);
    ContainerNode *containerNode = project->containerNode();
    QTC_ASSERT(containerNode, return nullptr);
    return rootItem()->findFirstLevelChild([containerNode](WrapperNode *node) {
        return node->m_node == containerNode;
    });
con's avatar
con committed
278 279
}

280
void FlatModel::loadExpandData()
con's avatar
con committed
281
{
282 283 284
    const QList<QVariant> data = SessionManager::value("ProjectTree.ExpandData").value<QList<QVariant>>();
    m_toExpand = Utils::transform<QSet>(data, [](const QVariant &v) { return ExpandData::fromSettings(v); });
    m_toExpand.remove(ExpandData());
con's avatar
con committed
285 286
}

287
void FlatModel::saveExpandData()
con's avatar
con committed
288
{
289 290 291
    // TODO if there are multiple ProjectTreeWidgets, the last one saves the data
    QList<QVariant> data = Utils::transform<QList>(m_toExpand, &ExpandData::toSettings);
    SessionManager::setValue(QLatin1String("ProjectTree.ExpandData"), data);
con's avatar
con committed
292 293
}

294
void FlatModel::addFolderNode(WrapperNode *parent, FolderNode *folderNode, QSet<Node *> *seen)
con's avatar
con committed
295
{
296 297
    for (Node *node : folderNode->nodes()) {
        if (FolderNode *subFolderNode = node->asFolderNode()) {
298 299
            const bool isHidden = m_filterProjects && !subFolderNode->showInSimpleTree();
            if (!isHidden && !seen->contains(subFolderNode)) {
300 301 302 303 304 305 306 307
                seen->insert(subFolderNode);
                auto node = new WrapperNode(subFolderNode);
                parent->appendChild(node);
                addFolderNode(node, subFolderNode, seen);
                node->sortChildren(&sortWrapperNodes);
            } else {
                addFolderNode(parent, subFolderNode, seen);
            }
308 309 310
        } else if (FileNode *fileNode = node->asFileNode()) {
            const bool isHidden = m_filterProjects && fileNode->isGenerated();
            if (!isHidden && !seen->contains(fileNode)) {
311 312 313
                seen->insert(fileNode);
                parent->appendChild(new WrapperNode(fileNode));
            }
314 315
        }
    }
con's avatar
con committed
316 317
}

318 319 320 321 322
Qt::DropActions FlatModel::supportedDragActions() const
{
    return Qt::MoveAction;
}

323 324
QStringList FlatModel::mimeTypes() const
{
325
    return Utils::DropSupport::mimeTypesForFilePaths();
326 327 328 329
}

QMimeData *FlatModel::mimeData(const QModelIndexList &indexes) const
{
330
    auto data = new Utils::DropMimeData;
331
    foreach (const QModelIndex &index, indexes) {
332 333 334 335 336
        if (Node *node = nodeForIndex(index)) {
            if (node->asFileNode())
                data->addFile(node->filePath().toString());
            data->addValue(QVariant::fromValue(node));
        }
337
    }
338
    return data;
339 340
}

341
WrapperNode *FlatModel::wrapperForNode(const Node *node) const
con's avatar
con committed
342
{
343 344 345 346
    return findNonRooItem([this, node](WrapperNode *item) {
        return item->m_node == node;
    });
}
con's avatar
con committed
347

348 349 350 351
QModelIndex FlatModel::indexForNode(const Node *node) const
{
    WrapperNode *wrapper = wrapperForNode(node);
    return wrapper ? indexForItem(wrapper) : QModelIndex();
con's avatar
con committed
352 353 354 355
}

void FlatModel::setProjectFilterEnabled(bool filter)
{
356 357
    if (filter == m_filterProjects)
        return;
con's avatar
con committed
358
    m_filterProjects = filter;
359
    rebuildModel();
con's avatar
con committed
360 361 362 363 364
}

void FlatModel::setGeneratedFilesFilterEnabled(bool filter)
{
    m_filterGeneratedFiles = filter;
365
    rebuildModel();
con's avatar
con committed
366 367
}

368 369 370 371 372 373 374 375 376 377
bool FlatModel::projectFilterEnabled()
{
    return m_filterProjects;
}

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

con's avatar
con committed
378 379
Node *FlatModel::nodeForIndex(const QModelIndex &index) const
{
380 381
    WrapperNode *flatNode = itemForIndex(index);
    return flatNode ? flatNode->m_node : nullptr;
con's avatar
con committed
382 383
}

384 385 386 387 388 389
const QLoggingCategory &FlatModel::logger()
{
    static QLoggingCategory logger("qtc.projectexplorer.flatmodel");
    return logger;
}

390 391 392 393 394 395 396 397 398 399 400
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);
}

}
401 402

} // namespace ProjectExplorer
403