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

con's avatar
con committed
30
#include "projecttreewidget.h"
hjk's avatar
hjk committed
31

con's avatar
con committed
32
#include "projectexplorer.h"
33
#include "projectnodes.h"
34 35
#include "project.h"
#include "session.h"
con's avatar
con committed
36 37 38
#include "projectexplorerconstants.h"
#include "projectmodels.h"

39
#include <coreplugin/actionmanager/command.h>
40
#include <coreplugin/coreconstants.h>
con's avatar
con committed
41 42
#include <coreplugin/icore.h>
#include <coreplugin/editormanager/editormanager.h>
dt's avatar
dt committed
43 44
#include <coreplugin/icontext.h>

hjk's avatar
hjk committed
45
#include <utils/qtcassert.h>
46
#include <utils/navigationtreeview.h>
hjk's avatar
hjk committed
47

48 49
#include <QDebug>
#include <QSettings>
con's avatar
con committed
50

51 52 53 54 55 56 57 58
#include <QHeaderView>
#include <QTreeView>
#include <QVBoxLayout>
#include <QToolButton>
#include <QFocusEvent>
#include <QAction>
#include <QPalette>
#include <QMenu>
con's avatar
con committed
59 60 61 62 63 64 65 66

using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;

namespace {
    bool debug = false;
}

67
class ProjectTreeView : public Utils::NavigationTreeView
con's avatar
con committed
68 69 70 71 72 73 74
{
public:
    ProjectTreeView()
    {
        setEditTriggers(QAbstractItemView::EditKeyPressed);
        setContextMenuPolicy(Qt::CustomContextMenu);
//        setExpandsOnDoubleClick(false);
75 76
        m_context = new Core::IContext(this);
        m_context->setContext(Core::Context(Constants::C_PROJECT_TREE));
77
        m_context->setWidget(this);
hjk's avatar
hjk committed
78
        Core::ICore::addContextObject(m_context);
dt's avatar
dt committed
79 80 81
    }
    ~ProjectTreeView()
    {
hjk's avatar
hjk committed
82
        Core::ICore::removeContextObject(m_context);
dt's avatar
dt committed
83
        delete m_context;
con's avatar
con committed
84
    }
dt's avatar
dt committed
85 86

private:
87
    Core::IContext *m_context;
con's avatar
con committed
88 89 90 91 92 93 94
};

/*!
  /class ProjectTreeWidget

  Shows the projects in form of a tree.
  */
hjk's avatar
hjk committed
95
ProjectTreeWidget::ProjectTreeWidget(QWidget *parent)
con's avatar
con committed
96 97 98 99 100
        : QWidget(parent),
          m_explorer(ProjectExplorerPlugin::instance()),
          m_view(0),
          m_model(0),
          m_filterProjectsAction(0),
101
          m_autoSync(false),
102
          m_autoExpand(true)
con's avatar
con committed
103 104
{
    m_model = new FlatModel(m_explorer->session()->sessionNode(), this);
105 106 107
    Project *pro = m_explorer->session()->startupProject();
    if (pro)
        m_model->setStartupProject(pro->rootProjectNode());
108 109 110
    NodesWatcher *watcher = new NodesWatcher(this);
    m_explorer->session()->sessionNode()->registerWatcher(watcher);

Robert Loehning's avatar
Robert Loehning committed
111 112 113 114
    connect(watcher, SIGNAL(foldersAboutToBeRemoved(FolderNode*,QList<FolderNode*>)),
            this, SLOT(foldersAboutToBeRemoved(FolderNode*,QList<FolderNode*>)));
    connect(watcher, SIGNAL(filesAboutToBeRemoved(FolderNode*,QList<FileNode*>)),
            this, SLOT(filesAboutToBeRemoved(FolderNode*,QList<FileNode*>)));
con's avatar
con committed
115 116 117 118 119 120 121 122 123 124 125

    m_view = new ProjectTreeView;
    m_view->setModel(m_model);
    setFocusProxy(m_view);
    initView();

    QVBoxLayout *layout = new QVBoxLayout();
    layout->addWidget(m_view);
    layout->setContentsMargins(0, 0, 0, 0);
    setLayout(layout);

Leena Miettinen's avatar
Leena Miettinen committed
126
    m_filterProjectsAction = new QAction(tr("Simplify Tree"), this);
con's avatar
con committed
127 128 129 130
    m_filterProjectsAction->setCheckable(true);
    m_filterProjectsAction->setChecked(false); // default is the traditional complex tree
    connect(m_filterProjectsAction, SIGNAL(toggled(bool)), this, SLOT(setProjectFilter(bool)));

Leena Miettinen's avatar
Leena Miettinen committed
131
    m_filterGeneratedFilesAction = new QAction(tr("Hide Generated Files"), this);
con's avatar
con committed
132 133 134 135 136 137 138
    m_filterGeneratedFilesAction->setCheckable(true);
    m_filterGeneratedFilesAction->setChecked(true);
    connect(m_filterGeneratedFilesAction, SIGNAL(toggled(bool)), this, SLOT(setGeneratedFilesFilter(bool)));

    // connections
    connect(m_model, SIGNAL(modelReset()),
            this, SLOT(initView()));
Robert Loehning's avatar
Robert Loehning committed
139 140 141 142 143 144 145 146 147 148
    connect(m_view, SIGNAL(activated(QModelIndex)),
            this, SLOT(openItem(QModelIndex)));
    connect(m_view->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),
            this, SLOT(handleCurrentItemChange(QModelIndex)));
    connect(m_view, SIGNAL(customContextMenuRequested(QPoint)),
            this, SLOT(showContextMenu(QPoint)));
    connect(m_explorer->session(), SIGNAL(singleProjectAdded(ProjectExplorer::Project*)),
            this, SLOT(handleProjectAdded(ProjectExplorer::Project*)));
    connect(m_explorer->session(), SIGNAL(startupProjectChanged(ProjectExplorer::Project*)),
            this, SLOT(startupProjectChanged(ProjectExplorer::Project*)));
con's avatar
con committed
149

150
    connect(m_explorer->session(), SIGNAL(aboutToLoadSession(QString)),
151
            this, SLOT(disableAutoExpand()));
152
    connect(m_explorer->session(), SIGNAL(sessionLoaded(QString)),
153 154 155 156
            this, SLOT(loadExpandData()));
    connect(m_explorer->session(), SIGNAL(aboutToSaveSession()),
            this, SLOT(saveExpandData()));

157
    m_toggleSync = new QToolButton;
158
    m_toggleSync->setIcon(QIcon(QLatin1String(Core::Constants::ICON_LINK)));
159 160 161 162 163
    m_toggleSync->setCheckable(true);
    m_toggleSync->setChecked(autoSynchronization());
    m_toggleSync->setToolTip(tr("Synchronize with Editor"));
    connect(m_toggleSync, SIGNAL(clicked(bool)), this, SLOT(toggleAutoSynchronization()));

164
    setAutoSynchronization(true);
165 166
}

167 168 169 170 171 172 173 174
void ProjectTreeWidget::disableAutoExpand()
{
    m_autoExpand = false;
}

void ProjectTreeWidget::loadExpandData()
{
    m_autoExpand = true;
175
    QStringList data = m_explorer->session()->value(QLatin1String("ProjectTree.ExpandData")).toStringList();
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
    recursiveLoadExpandData(m_view->rootIndex(), data.toSet());
}

void ProjectTreeWidget::recursiveLoadExpandData(const QModelIndex &index, const QSet<QString> &data)
{
    if (data.contains(m_model->nodeForIndex(index)->path())) {
        m_view->expand(index);
        int count = m_model->rowCount(index);
        for (int i = 0; i < count; ++i)
            recursiveLoadExpandData(index.child(i, 0), data);
    }
}

void ProjectTreeWidget::saveExpandData()
{
    QStringList data;
    recursiveSaveExpandData(m_view->rootIndex(), &data);
    // TODO if there are multiple ProjectTreeWidgets, the last one saves the data
194
    m_explorer->session()->setValue(QLatin1String("ProjectTree.ExpandData"), data);
195 196 197 198 199 200 201 202 203 204 205 206 207
}

void ProjectTreeWidget::recursiveSaveExpandData(const QModelIndex &index, QStringList *data)
{
    Q_ASSERT(data);
    if (m_view->isExpanded(index)) {
        data->append(m_model->nodeForIndex(index)->path());
        int count = m_model->rowCount(index);
        for (int i = 0; i < count; ++i)
            recursiveSaveExpandData(index.child(i, 0), data);
    }
}

208 209 210
void ProjectTreeWidget::foldersAboutToBeRemoved(FolderNode *, const QList<FolderNode*> &list)
{
    Node *n = m_explorer->currentNode();
211
    while (n) {
212 213
        if (FolderNode *fn = qobject_cast<FolderNode *>(n)) {
            if (list.contains(fn)) {
214 215 216 217 218
                ProjectNode *pn = n->projectNode();
                // Make sure the node we are switching too isn't going to be removed also
                while (list.contains(pn))
                    pn = pn->parentFolderNode()->projectNode();
                m_explorer->setCurrentNode(pn);
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
                break;
            }
        }
        n = n->parentFolderNode();
    }
}

void ProjectTreeWidget::filesAboutToBeRemoved(FolderNode *, const QList<FileNode*> &list)
{
    if (FileNode *fileNode = qobject_cast<FileNode *>(m_explorer->currentNode())) {
        if (list.contains(fileNode)) {
            m_explorer->setCurrentNode(fileNode->projectNode());
        }
    }
}

235 236 237
QToolButton *ProjectTreeWidget::toggleSync()
{
    return m_toggleSync;
con's avatar
con committed
238 239 240 241 242 243 244 245 246 247 248 249 250 251
}

void ProjectTreeWidget::toggleAutoSynchronization()
{
    setAutoSynchronization(!m_autoSync);
}

bool ProjectTreeWidget::autoSynchronization() const
{
    return m_autoSync;
}

void ProjectTreeWidget::setAutoSynchronization(bool sync, bool syncNow)
{
252
    m_toggleSync->setChecked(sync);
con's avatar
con committed
253 254 255 256 257 258 259 260
    if (sync == m_autoSync)
        return;

    m_autoSync = sync;

    if (debug)
        qDebug() << (m_autoSync ? "Enabling auto synchronization" : "Disabling auto synchronization");
    if (m_autoSync) {
Robert Loehning's avatar
Robert Loehning committed
261 262
        connect(m_explorer, SIGNAL(currentNodeChanged(ProjectExplorer::Node*,ProjectExplorer::Project*)),
                this, SLOT(setCurrentItem(ProjectExplorer::Node*,ProjectExplorer::Project*)));
con's avatar
con committed
263
        if (syncNow)
264
            setCurrentItem(m_explorer->currentNode(), ProjectExplorerPlugin::currentProject());
con's avatar
con committed
265
    } else {
Robert Loehning's avatar
Robert Loehning committed
266 267
        disconnect(m_explorer, SIGNAL(currentNodeChanged(ProjectExplorer::Node*,ProjectExplorer::Project*)),
                this, SLOT(setCurrentItem(ProjectExplorer::Node*,ProjectExplorer::Project*)));
con's avatar
con committed
268 269 270
    }
}

271 272 273 274 275
void ProjectTreeWidget::collapseAll()
{
    m_view->collapseAll();
}

con's avatar
con committed
276 277
void ProjectTreeWidget::editCurrentItem()
{
278 279
    if (m_view->selectionModel()->currentIndex().isValid())
        m_view->edit(m_view->selectionModel()->currentIndex());
con's avatar
con committed
280 281 282 283 284
}

void ProjectTreeWidget::setCurrentItem(Node *node, Project *project)
{
    if (debug)
285 286
        qDebug() << "ProjectTreeWidget::setCurrentItem(" << (project ? project->displayName() : QLatin1String("0"))
                 << ", " <<  (node ? node->path() : QLatin1String("0")) << ")";
287

con's avatar
con committed
288 289 290 291 292 293
    if (!project) {
        return;
    }

    const QModelIndex mainIndex = m_model->indexForNode(node);

294 295
    if (mainIndex.isValid() && mainIndex != m_view->selectionModel()->currentIndex()) {
        m_view->setCurrentIndex(mainIndex);
con's avatar
con committed
296
        m_view->scrollTo(mainIndex);
297 298 299 300
    } else {
        if (debug)
            qDebug() << "clear selection";
        m_view->clearSelection();
con's avatar
con committed
301
    }
302

con's avatar
con committed
303 304 305 306 307
}

void ProjectTreeWidget::handleCurrentItemChange(const QModelIndex &current)
{
    Node *node = m_model->nodeForIndex(current);
dt's avatar
dt committed
308
    // node might be 0. that's okay
con's avatar
con committed
309 310 311 312 313 314 315 316 317 318
    bool autoSync = autoSynchronization();
    setAutoSynchronization(false);
    m_explorer->setCurrentNode(node);
    setAutoSynchronization(autoSync, false);
}

void ProjectTreeWidget::showContextMenu(const QPoint &pos)
{
    QModelIndex index = m_view->indexAt(pos);
    Node *node = m_model->nodeForIndex(index);
319
    m_explorer->showContextMenu(this, m_view->mapToGlobal(pos), node);
con's avatar
con committed
320 321 322 323 324 325
}

void ProjectTreeWidget::handleProjectAdded(ProjectExplorer::Project *project)
{
    Node *node = project->rootProjectNode();
    QModelIndex idx = m_model->indexForNode(node);
326 327
    if (m_autoExpand) // disabled while session restoring
        m_view->setExpanded(idx, true);
328
    m_view->setCurrentIndex(idx);
con's avatar
con committed
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
}

void ProjectTreeWidget::startupProjectChanged(ProjectExplorer::Project *project)
{
    if (project) {
        ProjectNode *node = project->rootProjectNode();
        m_model->setStartupProject(node);
    } else {
        m_model->setStartupProject(0);
    }
}

void ProjectTreeWidget::initView()
{
    QModelIndex sessionIndex = m_model->index(0, 0);

    // hide root folder
    m_view->setRootIndex(sessionIndex);

    while (m_model->canFetchMore(sessionIndex))
        m_model->fetchMore(sessionIndex);

    // expand top level projects
hjk's avatar
hjk committed
352
    for (int i = 0; i < m_model->rowCount(sessionIndex); ++i)
con's avatar
con committed
353 354
        m_view->expand(m_model->index(i, 0, sessionIndex));

355
    setCurrentItem(m_explorer->currentNode(), ProjectExplorerPlugin::currentProject());
con's avatar
con committed
356 357 358 359 360
}

void ProjectTreeWidget::openItem(const QModelIndex &mainIndex)
{
    Node *node = m_model->nodeForIndex(mainIndex);
hjk's avatar
hjk committed
361 362
    if (node->nodeType() == FileNodeType)
        Core::EditorManager::openEditor(node->path(), Core::Id(), Core::EditorManager::ModeSwitch);
con's avatar
con committed
363 364 365 366 367 368 369 370 371 372 373 374 375 376
}

void ProjectTreeWidget::setProjectFilter(bool filter)
{
    m_model->setProjectFilterEnabled(filter);
    m_filterProjectsAction->setChecked(filter);
}

void ProjectTreeWidget::setGeneratedFilesFilter(bool filter)
{
    m_model->setGeneratedFilesFilterEnabled(filter);
    m_filterGeneratedFilesAction->setChecked(filter);
}

377 378 379 380 381 382 383 384 385 386 387
bool ProjectTreeWidget::generatedFilesFilter()
{
    return m_model->generatedFilesFilterEnabled();
}

bool ProjectTreeWidget::projectFilter()
{
    return m_model->projectFilterEnabled();
}


hjk's avatar
hjk committed
388
ProjectTreeWidgetFactory::ProjectTreeWidgetFactory()
con's avatar
con committed
389 390 391 392 393 394 395
{
}

ProjectTreeWidgetFactory::~ProjectTreeWidgetFactory()
{
}

396
QString ProjectTreeWidgetFactory::displayName() const
con's avatar
con committed
397 398 399 400
{
    return tr("Projects");
}

401 402 403 404 405
int ProjectTreeWidgetFactory::priority() const
{
    return 100;
}

406
Core::Id ProjectTreeWidgetFactory::id() const
407
{
408
    return Core::Id("Projects");
409 410 411
}

QKeySequence ProjectTreeWidgetFactory::activationSequence() const
con's avatar
con committed
412
{
413
    return QKeySequence(Core::UseMacShortcuts ? tr("Meta+X") : tr("Alt+X"));
con's avatar
con committed
414 415 416 417 418
}

Core::NavigationView ProjectTreeWidgetFactory::createWidget()
{
    Core::NavigationView n;
hjk's avatar
hjk committed
419
    ProjectTreeWidget *ptw = new ProjectTreeWidget;
con's avatar
con committed
420 421 422
    n.widget = ptw;

    QToolButton *filter = new QToolButton;
423
    filter->setIcon(QIcon(QLatin1String(Core::Constants::ICON_FILTER)));
Leena Miettinen's avatar
Leena Miettinen committed
424
    filter->setToolTip(tr("Filter Tree"));
con's avatar
con committed
425
    filter->setPopupMode(QToolButton::InstantPopup);
Eike Ziller's avatar
Eike Ziller committed
426
    filter->setProperty("noArrow", true);
con's avatar
con committed
427 428 429 430 431
    QMenu *filterMenu = new QMenu(filter);
    filterMenu->addAction(ptw->m_filterProjectsAction);
    filterMenu->addAction(ptw->m_filterGeneratedFilesAction);
    filter->setMenu(filterMenu);

Roberto Raggi's avatar
Roberto Raggi committed
432
    n.dockToolBarWidgets << filter << ptw->toggleSync();
con's avatar
con committed
433 434 435
    return n;
}

436 437 438 439
void ProjectTreeWidgetFactory::saveSettings(int position, QWidget *widget)
{
    ProjectTreeWidget *ptw = qobject_cast<ProjectTreeWidget *>(widget);
    Q_ASSERT(ptw);
hjk's avatar
hjk committed
440
    QSettings *settings = Core::ICore::settings();
441 442 443 444
    const QString baseKey = QLatin1String("ProjectTreeWidget.") + QString::number(position);
    settings->setValue(baseKey + QLatin1String(".ProjectFilter"), ptw->projectFilter());
    settings->setValue(baseKey + QLatin1String(".GeneratedFilter"), ptw->generatedFilesFilter());
    settings->setValue(baseKey + QLatin1String(".SyncWithEditor"), ptw->autoSynchronization());
445 446 447 448 449 450
}

void ProjectTreeWidgetFactory::restoreSettings(int position, QWidget *widget)
{
    ProjectTreeWidget *ptw = qobject_cast<ProjectTreeWidget *>(widget);
    Q_ASSERT(ptw);
hjk's avatar
hjk committed
451
    QSettings *settings = Core::ICore::settings();
452 453 454 455
    const QString baseKey = QLatin1String("ProjectTreeWidget.") + QString::number(position);
    ptw->setProjectFilter(settings->value(baseKey + QLatin1String(".ProjectFilter"), false).toBool());
    ptw->setGeneratedFilesFilter(settings->value(baseKey + QLatin1String(".GeneratedFilter"), true).toBool());
    ptw->setAutoSynchronization(settings->value(baseKey +  QLatin1String(".SyncWithEditor"), true).toBool());
456
}