callgraphview.cpp 92.4 KB
Newer Older
1
/* This file is part of KCachegrind.
Josef Weidendorfer's avatar
Josef Weidendorfer committed
2
   Copyright (c) 2007-2016 Josef Weidendorfer <Josef.Weidendorfer@gmx.de>
3 4 5 6 7 8 9 10 11 12 13 14

   KCachegrind is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public
   License as published by the Free Software Foundation, version 2.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; see the file COPYING.  If not, write to
15
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Dirk Mueller's avatar
Dirk Mueller committed
16
   Boston, MA 02110-1301, USA.
17 18 19 20 21 22
*/

/*
 * Callgraph View
 */

23 24
#include "callgraphview.h"

25 26 27
#include <stdlib.h>
#include <math.h>

28
#include <QApplication>
29
#include <QDebug>
30
#include <QDesktopServices>
31
#include <QFile>
32 33
#include <QFileDialog>
#include <QTemporaryFile>
34 35 36 37 38
#include <QTextStream>
#include <QMatrix>
#include <QPair>
#include <QPainter>
#include <QStyle>
39
#include <QScrollBar>
Nicolas Goutte's avatar
Nicolas Goutte committed
40 41 42 43
#include <QResizeEvent>
#include <QMouseEvent>
#include <QFocusEvent>
#include <QKeyEvent>
44
#include <QStyleOptionGraphicsItem>
Nicolas Goutte's avatar
Nicolas Goutte committed
45
#include <QContextMenuEvent>
46
#include <QList>
Nicolas Goutte's avatar
Nicolas Goutte committed
47
#include <QPixmap>
48
#include <QDesktopWidget>
49
#include <QProcess>
50
#include <QMenu>
51 52


53
#include "config.h"
54
#include "globalguiconfig.h"
55 56 57
#include "listutils.h"


Josef Weidendorfer's avatar
Josef Weidendorfer committed
58
#define DEBUG_GRAPH 0
59 60 61

// CallGraphView defaults

62 63 64 65 66 67
#define DEFAULT_FUNCLIMIT     .05
#define DEFAULT_CALLLIMIT     1.
#define DEFAULT_MAXCALLER     2
#define DEFAULT_MAXCALLEE     -1
#define DEFAULT_SHOWSKIPPED   false
#define DEFAULT_EXPANDCYCLES  false
68
#define DEFAULT_CLUSTERGROUPS false
69 70 71
#define DEFAULT_DETAILLEVEL   1
#define DEFAULT_LAYOUT        GraphOptions::TopDown
#define DEFAULT_ZOOMPOS       Auto
72 73


74 75 76 77 78 79 80 81
// LessThen functors as helpers for sorting of graph edges
// for keyboard navigation. Sorting is done according to
// the angle at which a edge spline goes out or in of a function.

// Sort angles of outgoing edges (edge seen as attached to the caller)
class CallerGraphEdgeLessThan
{
public:
82 83 84 85 86 87
    bool operator()(const GraphEdge* ge1, const GraphEdge* ge2) const
    {
        const CanvasEdge* ce1 = ge1->canvasEdge();
        const CanvasEdge* ce2 = ge2->canvasEdge();

        // sort invisible edges (ie. without matching CanvasEdge) in front
88 89 90 91
        if (!ce1 && !ce2) {
            // strict ordering required for std::sort
            return (ge1 < ge2);
        }
92 93 94 95 96 97 98 99 100 101 102 103
        if (!ce1) return true;
        if (!ce2) return false;

        QPolygon p1 = ce1->controlPoints();
        QPolygon p2 = ce2->controlPoints();
        QPoint d1 = p1.point(1) - p1.point(0);
        QPoint d2 = p2.point(1) - p2.point(0);
        double angle1 = atan2(double(d1.y()), double(d1.x()));
        double angle2 = atan2(double(d2.y()), double(d2.x()));

        return (angle1 < angle2);
    }
104 105 106 107 108 109
};

// Sort angles of ingoing edges (edge seen as attached to the callee)
class CalleeGraphEdgeLessThan
{
public:
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
    bool operator()(const GraphEdge* ge1, const GraphEdge* ge2) const
    {
        const CanvasEdge* ce1 = ge1->canvasEdge();
        const CanvasEdge* ce2 = ge2->canvasEdge();

        // sort invisible edges (ie. without matching CanvasEdge) in front
        if (!ce1) return true;
        if (!ce2) return false;

        QPolygon p1 = ce1->controlPoints();
        QPolygon p2 = ce2->controlPoints();
        QPoint d1 = p1.point(p1.count()-2) - p1.point(p1.count()-1);
        QPoint d2 = p2.point(p2.count()-2) - p2.point(p2.count()-1);
        double angle1 = atan2(double(d1.y()), double(d1.x()));
        double angle2 = atan2(double(d2.y()), double(d2.x()));

        // for ingoing edges sort according to descending angles
        return (angle2 < angle1);
    }
129
};
130 131 132 133 134 135 136 137 138



//
// GraphNode
//

GraphNode::GraphNode()
{
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
139
    _f=nullptr;
140
    self = incl = 0;
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
141
    _cn = nullptr;
142

143 144
    _visible = false;
    _lastCallerIndex = _lastCalleeIndex = -1;
145

146
    _lastFromCaller = true;
147 148
}

149 150
void GraphNode::clearEdges()
{
151 152
    callees.clear();
    callers.clear();
153 154 155 156 157 158 159
}

CallerGraphEdgeLessThan callerGraphEdgeLessThan;
CalleeGraphEdgeLessThan calleeGraphEdgeLessThan;

void GraphNode::sortEdges()
{
160 161
    std::sort(callers.begin(), callers.end(), callerGraphEdgeLessThan);
    std::sort(callees.begin(), callees.end(), calleeGraphEdgeLessThan);
162 163 164 165
}

void GraphNode::addCallee(GraphEdge* e)
{
166 167
    if (e)
        callees.append(e);
168 169 170 171
}

void GraphNode::addCaller(GraphEdge* e)
{
172 173
    if (e)
        callers.append(e);
174 175 176 177
}

void GraphNode::addUniqueCallee(GraphEdge* e)
{
178 179
    if (e && (callees.count(e) == 0))
        callees.append(e);
180 181 182 183
}

void GraphNode::addUniqueCaller(GraphEdge* e)
{
184 185
    if (e && (callers.count(e) == 0))
        callers.append(e);
186 187 188 189
}

void GraphNode::removeEdge(GraphEdge* e)
{
190 191
    callers.removeAll(e);
    callees.removeAll(e);
192 193 194 195
}

double GraphNode::calleeCostSum()
{
196
    double sum = 0.0;
197

198 199
    foreach(GraphEdge* e, callees)
        sum += e->cost;
200

201
    return sum;
202 203 204 205
}

double GraphNode::calleeCountSum()
{
206
    double sum = 0.0;
207

208 209
    foreach(GraphEdge* e, callees)
        sum += e->count;
210

211
    return sum;
212 213 214 215
}

double GraphNode::callerCostSum()
{
216
    double sum = 0.0;
217

218 219
    foreach(GraphEdge* e, callers)
        sum += e->cost;
220

221
    return sum;
222 223 224 225
}

double GraphNode::callerCountSum()
{
226
    double sum = 0.0;
227

228 229
    foreach(GraphEdge* e, callers)
        sum += e->count;
230

231
    return sum;
232 233 234
}


235 236
TraceCall* GraphNode::visibleCaller()
{
237 238 239 240 241 242 243
    if (0)
        qDebug("GraphNode::visibleCaller %s: last %d, count %d",
               qPrintable(_f->prettyName()), _lastCallerIndex, callers.count());

    // can not use at(): index can be -1 (out of bounds), result is 0 then
    GraphEdge* e = callers.value(_lastCallerIndex);
    if (e && !e->isVisible())
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
244
        e = nullptr;
245 246
    if (!e) {
        double maxCost = 0.0;
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
247
        GraphEdge* maxEdge = nullptr;
248 249 250 251 252 253 254 255 256 257
        for(int i = 0; i<callers.size(); i++) {
            e = callers[i];
            if (e->isVisible() && (e->cost > maxCost)) {
                maxCost = e->cost;
                maxEdge = e;
                _lastCallerIndex = i;
            }
        }
        e = maxEdge;
    }
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
258
    return e ? e->call() : nullptr;
259 260
}

261
TraceCall* GraphNode::visibleCallee()
262
{
263 264 265 266 267 268
    if (0)
        qDebug("GraphNode::visibleCallee %s: last %d, count %d",
               qPrintable(_f->prettyName()), _lastCalleeIndex, callees.count());

    GraphEdge* e = callees.value(_lastCalleeIndex);
    if (e && !e->isVisible())
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
269
        e = nullptr;
270 271 272

    if (!e) {
        double maxCost = 0.0;
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
273
        GraphEdge* maxEdge = nullptr;
274 275 276 277 278 279 280 281 282 283
        for(int i = 0; i<callees.size(); i++) {
            e = callees[i];
            if (e->isVisible() && (e->cost > maxCost)) {
                maxCost = e->cost;
                maxEdge = e;
                _lastCalleeIndex = i;
            }
        }
        e = maxEdge;
    }
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
284
    return e ? e->call() : nullptr;
285 286
}

287
void GraphNode::setCallee(GraphEdge* e)
288
{
289 290
    _lastCalleeIndex = callees.indexOf(e);
    _lastFromCaller = false;
291 292 293 294
}

void GraphNode::setCaller(GraphEdge* e)
{
295 296
    _lastCallerIndex = callers.indexOf(e);
    _lastFromCaller = true;
297 298 299 300
}

TraceFunction* GraphNode::nextVisible()
{
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
    TraceCall* c;

    if (_lastFromCaller) {
        c = nextVisibleCaller();
        if (c)
            return c->called(true);
        c = nextVisibleCallee();
        if (c)
            return c->caller(true);
    } else {
        c = nextVisibleCallee();
        if (c)
            return c->caller(true);
        c = nextVisibleCaller();
        if (c)
            return c->called(true);
    }
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
318
    return nullptr;
319 320 321 322
}

TraceFunction* GraphNode::priorVisible()
{
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
    TraceCall* c;

    if (_lastFromCaller) {
        c = priorVisibleCaller();
        if (c)
            return c->called(true);
        c = priorVisibleCallee();
        if (c)
            return c->caller(true);
    } else {
        c = priorVisibleCallee();
        if (c)
            return c->caller(true);
        c = priorVisibleCaller();
        if (c)
            return c->called(true);
    }
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
340
    return nullptr;
341 342
}

343
TraceCall* GraphNode::nextVisibleCaller(GraphEdge* e)
344
{
345 346 347 348 349 350 351 352 353
    int idx = e ? callers.indexOf(e) : _lastCallerIndex;
    idx++;
    while(idx < callers.size()) {
        if (callers[idx]->isVisible()) {
            _lastCallerIndex = idx;
            return callers[idx]->call();
        }
        idx++;
    }
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
354
    return nullptr;
355 356
}

357
TraceCall* GraphNode::nextVisibleCallee(GraphEdge* e)
358
{
359 360 361 362 363 364 365 366 367
    int idx = e ? callees.indexOf(e) : _lastCalleeIndex;
    idx++;
    while(idx < callees.size()) {
        if (callees[idx]->isVisible()) {
            _lastCalleeIndex = idx;
            return callees[idx]->call();
        }
        idx++;
    }
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
368
    return nullptr;
369 370
}

371
TraceCall* GraphNode::priorVisibleCaller(GraphEdge* e)
372
{
373
    int idx = e ? callers.indexOf(e) : _lastCallerIndex;
374

375 376 377 378 379 380 381 382
    idx = (idx<0) ? callers.size()-1 : idx-1;
    while(idx >= 0) {
        if (callers[idx]->isVisible()) {
            _lastCallerIndex = idx;
            return callers[idx]->call();
        }
        idx--;
    }
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
383
    return nullptr;
384 385
}

386
TraceCall* GraphNode::priorVisibleCallee(GraphEdge* e)
387
{
388
    int idx = e ? callees.indexOf(e) : _lastCalleeIndex;
389

390 391 392 393 394 395 396 397
    idx = (idx<0) ? callees.size()-1 : idx-1;
    while(idx >= 0) {
        if (callees[idx]->isVisible()) {
            _lastCalleeIndex = idx;
            return callees[idx]->call();
        }
        idx--;
    }
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
398
    return nullptr;
399 400
}

401

402 403 404 405 406 407
//
// GraphEdge
//

GraphEdge::GraphEdge()
{
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
408 409 410
    _c=nullptr;
    _from = _to = nullptr;
    _fromNode = _toNode = nullptr;
411
    cost = count = 0;
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
412
    _ce = nullptr;
413

414 415
    _visible = false;
    _lastFromCaller = true;
416 417 418 419
}

QString GraphEdge::prettyName()
{
420 421
    if (_c)
        return _c->prettyName();
422

423 424
    if (_from)
        return QObject::tr("Call(s) from %1").arg(_from->prettyName());
425

426 427
    if (_to)
        return QObject::tr("Call(s) to %1").arg(_to->prettyName());
428

429
    return QObject::tr("(unknown call)");
430
}
431 432 433

TraceFunction* GraphEdge::visibleCaller()
{
434 435 436 437 438 439
    if (_from) {
        _lastFromCaller = true;
        if (_fromNode)
            _fromNode->setCallee(this);
        return _from;
    }
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
440
    return nullptr;
441 442
}

443
TraceFunction* GraphEdge::visibleCallee()
444
{
445 446 447 448 449 450
    if (_to) {
        _lastFromCaller = false;
        if (_toNode)
            _toNode->setCaller(this);
        return _to;
    }
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
451
    return nullptr;
452 453 454 455
}

TraceCall* GraphEdge::nextVisible()
{
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
456
    TraceCall* res = nullptr;
457

458 459 460 461 462 463 464 465 466 467
    if (_lastFromCaller && _fromNode) {
        res = _fromNode->nextVisibleCallee(this);
        if (!res && _toNode)
            res = _toNode->nextVisibleCaller(this);
    } else if (_toNode) {
        res = _toNode->nextVisibleCaller(this);
        if (!res && _fromNode)
            res = _fromNode->nextVisibleCallee(this);
    }
    return res;
468 469 470 471
}

TraceCall* GraphEdge::priorVisible()
{
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
472
    TraceCall* res = nullptr;
473

474 475 476 477 478 479 480 481 482 483
    if (_lastFromCaller && _fromNode) {
        res = _fromNode->priorVisibleCallee(this);
        if (!res && _toNode)
            res = _toNode->priorVisibleCaller(this);
    } else if (_toNode) {
        res = _toNode->priorVisibleCaller(this);
        if (!res && _fromNode)
            res = _fromNode->priorVisibleCallee(this);
    }
    return res;
484 485 486 487 488 489 490 491 492 493
}



//
// GraphOptions
//

QString GraphOptions::layoutString(Layout l)
{
494 495 496 497 498
    if (l == Circular)
        return QStringLiteral("Circular");
    if (l == LeftRight)
        return QStringLiteral("LeftRight");
    return QStringLiteral("TopDown");
499 500 501 502
}

GraphOptions::Layout GraphOptions::layout(QString s)
{
503
    if (s == QLatin1String("Circular"))
504
        return Circular;
505
    if (s == QLatin1String("LeftRight"))
506 507
        return LeftRight;
    return TopDown;
508 509 510 511 512 513 514 515 516
}


//
// StorableGraphOptions
//

StorableGraphOptions::StorableGraphOptions()
{
517 518 519 520 521 522 523 524 525
    // default options
    _funcLimit         = DEFAULT_FUNCLIMIT;
    _callLimit         = DEFAULT_CALLLIMIT;
    _maxCallerDepth    = DEFAULT_MAXCALLER;
    _maxCalleeDepth    = DEFAULT_MAXCALLEE;
    _showSkipped       = DEFAULT_SHOWSKIPPED;
    _expandCycles      = DEFAULT_EXPANDCYCLES;
    _detailLevel       = DEFAULT_DETAILLEVEL;
    _layout            = DEFAULT_LAYOUT;
526 527 528 529 530 531 532 533 534 535 536
}




//
// GraphExporter
//

GraphExporter::GraphExporter()
{
537
    _go = this;
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
538 539 540
    _tmpFile = nullptr;
    _item = nullptr;
    reset(nullptr, nullptr, nullptr, ProfileContext::InvalidType, QString());
541 542
}

543
GraphExporter::GraphExporter(TraceData* d, TraceFunction* f,
544
                             EventType* ct, ProfileContext::Type gt,
545
                             QString filename)
546
{
547
    _go = this;
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
548 549
    _tmpFile = nullptr;
    _item = nullptr;
550
    reset(d, f, ct, gt, filename);
551 552 553 554
}

GraphExporter::~GraphExporter()
{
555
    if (_item && _tmpFile) {
Josef Weidendorfer's avatar
Josef Weidendorfer committed
556
#if DEBUG_GRAPH
557
        _tmpFile->setAutoRemove(true);
Josef Weidendorfer's avatar
Josef Weidendorfer committed
558
#endif
559 560
        delete _tmpFile;
    }
561 562 563
}


564
void GraphExporter::reset(TraceData*, CostItem* i, EventType* ct,
565
                          ProfileContext::Type gt, QString filename)
566
{
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
    _graphCreated = false;
    _nodeMap.clear();
    _edgeMap.clear();

    if (_item && _tmpFile) {
        _tmpFile->setAutoRemove(true);
        delete _tmpFile;
    }

    if (i) {
        switch (i->type()) {
        case ProfileContext::Function:
        case ProfileContext::FunctionCycle:
        case ProfileContext::Call:
            break;
        default:
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
583
            i = nullptr;
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
        }
    }

    _item = i;
    _eventType = ct;
    _groupType = gt;
    if (!i)
        return;

    if (filename.isEmpty()) {
        _tmpFile = new QTemporaryFile();
        //_tmpFile->setSuffix(".dot");
        _tmpFile->setAutoRemove(false);
        _tmpFile->open();
        _dotName = _tmpFile->fileName();
        _useBox = true;
    } else {
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
601
        _tmpFile = nullptr;
602 603 604
        _dotName = filename;
        _useBox = false;
    }
605 606 607 608 609 610
}



void GraphExporter::setGraphOptions(GraphOptions* go)
{
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
611
    if (go == nullptr)
612 613
        go = this;
    _go = go;
614 615 616 617
}

void GraphExporter::createGraph()
{
618 619 620 621 622 623 624 625 626 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 654 655 656 657 658 659 660 661 662 663
    if (!_item)
        return;
    if (_graphCreated)
        return;
    _graphCreated = true;

    if ((_item->type() == ProfileContext::Function) ||(_item->type()
                                                       == ProfileContext::FunctionCycle)) {
        TraceFunction* f = (TraceFunction*) _item;

        double incl = f->inclusive()->subCost(_eventType);
        _realFuncLimit = incl * _go->funcLimit();
        _realCallLimit = _realFuncLimit * _go->callLimit();

        buildGraph(f, 0, true, 1.0); // down to callees

        // set costs of function back to 0, as it will be added again
        GraphNode& n = _nodeMap[f];
        n.self = n.incl = 0.0;

        buildGraph(f, 0, false, 1.0); // up to callers
    } else {
        TraceCall* c = (TraceCall*) _item;

        double incl = c->subCost(_eventType);
        _realFuncLimit = incl * _go->funcLimit();
        _realCallLimit = _realFuncLimit * _go->callLimit();

        // create edge
        TraceFunction *caller, *called;
        caller = c->caller(false);
        called = c->called(false);
        QPair<TraceFunction*,TraceFunction*> p(caller, called);
        GraphEdge& e = _edgeMap[p];
        e.setCall(c);
        e.setCaller(p.first);
        e.setCallee(p.second);
        e.cost = c->subCost(_eventType);
        e.count = c->callCount();

        SubCost s = called->inclusive()->subCost(_eventType);
        buildGraph(called, 0, true, e.cost / s); // down to callees
        s = caller->inclusive()->subCost(_eventType);
        buildGraph(caller, 0, false, e.cost / s); // up to callers
    }
}
664 665


666
bool GraphExporter::writeDot(QIODevice* device)
667 668
{
    if (!_item)
669
        return false;
670

Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
671 672
    QFile* file = nullptr;
    QTextStream* stream = nullptr;
673 674 675 676 677 678 679 680 681 682 683

    if (device)
        stream = new QTextStream(device);
    else {
        if (_tmpFile)
            stream = new QTextStream(_tmpFile);
        else {
            file = new QFile(_dotName);
            if ( !file->open(QIODevice::WriteOnly ) ) {
                qDebug() << "Can not write dot file '"<< _dotName << "'";
                delete file;
684
                return false;
685 686 687 688
            }
            stream = new QTextStream(file);
        }
    }
689

690 691 692 693 694 695 696 697 698 699 700 701 702 703
    if (!_graphCreated)
        createGraph();

    /* Generate dot format...
     * When used for the CallGraphView (in contrast to "Export Callgraph..."),
     * the labels are only dummy placeholders to reserve space for our own
     * drawings.
     */

    *stream << "digraph \"callgraph\" {\n";

    if (_go->layout() == LeftRight) {
        *stream << QStringLiteral("  rankdir=LR;\n");
    } else if (_go->layout() == Circular) {
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
704
        TraceFunction *f = nullptr;
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
        switch (_item->type()) {
        case ProfileContext::Function:
        case ProfileContext::FunctionCycle:
            f = (TraceFunction*) _item;
            break;
        case ProfileContext::Call:
            f = ((TraceCall*)_item)->caller(true);
            break;
        default:
            break;
        }
        if (f)
            *stream << QStringLiteral("  center=F%1;\n").arg((qptrdiff)f, 0, 16);
        *stream << QStringLiteral("  overlap=false;\n  splines=true;\n");
    }
720

721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
    // for clustering
    QMap<TraceCostItem*,QList<GraphNode*> > nLists;

    GraphNodeMap::Iterator nit;
    for (nit = _nodeMap.begin(); nit != _nodeMap.end(); ++nit ) {
        GraphNode& n = *nit;

        if (n.incl <= _realFuncLimit)
            continue;

        // for clustering: get cost item group of function
        TraceCostItem* g;
        TraceFunction* f = n.function();
        switch (_groupType) {
        case ProfileContext::Object:
            g = f->object();
            break;
        case ProfileContext::Class:
            g = f->cls();
            break;
        case ProfileContext::File:
            g = f->file();
            break;
        case ProfileContext::FunctionCycle:
            g = f->cycle();
            break;
        default:
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
748
            g = nullptr;
749 750 751 752
            break;
        }
        nLists[g].append(&n);
    }
753

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
    QMap<TraceCostItem*,QList<GraphNode*> >::Iterator lit;
    int cluster = 0;
    for (lit = nLists.begin(); lit != nLists.end(); ++lit, cluster++) {
        QList<GraphNode*>& l = lit.value();
        TraceCostItem* i = lit.key();

        if (_go->clusterGroups() && i) {
            QString iabr = GlobalConfig::shortenSymbol(i->prettyName());
            // escape quotation marks in symbols to avoid invalid dot syntax
            iabr.replace("\"", "\\\"");
            *stream << QStringLiteral("subgraph \"cluster%1\" { label=\"%2\";\n")
                       .arg(cluster).arg(iabr);
        }

        foreach(GraphNode* np, l) {
            TraceFunction* f = np->function();

            QString abr = GlobalConfig::shortenSymbol(f->prettyName());
            // escape quotation marks to avoid invalid dot syntax
            abr.replace("\"", "\\\"");
            *stream << QStringLiteral("  F%1 [").arg((qptrdiff)f, 0, 16);
            if (_useBox) {
                // we want a minimal size for cost display
                if ((int)abr.length() < 8) abr = abr + QString(8 - abr.length(),'_');

                // make label 3 lines for CallGraphView
                *stream << QStringLiteral("shape=box,label=\"** %1 **\\n**\\n%2\"];\n")
                           .arg(abr)
                           .arg(SubCost(np->incl).pretty());
            } else
                *stream << QStringLiteral("label=\"%1\\n%2\"];\n")
                           .arg(abr)
                           .arg(SubCost(np->incl).pretty());
        }

        if (_go->clusterGroups() && i)
            *stream << QStringLiteral("}\n");
    }
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 824 825 826 827 828 829 830 831 832 833 834
    GraphEdgeMap::Iterator eit;
    for (eit = _edgeMap.begin(); eit != _edgeMap.end(); ++eit ) {
        GraphEdge& e = *eit;

        if (e.cost < _realCallLimit)
            continue;
        if (!_go->expandCycles()) {
            // do not show inner cycle calls
            if (e.call()->inCycle()>0)
                continue;
        }

        GraphNode& from = _nodeMap[e.from()];
        GraphNode& to = _nodeMap[e.to()];

        e.setCallerNode(&from);
        e.setCalleeNode(&to);

        if ((from.incl <= _realFuncLimit) ||(to.incl <= _realFuncLimit))
            continue;

        // remove dumped edges from n.callers/n.callees
        from.removeEdge(&e);
        to.removeEdge(&e);

        *stream << QStringLiteral("  F%1 -> F%2 [weight=%3")
                   .arg((qptrdiff)e.from(), 0, 16)
                   .arg((qptrdiff)e.to(), 0, 16)
                   .arg((long)log(log(e.cost)));

        if (_go->detailLevel() ==1) {
            *stream << QStringLiteral(",label=\"%1 (%2x)\"")
                       .arg(SubCost(e.cost).pretty())
                       .arg(SubCost(e.count).pretty());
        }
        else if (_go->detailLevel() ==2)
            *stream << QStringLiteral(",label=\"%3\\n%4 x\"")
                       .arg(SubCost(e.cost).pretty())
                       .arg(SubCost(e.count).pretty());

        *stream << QStringLiteral("];\n");
    }
835

836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
    if (_go->showSkipped()) {

        // Create sum-edges for skipped edges
        GraphEdge* e;
        double costSum, countSum;
        for (nit = _nodeMap.begin(); nit != _nodeMap.end(); ++nit ) {
            GraphNode& n = *nit;
            if (n.incl <= _realFuncLimit)
                continue;

            // add edge for all skipped callers if cost sum is high enough
            costSum = n.callerCostSum();
            countSum = n.callerCountSum();
            if (costSum > _realCallLimit) {

Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
851
                QPair<TraceFunction*,TraceFunction*> p(nullptr, n.function());
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
                e = &(_edgeMap[p]);
                e->setCallee(p.second);
                e->cost = costSum;
                e->count = countSum;

                *stream << QStringLiteral("  R%1 [shape=point,label=\"\"];\n")
                           .arg((qptrdiff)n.function(), 0, 16);
                *stream << QStringLiteral("  R%1 -> F%2 [label=\"%3\\n%4 x\",weight=%5];\n")
                           .arg((qptrdiff)n.function(), 0, 16)
                           .arg((qptrdiff)n.function(), 0, 16)
                           .arg(SubCost(costSum).pretty())
                           .arg(SubCost(countSum).pretty())
                           .arg((int)log(costSum));
            }

            // add edge for all skipped callees if cost sum is high enough
            costSum = n.calleeCostSum();
            countSum = n.calleeCountSum();
            if (costSum > _realCallLimit) {

Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
872
                QPair<TraceFunction*,TraceFunction*> p(n.function(), nullptr);
873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
                e = &(_edgeMap[p]);
                e->setCaller(p.first);
                e->cost = costSum;
                e->count = countSum;

                *stream << QStringLiteral("  S%1 [shape=point,label=\"\"];\n")
                           .arg((qptrdiff)n.function(), 0, 16);
                *stream << QStringLiteral("  F%1 -> S%2 [label=\"%3\\n%4 x\",weight=%5];\n")
                           .arg((qptrdiff)n.function(), 0, 16)
                           .arg((qptrdiff)n.function(), 0, 16)
                           .arg(SubCost(costSum).pretty())
                           .arg(SubCost(countSum).pretty())
                           .arg((int)log(costSum));
            }
        }
    }
889

890 891 892 893 894 895
    // clear edges here completely.
    // Visible edges are inserted again on parsing in CallGraphView::refresh
    for (nit = _nodeMap.begin(); nit != _nodeMap.end(); ++nit ) {
        GraphNode& n = *nit;
        n.clearEdges();
    }
896

897 898 899 900 901 902 903 904 905 906 907 908
    *stream << "}\n";

    if (!device) {
        if (_tmpFile) {
            stream->flush();
            _tmpFile->seek(0);
        } else {
            file->close();
            delete file;
        }
    }
    delete stream;
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 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966
    return true;
}

bool GraphExporter::savePrompt(QWidget *parent, TraceData *data,
                               TraceFunction *function, EventType *eventType,
                               ProfileContext::Type groupType,
                               CallGraphView* cgv)
{
    // More formats can be added; it's a matter of adding the filter and if
    QFileDialog saveDialog(parent, QObject::tr("Export Graph"));
    saveDialog.setMimeTypeFilters( {"text/vnd.graphviz", "application/pdf", "application/postscript"} );
    saveDialog.setFileMode(QFileDialog::AnyFile);
    saveDialog.setAcceptMode(QFileDialog::AcceptSave);

    if (saveDialog.exec()) {
        QString intendedName = saveDialog.selectedFiles().first();
        if (intendedName.isNull() || intendedName.isEmpty())
            return false;
        bool wrote = false;
        QString dotName, dotRenderType;
        QTemporaryFile maybeTemp;
        maybeTemp.open();
        const QString mime = saveDialog.selectedMimeTypeFilter();
        if (mime == "text/vnd.graphviz") {
            dotName = intendedName;
            dotRenderType = "";
        }
        else if (mime == "application/pdf") {
            dotName = maybeTemp.fileName();
            dotRenderType = "-Tpdf";
        }
        else if (mime == "application/postscript") {
            dotName = maybeTemp.fileName();
            dotRenderType = "-Tps";
        }
        GraphExporter ge(data, function, eventType, groupType, dotName);
        if (cgv != nullptr)
            ge.setGraphOptions(cgv);
        wrote = ge.writeDot();
        if (wrote && mime != "text/vnd.graphviz") {
            QProcess proc;
            proc.setStandardOutputFile(intendedName, QFile::Truncate);
            proc.start("dot", { dotRenderType, dotName }, QProcess::ReadWrite);
            proc.waitForFinished();
            wrote = proc.exitStatus() == QProcess::NormalExit;

            // Open in the default app, except for GraphViz files. The .dot
            // association is usually for Microsoft Word templates and will
            // open a word processor instead, which isn't what we want.
            if (wrote) {
                QDesktopServices::openUrl(QUrl::fromLocalFile(intendedName));
            }
        }

        return wrote;
    }

    return false;
967 968 969 970
}

void GraphExporter::sortEdges()
{
971 972 973 974 975
    GraphNodeMap::Iterator nit;
    for (nit = _nodeMap.begin(); nit != _nodeMap.end(); ++nit ) {
        GraphNode& n = *nit;
        n.sortEdges();
    }
976 977 978 979
}

TraceFunction* GraphExporter::toFunc(QString s)
{
980
    if (s[0] != 'F')
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
981
        return nullptr;
982 983 984
    bool ok;
    TraceFunction* f = (TraceFunction*) s.midRef(1).toULongLong(&ok, 16);
    if (!ok)
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
985
        return nullptr;
986

987
    return f;
988 989 990 991
}

GraphNode* GraphExporter::node(TraceFunction* f)
{
992
    if (!f)
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
993
        return nullptr;
994

995 996
    GraphNodeMap::Iterator it = _nodeMap.find(f);
    if (it == _nodeMap.end())
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
997
        return nullptr;
998

999
    return &(*it);
1000 1001 1002 1003
}

GraphEdge* GraphExporter::edge(TraceFunction* f1, TraceFunction* f2)
{
1004 1005
    GraphEdgeMap::Iterator it = _edgeMap.find(qMakePair(f1, f2));
    if (it == _edgeMap.end())
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
1006
        return nullptr;
1007

1008
    return &(*it);
1009 1010 1011
}

/**
1012
 * We do a DFS and do not stop on already visited nodes/edges,
1013 1014 1015 1016 1017 1018 1019
 * but add up costs. We only stop if limits/max depth is reached.
 *
 * For a node/edge, it can happen that the first time visited the
 * cost will below the limit, so the search is stopped.
 * If on a further visit of the node/edge the limit is reached,
 * we use the whole node/edge cost and continue search.
 */
1020
void GraphExporter::buildGraph(TraceFunction* f, int depth, bool toCallees,
1021
                               double factor)
1022
{
Josef Weidendorfer's avatar
Josef Weidendorfer committed
1023
#if DEBUG_GRAPH
1024 1025
    qDebug() << "buildGraph(" << f->prettyName() << "," << d << "," << factor
             << ") [to " << (toCallees ? "Callees":"Callers") << "]";
Josef Weidendorfer's avatar
Josef Weidendorfer committed
1026
#endif
1027

1028 1029
    double oldIncl = 0.0;
    GraphNode& n = _nodeMap[f];
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
1030
    if (n.function() == nullptr) {
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
        n.setFunction(f);
    } else
        oldIncl = n.incl;

    double incl = f->inclusive()->subCost(_eventType) * factor;
    n.incl += incl;
    n.self += f->subCost(_eventType) * factor;
    if (0)
        qDebug("  Added Incl. %f, now %f", incl, n.incl);

    // A negative depth limit means "unlimited"
    int maxDepth = toCallees ? _go->maxCalleeDepth()
                             : _go->maxCallerDepth();
1044
    // Never go beyond a depth of 100
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 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 1088 1089 1090 1091 1092 1093 1094
    if ((maxDepth < 0) || (maxDepth>100)) maxDepth = 100;
    if (depth >= maxDepth) {
        if (0)
            qDebug("  Cutoff, max depth reached");
        return;
    }

    // if we just reached the limit by summing, do a DFS
    // from here with full incl. cost because of previous cutoffs
    if ((n.incl >= _realFuncLimit) && (oldIncl < _realFuncLimit))
        incl = n.incl;

    if (f->cycle()) {
        // for cycles members, we never stop on first visit, but always on 2nd
        // note: a 2nd visit never should happen, as we do not follow inner-cycle
        //       calls
        if (oldIncl > 0.0) {
            if (0)
                qDebug("  Cutoff, 2nd visit to Cycle Member");
            // and takeback cost addition, as it is added twice
            n.incl = oldIncl;
            n.self -= f->subCost(_eventType) * factor;
            return;
        }
    } else if (incl <= _realFuncLimit) {
        if (0)
            qDebug("  Cutoff, below limit");
        return;
    }

    TraceFunction* f2;

    // on entering a cycle, only go the FunctionCycle
    TraceCallList l = toCallees ? f->callings(false) : f->callers(false);

    foreach(TraceCall* call, l) {

        f2 = toCallees ? call->called(false) : call->caller(false);

        double count = call->callCount() * factor;
        double cost = call->subCost(_eventType) * factor;

        // ignore function calls with absolute cost < 3 per call
        // No: This would skip a lot of functions e.g. with L2 cache misses
        // if (count>0.0 && (cost/count < 3)) continue;

        double oldCost = 0.0;
        QPair<TraceFunction*,TraceFunction*> p(toCallees ? f : f2,
                                               toCallees ? f2 : f);
        GraphEdge& e = _edgeMap[p];
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
1095
        if (e.call() == nullptr) {
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
            e.setCall(call);
            e.setCaller(p.first);
            e.setCallee(p.second);
        } else
            oldCost = e.cost;

        e.cost += cost;
        e.count += count;
        if (0)
            qDebug("  Edge to %s, added cost %f, now %f",
                   qPrintable(f2->prettyName()), cost, e.cost);

        // if this call goes into a FunctionCycle, we also show the real call
        if (f2->cycle() == f2) {
            TraceFunction* realF;
            realF = toCallees ? call->called(true) : call->caller(true);
            QPair<TraceFunction*,TraceFunction*>
                    realP(toCallees ? f : realF, toCallees ? realF : f);
            GraphEdge& e = _edgeMap[realP];
Friedrich W. H. Kossebau's avatar
Friedrich W. H. Kossebau committed
1115
            if (e.call() == nullptr) {
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
                e.setCall(call);
                e.setCaller(realP.first);
                e.setCallee(realP.second);
            }
            e.cost += cost;
            e.count += count;
        }

        // - do not do a DFS on calls in recursion/cycle
        if (call->inCycle()>0)
            continue;
        if (call->isRecursion())
            continue;

        if (toCallees)
            n.addUniqueCallee(&e);
        else
            n.addUniqueCaller(&e);

        // if we just reached the call limit (=func limit by summing, do a DFS
        // from here with full incl. cost because of previous cutoffs
        if ((e.cost >= _realCallLimit) && (oldCost < _realCallLimit))
            cost = e.cost;
        if ((cost <= 0) || (cost <= _realCallLimit)) {
            if (0)
                qDebug("  Edge Cutoff, limit not reached");
            continue;
        }

        SubCost s;
        if (call->inCycle())
            s = f2->cycle()->inclusive()->subCost(_eventType);
        else
            s = f2->inclusive()->subCost(_eventType);
        SubCost v = call->subCost(_eventType);

        // Never recurse if s or v is 0 (can happen with bogus input)
        if ((v == 0) || (s== 0)) continue;

        buildGraph(f2, depth+1, toCallees, factor * v / s);
    }
1157 1158 1159 1160 1161
}

//
// PannerView
//
1162
PanningView::PanningView(QWidget * parent)
1163
    : QGraphicsView(parent)
1164
{
1165
    _movingZoomRect = false;
1166

1167 1168
    // FIXME: Why does this not work?
    viewport()->setFocusPolicy(Qt::NoFocus);
1169 1170
}

1171
void PanningView::setZoomRect(const QRectF& r)
1172
{
1173 1174
    _zoomRect = r;
    viewport()->update();
1175 1176
}

1177
void PanningView::drawForeground(QPainter * p, const QRectF&)
1178
{
1179 1180
    if (!_zoomRect.isValid())
        return;
1181

1182
    QColor red(Qt::red);
1183
    QPen pen(red.darker());
1184 1185
    pen.setWidthF(2.0 / matrix().m11());
    p->setPen(pen);
1186

1187
    QColor c(red.darker());