callgrindtool.cpp 32.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** 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, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/

#include "callgrindtool.h"

#include "callgrindcostdelegate.h"
#include "callgrindcostview.h"
#include "callgrindengine.h"
#include "callgrindtextmark.h"
#include "callgrindvisualisation.h"

#include <valgrind/callgrind/callgrindcallmodel.h>
#include <valgrind/callgrind/callgrindcostitem.h>
#include <valgrind/callgrind/callgrinddatamodel.h>
#include <valgrind/callgrind/callgrindfunction.h>
#include <valgrind/callgrind/callgrindfunctioncall.h>
#include <valgrind/callgrind/callgrindparsedata.h>
#include <valgrind/callgrind/callgrindproxymodel.h>
#include <valgrind/callgrind/callgrindstackbrowser.h>
hjk's avatar
hjk committed
49
#include <valgrind/valgrindplugin.h>
50
#include <valgrind/valgrindsettings.h>
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117

#include <analyzerbase/analyzermanager.h>
#include <analyzerbase/analyzersettings.h>
#include <analyzerbase/analyzerutils.h>
#include <analyzerbase/analyzerconstants.h>

#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/icontext.h>
#include <coreplugin/icore.h>

#include <cplusplus/LookupContext.h>
#include <cplusplus/Overview.h>
#include <cppeditor/cppeditorconstants.h>
#include <extensionsystem/iplugin.h>
#include <texteditor/basetexteditor.h>

#include <utils/qtcassert.h>
#include <utils/fancymainwindow.h>
#include <utils/styledbar.h>

#include <projectexplorer/project.h>
#include <projectexplorer/projectexplorer.h>

#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtCore/QTimer>

#include <QtGui/QAction>
#include <QtGui/QActionGroup>
#include <QtGui/QCheckBox>
#include <QtGui/QComboBox>
#include <QtGui/QDockWidget>
#include <QtGui/QGraphicsItem>
#include <QtGui/QHBoxLayout>
#include <QtGui/QLineEdit>
#include <QtGui/QMenu>
#include <QtGui/QSortFilterProxyModel>
#include <QtGui/QToolBar>
#include <QtGui/QToolButton>
#include <QtGui/QVBoxLayout>

// shared/cplusplus includes
#include <Symbols.h>

using namespace Analyzer;
using namespace Core;
using namespace Valgrind::Callgrind;

namespace Valgrind {
namespace Internal {

class CallgrindToolPrivate : public QObject
{
    Q_OBJECT

public:
    friend class CallgrindTool;

    explicit CallgrindToolPrivate(CallgrindTool *parent);
    virtual ~CallgrindToolPrivate();

    void setParseData(ParseData *data);

    CostDelegate::CostFormat costFormat() const;
118
    QWidget *createWidgets();
119 120 121 122 123

    void doClear(bool clearParseData);
    void updateEventCombo();

    IAnalyzerEngine *createEngine(const AnalyzerStartParameters &sp,
124
        ProjectExplorer::RunConfiguration *runConfiguration = 0);
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

signals:
    void cycleDetectionEnabled(bool enabled);
    void dumpRequested();
    void resetRequested();
    void pauseToggled(bool checked);

public slots:
    void slotClear();
    void slotRequestDump();

    void selectFunction(const Valgrind::Callgrind::Function *);
    void setCostFormat(Valgrind::Internal::CostDelegate::CostFormat format);
    void enableCycleDetection(bool enabled);
    void setCostEvent(int index);

    /// This function will add custom text marks to the editor
    /// \note Call this after the data model has been populated
    void createTextMarks();

    /// This function will clear all text marks from the editor
    void clearTextMarks();

    void updateFilterString();
    void updateCostFormat();

    void handleFilterProjectCosts();
    void handleShowCostsAction();
    void handleShowCostsOfFunction();

    void slotGoToOverview();
    void stackBrowserChanged();

    /// If \param busy is true, all widgets get a busy cursor when hovered
    void setBusy(bool busy);

    void dataFunctionSelected(const QModelIndex &index);
    void calleeFunctionSelected(const QModelIndex &index);
    void callerFunctionSelected(const QModelIndex &index);
    void visualisationFunctionSelected(const Valgrind::Callgrind::Function *function);
    void showParserResults(const Valgrind::Callgrind::ParseData *data);

    void takeParserData(CallgrindEngine *engine);
    void engineStarting(const Analyzer::IAnalyzerEngine *);
    void engineFinished();

    void editorOpened(Core::IEditor *);
    void requestContextMenu(TextEditor::ITextEditor *editor, int line, QMenu *menu);

public:
    CallgrindTool *q;

    DataModel *m_dataModel;
    DataProxyModel *m_proxyModel;
    StackBrowser *m_stackBrowser;

    CallModel *m_callersModel;
    CallModel *m_calleesModel;

    // callgrind widgets
    CostView *m_flatView;
    CostView *m_callersView;
    CostView *m_calleesView;
    Visualisation *m_visualisation;

    // navigation
    QAction *m_goBack;
192
    QAction *m_goNext;
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
    QLineEdit *m_searchFilter;

    // cost formatting
    QAction *m_filterProjectCosts;
    QAction *m_costAbsolute;
    QAction *m_costRelative;
    QAction *m_costRelativeToParent;
    QAction *m_cycleDetection;
    QComboBox *m_eventCombo;

    QTimer *m_updateTimer;

    QVector<CallgrindTextMark *> m_textMarks;

    QAction *m_dumpAction;
    QAction *m_resetAction;
    QAction *m_pauseAction;
    QAction *m_showCostsOfFunctionAction;

    QString m_toggleCollectFunction;
213
    ValgrindGlobalSettings *m_settings; // Not owned
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
};


CallgrindToolPrivate::CallgrindToolPrivate(CallgrindTool *parent)
    : q(parent)
    , m_dataModel(new DataModel(this))
    , m_proxyModel(new DataProxyModel(this))
    , m_stackBrowser(new StackBrowser(this))
    , m_callersModel(new CallModel(this))
    , m_calleesModel(new CallModel(this))
    , m_flatView(0)
    , m_callersView(0)
    , m_calleesView(0)
    , m_visualisation(0)
    , m_goBack(0)
229
    , m_goNext(0)
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
    , m_searchFilter(0)
    , m_filterProjectCosts(0)
    , m_costAbsolute(0)
    , m_costRelative(0)
    , m_costRelativeToParent(0)
    , m_eventCombo(0)
    , m_updateTimer(new QTimer(this))
    , m_dumpAction(0)
    , m_resetAction(0)
    , m_pauseAction(0)
    , m_showCostsOfFunctionAction(0)
    , m_settings(0)
{
    m_updateTimer->setInterval(200);
    m_updateTimer->setSingleShot(true);

    m_proxyModel->setSourceModel(m_dataModel);
    m_proxyModel->setDynamicSortFilter(true);
    m_proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
    m_proxyModel->setFilterKeyColumn(DataModel::NameColumn);
    m_proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);

252
    m_settings = AnalyzerGlobalSettings::instance()->subConfig<ValgrindGlobalSettings>();
253 254 255

    connect(m_stackBrowser, SIGNAL(currentChanged()), SLOT(stackBrowserChanged()));
    connect(m_updateTimer, SIGNAL(timeout()), SLOT(updateFilterString()));
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 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
}

CallgrindToolPrivate::~CallgrindToolPrivate()
{
    qDeleteAll(m_textMarks);
    doClear(false);
}

void CallgrindToolPrivate::slotGoToOverview()
{
    selectFunction(0);
}

void CallgrindToolPrivate::slotClear()
{
    doClear(true);
}

void CallgrindToolPrivate::doClear(bool clearParseData)
{
    if (clearParseData) // Crashed when done from destructor.
        setParseData(0);

    // clear filters
    if (m_filterProjectCosts)
        m_filterProjectCosts->setChecked(false);
    m_proxyModel->setFilterBaseDir(QString());
    if (m_searchFilter)
        m_searchFilter->setText(QString());
    m_proxyModel->setFilterFixedString(QString());
}

void CallgrindToolPrivate::setBusy(bool busy)
{
    QCursor cursor(busy ? Qt::BusyCursor : Qt::ArrowCursor);
    m_flatView->setCursor(cursor);
    m_calleesView->setCursor(cursor);
    m_callersView->setCursor(cursor);
    m_visualisation->setCursor(cursor);
}

void CallgrindToolPrivate::selectFunction(const Function *func)
{
    if (!func) {
        m_flatView->clearSelection();
        m_visualisation->setFunction(0);
        m_callersModel->clear();
        m_calleesModel->clear();
        return;
    }

    const QModelIndex index = m_dataModel->indexForObject(func);
    const QModelIndex proxyIndex = m_proxyModel->mapFromSource(index);
    m_flatView->selectionModel()->clearSelection();
    m_flatView->selectionModel()->setCurrentIndex(proxyIndex,
                                                  QItemSelectionModel::ClearAndSelect |
                                                  QItemSelectionModel::Rows);
    m_flatView->scrollTo(proxyIndex);

    m_callersModel->setCalls(func->incomingCalls(), func);
    m_calleesModel->setCalls(func->outgoingCalls(), func);
    m_visualisation->setFunction(func);

    const Function *item = m_stackBrowser->current();
    if (!item || item != func)
        m_stackBrowser->select(func);

    if (QFile::exists(func->file())) {
        ///TODO: custom position support?
        int line = func->lineNumber();
        TextEditor::BaseTextEditorWidget::openEditorAt(func->file(), qMax(line, 0));
    }
}

void CallgrindToolPrivate::stackBrowserChanged()
{
332 333
    m_goBack->setEnabled(m_stackBrowser->hasPrevious());
    m_goNext->setEnabled(m_stackBrowser->hasNext());
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 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 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 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 489 490 491 492 493 494
    const Function *item = m_stackBrowser->current();
    selectFunction(item);
}

void CallgrindToolPrivate::updateFilterString()
{
    m_proxyModel->setFilterFixedString(m_searchFilter->text());
}

void CallgrindToolPrivate::setCostFormat(CostDelegate::CostFormat format)
{
    switch (format) {
        case CostDelegate::FormatAbsolute:
            m_costAbsolute->setChecked(true);
            break;
        case CostDelegate::FormatRelative:
            m_costRelative->setChecked(true);
            break;
        case CostDelegate::FormatRelativeToParent:
            m_costRelativeToParent->setChecked(true);
            break;
    }
}

void CallgrindToolPrivate::setCostEvent(int index)
{
    // prevent assert in model, don't try to set event to -1
    // happens when we clear the eventcombo
    if (index == -1)
        index = 0;

    m_dataModel->setCostEvent(index);
    m_calleesModel->setCostEvent(index);
    m_callersModel->setCostEvent(index);
}

void CallgrindToolPrivate::enableCycleDetection(bool enabled)
{
    m_cycleDetection->setChecked(enabled);
}

// Following functions can be called with actions=0 or widgets=0
// depending on initialization sequence (whether callgrind was current).
CostDelegate::CostFormat CallgrindToolPrivate::costFormat() const
{
    if (m_costRelativeToParent && m_costRelativeToParent->isChecked())
        return CostDelegate::FormatRelativeToParent;
    if (m_costRelative && m_costRelative->isChecked())
        return CostDelegate::FormatRelative;
    return CostDelegate::FormatAbsolute;
}

void CallgrindToolPrivate::updateCostFormat()
{
    const CostDelegate::CostFormat format = costFormat();
    if (m_flatView)
        m_flatView->setCostFormat(format);
    if (m_calleesView) {
        m_calleesView->setCostFormat(format);
        m_callersView->setCostFormat(format);
    }
    if (m_settings)
        m_settings->setCostFormat(format);
}

void CallgrindToolPrivate::handleFilterProjectCosts()
{
    ProjectExplorer::ProjectExplorerPlugin *pe = ProjectExplorer::ProjectExplorerPlugin::instance();
    ProjectExplorer::Project *pro = pe->currentProject();
    QTC_ASSERT(pro, return)

    if (m_filterProjectCosts->isChecked()) {
        const QString projectDir = pro->projectDirectory();
        m_proxyModel->setFilterBaseDir(projectDir);
    }
    else {
        m_proxyModel->setFilterBaseDir(QString());
    }
}

void CallgrindToolPrivate::dataFunctionSelected(const QModelIndex &index)
{
    const Function *func = index.data(DataModel::FunctionRole).value<const Function *>();
    QTC_ASSERT(func, return);

    selectFunction(func);
}

void CallgrindToolPrivate::calleeFunctionSelected(const QModelIndex &index)
{
    const FunctionCall *call = index.data(CallModel::FunctionCallRole).value<const FunctionCall *>();
    QTC_ASSERT(call, return);

    selectFunction(call->callee());
}

void CallgrindToolPrivate::callerFunctionSelected(const QModelIndex &index)
{
    const FunctionCall *call = index.data(CallModel::FunctionCallRole).value<const FunctionCall *>();
    QTC_ASSERT(call, return);

    selectFunction(call->caller());
}

void CallgrindToolPrivate::visualisationFunctionSelected(const Function *function)
{
    if (function && function == m_visualisation->function())
        // up-navigation when the initial function was activated
        m_stackBrowser->goBack();
    else
        selectFunction(function);
}

void CallgrindToolPrivate::setParseData(ParseData *data)
{
    // we have new parse data, invalidate filters in the proxy model
    m_visualisation->setFunction(0);

    // invalidate parse data in the data model
    delete m_dataModel->parseData();

    if (data && data->events().isEmpty()) {
        // might happen if the user cancelled the profile run
        // callgrind then sometimes produces empty callgrind.out.PID files
        delete data;
        data = 0;
    }
    m_dataModel->setParseData(data);
    m_calleesModel->setParseData(data);
    m_callersModel->setParseData(data);

    updateEventCombo();

    // clear history for new data
    m_stackBrowser->clear();

    // unset busy state
    setBusy(false);
}

void CallgrindToolPrivate::updateEventCombo()
{
    QTC_ASSERT(m_eventCombo, return)

    m_eventCombo->clear();

    const ParseData *data = m_dataModel->parseData();
    if (!data || data->events().isEmpty()) {
        m_eventCombo->hide();
        return;
    }

    m_eventCombo->show();
    foreach (const QString &event, data->events())
        m_eventCombo->addItem(ParseData::prettyStringForEvent(event));
}

static QToolButton *createToolButton(QAction *action)
{
    QToolButton *button = new QToolButton;
    button->setDefaultAction(action);
495
    //button->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
496 497 498
    return button;
}

499
CallgrindTool::CallgrindTool(QObject *parent)
500 501 502
    : Analyzer::IAnalyzerTool(parent)
{
    d = new CallgrindToolPrivate(this);
503
    setObjectName(QLatin1String("CallgrindTool"));
504

505
    Core::ICore *core = Core::ICore::instance();
506 507 508 509 510 511 512 513 514 515
    QObject *editorManager = core->editorManager();
    connect(editorManager, SIGNAL(editorOpened(Core::IEditor*)),
        d, SLOT(editorOpened(Core::IEditor*)));
}

CallgrindTool::~CallgrindTool()
{
    delete d;
}

516
QByteArray CallgrindTool::id() const
517
{
518
    return "Callgrind";
519 520 521 522
}

QString CallgrindTool::displayName() const
{
523
    return tr("Valgrind Function Profiler");
524 525 526 527 528 529
}

QString CallgrindTool::description() const
{
    return tr("Valgrind Profile uses the \"callgrind\" tool to "
              "record function calls when a program runs.");
530 531
}

532
IAnalyzerTool::ToolMode CallgrindTool::toolMode() const
533
{
534
    return ReleaseMode;
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
}

void CallgrindTool::extensionsInitialized()
{
    Core::ICore *core = Core::ICore::instance();
    Core::ActionManager *actionManager = core->actionManager();

    Core::Context analyzerContext = Core::Context(Analyzer::Constants::C_ANALYZEMODE);

    // check if there is a CppEditor context menu, if true, add our own context menu actions
    if (Core::ActionContainer *editorContextMenu =
            actionManager->actionContainer(CppEditor::Constants::M_CONTEXT)) {
        QAction *action = 0;
        Core::Command *cmd = 0;

        action = new QAction(this);
        action->setSeparator(true);
        cmd = actionManager->registerAction(action, "Analyzer.Callgrind.ContextMenu.Sep",
            analyzerContext);
        editorContextMenu->addAction(cmd);

        action = new QAction(tr("Profile Costs of this Function and its Callees"), this);
        action->setIcon(QIcon(Analyzer::Constants::ANALYZER_CONTROL_START_ICON));
        connect(action, SIGNAL(triggered()), d, SLOT(handleShowCostsOfFunction()));
        cmd = actionManager->registerAction(action, "Analyzer.Callgrind.ShowCostsOfFunction",
            analyzerContext);
        editorContextMenu->addAction(cmd);
        cmd->setAttribute(Core::Command::CA_Hide);
        cmd->setAttribute(Core::Command::CA_NonConfigurable);
        d->m_showCostsOfFunctionAction = action;
    }
}

568 569 570 571 572 573 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
IAnalyzerEngine *CallgrindTool::createEngine(const AnalyzerStartParameters &sp,
    ProjectExplorer::RunConfiguration *runConfiguration)
{
    return d->createEngine(sp, runConfiguration);
}

IAnalyzerEngine *CallgrindToolPrivate::createEngine(const AnalyzerStartParameters &sp,
    ProjectExplorer::RunConfiguration *runConfiguration)
{
    CallgrindEngine *engine = new CallgrindEngine(q, sp, runConfiguration);

    connect(engine, SIGNAL(parserDataReady(CallgrindEngine *)),
            SLOT(takeParserData(CallgrindEngine *)));
    connect(engine, SIGNAL(starting(const Analyzer::IAnalyzerEngine*)),
            SLOT(engineStarting(const Analyzer::IAnalyzerEngine*)));
    connect(engine, SIGNAL(finished()),
            SLOT(engineFinished()));

    connect(this, SIGNAL(dumpRequested()), engine, SLOT(dump()));
    connect(this, SIGNAL(resetRequested()), engine, SLOT(reset()));
    connect(this, SIGNAL(pauseToggled(bool)), engine, SLOT(setPaused(bool)));

    // initialize engine
    engine->setPaused(m_pauseAction->isChecked());

    // we may want to toggle collect for one function only in this run
    engine->setToggleCollectFunction(m_toggleCollectFunction);
    m_toggleCollectFunction.clear();

    AnalyzerManager::showStatusMessage(AnalyzerManager::msgToolStarted(q->displayName()));

    QTC_ASSERT(m_visualisation, return engine);

601 602 603 604 605 606 607 608 609 610
    // apply project settings
    if (runConfiguration) {
        if (const AnalyzerProjectSettings *analyzerSettings = runConfiguration->extraAspect<AnalyzerProjectSettings>()) {
            if (const ValgrindProjectSettings *settings = analyzerSettings->subConfig<ValgrindProjectSettings>()) {
                m_visualisation->setMinimumInclusiveCostRatio(settings->visualisationMinimumInclusiveCostRatio() / 100.0);
                m_proxyModel->setMinimumInclusiveCostRatio(settings->minimumInclusiveCostRatio() / 100.0);
                m_dataModel->setVerboseToolTipsEnabled(settings->enableEventToolTips());
            }
        }
    }
611 612 613 614
    return engine;
}

void CallgrindTool::startTool(StartMode mode)
615
{
616
    ValgrindPlugin::startValgrindTool(this, mode);
617 618
}

619
QWidget *CallgrindTool::createWidgets()
620
{
621 622 623 624 625 626 627 628 629 630
    return d->createWidgets();
}

QWidget *CallgrindToolPrivate::createWidgets()
{
    QTC_ASSERT(!m_visualisation, return 0);

    //
    // DockWidgets
    //
631
    Utils::FancyMainWindow *mw = AnalyzerManager::mainWindow();
632 633
    m_visualisation = new Visualisation(mw);
    m_visualisation->setFrameStyle(QFrame::NoFrame);
634
    m_visualisation->setObjectName("Valgrind.CallgrindTool.Visualisation");
635 636 637 638 639
    m_visualisation->setModel(m_dataModel);
    connect(m_visualisation, SIGNAL(functionActivated(const Valgrind::Callgrind::Function*)),
            this, SLOT(visualisationFunctionSelected(const Valgrind::Callgrind::Function*)));

    m_callersView = new CostView(mw);
640
    m_callersView->setObjectName("Valgrind.CallgrindTool.CallersView");
641 642 643 644 645 646 647 648 649 650 651
    m_callersView->sortByColumn(CallModel::CostColumn);
    m_callersView->setFrameStyle(QFrame::NoFrame);
    // enable sorting
    QSortFilterProxyModel *callerProxy = new QSortFilterProxyModel(m_callersModel);
    callerProxy->setSourceModel(m_callersModel);
    m_callersView->setModel(callerProxy);
    m_callersView->hideColumn(CallModel::CalleeColumn);
    connect(m_callersView, SIGNAL(activated(QModelIndex)),
            this, SLOT(callerFunctionSelected(QModelIndex)));

    m_calleesView = new CostView(mw);
652
    m_calleesView->setObjectName("Valgrind.CallgrindTool.CalleesView");
653 654 655 656 657 658 659 660 661 662 663
    m_calleesView->sortByColumn(CallModel::CostColumn);
    m_calleesView->setFrameStyle(QFrame::NoFrame);
    // enable sorting
    QSortFilterProxyModel *calleeProxy = new QSortFilterProxyModel(m_calleesModel);
    calleeProxy->setSourceModel(m_calleesModel);
    m_calleesView->setModel(calleeProxy);
    m_calleesView->hideColumn(CallModel::CallerColumn);
    connect(m_calleesView, SIGNAL(activated(QModelIndex)),
            this, SLOT(calleeFunctionSelected(QModelIndex)));

    m_flatView = new CostView(mw);
664
    m_flatView->setObjectName("Valgrind.CallgrindTool.FlatView");
665 666 667 668 669 670 671 672 673
    m_flatView->sortByColumn(DataModel::SelfCostColumn);
    m_flatView->setFrameStyle(QFrame::NoFrame);
    m_flatView->setAttribute(Qt::WA_MacShowFocusRect, false);
    m_flatView->setModel(m_proxyModel);
    connect(m_flatView, SIGNAL(activated(QModelIndex)),
            this, SLOT(dataFunctionSelected(QModelIndex)));

    updateCostFormat();

674 675
    QDockWidget *callersDock = AnalyzerManager::createDockWidget
        (q, tr("Callers"), m_callersView, Qt::BottomDockWidgetArea);
676

677 678
    QDockWidget *flatDock = AnalyzerManager::createDockWidget
        (q, tr("Functions"), m_flatView, Qt::BottomDockWidgetArea);
679

680 681
    QDockWidget *calleesDock = AnalyzerManager::createDockWidget
        (q, tr("Callees"), m_calleesView, Qt::BottomDockWidgetArea);
682

683 684
    QDockWidget *visualizationDock = AnalyzerManager::createDockWidget
        (q, tr("Visualization"), m_visualisation, Qt::RightDockWidgetArea);
685 686 687 688

    callersDock->show();
    calleesDock->show();
    flatDock->show();
689 690 691
    visualizationDock->hide();

    mw->splitDockWidget(mw->toolBarDockWidget(), flatDock, Qt::Vertical);
692 693
    mw->splitDockWidget(mw->toolBarDockWidget(), calleesDock, Qt::Vertical);
    mw->splitDockWidget(calleesDock, callersDock, Qt::Horizontal);
694

695 696 697
    //
    // Control Widget
    //
698 699 700 701 702 703 704 705 706 707 708 709
    QAction *action = 0;
    QWidget *widget = new QWidget;
    QHBoxLayout *layout = new QHBoxLayout;

    layout->setMargin(0);
    layout->setSpacing(0);
    widget->setLayout(layout);

    // dump action
    action = new QAction(this);
    action->setDisabled(true);
    action->setIcon(QIcon(QLatin1String(Core::Constants::ICON_REDO)));
710
    //action->setText(tr("Dump"));
711 712 713 714 715 716 717 718 719
    action->setToolTip(tr("Request the dumping of profile information. This will update the callgrind visualization."));
    connect(action, SIGNAL(triggered()), this, SLOT(slotRequestDump()));
    layout->addWidget(createToolButton(action));
    m_dumpAction = action;

    // reset action
    action = new QAction(this);
    action->setDisabled(true);
    action->setIcon(QIcon(QLatin1String(Core::Constants::ICON_CLEAR)));
720 721
    //action->setText(tr("Reset"));
    action->setToolTip(tr("Reset all event counters."));
722 723 724 725 726 727 728 729
    connect(action, SIGNAL(triggered()), this, SIGNAL(resetRequested()));
    layout->addWidget(createToolButton(action));
    m_resetAction = action;

    // pause action
    action = new QAction(this);
    action->setCheckable(true);
    action->setIcon(QIcon(QLatin1String(":/qml/images/pause-small.png")));
730 731
    //action->setText(tr("Ignore"));
    action->setToolTip(tr("Pause event logging. No events are counted which will speed up program execution during profiling."));
732 733 734 735 736 737 738 739
    connect(action, SIGNAL(toggled(bool)), this, SIGNAL(pauseToggled(bool)));
    layout->addWidget(createToolButton(action));
    m_pauseAction = action;

    // navigation
    // go back
    action = new QAction(this);
    action->setDisabled(true);
740
    action->setIcon(QIcon(QLatin1String(":core/images/prev.png")));
741 742 743 744 745
    action->setToolTip(tr("Go back one step in history. This will select the previously selected item."));
    connect(action, SIGNAL(triggered(bool)), m_stackBrowser, SLOT(goBack()));
    layout->addWidget(createToolButton(action));
    m_goBack = action;

746 747 748 749 750 751 752 753
    // go forward
    action = new QAction(this);
    action->setDisabled(true);
    action->setIcon(QIcon(QLatin1String(":core/images/next.png")));
    action->setToolTip(tr("Go forward one step in history."));
    connect(action, SIGNAL(triggered(bool)), m_stackBrowser, SLOT(goNext()));
    layout->addWidget(createToolButton(action));
    m_goNext = action;
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 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

    layout->addWidget(new Utils::StyledSeparator);

    // event selection
    m_eventCombo = new QComboBox;
    m_eventCombo->setToolTip(tr("Selects which events from the profiling data are shown and visualized."));
    connect(m_eventCombo, SIGNAL(currentIndexChanged(int)),
            this, SLOT(setCostEvent(int)));
    updateEventCombo();
    layout->addWidget(m_eventCombo);

    // cost formatting
    {
    QMenu *menu = new QMenu(layout->parentWidget());
    QActionGroup *group = new QActionGroup(this);

    // show costs as absolute numbers
    m_costAbsolute = new QAction(tr("Absolute Costs"), this);
    ///FIXME: icon
    m_costAbsolute->setToolTip(tr("Show costs as absolute numbers."));
    m_costAbsolute->setCheckable(true);
    m_costAbsolute->setChecked(true);
    connect(m_costAbsolute, SIGNAL(toggled(bool)), SLOT(updateCostFormat()));
    group->addAction(m_costAbsolute);
    menu->addAction(m_costAbsolute);

    // show costs in percentages
    m_costRelative = new QAction(tr("Relative Costs"), this);
    ///FIXME: icon (percentage sign?)
    m_costRelative->setToolTip(tr("Show costs relative to total inclusive cost."));
    m_costRelative->setCheckable(true);
    connect(m_costRelative, SIGNAL(toggled(bool)), SLOT(updateCostFormat()));
    group->addAction(m_costRelative);
    menu->addAction(m_costRelative);

    // show costs relative to parent
    m_costRelativeToParent = new QAction(tr("Relative Costs to Parent"), this);
    ///FIXME: icon
    m_costRelativeToParent->setToolTip(tr("Show costs relative to parent functions inclusive cost."));
    m_costRelativeToParent->setCheckable(true);
    connect(m_costRelativeToParent, SIGNAL(toggled(bool)), SLOT(updateCostFormat()));
    group->addAction(m_costRelativeToParent);
    menu->addAction(m_costRelativeToParent);

    QToolButton *button = new QToolButton;
    button->setMenu(menu);
    button->setPopupMode(QToolButton::InstantPopup);
    button->setText(tr("Cost Format"));
    layout->addWidget(button);
    }

    // cycle detection
    action = new QAction(tr("Cycle Detection"), this); ///FIXME: icon
    action->setToolTip(tr("Enable cycle detection to properly handle recursive or circular function calls."));
    action->setCheckable(true);
    connect(action, SIGNAL(toggled(bool)), m_dataModel, SLOT(enableCycleDetection(bool)));
    connect(action, SIGNAL(toggled(bool)), m_settings, SLOT(setDetectCycles(bool)));
    layout->addWidget(createToolButton(action));
    m_cycleDetection = action;

    // filtering
    action = new QAction(tr("Show Project Costs Only"), this);
    action->setIcon(QIcon(Core::Constants::ICON_FILTER));
    action->setToolTip(tr("Show only profiling info that originated from this project source."));
    action->setCheckable(true);
    connect(action, SIGNAL(toggled(bool)), this, SLOT(handleFilterProjectCosts()));
    layout->addWidget(createToolButton(action));
    m_filterProjectCosts = action;

    // filter
824
    ///FIXME: find workaround for https://bugreports.qt.nokia.com/browse/QTCREATORBUG-3247
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
    QLineEdit *filter = new QLineEdit;
    filter->setPlaceholderText(tr("Filter..."));
    connect(filter, SIGNAL(textChanged(QString)), m_updateTimer, SLOT(start()));
    layout->addWidget(filter);
    m_searchFilter = filter;

    setCostFormat(m_settings->costFormat());
    enableCycleDetection(m_settings->detectCycles());

    layout->addWidget(new Utils::StyledSeparator);
    layout->addStretch();

    return widget;
}

void CallgrindToolPrivate::clearTextMarks()
{
    qDeleteAll(m_textMarks);
    m_textMarks.clear();
}

void CallgrindToolPrivate::engineStarting(const Analyzer::IAnalyzerEngine *)
{
    // enable/disable actions
    m_resetAction->setEnabled(true);
    m_dumpAction->setEnabled(true);
    clearTextMarks();
    slotClear();
}

void CallgrindToolPrivate::engineFinished()
{
    // enable/disable actions
    m_resetAction->setEnabled(false);
    m_dumpAction->setEnabled(false);

    const ParseData *data = m_dataModel->parseData();
    if (data)
        showParserResults(data);
    else
865
        AnalyzerManager::showStatusMessage(tr("Profiling aborted."));
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
}

void CallgrindToolPrivate::showParserResults(const ParseData *data)
{
    QString msg;
    if (data) {
        // be careful, the list of events might be empty
        if (data->events().isEmpty()) {
            msg = tr("Parsing finished, no data.");
        } else {
            const QString costStr = QString("%1 %2").arg(QString::number(data->totalCost(0)), data->events().first());
            msg = tr("Parsing finished, total cost of %1 reported.").arg(costStr);
        }
    } else {
        msg = tr("Parsing failed.");
    }
882
    AnalyzerManager::showStatusMessage(msg);
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940
}

void CallgrindToolPrivate::editorOpened(Core::IEditor *editor)
{
    TextEditor::ITextEditor *textEditor = qobject_cast<TextEditor::ITextEditor *>(editor);
    if (!textEditor)
        return;

    connect(textEditor,
        SIGNAL(markContextMenuRequested(TextEditor::ITextEditor*,int,QMenu*)),
        SLOT(requestContextMenu(TextEditor::ITextEditor*,int,QMenu*)));
}

void CallgrindToolPrivate::requestContextMenu(TextEditor::ITextEditor *editor, int line, QMenu *menu)
{
    // find callgrind text mark that corresponds to this editor's file and line number
    const Function *func = 0;
    foreach (CallgrindTextMark *textMark, m_textMarks) {
        if (textMark->fileName() == editor->file()->fileName() && textMark->lineNumber() == line) {
            func = textMark->function();
            break;
        }
    }
    if (!func)
        return; // no callgrind text mark under cursor, return

    // add our action to the context menu
    QAction *action = new QAction(tr("Select this Function in the Analyzer Output"), menu);
    connect(action, SIGNAL(triggered()), SLOT(handleShowCostsAction()));
    action->setData(QVariant::fromValue<const Function *>(func));
    menu->addAction(action);
}

void CallgrindToolPrivate::handleShowCostsAction()
{
    const QAction *action = qobject_cast<QAction *>(sender());
    QTC_ASSERT(action, return)

    const Function *func = action->data().value<const Function *>();
    QTC_ASSERT(func, return)

    selectFunction(func);
}

void CallgrindToolPrivate::handleShowCostsOfFunction()
{
    CPlusPlus::Symbol *symbol = AnalyzerUtils::findSymbolUnderCursor();
    if (!symbol)
        return;

    if (!symbol->isFunction())
        return;

    CPlusPlus::Overview view;
    const QString qualifiedFunctionName = view.prettyName(CPlusPlus::LookupContext::fullyQualifiedName(symbol));

    m_toggleCollectFunction = QString("%1()").arg(qualifiedFunctionName);

941 942
    AnalyzerManager::selectTool(q, StartMode(StartLocal));
    AnalyzerManager::startTool(q, StartMode(StartLocal));
943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
}

void CallgrindToolPrivate::slotRequestDump()
{
    setBusy(true);
    m_visualisation->setText(tr("Populating..."));
    dumpRequested();
}

void CallgrindToolPrivate::takeParserData(CallgrindEngine *engine)
{
    ParseData *data = engine->takeParserData();
    showParserResults(data);

    if (!data)
        return;

    // clear first
    clearTextMarks();
    slotClear();

    setParseData(data);
    createTextMarks();
}

void CallgrindToolPrivate::createTextMarks()
{
    DataModel *model = m_dataModel;
    QTC_ASSERT(model, return)

    QList<QString> locations;
    for (int row = 0; row < model->rowCount(); ++row) {
        const QModelIndex index = model->index(row, DataModel::InclusiveCostColumn);

        QString fileName = index.data(DataModel::FileNameRole).toString();
        if (fileName.isEmpty() || fileName == "???")
            continue;

        bool ok = false;
        const int lineNumber = index.data(DataModel::LineNumberRole).toInt(&ok);
        QTC_ASSERT(ok, continue);

        // sanitize filename, text marks need a canonical (i.e. no ".."s) path
        // BaseTextMark::editorOpened(Core::IEditor *editor) compares file names on string basis
        QFileInfo info(fileName);
        fileName = info.canonicalFilePath();
        if (fileName.isEmpty())
            continue; // isEmpty == true => file does not exist, continue then

        // create only one text mark per location
        const QString location = QString("%1:%2").arg(fileName, QString::number(lineNumber));
        if (locations.contains(location))
            continue;
        locations << location;

        m_textMarks.append(new CallgrindTextMark(index, fileName, lineNumber));
    }
}

} // namespace Internal
} // namespace Valgrind

#include "callgrindtool.moc"