cppcodemodelinspectordialog.cpp 55.6 KB
Newer Older
1 2
/****************************************************************************
**
Eike Ziller's avatar
Eike Ziller committed
3 4
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
5 6 7 8 9 10 11
**
** This file is part of Qt Creator.
**
** 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 17
**
** GNU Lesser General Public License Usage
** 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.
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
27 28 29 30 31 32
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "cppcodemodelinspectordialog.h"
#include "ui_cppcodemodelinspectordialog.h"
33
#include "cppeditor.h"
34
#include "cppeditordocument.h"
35 36 37

#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/icore.h>
38
#include <cpptools/baseeditordocumentprocessor.h>
39
#include <cpptools/cppcodemodelinspectordumper.h>
40
#include <cpptools/cppmodelmanager.h>
Marco Bubke's avatar
Marco Bubke committed
41
#include <cpptools/cpptoolsbridge.h>
42
#include <cpptools/cppworkingcopy.h>
43 44 45 46 47 48 49 50 51 52 53 54 55
#include <projectexplorer/project.h>

#include <cplusplus/CppDocument.h>
#include <cplusplus/Overview.h>
#include <cplusplus/Token.h>
#include <utils/qtcassert.h>

#include <QAbstractTableModel>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QSortFilterProxyModel>

56
using namespace CPlusPlus;
57
using namespace CppTools;
58
namespace CMI = CppCodeModelInspector;
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75

namespace {

template <class T> void resizeColumns(QTreeView *view)
{
    for (int column = 0; column < T::ColumnCount - 1; ++column)
        view->resizeColumnToContents(column);
}

TextEditor::BaseTextEditor *currentEditor()
{
    return qobject_cast<TextEditor::BaseTextEditor*>(Core::EditorManager::currentEditor());
}

QString fileInCurrentEditor()
{
    if (TextEditor::BaseTextEditor *editor = currentEditor())
76
        return editor->document()->filePath().toString();
77 78 79
    return QString();
}

80
class DepthFinder : public SymbolVisitor {
81 82 83
public:
    DepthFinder() : m_symbol(0), m_depth(-1), m_foundDepth(-1), m_stop(false) {}

84
    int operator()(const Document::Ptr &document, Symbol *symbol)
85 86 87 88 89 90
    {
        m_symbol = symbol;
        accept(document->globalNamespace());
        return m_foundDepth;
    }

91
    bool preVisit(Symbol *symbol)
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
    {
        if (m_stop)
            return false;

        if (symbol->asScope()) {
            ++m_depth;
            if (symbol == m_symbol) {
                m_foundDepth = m_depth;
                m_stop = true;
            }
            return true;
        }

        return false;
    }

108
    void postVisit(Symbol *symbol)
109 110 111 112 113 114
    {
        if (symbol->asScope())
            --m_depth;
    }

private:
115
    Symbol *m_symbol;
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
    int m_depth;
    int m_foundDepth;
    bool m_stop;
};

} // anonymous namespace

namespace CppEditor {
namespace Internal {

// --- FilterableView -----------------------------------------------------------------------------

class FilterableView : public QWidget
{
    Q_OBJECT
public:
    FilterableView(QWidget *parent);

    void setModel(QAbstractItemModel *model);
    QItemSelectionModel *selectionModel() const;
    void selectIndex(const QModelIndex &index);
    void resizeColumns(int columnCount);

signals:
    void filterChanged(const QString &filterText);

public slots:
    void clearFilter();

private:
    QTreeView *view;
    QLineEdit *lineEdit;
};

FilterableView::FilterableView(QWidget *parent)
    : QWidget(parent)
{
    view = new QTreeView(this);
    view->setAlternatingRowColors(true);
    view->setTextElideMode(Qt::ElideMiddle);
    view->setSortingEnabled(true);

    lineEdit = new QLineEdit(this);
    lineEdit->setPlaceholderText(QLatin1String("File Path"));
    QObject::connect(lineEdit, SIGNAL(textChanged(QString)), SIGNAL(filterChanged(QString)));

    QLabel *label = new QLabel(QLatin1String("&Filter:"), this);
    label->setBuddy(lineEdit);

    QPushButton *clearButton = new QPushButton(QLatin1String("&Clear"), this);
    QObject::connect(clearButton, SIGNAL(clicked()), SLOT(clearFilter()));

    QHBoxLayout *filterBarLayout = new QHBoxLayout();
    filterBarLayout->addWidget(label);
    filterBarLayout->addWidget(lineEdit);
    filterBarLayout->addWidget(clearButton);

    QVBoxLayout *mainLayout = new QVBoxLayout();
    mainLayout->addWidget(view);
    mainLayout->addLayout(filterBarLayout);

    setLayout(mainLayout);
}

void FilterableView::setModel(QAbstractItemModel *model)
{
    view->setModel(model);
}

QItemSelectionModel *FilterableView::selectionModel() const
{
    return view->selectionModel();
}

void FilterableView::selectIndex(const QModelIndex &index)
{
    if (index.isValid())  {
        view->selectionModel()->setCurrentIndex(index,
            QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
    }
}

void FilterableView::resizeColumns(int columnCount)
{
    for (int column = 0; column < columnCount - 1; ++column)
        view->resizeColumnToContents(column);
}

void FilterableView::clearFilter()
{
    lineEdit->clear();
}

// --- KeyValueModel ------------------------------------------------------------------------------

class KeyValueModel : public QAbstractListModel
{
    Q_OBJECT
public:
    typedef QList<QPair<QString, QString> > Table;

    KeyValueModel(QObject *parent);
    void configure(const Table &table);
    void clear();

    enum Columns { KeyColumn, ValueColumn, ColumnCount };

    int rowCount(const QModelIndex &parent = QModelIndex()) const;
    int columnCount(const QModelIndex &parent = QModelIndex()) const;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
    QVariant headerData(int section, Qt::Orientation orientation, int role) const;

private:
    Table m_table;
};

KeyValueModel::KeyValueModel(QObject *parent) : QAbstractListModel(parent)
{
}

void KeyValueModel::configure(const Table &table)
{
    emit layoutAboutToBeChanged();
    m_table = table;
    emit layoutChanged();
}

void KeyValueModel::clear()
{
    emit layoutAboutToBeChanged();
    m_table.clear();
    emit layoutChanged();
}

int KeyValueModel::rowCount(const QModelIndex &/*parent*/) const
{
    return m_table.size();
}

int KeyValueModel::columnCount(const QModelIndex &/*parent*/) const
{
    return KeyValueModel::ColumnCount;
}

QVariant KeyValueModel::data(const QModelIndex &index, int role) const
{
    if (role == Qt::DisplayRole) {
        const int row = index.row();
        const int column = index.column();
        if (column == KeyColumn) {
            return m_table.at(row).first;
        } else if (column == ValueColumn) {
            return m_table.at(row).second;
        }
    }
    return QVariant();
}

QVariant KeyValueModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
        switch (section) {
        case KeyColumn:
            return QLatin1String("Key");
        case ValueColumn:
            return QLatin1String("Value");
        default:
            return QVariant();
        }
    }
    return QVariant();
}

// --- SnapshotModel ------------------------------------------------------------------------------

class SnapshotModel : public QAbstractListModel
{
    Q_OBJECT
public:
    SnapshotModel(QObject *parent);
296 297
    void configure(const Snapshot &snapshot);
    void setGlobalSnapshot(const Snapshot &snapshot);
298 299 300 301 302 303 304 305 306 307 308

    QModelIndex indexForDocument(const QString &filePath);

    enum Columns { SymbolCountColumn, SharedColumn, FilePathColumn, ColumnCount };

    int rowCount(const QModelIndex &parent = QModelIndex()) const;
    int columnCount(const QModelIndex &parent = QModelIndex()) const;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
    QVariant headerData(int section, Qt::Orientation orientation, int role) const;

private:
309 310
    QList<Document::Ptr> m_documents;
    Snapshot m_globalSnapshot;
311 312 313 314 315 316
};

SnapshotModel::SnapshotModel(QObject *parent) : QAbstractListModel(parent)
{
}

317
void SnapshotModel::configure(const Snapshot &snapshot)
318 319
{
    emit layoutAboutToBeChanged();
320
    m_documents = CMI::Utils::snapshotToList(snapshot);
321 322 323
    emit layoutChanged();
}

324
void SnapshotModel::setGlobalSnapshot(const Snapshot &snapshot)
325 326 327 328 329 330 331
{
    m_globalSnapshot = snapshot;
}

QModelIndex SnapshotModel::indexForDocument(const QString &filePath)
{
    for (int i = 0, total = m_documents.size(); i < total; ++i) {
332
        const Document::Ptr document = m_documents.at(i);
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
        if (document->fileName() == filePath)
            return index(i, FilePathColumn);
    }
    return QModelIndex();
}

int SnapshotModel::rowCount(const QModelIndex &/*parent*/) const
{
    return m_documents.size();
}

int SnapshotModel::columnCount(const QModelIndex &/*parent*/) const
{
    return SnapshotModel::ColumnCount;
}

QVariant SnapshotModel::data(const QModelIndex &index, int role) const
{
    if (role == Qt::DisplayRole) {
        const int column = index.column();
353
        Document::Ptr document = m_documents.at(index.row());
354 355 356
        if (column == SymbolCountColumn) {
            return document->control()->symbolCount();
        } else if (column == SharedColumn) {
357
            Document::Ptr globalDocument = m_globalSnapshot.document(document->fileName());
358 359
            const bool isShared
                = globalDocument && globalDocument->fingerprint() == document->fingerprint();
360
            return CMI::Utils::toString(isShared);
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
        } else if (column == FilePathColumn) {
            return QDir::toNativeSeparators(document->fileName());
        }
    }
    return QVariant();
}

QVariant SnapshotModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
        switch (section) {
        case SymbolCountColumn:
            return QLatin1String("Symbols");
        case SharedColumn:
            return QLatin1String("Shared");
        case FilePathColumn:
            return QLatin1String("File Path");
        default:
            return QVariant();
        }
    }
    return QVariant();
}

// --- IncludesModel ------------------------------------------------------------------------------

387 388
static bool includesSorter(const Document::Include &i1,
                           const Document::Include &i2)
389 390 391 392 393 394 395 396 397
{
    return i1.line() < i2.line();
}

class IncludesModel : public QAbstractListModel
{
    Q_OBJECT
public:
    IncludesModel(QObject *parent);
398
    void configure(const QList<Document::Include> &includes);
399 400 401 402 403 404 405 406 407 408
    void clear();

    enum Columns { ResolvedOrNotColumn, LineNumberColumn, FilePathsColumn, ColumnCount };

    int rowCount(const QModelIndex &parent = QModelIndex()) const;
    int columnCount(const QModelIndex &parent = QModelIndex()) const;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
    QVariant headerData(int section, Qt::Orientation orientation, int role) const;

private:
409
    QList<Document::Include> m_includes;
410 411 412 413 414 415
};

IncludesModel::IncludesModel(QObject *parent) : QAbstractListModel(parent)
{
}

416
void IncludesModel::configure(const QList<Document::Include> &includes)
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
{
    emit layoutAboutToBeChanged();
    m_includes = includes;
    qStableSort(m_includes.begin(), m_includes.end(), includesSorter);
    emit layoutChanged();
}

void IncludesModel::clear()
{
    emit layoutAboutToBeChanged();
    m_includes.clear();
    emit layoutChanged();
}

int IncludesModel::rowCount(const QModelIndex &/*parent*/) const
{
    return m_includes.size();
}

int IncludesModel::columnCount(const QModelIndex &/*parent*/) const
{
    return IncludesModel::ColumnCount;
}

QVariant IncludesModel::data(const QModelIndex &index, int role) const
{
    if (role != Qt::DisplayRole && role != Qt::ForegroundRole)
        return QVariant();

    static const QBrush greenBrush(QColor(0, 139, 69));
    static const QBrush redBrush(QColor(205, 38, 38));

449
    const Document::Include include = m_includes.at(index.row());
450 451 452 453 454 455
    const QString resolvedFileName = QDir::toNativeSeparators(include.resolvedFileName());
    const bool isResolved = !resolvedFileName.isEmpty();

    if (role == Qt::DisplayRole) {
        const int column = index.column();
        if (column == ResolvedOrNotColumn) {
456
            return CMI::Utils::toString(isResolved);
457 458 459
        } else if (column == LineNumberColumn) {
            return include.line();
        } else if (column == FilePathsColumn) {
460 461
            return QVariant(CMI::Utils::unresolvedFileNameWithDelimiters(include)
                            + QLatin1String(" --> ") + resolvedFileName);
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
        }
    } else if (role == Qt::ForegroundRole) {
        return isResolved ? greenBrush : redBrush;
    }

    return QVariant();
}

QVariant IncludesModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
        switch (section) {
        case ResolvedOrNotColumn:
            return QLatin1String("Resolved");
        case LineNumberColumn:
            return QLatin1String("Line");
        case FilePathsColumn:
            return QLatin1String("File Paths");
        default:
            return QVariant();
        }
    }
    return QVariant();
}

// --- DiagnosticMessagesModel --------------------------------------------------------------------

489 490
static bool diagnosticMessagesModelSorter(const Document::DiagnosticMessage &m1,
                                          const Document::DiagnosticMessage &m2)
491 492 493 494 495 496 497 498 499
{
    return m1.line() < m2.line();
}

class DiagnosticMessagesModel : public QAbstractListModel
{
    Q_OBJECT
public:
    DiagnosticMessagesModel(QObject *parent);
500
    void configure(const QList<Document::DiagnosticMessage> &messages);
501 502 503 504 505 506 507 508 509 510
    void clear();

    enum Columns { LevelColumn, LineColumnNumberColumn, MessageColumn, ColumnCount };

    int rowCount(const QModelIndex &parent = QModelIndex()) const;
    int columnCount(const QModelIndex &parent = QModelIndex()) const;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
    QVariant headerData(int section, Qt::Orientation orientation, int role) const;

private:
511
    QList<Document::DiagnosticMessage> m_messages;
512 513 514 515 516 517 518
};

DiagnosticMessagesModel::DiagnosticMessagesModel(QObject *parent) : QAbstractListModel(parent)
{
}

void DiagnosticMessagesModel::configure(
519
        const QList<Document::DiagnosticMessage> &messages)
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
{
    emit layoutAboutToBeChanged();
    m_messages = messages;
    qStableSort(m_messages.begin(), m_messages.end(), diagnosticMessagesModelSorter);
    emit layoutChanged();
}

void DiagnosticMessagesModel::clear()
{
    emit layoutAboutToBeChanged();
    m_messages.clear();
    emit layoutChanged();
}

int DiagnosticMessagesModel::rowCount(const QModelIndex &/*parent*/) const
{
    return m_messages.size();
}

int DiagnosticMessagesModel::columnCount(const QModelIndex &/*parent*/) const
{
    return DiagnosticMessagesModel::ColumnCount;
}

QVariant DiagnosticMessagesModel::data(const QModelIndex &index, int role) const
{
    if (role != Qt::DisplayRole && role != Qt::ForegroundRole)
        return QVariant();

    static const QBrush yellowOrangeBrush(QColor(237, 145, 33));
    static const QBrush redBrush(QColor(205, 38, 38));
    static const QBrush darkRedBrushQColor(QColor(139, 0, 0));

553 554 555
    const Document::DiagnosticMessage message = m_messages.at(index.row());
    const Document::DiagnosticMessage::Level level
        = static_cast<Document::DiagnosticMessage::Level>(message.level());
556 557 558 559

    if (role == Qt::DisplayRole) {
        const int column = index.column();
        if (column == LevelColumn) {
560
            return CMI::Utils::toString(level);
561 562 563 564 565 566 567 568
        } else if (column == LineColumnNumberColumn) {
            return QVariant(QString::number(message.line()) + QLatin1Char(':')
                            + QString::number(message.column()));
        } else if (column == MessageColumn) {
            return message.text();
        }
    } else if (role == Qt::ForegroundRole) {
        switch (level) {
569
        case Document::DiagnosticMessage::Warning:
570
            return yellowOrangeBrush;
571
        case Document::DiagnosticMessage::Error:
572
            return redBrush;
573
        case Document::DiagnosticMessage::Fatal:
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
            return darkRedBrushQColor;
        default:
            return QVariant();
        }
    }

    return QVariant();
}

QVariant DiagnosticMessagesModel::headerData(int section, Qt::Orientation orientation, int role)
    const
{
    if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
        switch (section) {
        case LevelColumn:
            return QLatin1String("Level");
        case LineColumnNumberColumn:
            return QLatin1String("Line:Column");
        case MessageColumn:
            return QLatin1String("Message");
        default:
            return QVariant();
        }
    }
    return QVariant();
}

// --- MacrosModel --------------------------------------------------------------------------------

class MacrosModel : public QAbstractListModel
{
    Q_OBJECT
public:
    MacrosModel(QObject *parent);
608
    void configure(const QList<Macro> &macros);
609 610 611 612 613 614 615 616 617 618
    void clear();

    enum Columns { LineNumberColumn, MacroColumn, ColumnCount };

    int rowCount(const QModelIndex &parent = QModelIndex()) const;
    int columnCount(const QModelIndex &parent = QModelIndex()) const;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
    QVariant headerData(int section, Qt::Orientation orientation, int role) const;

private:
619
    QList<Macro> m_macros;
620 621 622 623 624 625
};

MacrosModel::MacrosModel(QObject *parent) : QAbstractListModel(parent)
{
}

626
void MacrosModel::configure(const QList<Macro> &macros)
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
{
    emit layoutAboutToBeChanged();
    m_macros = macros;
    emit layoutChanged();
}

void MacrosModel::clear()
{
    emit layoutAboutToBeChanged();
    m_macros.clear();
    emit layoutChanged();
}

int MacrosModel::rowCount(const QModelIndex &/*parent*/) const
{
    return m_macros.size();
}

int MacrosModel::columnCount(const QModelIndex &/*parent*/) const
{
    return MacrosModel::ColumnCount;
}

QVariant MacrosModel::data(const QModelIndex &index, int role) const
{
    const int column = index.column();
    if (role == Qt::DisplayRole || (role == Qt::ToolTipRole && column == MacroColumn)) {
654
        const Macro macro = m_macros.at(index.row());
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
        if (column == LineNumberColumn)
            return macro.line();
        else if (column == MacroColumn)
            return macro.toString();
    } else if (role == Qt::TextAlignmentRole) {
        return Qt::AlignTop + Qt::AlignLeft;
    }
    return QVariant();
}

QVariant MacrosModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
        switch (section) {
        case LineNumberColumn:
            return QLatin1String("Line");
        case MacroColumn:
            return QLatin1String("Macro");
        default:
            return QVariant();
        }
    }
    return QVariant();
}

// --- SymbolsModel -------------------------------------------------------------------------------

class SymbolsModel : public QAbstractItemModel
{
    Q_OBJECT
public:
    SymbolsModel(QObject *parent);
687
    void configure(const Document::Ptr &document);
688 689 690 691 692 693 694 695 696 697 698 699
    void clear();

    enum Columns { SymbolColumn, LineNumberColumn, ColumnCount };

    QModelIndex index(int row, int column, const QModelIndex &parent) const;
    QModelIndex parent(const QModelIndex &child) const;
    int rowCount(const QModelIndex &parent = QModelIndex()) const;
    int columnCount(const QModelIndex &parent = QModelIndex()) const;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
    QVariant headerData(int section, Qt::Orientation orientation, int role) const;

private:
700
    Document::Ptr m_document;
701 702 703 704 705 706
};

SymbolsModel::SymbolsModel(QObject *parent) : QAbstractItemModel(parent)
{
}

707
void SymbolsModel::configure(const Document::Ptr &document)
708 709 710 711 712 713 714 715 716 717 718 719 720 721
{
    QTC_CHECK(document);
    emit layoutAboutToBeChanged();
    m_document = document;
    emit layoutChanged();
}

void SymbolsModel::clear()
{
    emit layoutAboutToBeChanged();
    m_document.clear();
    emit layoutChanged();
}

722
static Symbol *indexToSymbol(const QModelIndex &index)
723
{
724
    if (Symbol *symbol = static_cast<Symbol*>(index.internalPointer()))
725 726 727 728
        return symbol;
    return 0;
}

729
static Scope *indexToScope(const QModelIndex &index)
730
{
731
    if (Symbol *symbol = indexToSymbol(index))
732 733 734 735 736 737
        return symbol->asScope();
    return 0;
}

QModelIndex SymbolsModel::index(int row, int column, const QModelIndex &parent) const
{
738
    Scope *scope = 0;
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
    if (parent.isValid())
        scope = indexToScope(parent);
    else if (m_document)
        scope = m_document->globalNamespace();

    if (scope) {
        if ((unsigned)row < scope->memberCount())
            return createIndex(row, column, scope->memberAt(row));
    }

    return QModelIndex();
}

QModelIndex SymbolsModel::parent(const QModelIndex &child) const
{
    if (!child.isValid())
        return QModelIndex();

757 758
    if (Symbol *symbol = indexToSymbol(child)) {
        if (Scope *scope = symbol->enclosingScope()) {
759 760 761 762 763 764 765 766 767 768 769
            const int row = DepthFinder()(m_document, scope);
            return createIndex(row, 0, scope);
        }
    }

    return QModelIndex();
}

int SymbolsModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid()) {
770
        if (Scope *scope = indexToScope(parent))
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
            return scope->memberCount();
    } else {
        if (m_document)
            return m_document->globalNamespace()->memberCount();
    }
    return 0;
}

int SymbolsModel::columnCount(const QModelIndex &) const
{
    return ColumnCount;
}

QVariant SymbolsModel::data(const QModelIndex &index, int role) const
{
    const int column = index.column();
    if (role == Qt::DisplayRole) {
788
        Symbol *symbol = indexToSymbol(index);
789 790 791 792 793
        if (!symbol)
            return QVariant();
        if (column == LineNumberColumn) {
            return symbol->line();
        } else if (column == SymbolColumn) {
794
            QString name = Overview().prettyName(symbol->name());
795
            if (name.isEmpty())
796
                name = QLatin1String(symbol->isBlock() ? "<block>" : "<no name>");
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
            return name;
        }
    }
    return QVariant();
}

QVariant SymbolsModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
        switch (section) {
        case SymbolColumn:
            return QLatin1String("Symbol");
        case LineNumberColumn:
            return QLatin1String("Line");
        default:
            return QVariant();
        }
    }
    return QVariant();
}

// --- TokensModel --------------------------------------------------------------------------------

class TokensModel : public QAbstractListModel
{
    Q_OBJECT
public:
    TokensModel(QObject *parent);
825
    void configure(TranslationUnit *translationUnit);
826 827 828
    void clear();

    enum Columns { SpelledColumn, KindColumn, IndexColumn, OffsetColumn, LineColumnNumberColumn,
829
                   BytesAndCodePointsColumn, GeneratedColumn, ExpandedColumn, WhiteSpaceColumn,
830
                   NewlineColumn, ColumnCount };
831 832 833 834 835 836 837 838

    int rowCount(const QModelIndex &parent = QModelIndex()) const;
    int columnCount(const QModelIndex &parent = QModelIndex()) const;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
    QVariant headerData(int section, Qt::Orientation orientation, int role) const;

private:
    struct TokenInfo {
839
        Token token;
840 841 842 843 844 845 846 847 848 849
        unsigned line;
        unsigned column;
    };
    QList<TokenInfo> m_tokenInfos;
};

TokensModel::TokensModel(QObject *parent) : QAbstractListModel(parent)
{
}

850
void TokensModel::configure(TranslationUnit *translationUnit)
851 852 853 854 855 856 857 858 859
{
    if (!translationUnit)
        return;

    emit layoutAboutToBeChanged();
    m_tokenInfos.clear();
    for (int i = 0, total = translationUnit->tokenCount(); i < total; ++i) {
        TokenInfo info;
        info.token = translationUnit->tokenAt(i);
860
        translationUnit->getPosition(info.token.utf16charsBegin(), &info.line, &info.column);
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
        m_tokenInfos.append(info);
    }
    emit layoutChanged();
}

void TokensModel::clear()
{
    emit layoutAboutToBeChanged();
    m_tokenInfos.clear();
    emit layoutChanged();
}

int TokensModel::rowCount(const QModelIndex &/*parent*/) const
{
    return m_tokenInfos.size();
}

int TokensModel::columnCount(const QModelIndex &/*parent*/) const
{
    return TokensModel::ColumnCount;
}

QVariant TokensModel::data(const QModelIndex &index, int role) const
{
    const int column = index.column();
    if (role == Qt::DisplayRole) {
        const TokenInfo info = m_tokenInfos.at(index.row());
888
        const Token token = info.token;
889 890 891
        if (column == SpelledColumn)
            return QString::fromUtf8(token.spell());
        else if (column == KindColumn)
892
            return CMI::Utils::toString(static_cast<Kind>(token.kind()));
893 894 895
        else if (column == IndexColumn)
            return index.row();
        else if (column == OffsetColumn)
896
            return token.bytesBegin();
897
        else if (column == LineColumnNumberColumn)
898 899 900 901 902
            return QString::fromLatin1("%1:%2").arg(CMI::Utils::toString(info.line),
                                                    CMI::Utils::toString(info.column));
        else if (column == BytesAndCodePointsColumn)
            return QString::fromLatin1("%1/%2").arg(CMI::Utils::toString(token.bytes()),
                                                    CMI::Utils::toString(token.utf16chars()));
903
        else if (column == GeneratedColumn)
904
            return CMI::Utils::toString(token.generated());
905
        else if (column == ExpandedColumn)
906
            return CMI::Utils::toString(token.expanded());
907
        else if (column == WhiteSpaceColumn)
908
            return CMI::Utils::toString(token.whitespace());
909
        else if (column == NewlineColumn)
910
            return CMI::Utils::toString(token.newline());
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
    } else if (role == Qt::TextAlignmentRole) {
        return Qt::AlignTop + Qt::AlignLeft;
    }
    return QVariant();
}

QVariant TokensModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
        switch (section) {
        case SpelledColumn:
            return QLatin1String("Spelled");
        case KindColumn:
            return QLatin1String("Kind");
        case IndexColumn:
            return QLatin1String("Index");
        case OffsetColumn:
            return QLatin1String("Offset");
        case LineColumnNumberColumn:
            return QLatin1String("Line:Column");
931 932
        case BytesAndCodePointsColumn:
            return QLatin1String("Bytes/Codepoints");
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
        case GeneratedColumn:
            return QLatin1String("Generated");
        case ExpandedColumn:
            return QLatin1String("Expanded");
        case WhiteSpaceColumn:
            return QLatin1String("Whitespace");
        case NewlineColumn:
            return QLatin1String("Newline");
        default:
            return QVariant();
        }
    }
    return QVariant();
}

// --- ProjectPartsModel --------------------------------------------------------------------------

class ProjectPartsModel : public QAbstractListModel
{
    Q_OBJECT
public:
    ProjectPartsModel(QObject *parent);

956
    void configure(const QList<ProjectInfo> &projectInfos,
957 958 959
                   const ProjectPart::Ptr &currentEditorsProjectPart);

    QModelIndex indexForCurrentEditorsProjectPart() const;
960
    ProjectPart::Ptr projectPartForProjectId(const QString &projectPartId) const;
961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978

    enum Columns { PartNameColumn, PartFilePathColumn, ColumnCount };

    int rowCount(const QModelIndex &parent = QModelIndex()) const;
    int columnCount(const QModelIndex &parent = QModelIndex()) const;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
    QVariant headerData(int section, Qt::Orientation orientation, int role) const;

private:
    QList<ProjectPart::Ptr> m_projectPartsList;
    int m_currentEditorsProjectPartIndex;
};

ProjectPartsModel::ProjectPartsModel(QObject *parent)
    : QAbstractListModel(parent), m_currentEditorsProjectPartIndex(-1)
{
}

979
void ProjectPartsModel::configure(const QList<ProjectInfo> &projectInfos,
980 981 982 983
                                  const ProjectPart::Ptr &currentEditorsProjectPart)
{
    emit layoutAboutToBeChanged();
    m_projectPartsList.clear();
984
    foreach (const ProjectInfo &info, projectInfos) {
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
        foreach (const ProjectPart::Ptr &projectPart, info.projectParts()) {
            if (!m_projectPartsList.contains(projectPart)) {
                m_projectPartsList << projectPart;
                if (projectPart == currentEditorsProjectPart)
                    m_currentEditorsProjectPartIndex = m_projectPartsList.size() - 1;
            }
        }
    }
    emit layoutChanged();
}

QModelIndex ProjectPartsModel::indexForCurrentEditorsProjectPart() const
{
    if (m_currentEditorsProjectPartIndex == -1)
        return QModelIndex();
    return createIndex(m_currentEditorsProjectPartIndex, PartFilePathColumn);
}

1003
ProjectPart::Ptr ProjectPartsModel::projectPartForProjectId(const QString &projectPartId) const
1004 1005
{
    foreach (const ProjectPart::Ptr &part, m_projectPartsList) {
1006
        if (part->id() == projectPartId)
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
            return part;
    }
    return ProjectPart::Ptr();
}

int ProjectPartsModel::rowCount(const QModelIndex &/*parent*/) const
{
    return m_projectPartsList.size();
}

int ProjectPartsModel::columnCount(const QModelIndex &/*parent*/) const
{
    return ProjectPartsModel::ColumnCount;
}

QVariant ProjectPartsModel::data(const QModelIndex &index, int role) const
{
    const int row = index.row();
    if (role == Qt::DisplayRole) {
        const int column = index.column();
        if (column == PartNameColumn)
            return m_projectPartsList.at(row)->displayName;
        else if (column == PartFilePathColumn)
            return QDir::toNativeSeparators(m_projectPartsList.at(row)->projectFile);
1031 1032
    } else if (role == Qt::UserRole) {
        return m_projectPartsList.at(row)->id();
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
    }
    return QVariant();
}

QVariant ProjectPartsModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
        switch (section) {
        case PartNameColumn:
            return QLatin1String("Name");
        case PartFilePathColumn:
            return QLatin1String("Project File Path");
        default:
            return QVariant();
        }
    }
    return QVariant();
}

// --- WorkingCopyModel ---------------------------------------------------------------------------

class WorkingCopyModel : public QAbstractListModel
{
    Q_OBJECT
public:
    WorkingCopyModel(QObject *parent);

1060
    void configure(const WorkingCopy &workingCopy);
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
    QModelIndex indexForFile(const QString &filePath);

    enum Columns { RevisionColumn, FilePathColumn, ColumnCount };

    int rowCount(const QModelIndex &parent = QModelIndex()) const;
    int columnCount(const QModelIndex &parent = QModelIndex()) const;
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
    QVariant headerData(int section, Qt::Orientation orientation, int role) const;

private:
    struct WorkingCopyEntry {
        WorkingCopyEntry(const QString &filePath, const QByteArray &source, unsigned revision)
            : filePath(filePath), source(source), revision(revision)
        {}

        QString filePath;
        QByteArray source;
        unsigned revision;
    };

    QList<WorkingCopyEntry> m_workingCopyList;
};

WorkingCopyModel::WorkingCopyModel(QObject *parent) : QAbstractListModel(parent)
{
}

1088
void WorkingCopyModel::configure(const WorkingCopy &workingCopy)
1089 1090 1091
{
    emit layoutAboutToBeChanged();
    m_workingCopyList.clear();
1092
    QHashIterator<Utils::FileName, QPair<QByteArray, unsigned> > it = workingCopy.iterator();
1093 1094
    while (it.hasNext()) {
        it.next();
1095 1096
        m_workingCopyList << WorkingCopyEntry(it.key().toString(), it.value().first,
                                              it.value().second);
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
    }
    emit layoutChanged();
}

QModelIndex WorkingCopyModel::indexForFile(const QString &filePath)
{
    for (int i = 0, total = m_workingCopyList.size(); i < total; ++i) {
        const WorkingCopyEntry entry = m_workingCopyList.at(i);
        if (entry.filePath == filePath)
            return index(i, FilePathColumn);
    }
    return QModelIndex();
}

int WorkingCopyModel::rowCount(const QModelIndex &/*parent*/) const
{
    return m_workingCopyList.size();
}

int WorkingCopyModel::columnCount(const QModelIndex &/*parent*/) const
{
    return WorkingCopyModel::ColumnCount;
}

QVariant WorkingCopyModel::data(const QModelIndex &index, int role) const
{
    const int row = index.row();
    if (role == Qt::DisplayRole) {
        const int column = index.column();
        if (column == RevisionColumn)
            return m_workingCopyList.at(row).revision;
        else if (column == FilePathColumn)
            return m_workingCopyList.at(row).filePath;
    } else if (role == Qt::UserRole) {
        return m_workingCopyList.at(row).source;
    }
    return QVariant();
}

QVariant WorkingCopyModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
        switch (section) {
        case RevisionColumn:
            return QLatin1String("Revision");
        case FilePathColumn:
            return QLatin1String("File Path");
        default:
            return QVariant();
        }
    }
    return QVariant();
}

// --- SnapshotInfo -------------------------------------------------------------------------------

class SnapshotInfo
{
public:
    enum Type { GlobalSnapshot, EditorSnapshot };
1157
    SnapshotInfo(const Snapshot &snapshot, Type type)
1158 1159
        : snapshot(snapshot), type(type) {}

1160
    Snapshot snapshot;
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
    Type type;
};

// --- CppCodeModelInspectorDialog ----------------------------------------------------------------

CppCodeModelInspectorDialog::CppCodeModelInspectorDialog(QWidget *parent)
    : QDialog(parent)
    , m_ui(new Ui::CppCodeModelInspectorDialog)
    , m_snapshotInfos(new QList<SnapshotInfo>())
    , m_snapshotView(new FilterableView(this))
    , m_snapshotModel(new SnapshotModel(this))
    , m_proxySnapshotModel(new QSortFilterProxyModel(this))
    , m_docGenericInfoModel(new KeyValueModel(this))
    , m_docIncludesModel(new IncludesModel(this))
    , m_docDiagnosticMessagesModel(new DiagnosticMessagesModel(this))
    , m_docMacrosModel(new MacrosModel(this))
    , m_docSymbolsModel(new SymbolsModel(this))
    , m_docTokensModel(new TokensModel(this))
    , m_projectPartsView(new FilterableView(this))
    , m_projectPartsModel(new ProjectPartsModel(this))
    , m_proxyProjectPartsModel(new QSortFilterProxyModel(this))
    , m_partGenericInfoModel(new KeyValueModel(this))
    , m_workingCopyView(new FilterableView(this))
    , m_workingCopyModel(new WorkingCopyModel(this))
    , m_proxyWorkingCopyModel(new QSortFilterProxyModel(this))
{
    m_ui->setupUi(this);
    m_ui->snapshotSelectorAndViewLayout->addWidget(m_snapshotView);
    m_ui->projectPartsSplitter->insertWidget(0, m_projectPartsView);
    m_ui->workingCopySplitter->insertWidget(0, m_workingCopyView);

    setAttribute(Qt::WA_DeleteOnClose);
    connect(Core::ICore::instance(), SIGNAL(coreAboutToClose()), SLOT(close()));

    m_proxySnapshotModel->setSourceModel(m_snapshotModel);
    m_proxySnapshotModel->setFilterKeyColumn(SnapshotModel::FilePathColumn);
    m_snapshotView->setModel(m_proxySnapshotModel);
    m_ui->docGeneralView->setModel(m_docGenericInfoModel);
    m_ui->docIncludesView->setModel(m_docIncludesModel);
    m_ui->docDiagnosticMessagesView->setModel(m_docDiagnosticMessagesModel);
    m_ui->docDefinedMacrosView->setModel(m_docMacrosModel);
    m_ui->docSymbolsView->setModel(m_docSymbolsModel);
    m_ui->docTokensView->setModel(m_docTokensModel);

    m_proxyProjectPartsModel->setSourceModel(m_projectPartsModel);
    m_proxyProjectPartsModel->setFilterKeyColumn(ProjectPartsModel::PartFilePathColumn);
    m_projectPartsView->setModel(m_proxyProjectPartsModel);
    m_ui->partGeneralView->setModel(m_partGenericInfoModel);

    m_proxyWorkingCopyModel->setSourceModel(m_workingCopyModel);
    m_proxyWorkingCopyModel->setFilterKeyColumn(WorkingCopyModel::FilePathColumn);
    m_workingCopyView->setModel(m_proxyWorkingCopyModel);

    connect(m_snapshotView->selectionModel(),
1215 1216
            SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
            SLOT(onDocumentSelected(QModelIndex,QModelIndex)));
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
    connect(m_snapshotView, SIGNAL(filterChanged(QString)),
            SLOT(onSnapshotFilterChanged(QString)));
    connect(m_ui->snapshotSelector, SIGNAL(currentIndexChanged(int)),
            SLOT(onSnapshotSelected(int)));
    connect(m_ui->docSymbolsView, SIGNAL(expanded(QModelIndex)),
            SLOT(onSymbolsViewExpandedOrCollapsed(QModelIndex)));
    connect(m_ui->docSymbolsView, SIGNAL(collapsed(QModelIndex)),
            SLOT(onSymbolsViewExpandedOrCollapsed(QModelIndex)));

    connect(m_projectPartsView->selectionModel(),
1227 1228
            SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
            SLOT(onProjectPartSelected(QModelIndex,QModelIndex)));
1229 1230 1231 1232
    connect(m_projectPartsView, SIGNAL(filterChanged(QString)),
            SLOT(onProjectPartFilterChanged(QString)));

    connect(m_workingCopyView->selectionModel(),
1233 1234
            SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
            SLOT(onWorkingCopyDocumentSelected(QModelIndex,QModelIndex)));
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
    connect(m_workingCopyView, SIGNAL(filterChanged(QString)),
            SLOT(onWorkingCopyFilterChanged(QString)));

    connect(m_ui->refreshButton, SIGNAL(clicked()), SLOT(onRefreshRequested()));
    connect(m_ui->closeButton, SIGNAL(clicked()), SLOT(close()));

    refresh();
}

CppCodeModelInspectorDialog::~CppCodeModelInspectorDialog()
{
    delete m_snapshotInfos;
    delete m_ui;
}

void CppCodeModelInspectorDialog::onRefreshRequested()
{
    refresh();
}

void CppCodeModelInspectorDialog::onSnapshotFilterChanged(const QString &pattern)
{
    m_proxySnapshotModel->setFilterWildcard(pattern);
}

void CppCodeModelInspectorDialog::onSnapshotSelected(int row)
{
    if (row < 0 || row >= m_snapshotInfos->size())
        return;

    m_snapshotView->clearFilter();
    const SnapshotInfo info = m_snapshotInfos->at(row);
    m_snapshotModel->configure(info.snapshot);
    m_snapshotView->resizeColumns(SnapshotModel::ColumnCount);

    if (info.type == SnapshotInfo::GlobalSnapshot) {
        // Select first document
        const QModelIndex index = m_proxySnapshotModel->index(0, SnapshotModel::FilePathColumn);
        m_snapshotView->selectIndex(index);
    } else if (info.type == SnapshotInfo::EditorSnapshot) {
        // Select first document, unless we can find the editor document
        QModelIndex index = m_snapshotModel->indexForDocument(fileInCurrentEditor());
        index = m_proxySnapshotModel->mapFromSource(index);
        if (!index.isValid())
            index = m_proxySnapshotModel->index(0, SnapshotModel::FilePathColumn);
        m_snapshotView->selectIndex(index);
    }
}

void CppCodeModelInspectorDialog::onDocumentSelected(const QModelIndex &current,
                                                     const QModelIndex &)
{
    if (current.isValid()) {
        const QModelIndex index = m_proxySnapshotModel->index(current.row(),
                                                              SnapshotModel::FilePathColumn);
        const QString filePath = QDir::fromNativeSeparators(
            m_proxySnapshotModel->data(index, Qt::DisplayRole).toString());
        const SnapshotInfo info = m_snapshotInfos->at(m_ui->snapshotSelector->currentIndex());
        updateDocumentData(info.snapshot.document(filePath));
    } else {
        clearDocumentData();
    }
}

void CppCodeModelInspectorDialog::onSymbolsViewExpandedOrCollapsed(const QModelIndex &)
{
    resizeColumns<SymbolsModel>(m_ui->docSymbolsView);
}

void CppCodeModelInspectorDialog::onProjectPartFilterChanged(const QString &pattern)
{
    m_proxyProjectPartsModel->setFilterWildcard(pattern);
}

void CppCodeModelInspectorDialog::onProjectPartSelected(const QModelIndex &current,
                                                        const QModelIndex &)
{
    if (current.isValid()) {
        QModelIndex index = m_proxyProjectPartsModel->mapToSource(current);
        if (index.isValid()) {
            index = m_projectPartsModel->index(index.row(), ProjectPartsModel::PartFilePathColumn);
1316 1317
            const QString projectPartId = m_projectPartsModel->data(index, Qt::UserRole).toString();
            updateProjectPartData(m_projectPartsModel->projectPartForProjectId(projectPartId));
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
        }
    } else {
        clearProjectPartData();
    }
}

void CppCodeModelInspectorDialog::onWorkingCopyFilterChanged(const QString &pattern)
{
    m_proxyWorkingCopyModel->setFilterWildcard(pattern);
}

void CppCodeModelInspectorDialog::onWorkingCopyDocumentSelected(const QModelIndex &current,
                                                                const QModelIndex &)
{
    if (current.isValid()) {
        const QModelIndex index = m_proxyWorkingCopyModel->mapToSource(current);
        if (index.isValid()) {
            const QString source
                = QString::fromUtf8(m_workingCopyModel->data(index, Qt::UserRole).toByteArray());
            m_ui->workingCopySourceEdit->setPlainText(source);
        }
    } else {
1340
        m_ui->workingCopySourceEdit->clear();
1341 1342 1343 1344 1345
    }
}

void CppCodeModelInspectorDialog::refresh()
{
1346
    CppModelManager *cmmi = CppModelManager::instance();
1347 1348 1349 1350 1351 1352 1353 1354 1355

    const int oldSnapshotIndex = m_ui->snapshotSelector->currentIndex();
    const bool selectEditorRelevant
        = m_ui->selectEditorRelevantEntriesAfterRefreshCheckBox->isChecked();

    // Snapshots and Documents
    m_snapshotInfos->clear();
    m_ui->snapshotSelector->clear();

1356
    const Snapshot globalSnapshot = cmmi->snapshot();
1357
    CppCodeModelInspector::Dumper dumper(globalSnapshot);
1358 1359 1360 1361 1362 1363 1364 1365 1366
    m_snapshotModel->setGlobalSnapshot(globalSnapshot);

    m_snapshotInfos->append(SnapshotInfo(globalSnapshot, SnapshotInfo::GlobalSnapshot));
    const QString globalSnapshotTitle
        = QString::fromLatin1("Global/Indexing Snapshot (%1 Documents)").arg(globalSnapshot.size());
    m_ui->snapshotSelector->addItem(globalSnapshotTitle);
    dumper.dumpSnapshot(globalSnapshot, globalSnapshotTitle, /*isGlobalSnapshot=*/ true);

    TextEditor::BaseTextEditor *editor = currentEditor();
1367
    CppTools::CppEditorDocumentHandle *cppEditorDocument = 0;
1368
    if (editor) {
1369
        const QString editorFilePath = editor->document()->filePath().toString();
1370
        cppEditorDocument = cmmi->cppEditorDocument(editorFilePath);
Marco Bubke's avatar
Marco Bubke committed
1371
        if (auto *documentProcessor = CppToolsBridge::baseEditorDocumentProcessor(editorFilePath)) {
1372
            const Snapshot editorSnapshot = documentProcessor->snapshot();
1373 1374 1375 1376 1377 1378 1379
            m_snapshotInfos->append(SnapshotInfo(editorSnapshot, SnapshotInfo::EditorSnapshot));
            const QString editorSnapshotTitle
                = QString::fromLatin1("Current Editor's Snapshot (%1 Documents)")
                    .arg(editorSnapshot.size());
            dumper.dumpSnapshot(editorSnapshot, editorSnapshotTitle);
            m_ui->snapshotSelector->addItem(editorSnapshotTitle);
        }
1380
        CppEditorWidget *cppEditorWidget = qobject_cast<CppEditorWidget *>(editor->editorWidget());
1381 1382
        if (cppEditorWidget) {
            SemanticInfo semanticInfo = cppEditorWidget->semanticInfo();
1383
            Snapshot snapshot;
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393

            // Add semantic info snapshot
            snapshot = semanticInfo.snapshot;
            m_snapshotInfos->append(SnapshotInfo(snapshot, SnapshotInfo::EditorSnapshot));
            m_ui->snapshotSelector->addItem(
                QString::fromLatin1("Current Editor's Semantic Info Snapshot (%1 Documents)")
                    .arg(snapshot.size()));

            // Add a pseudo snapshot containing only the semantic info document since this document
            // is not part of the semantic snapshot.
1394
            snapshot = Snapshot();
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
            snapshot.insert(cppEditorWidget->semanticInfo().doc);
            m_snapshotInfos->append(SnapshotInfo(snapshot, SnapshotInfo::EditorSnapshot));
            const QString snapshotTitle
                = QString::fromLatin1("Current Editor's Pseudo Snapshot with Semantic Info Document (%1 Documents)")
                    .arg(snapshot.size());
            dumper.dumpSnapshot(snapshot, snapshotTitle);
            m_ui->snapshotSelector->addItem(snapshotTitle);
        }
    }

    int snapshotIndex = 0;
    if (selectEditorRelevant) {
        for (int i = 0, total = m_snapshotInfos->size(); i < total; ++i) {
            const SnapshotInfo info = m_snapshotInfos->at(i);
            if (info.type == SnapshotInfo::EditorSnapshot) {
                snapshotIndex = i;
                break;
            }
        }
    } else if (oldSnapshotIndex < m_snapshotInfos->size()) {
        snapshotIndex = oldSnapshotIndex;
    }
    m_ui->snapshotSelector->setCurrentIndex(snapshotIndex);
    onSnapshotSelected(snapshotIndex);

    // Project Parts
1421 1422
    const ProjectPart::Ptr editorsProjectPart = cppEditorDocument
        ? cppEditorDocument->processor()->parser()->projectPart()
1423 1424
        : ProjectPart::Ptr();

1425
    const QList<ProjectInfo> projectInfos = cmmi->projectInfos();
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440
    dumper.dumpProjectInfos(projectInfos);
    m_projectPartsModel->configure(projectInfos, editorsProjectPart);
    m_projectPartsView->resizeColumns(ProjectPartsModel::ColumnCount);
    QModelIndex index = m_proxyProjectPartsModel->index(0, ProjectPartsModel::PartFilePathColumn);
    if (index.isValid()) {
        if (selectEditorRelevant && editorsProjectPart) {
            QModelIndex editorPartIndex = m_projectPartsModel->indexForCurrentEditorsProjectPart();
            editorPartIndex = m_proxyProjectPartsModel->mapFromSource(editorPartIndex);
            if (editorPartIndex.isValid())
                index = editorPartIndex;
        }
        m_projectPartsView->selectIndex(index);
    }

    // Working Copy
1441
    const WorkingCopy workingCopy = cmmi->workingCopy();
1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453
    dumper.dumpWorkingCopy(workingCopy);
    m_workingCopyModel->configure(workingCopy);
    m_workingCopyView->resizeColumns(WorkingCopyModel::ColumnCount);
    if (workingCopy.size() > 0) {
        QModelIndex index = m_proxyWorkingCopyModel->index(0, WorkingCopyModel::FilePathColumn);
        if (selectEditorRelevant) {
            const QModelIndex eindex = m_workingCopyModel->indexForFile(fileInCurrentEditor());
            if (eindex.isValid())
                index = m_proxyWorkingCopyModel->mapFromSource(eindex);
        }
        m_workingCopyView->selectIndex(index);
    }
1454 1455

    // Merged entities
1456
    dumper.dumpMergedEntities(cmmi->headerPaths(), cmmi->definedMacros());
1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
}

enum DocumentTabs {
    DocumentGeneralTab,
    DocumentIncludesTab,
    DocumentDiagnosticsTab,
    DocumentDefinedMacrosTab,
    DocumentPreprocessedSourceTab,
    DocumentSymbolsTab,
    DocumentTokensTab
};

static QString docTabName(int tabIndex, int numberOfEntries = -1)
{
    const char *names[] = {
        "&General",
        "&Includes",
        "&Diagnostic Messages",
        "(Un)Defined &Macros",
        "P&reprocessed Source",
        "&Symbols",
        "&Tokens"
    };
    QString result = QLatin1String(names[tabIndex]);
    if (numberOfEntries != -1)
        result += QString::fromLatin1(" (%1)").arg(numberOfEntries);
    return result;
}

void CppCodeModelInspectorDialog::clearDocumentData()
{
    m_docGenericInfoModel->clear();

    m_ui->docTab->setTabText(DocumentIncludesTab, docTabName(DocumentIncludesTab));
    m_docIncludesModel->clear();

    m_ui->docTab->setTabText(DocumentDiagnosticsTab, docTabName(DocumentDiagnosticsTab));
    m_docDiagnosticMessagesModel->clear();

    m_ui->docTab->setTabText(DocumentDefinedMacrosTab, docTabName(DocumentDefinedMacrosTab));
    m_docMacrosModel->clear();

1499
    m_ui->docPreprocessedSourceEdit->clear();
1500 1501 1502 1503 1504 1505 1506

    m_docSymbolsModel->clear();

    m_ui->docTab->setTabText(DocumentTokensTab, docTabName(DocumentTokensTab));
    m_docTokensModel->clear();
}

1507
void CppCodeModelInspectorDialog::updateDocumentData(const Document::Ptr &document)
1508 1509 1510 1511 1512 1513 1514
{
    QTC_ASSERT(document, return);

    // General
    KeyValueModel::Table table = KeyValueModel::Table()
        << qMakePair(QString::fromLatin1("File Path"),
                     QDir::toNativeSeparators(document->fileName()))
1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
        << qMakePair(QString::fromLatin1("Last Modified"),
                     CMI::Utils::toString(document->lastModified()))
        << qMakePair(QString::fromLatin1("Revision"),
                     CMI::Utils::toString(document->revision()))
        << qMakePair(QString::fromLatin1("Editor Revision"),
                     CMI::Utils::toString(document->editorRevision()))
        << qMakePair(QString::fromLatin1("Check Mode"),
                     CMI::Utils::toString(document->checkMode()))
        << qMakePair(QString::fromLatin1("Tokenized"),
                     CMI::Utils::toString(document->isTokenized()))
        << qMakePair(QString::fromLatin1("Parsed"),
                     CMI::Utils::toString(document->isParsed()))
        << qMakePair(QString::fromLatin1("Project Parts"),
                     CMI::Utils::partsForFile(document->fileName()))
1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568
        ;
    m_docGenericInfoModel->configure(table);
    resizeColumns<KeyValueModel>(m_ui->docGeneralView);

    // Includes
    m_docIncludesModel->configure(document->resolvedIncludes() + document->unresolvedIncludes());
    resizeColumns<IncludesModel>(m_ui->docIncludesView);
    m_ui->docTab->setTabText(DocumentIncludesTab,
        docTabName(DocumentIncludesTab, m_docIncludesModel->rowCount()));

    // Diagnostic Messages
    m_docDiagnosticMessagesModel->configure(document->diagnosticMessages());
    resizeColumns<DiagnosticMessagesModel>(m_ui->docDiagnosticMessagesView);
    m_ui->docTab->setTabText(DocumentDiagnosticsTab,
        docTabName(DocumentDiagnosticsTab, m_docDiagnosticMessagesModel->rowCount()));

    // Macros
    m_docMacrosModel->configure(document->definedMacros());
    resizeColumns<MacrosModel>(m_ui->docDefinedMacrosView);
    m_ui->docTab->setTabText(DocumentDefinedMacrosTab,
        docTabName(DocumentDefinedMacrosTab, m_docMacrosModel->rowCount()));

    // Source
    m_ui->docPreprocessedSourceEdit->setPlainText(QString::fromUtf8(document->utf8Source()));

    // Symbols
    m_docSymbolsModel->configure(document);
    resizeColumns<SymbolsModel>(m_ui->docSymbolsView);

    // Tokens
    m_docTokensModel->configure(document->translationUnit());
    resizeColumns<TokensModel>(m_ui->docTokensView);
    m_ui->docTab->setTabText(DocumentTokensTab,
        docTabName(DocumentTokensTab, m_docTokensModel->rowCount()));
}

enum ProjectPartTabs {
    ProjectPartGeneralTab,
    ProjectPartFilesTab,
    ProjectPartDefinesTab,
1569
    ProjectPartHeaderPathsTab,
1570 1571 1572 1573 1574 1575 1576 1577 1578
    ProjectPartPrecompiledHeadersTab
};

static QString partTabName(int tabIndex, int numberOfEntries = -1)
{
    const char *names[] = {
        "&General",
        "Project &Files",
        "&Defines",
1579
        "&Header Paths",
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591
        "Pre&compiled Headers"
    };
    QString result = QLatin1String(names[tabIndex]);
    if (numberOfEntries != -1)
        result += QString::fromLatin1(" (%1)").arg(numberOfEntries);
    return result;
}

void CppCodeModelInspectorDialog::clearProjectPartData()
{
    m_partGenericInfoModel->clear();

1592
    m_ui->partProjectFilesEdit->clear();
1593 1594
    m_ui->projectPartTab->setTabText(ProjectPartFilesTab, partTabName(ProjectPartFilesTab));

1595 1596
    m_ui->partToolchainDefinesEdit->clear();
    m_ui->partProjectDefinesEdit->clear();
1597 1598
    m_ui->projectPartTab->setTabText(ProjectPartDefinesTab, partTabName(ProjectPartDefinesTab));

1599
    m_ui->partHeaderPathsEdit->clear();
1600 1601
    m_ui->projectPartTab->setTabText(ProjectPartHeaderPathsTab,
                                     partTabName(ProjectPartHeaderPathsTab));
1602

1603
    m_ui->partPrecompiledHeadersEdit->clear();
1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
    m_ui->projectPartTab->setTabText(ProjectPartPrecompiledHeadersTab,
                                     partTabName(ProjectPartPrecompiledHeadersTab));
}

void CppCodeModelInspectorDialog::updateProjectPartData(const ProjectPart::Ptr &part)
{
    QTC_ASSERT(part, return);

    // General
    QString projectName = QLatin1String("<None>");
    QString projectFilePath = QLatin1String("<None>");
    if (ProjectExplorer::Project *project = part->project) {
        projectName = project->displayName();
1617
        projectFilePath = project->projectFilePath().toUserOutput();
1618 1619 1620 1621 1622 1623
    }
    KeyValueModel::Table table = KeyValueModel::Table()
        << qMakePair(QString::fromLatin1("Project Part Name"), part->displayName)
        << qMakePair(QString::fromLatin1("Project Part File"),
                     QDir::toNativeSeparators(part->projectFile))
        << qMakePair(QString::fromLatin1("Project Name"), projectName)
1624
        << qMakePair(QString::fromLatin1("Project File"), projectFilePath)
1625 1626 1627 1628
        << qMakePair(QString::fromLatin1("Language Version"),
                     CMI::Utils::toString(part->languageVersion))
        << qMakePair(QString::fromLatin1("Language Extensions"),
                     CMI::Utils::toString(part->languageExtensions))
1629 1630
        << qMakePair(QString::fromLatin1("Qt Version"),
                     CMI::Utils::toString(part->qtVersion))
1631
        ;
1632 1633 1634
    if (!part->projectConfigFile.isEmpty())
        table.prepend(qMakePair(QString::fromLatin1("Project Config File"),
                                part->projectConfigFile));
1635 1636 1637 1638
    m_partGenericInfoModel->configure(table);
    resizeColumns<KeyValueModel>(m_ui->partGeneralView);

    // Project Files
1639
    m_ui->partProjectFilesEdit->setPlainText(CMI::Utils::toString(part->files));
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655
    m_ui->projectPartTab->setTabText(ProjectPartFilesTab,
        partTabName(ProjectPartFilesTab, part->files.size()));

    // Defines
    const QList<QByteArray> defineLines = part->toolchainDefines.split('\n')
        + part->projectDefines.split('\n');
    int numberOfDefines = 0;
    foreach (const QByteArray &line, defineLines) {
        if (line.startsWith("#define "))
            ++numberOfDefines;
    }
    m_ui->partToolchainDefinesEdit->setPlainText(QString::fromUtf8(part->toolchainDefines));
    m_ui->partProjectDefinesEdit->setPlainText(QString::fromUtf8(part->projectDefines));
    m_ui->projectPartTab->setTabText(ProjectPartDefinesTab,
        partTabName(ProjectPartDefinesTab, numberOfDefines));

1656 1657 1658 1659
    // Header Paths
    m_ui->partHeaderPathsEdit->setPlainText(CMI::Utils::pathListToString(part->headerPaths));
    m_ui->projectPartTab->setTabText(ProjectPartHeaderPathsTab,
        partTabName(ProjectPartHeaderPathsTab, part->headerPaths.size()));
1660 1661

    // Precompiled Headers
1662 1663
    m_ui->partPrecompiledHeadersEdit->setPlainText(
                CMI::Utils::pathListToString(part->precompiledHeaders));
1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684
    m_ui->projectPartTab->setTabText(ProjectPartPrecompiledHeadersTab,
        partTabName(ProjectPartPrecompiledHeadersTab, part->precompiledHeaders.size()));
}

bool CppCodeModelInspectorDialog::event(QEvent *e)
{
    if (e->type() == QEvent::ShortcutOverride) {
        QKeyEvent *ke = static_cast<QKeyEvent *>(e);
        if (ke->key() == Qt::Key_Escape && !ke->modifiers()) {
            ke->accept();
            close();
            return false;
        }
    }
    return QDialog::event(e);
}

} // namespace Internal
} // namespace CppEditor

#include "cppcodemodelinspectordialog.moc"