qmlprofilerdatamodel.cpp 56 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
Christiaan Janssen's avatar
Christiaan Janssen committed
2
**
hjk's avatar
hjk committed
3
4
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
Christiaan Janssen's avatar
Christiaan Janssen committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
Christiaan Janssen's avatar
Christiaan Janssen committed
7
**
hjk's avatar
hjk committed
8
9
10
11
12
13
14
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
Christiaan Janssen's avatar
Christiaan Janssen committed
15
16
**
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
18
19
20
21
22
23
24
25
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
Christiaan Janssen's avatar
Christiaan Janssen committed
26
27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
Christiaan Janssen's avatar
Christiaan Janssen committed
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

#include "qmlprofilerdatamodel.h"

#include <QUrl>
#include <QHash>
#include <QtAlgorithms>
#include <QString>
#include <QStringList>

#include <QFile>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>

#include <QTimer>
#include <utils/qtcassert.h>

45
using namespace QmlDebug;
Christiaan Janssen's avatar
Christiaan Janssen committed
46
47
48
49
50
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
118
119
120
121
122
123
124
125
126

namespace QmlProfiler {
namespace Internal {

///////////////////////////////////////////////////////////
QmlRangeEventData::QmlRangeEventData()
{
    eventType = MaximumQmlEventType;
    eventId = -1;
    duration = 0;
    calls = 0;
    minTime = 0;
    maxTime = 0;
    timePerCall = 0;
    percentOfTime = 0;
    medianTime = 0;
    isBindingLoop = false;
}

QmlRangeEventData::~QmlRangeEventData()
{
    qDeleteAll(parentHash.values());
    parentHash.clear();
    qDeleteAll(childrenHash.values());
    childrenHash.clear();
}

QmlRangeEventData &QmlRangeEventData::operator=(const QmlRangeEventData &ref)
{
    if (this == &ref)
        return *this;

    displayName = ref.displayName;
    location = ref.location;
    eventHashStr = ref.eventHashStr;
    details = ref.details;
    eventType = ref.eventType;
    duration = ref.duration;
    calls = ref.calls;
    minTime = ref.minTime;
    maxTime = ref.maxTime;
    timePerCall = ref.timePerCall;
    percentOfTime = ref.percentOfTime;
    medianTime = ref.medianTime;
    eventId = ref.eventId;
    isBindingLoop = ref.isBindingLoop;

    qDeleteAll(parentHash.values());
    parentHash.clear();
    foreach (const QString &key, ref.parentHash.keys()) {
        parentHash.insert(key, new QmlRangeEventRelative(ref.parentHash.value(key)));
    }

    qDeleteAll(childrenHash.values());
    childrenHash.clear();
    foreach (const QString &key, ref.childrenHash.keys()) {
        childrenHash.insert(key, new QmlRangeEventRelative(ref.childrenHash.value(key)));
    }

    return *this;
}

///////////////////////////////////////////////////////////

// endtimedata
struct QmlRangeEventEndInstance {
    qint64 endTime;
    int startTimeIndex;
    QmlRangeEventData *description;
};

// starttimedata
struct QmlRangeEventStartInstance {
    qint64 startTime;
    qint64 duration;
    qint64 level;
    int endTimeIndex;
    qint64 nestingLevel;
    qint64 nestingDepth;
    QmlRangeEventData *statsInfo;

127
128
    int baseEventIndex;

Christiaan Janssen's avatar
Christiaan Janssen committed
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
    // animation-related data
    int frameRate;
    int animationCount;

    int bindingLoopHead;
};

struct QmlRangeEventTypeCount {
    QVector<int> eventIds;
    int nestingCount;
};

// used by quicksort
bool compareEndTimes(const QmlRangeEventEndInstance &t1, const QmlRangeEventEndInstance &t2)
{
    return t1.endTime < t2.endTime;
}

bool compareStartTimes(const QmlRangeEventStartInstance &t1, const QmlRangeEventStartInstance &t2)
{
    return t1.startTime < t2.startTime;
}

bool compareStartIndexes(const QmlRangeEventEndInstance &t1, const QmlRangeEventEndInstance &t2)
{
    return t1.startTimeIndex < t2.startTimeIndex;
}

//////////////////////////////////////////////////////////////
class QmlProfilerDataModel::QmlProfilerDataModelPrivate
{
public:
    QmlProfilerDataModelPrivate(QmlProfilerDataModel *qq) : q(qq) {}

    QmlProfilerDataModel *q;

    // convenience functions
    void clearQmlRootEvent();
    void insertQmlRootEvent();
    void postProcess();
    void sortEndTimes();
    void findAnimationLimits();
    void sortStartTimes();
    void computeNestingLevels();
    void computeNestingDepth();
    void prepareForDisplay();
    void linkStartsToEnds();
    void linkEndsToStarts();
    bool checkBindingLoop(QmlRangeEventData *from, QmlRangeEventData *current, QList<QmlRangeEventData *>visited);


    // stats
    void clearStatistics();
    void redoTree(qint64 fromTime, qint64 toTime);
    void computeMedianTime(qint64 fromTime, qint64 toTime);
    void findBindingLoops(qint64 fromTime, qint64 toTime);

    QmlProfilerDataModel::State listState;

    // Stored data
    QHash<QString, QmlRangeEventData *> rangeEventDictionary;
    QVector<QmlRangeEventEndInstance> endInstanceList;
    QVector<QmlRangeEventStartInstance> startInstanceList;

    QmlRangeEventData qmlRootEvent;

    QV8ProfilerDataModel *v8DataModel;

    QHash<int, QmlRangeEventTypeCount *> typeCounts;

    qint64 traceEndTime;
    qint64 traceStartTime;
    qint64 qmlMeasuredTime;

203
    int lastFrameEventIndex;
Christiaan Janssen's avatar
Christiaan Janssen committed
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
    qint64 maxAnimationCount;
    qint64 minAnimationCount;

    // file to load
    QString fileName;
};


////////////////////////////////////////////////////////////////////////////////////


QmlProfilerDataModel::QmlProfilerDataModel(QObject *parent) :
    QObject(parent), d(new QmlProfilerDataModelPrivate(this))
{
    setObjectName("QmlProfilerDataModel");

    d->listState = Empty;

    d->traceEndTime = 0;
    d->traceStartTime = -1;
    d->qmlMeasuredTime = 0;
    d->clearQmlRootEvent();
226
    d->lastFrameEventIndex = -1;
Christiaan Janssen's avatar
Christiaan Janssen committed
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
    d->maxAnimationCount = 0;
    d->minAnimationCount = 0;
    d->v8DataModel = new QV8ProfilerDataModel(this, this);
}

QmlProfilerDataModel::~QmlProfilerDataModel()
{
    clear();
    delete d;
}

////////////////////////////////////////////////////////////////////////////////////
QList<QmlRangeEventData *> QmlProfilerDataModel::getEventDescriptions() const
{
    return d->rangeEventDictionary.values();
}

QmlRangeEventData *QmlProfilerDataModel::eventDescription(int eventId) const
{
    foreach (QmlRangeEventData *event, d->rangeEventDictionary.values()) {
        if (event->eventId == eventId)
            return event;
    }
    return 0;
}

QList<QV8EventData *> QmlProfilerDataModel::getV8Events() const
{
    return d->v8DataModel->getV8Events();
}

QV8EventData *QmlProfilerDataModel::v8EventDescription(int eventId) const
{
    return d->v8DataModel->v8EventDescription(eventId);
}

////////////////////////////////////////////////////////////////////////////////////

void QmlProfilerDataModel::clear()
{
    qDeleteAll(d->rangeEventDictionary.values());
    d->rangeEventDictionary.clear();

    d->endInstanceList.clear();
    d->startInstanceList.clear();

    d->clearQmlRootEvent();

    foreach (QmlRangeEventTypeCount *typeCount, d->typeCounts.values())
        delete typeCount;
    d->typeCounts.clear();

    d->traceEndTime = 0;
    d->traceStartTime = -1;
    d->qmlMeasuredTime = 0;

283
    d->lastFrameEventIndex = -1;
Christiaan Janssen's avatar
Christiaan Janssen committed
284
285
286
287
288
289
290
291
292
    d->maxAnimationCount = 0;
    d->minAnimationCount = 0;

    d->v8DataModel->clear();

    emit countChanged();
    setState(Empty);
}

293
294
295
296
297
void QmlProfilerDataModel::prepareForWriting()
{
    setState(AcquiringData);
}

298
299
void QmlProfilerDataModel::addRangedEvent(int type, int bindingType, qint64 startTime,
                                          qint64 length, const QStringList &data,
300
                                          const QmlDebug::QmlEventLocation &location)
Christiaan Janssen's avatar
Christiaan Janssen committed
301
302
303
{
    const QChar colon = QLatin1Char(':');
    QString displayName, eventHashStr, details;
304
    QmlDebug::QmlEventLocation eventLocation = location;
Christiaan Janssen's avatar
Christiaan Janssen committed
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323

    setState(AcquiringData);

    // generate details string
    if (data.isEmpty())
        details = tr("Source code not available");
    else {
        details = data.join(" ").replace('\n'," ").simplified();
        QRegExp rewrite("\\(function \\$(\\w+)\\(\\) \\{ (return |)(.+) \\}\\)");
        bool match = rewrite.exactMatch(details);
        if (match) {
            details = rewrite.cap(1) + ": " + rewrite.cap(3);
        }
        if (details.startsWith(QString("file://")))
            details = details.mid(details.lastIndexOf(QChar('/')) + 1);
    }

    // backwards compatibility: "compiling" events don't have a proper location in older
    // version of the protocol, but the filename is passed in the details string
324
    if (type == QmlDebug::Compiling && eventLocation.filename.isEmpty()) {
Christiaan Janssen's avatar
Christiaan Janssen committed
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
        eventLocation.filename = details;
        eventLocation.line = 1;
        eventLocation.column = 1;
    }

    // generate hash
    if (eventLocation.filename.isEmpty()) {
        displayName = tr("<bytecode>");
        eventHashStr = getHashStringForQmlEvent(eventLocation, type);
    } else {
        const QString filePath = QUrl(eventLocation.filename).path();
        displayName = filePath.mid(filePath.lastIndexOf(QChar('/')) + 1) + colon +
                QString::number(eventLocation.line);
        eventHashStr = getHashStringForQmlEvent(eventLocation, type);
    }

    QmlRangeEventData *newEvent;
    if (d->rangeEventDictionary.contains(eventHashStr)) {
        newEvent = d->rangeEventDictionary[eventHashStr];
    } else {
        newEvent = new QmlRangeEventData;
        newEvent->displayName = displayName;
        newEvent->location = eventLocation;
        newEvent->eventHashStr = eventHashStr;
349
        newEvent->eventType = (QmlDebug::QmlEventType)type;
Christiaan Janssen's avatar
Christiaan Janssen committed
350
        newEvent->details = details;
351
        newEvent->bindingType = bindingType;
Christiaan Janssen's avatar
Christiaan Janssen committed
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
        d->rangeEventDictionary.insert(eventHashStr, newEvent);
    }

    QmlRangeEventEndInstance endTimeData;
    endTimeData.endTime = startTime + length;
    endTimeData.description = newEvent;
    endTimeData.startTimeIndex = d->startInstanceList.count();

    QmlRangeEventStartInstance startTimeData;
    startTimeData.startTime = startTime;
    startTimeData.duration = length;
    startTimeData.statsInfo = newEvent;
    startTimeData.endTimeIndex = d->endInstanceList.count();
    startTimeData.animationCount = -1;
    startTimeData.frameRate = 1e9/length;
367
    startTimeData.baseEventIndex = d->startInstanceList.count(); // point to itself by default
Christiaan Janssen's avatar
Christiaan Janssen committed
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

    d->endInstanceList << endTimeData;
    d->startInstanceList << startTimeData;

    emit countChanged();
}

void QmlProfilerDataModel::addV8Event(int depth, const QString &function,
                                      const QString &filename, int lineNumber,
                                      double totalTime, double selfTime)
{
    d->v8DataModel->addV8Event(depth, function, filename, lineNumber, totalTime, selfTime);
}

void QmlProfilerDataModel::addFrameEvent(qint64 time, int framerate, int animationcount)
{
    QString displayName, eventHashStr, details;

    setState(AcquiringData);

    details = tr("Animation Timer Update");
    displayName = tr("<Animation Update>");
    eventHashStr = displayName;

    QmlRangeEventData *newEvent;
    if (d->rangeEventDictionary.contains(eventHashStr)) {
        newEvent = d->rangeEventDictionary[eventHashStr];
    } else {
        newEvent = new QmlRangeEventData;
        newEvent->displayName = displayName;
        newEvent->eventHashStr = eventHashStr;
399
        newEvent->eventType = QmlDebug::Painting;
Christiaan Janssen's avatar
Christiaan Janssen committed
400
401
402
403
404
405
        newEvent->details = details;
        d->rangeEventDictionary.insert(eventHashStr, newEvent);
    }

    qint64 length = 1e9/framerate;
    // avoid overlap
406
407
408
409
410
411
412
413
    QmlRangeEventStartInstance *lastFrameEvent = 0;
    if (d->lastFrameEventIndex > -1) {
        lastFrameEvent = &d->startInstanceList[d->lastFrameEventIndex];
        if (lastFrameEvent->startTime + lastFrameEvent->duration >= time) {
            lastFrameEvent->duration = time - 1 - lastFrameEvent->startTime;
            d->endInstanceList[lastFrameEvent->endTimeIndex].endTime =
                    lastFrameEvent->startTime + lastFrameEvent->duration;
        }
Christiaan Janssen's avatar
Christiaan Janssen committed
414
415
416
417
418
419
420
421
422
423
424
425
426
427
    }

    QmlRangeEventEndInstance endTimeData;
    endTimeData.endTime = time + length;
    endTimeData.description = newEvent;
    endTimeData.startTimeIndex = d->startInstanceList.count();

    QmlRangeEventStartInstance startTimeData;
    startTimeData.startTime = time;
    startTimeData.duration = length;
    startTimeData.statsInfo = newEvent;
    startTimeData.endTimeIndex = d->endInstanceList.count();
    startTimeData.animationCount = animationcount;
    startTimeData.frameRate = framerate;
428
    startTimeData.baseEventIndex = d->startInstanceList.count(); // point to itself by default
Christiaan Janssen's avatar
Christiaan Janssen committed
429
430
431
432

    d->endInstanceList << endTimeData;
    d->startInstanceList << startTimeData;

433
    d->lastFrameEventIndex = d->startInstanceList.count() - 1;
Christiaan Janssen's avatar
Christiaan Janssen committed
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450

    emit countChanged();
}

void QmlProfilerDataModel::setTraceEndTime(qint64 time)
{
    d->traceEndTime = time;
}

void QmlProfilerDataModel::setTraceStartTime(qint64 time)
{
    d->traceStartTime = time;
}

////////////////////////////////////////////////////////////////////////////////////

QString QmlProfilerDataModel::getHashStringForQmlEvent(
451
        const QmlDebug::QmlEventLocation &location, int eventType)
Christiaan Janssen's avatar
Christiaan Janssen committed
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
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
{
    return QString("%1:%2:%3:%4").arg(location.filename,
                                      QString::number(location.line),
                                      QString::number(location.column),
                                      QString::number(eventType));
}

QString QmlProfilerDataModel::getHashStringForV8Event(const QString &displayName,
                                                      const QString &function)
{
    return QString("%1:%2").arg(displayName, function);
}

QString QmlProfilerDataModel::rootEventName()
{
    return tr("<program>");
}

QString QmlProfilerDataModel::rootEventDescription()
{
    return tr("Main Program");
}

QString QmlProfilerDataModel::qmlEventTypeAsString(QmlEventType typeEnum)
{
    switch (typeEnum) {
    case Painting:
        return QLatin1String(Constants::TYPE_PAINTING_STR);
        break;
    case Compiling:
        return QLatin1String(Constants::TYPE_COMPILING_STR);
        break;
    case Creating:
        return QLatin1String(Constants::TYPE_CREATING_STR);
        break;
    case Binding:
        return QLatin1String(Constants::TYPE_BINDING_STR);
        break;
    case HandlingSignal:
        return QLatin1String(Constants::TYPE_HANDLINGSIGNAL_STR);
        break;
    default:
        return QString::number((int)typeEnum);
    }
}

QmlEventType QmlProfilerDataModel::qmlEventTypeAsEnum(const QString &typeString)
{
    if (typeString == QLatin1String(Constants::TYPE_PAINTING_STR)) {
        return Painting;
    } else if (typeString == QLatin1String(Constants::TYPE_COMPILING_STR)) {
        return Compiling;
    } else if (typeString == QLatin1String(Constants::TYPE_CREATING_STR)) {
        return Creating;
    } else if (typeString == QLatin1String(Constants::TYPE_BINDING_STR)) {
        return Binding;
    } else if (typeString == QLatin1String(Constants::TYPE_HANDLINGSIGNAL_STR)) {
        return HandlingSignal;
    } else {
        bool isNumber = false;
        int type = typeString.toUInt(&isNumber);
        if (isNumber) {
            return (QmlEventType)type;
        } else {
            return MaximumQmlEventType;
        }
    }
}

////////////////////////////////////////////////////////////////////////////////////

int QmlProfilerDataModel::findFirstIndex(qint64 startTime) const
{
    int candidate = -1;
    // in the "endtime" list, find the first event that ends after startTime
    if (d->endInstanceList.isEmpty())
        return 0; // -1
    if (d->endInstanceList.count() == 1 || d->endInstanceList.first().endTime >= startTime)
        candidate = 0;
    else
        if (d->endInstanceList.last().endTime <= startTime)
            return 0; // -1

    if (candidate == -1)
    {
        int fromIndex = 0;
        int toIndex = d->endInstanceList.count()-1;
        while (toIndex - fromIndex > 1) {
            int midIndex = (fromIndex + toIndex)/2;
            if (d->endInstanceList[midIndex].endTime < startTime)
                fromIndex = midIndex;
            else
                toIndex = midIndex;
        }

        candidate = toIndex;
    }

550
551
    int eventIndex = d->endInstanceList[candidate].startTimeIndex;
    return d->startInstanceList[eventIndex].baseEventIndex;
Christiaan Janssen's avatar
Christiaan Janssen committed
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
}

int QmlProfilerDataModel::findFirstIndexNoParents(qint64 startTime) const
{
    int candidate = -1;
    // in the "endtime" list, find the first event that ends after startTime
    if (d->endInstanceList.isEmpty())
        return 0; // -1
    if (d->endInstanceList.count() == 1 || d->endInstanceList.first().endTime >= startTime)
        candidate = 0;
    else
        if (d->endInstanceList.last().endTime <= startTime)
            return 0; // -1

    if (candidate == -1) {
        int fromIndex = 0;
        int toIndex = d->endInstanceList.count()-1;
        while (toIndex - fromIndex > 1) {
            int midIndex = (fromIndex + toIndex)/2;
            if (d->endInstanceList[midIndex].endTime < startTime)
                fromIndex = midIndex;
            else
                toIndex = midIndex;
        }

        candidate = toIndex;
    }

    int ndx = d->endInstanceList[candidate].startTimeIndex;

    return ndx;
}

int QmlProfilerDataModel::findLastIndex(qint64 endTime) const
{
    // in the "starttime" list, find the last event that starts before endtime
    if (d->startInstanceList.isEmpty())
        return 0; // -1
    if (d->startInstanceList.first().startTime >= endTime)
        return 0; // -1
    if (d->startInstanceList.count() == 1)
        return 0;
    if (d->startInstanceList.last().startTime <= endTime)
        return d->startInstanceList.count()-1;

    int fromIndex = 0;
    int toIndex = d->startInstanceList.count()-1;
    while (toIndex - fromIndex > 1) {
        int midIndex = (fromIndex + toIndex)/2;
        if (d->startInstanceList[midIndex].startTime < endTime)
            fromIndex = midIndex;
        else
            toIndex = midIndex;
    }

    return fromIndex;
}

qint64 QmlProfilerDataModel::firstTimeMark() const
{
    if (d->startInstanceList.isEmpty())
        return 0;
    else {
        return d->startInstanceList[0].startTime;
    }
}

qint64 QmlProfilerDataModel::lastTimeMark() const
{
    if (d->endInstanceList.isEmpty())
        return 0;
    else {
        return d->endInstanceList.last().endTime;
    }
}

////////////////////////////////////////////////////////////////////////////////////

int QmlProfilerDataModel::count() const
{
    return d->startInstanceList.count();
}

bool QmlProfilerDataModel::isEmpty() const
{
    return d->startInstanceList.isEmpty() && d->v8DataModel->isEmpty();
}

qint64 QmlProfilerDataModel::getStartTime(int index) const
{
    return d->startInstanceList[index].startTime;
}

qint64 QmlProfilerDataModel::getEndTime(int index) const
{
    return d->startInstanceList[index].startTime + d->startInstanceList[index].duration;
}

qint64 QmlProfilerDataModel::getDuration(int index) const
{
    return d->startInstanceList[index].duration;
}

int QmlProfilerDataModel::getType(int index) const
{
    return d->startInstanceList[index].statsInfo->eventType;
}

int QmlProfilerDataModel::getNestingLevel(int index) const
{
    return d->startInstanceList[index].nestingLevel;
}

int QmlProfilerDataModel::getNestingDepth(int index) const
{
    return d->startInstanceList[index].nestingDepth;
}

QString QmlProfilerDataModel::getFilename(int index) const
{
    return d->startInstanceList[index].statsInfo->location.filename;
}

int QmlProfilerDataModel::getLine(int index) const
{
    return d->startInstanceList[index].statsInfo->location.line;
}

int QmlProfilerDataModel::getColumn(int index) const
{
    return d->startInstanceList[index].statsInfo->location.column;
}

QString QmlProfilerDataModel::getDetails(int index) const
{
    // special: animations
688
    if (d->startInstanceList[index].statsInfo->eventType == QmlDebug::Painting &&
Christiaan Janssen's avatar
Christiaan Janssen committed
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
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
748
749
750
751
752
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
792
793
794
795
796
797
798
799
800
801
802
803
804
            d->startInstanceList[index].animationCount >= 0)
        return tr("%1 animations at %2 FPS").arg(
                    QString::number(d->startInstanceList[index].animationCount),
                    QString::number(d->startInstanceList[index].frameRate));
    return d->startInstanceList[index].statsInfo->details;
}

int QmlProfilerDataModel::getEventId(int index) const
{
    return d->startInstanceList[index].statsInfo->eventId;
}

int QmlProfilerDataModel::getBindingLoopDest(int index) const
{
    return d->startInstanceList[index].bindingLoopHead;
}

int QmlProfilerDataModel::getFramerate(int index) const
{
    return d->startInstanceList[index].frameRate;
}

int QmlProfilerDataModel::getAnimationCount(int index) const
{
    return d->startInstanceList[index].animationCount;
}

int QmlProfilerDataModel::getMaximumAnimationCount() const
{
    return d->maxAnimationCount;
}

int QmlProfilerDataModel::getMinimumAnimationCount() const
{
    return d->minAnimationCount;
}

/////////////////////////////////////////

int QmlProfilerDataModel::uniqueEventsOfType(int type) const
{
    if (!d->typeCounts.contains(type))
        return 0;
    return d->typeCounts[type]->eventIds.count();
}

int QmlProfilerDataModel::maxNestingForType(int type) const
{
    if (!d->typeCounts.contains(type))
        return 0;
    return d->typeCounts[type]->nestingCount;
}

QString QmlProfilerDataModel::eventTextForType(int type, int index) const
{
    if (!d->typeCounts.contains(type))
        return QString();
    return d->rangeEventDictionary.values().at(d->typeCounts[type]->eventIds[index])->details;
}

QString QmlProfilerDataModel::eventDisplayNameForType(int type, int index) const
{
    if (!d->typeCounts.contains(type))
        return QString();
    return d->rangeEventDictionary.values().at(d->typeCounts[type]->eventIds[index])->displayName;
}

int QmlProfilerDataModel::eventIdForType(int type, int index) const
{
    if (!d->typeCounts.contains(type))
        return -1;
    return d->typeCounts[type]->eventIds[index];
}

int QmlProfilerDataModel::eventPosInType(int index) const
{
    int eventType = d->startInstanceList[index].statsInfo->eventType;
    return d->typeCounts[eventType]->eventIds.indexOf(d->startInstanceList[index].statsInfo->eventId);
}

/////////////////////////////////////////

qint64 QmlProfilerDataModel::traceStartTime() const
{
    return d->traceStartTime != -1? d->traceStartTime : firstTimeMark();
}

qint64 QmlProfilerDataModel::traceEndTime() const
{
    return d->traceEndTime ? d->traceEndTime : lastTimeMark();
}

qint64 QmlProfilerDataModel::traceDuration() const
{
    return traceEndTime() - traceStartTime();
}

qint64 QmlProfilerDataModel::qmlMeasuredTime() const
{
    return d->qmlMeasuredTime;
}
qint64 QmlProfilerDataModel::v8MeasuredTime() const
{
    return d->v8DataModel->v8MeasuredTime();
}

////////////////////////////////////////////////////////////////////////////////////

void QmlProfilerDataModel::complete()
{
    if (currentState() == AcquiringData) {
        setState(ProcessingData);
        d->v8DataModel->collectV8Statistics();
        d->postProcess();
    } else
    if (currentState() == Empty) {
805
806
        d->v8DataModel->collectV8Statistics();
        compileStatistics(traceStartTime(), traceEndTime());
Christiaan Janssen's avatar
Christiaan Janssen committed
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
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
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
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
941
942
943
944
945
946
947
948
949
        setState(Done);
    } else {
        emit error("Unexpected complete signal in data model");
    }
}

void QmlProfilerDataModel::QmlProfilerDataModelPrivate::postProcess()
{
    if (q->count() != 0) {
        sortStartTimes();
        sortEndTimes();
        findAnimationLimits();
        computeNestingLevels();
        computeNestingDepth();
        linkEndsToStarts();
        insertQmlRootEvent();
        q->reloadDetails();
        prepareForDisplay();
        q->compileStatistics(q->traceStartTime(), q->traceEndTime());
    }
    q->setState(Done);
}


void QmlProfilerDataModel::QmlProfilerDataModelPrivate::prepareForDisplay()
{
    // generate numeric ids
    int ndx = 0;
    foreach (QmlRangeEventData *binding, rangeEventDictionary.values()) {
        binding->eventId = ndx++;
    }

    // collect type counts
    foreach (const QmlRangeEventStartInstance &eventStartData, startInstanceList) {
        int typeNumber = eventStartData.statsInfo->eventType;
        if (!typeCounts.contains(typeNumber)) {
            typeCounts[typeNumber] = new QmlRangeEventTypeCount;
            typeCounts[typeNumber]->nestingCount = 0;
        }
        if (eventStartData.nestingLevel > typeCounts[typeNumber]->nestingCount) {
            typeCounts[typeNumber]->nestingCount = eventStartData.nestingLevel;
        }
        if (!typeCounts[typeNumber]->eventIds.contains(eventStartData.statsInfo->eventId))
            typeCounts[typeNumber]->eventIds << eventStartData.statsInfo->eventId;
    }
}

void QmlProfilerDataModel::QmlProfilerDataModelPrivate::sortStartTimes()
{
    if (startInstanceList.count() < 2)
        return;

    // assuming startTimes is partially sorted
    // identify blocks of events and sort them with quicksort
    QVector<QmlRangeEventStartInstance>::iterator itFrom = startInstanceList.end() - 2;
    QVector<QmlRangeEventStartInstance>::iterator itTo = startInstanceList.end() - 1;

    while (itFrom != startInstanceList.begin() && itTo != startInstanceList.begin()) {
        // find block to sort
        while (itFrom != startInstanceList.begin()
                && itTo->startTime > itFrom->startTime) {
            itTo--;
            itFrom = itTo - 1;
        }

        // if we're at the end of the list
        if (itFrom == startInstanceList.begin())
            break;

        // find block length
        while (itFrom != startInstanceList.begin()
                && itTo->startTime <= itFrom->startTime)
            itFrom--;

        if (itTo->startTime <= itFrom->startTime)
            qSort(itFrom, itTo + 1, compareStartTimes);
        else
            qSort(itFrom + 1, itTo + 1, compareStartTimes);

        // move to next block
        itTo = itFrom;
        itFrom = itTo - 1;
    }

    // link back the endTimes
    linkEndsToStarts();
}

void QmlProfilerDataModel::QmlProfilerDataModelPrivate::sortEndTimes()
{
    // assuming endTimes is partially sorted
    // identify blocks of events and sort them with quicksort

    if (endInstanceList.count() < 2)
        return;

    QVector<QmlRangeEventEndInstance>::iterator itFrom = endInstanceList.begin();
    QVector<QmlRangeEventEndInstance>::iterator itTo = endInstanceList.begin() + 1;

    while (itTo != endInstanceList.end() && itFrom != endInstanceList.end()) {
        // find block to sort
        while (itTo != endInstanceList.end()
                && startInstanceList[itTo->startTimeIndex].startTime >
                startInstanceList[itFrom->startTimeIndex].startTime +
                startInstanceList[itFrom->startTimeIndex].duration) {
            itFrom++;
            itTo = itFrom+1;
        }

        // if we're at the end of the list
        if (itTo == endInstanceList.end())
            break;

        // find block length
        while (itTo != endInstanceList.end()
                && startInstanceList[itTo->startTimeIndex].startTime <=
                startInstanceList[itFrom->startTimeIndex].startTime +
                startInstanceList[itFrom->startTimeIndex].duration)
            itTo++;

        // sort block
        qSort(itFrom, itTo, compareEndTimes);

        // move to next block
        itFrom = itTo;
        itTo = itFrom+1;

    }

    // link back the startTimes
    linkStartsToEnds();
}

void QmlProfilerDataModel::QmlProfilerDataModelPrivate::linkStartsToEnds()
{
    for (int i = 0; i < endInstanceList.count(); i++)
        startInstanceList[endInstanceList[i].startTimeIndex].endTimeIndex = i;
}

void QmlProfilerDataModel::QmlProfilerDataModelPrivate::findAnimationLimits()
{
    maxAnimationCount = 0;
    minAnimationCount = 0;
950
    lastFrameEventIndex = -1;
Christiaan Janssen's avatar
Christiaan Janssen committed
951
952

    for (int i = 0; i < startInstanceList.count(); i++) {
953
        if (startInstanceList[i].statsInfo->eventType == QmlDebug::Painting &&
Christiaan Janssen's avatar
Christiaan Janssen committed
954
955
                startInstanceList[i].animationCount >= 0) {
            int animationcount = startInstanceList[i].animationCount;
956
            if (lastFrameEventIndex > -1) {
Christiaan Janssen's avatar
Christiaan Janssen committed
957
958
959
960
961
962
963
964
                if (animationcount > maxAnimationCount)
                    maxAnimationCount = animationcount;
                if (animationcount < minAnimationCount)
                    minAnimationCount = animationcount;
            } else {
                maxAnimationCount = animationcount;
                minAnimationCount = animationcount;
            }
965
            lastFrameEventIndex = i;
Christiaan Janssen's avatar
Christiaan Janssen committed
966
967
968
969
970
971
972
973
974
975
976
977
        }
    }
}

void QmlProfilerDataModel::QmlProfilerDataModelPrivate::computeNestingLevels()
{
    // compute levels
    QHash<int, qint64> endtimesPerLevel;
    QList<int> nestingLevels;
    QList< QHash<int, qint64> > endtimesPerNestingLevel;
    int level = Constants::QML_MIN_LEVEL;
    endtimesPerLevel[Constants::QML_MIN_LEVEL] = 0;
978
979
    int lastBaseEventIndex = 0;
    qint64 lastBaseEventEndTime = traceStartTime;
Christiaan Janssen's avatar
Christiaan Janssen committed
980

981
    for (int i = 0; i < QmlDebug::MaximumQmlEventType; i++) {
Christiaan Janssen's avatar
Christiaan Janssen committed
982
983
984
985
986
987
988
989
990
991
        nestingLevels << Constants::QML_MIN_LEVEL;
        QHash<int, qint64> dummyHash;
        dummyHash[Constants::QML_MIN_LEVEL] = 0;
        endtimesPerNestingLevel << dummyHash;
    }

    for (int i=0; i<startInstanceList.count(); i++) {
        qint64 st = startInstanceList[i].startTime;
        int type = startInstanceList[i].statsInfo->eventType;

992
        if (type == QmlDebug::Painting) {
Christiaan Janssen's avatar
Christiaan Janssen committed
993
994
995
996
            // animation/paint events have level 0 by definition (same as "mainprogram"),
            // but are not considered parents of other events for statistical purposes
            startInstanceList[i].level = Constants::QML_MIN_LEVEL - 1;
            startInstanceList[i].nestingLevel = Constants::QML_MIN_LEVEL;
997
998
999
1000
1001
            if (lastBaseEventEndTime < startInstanceList[i].startTime) {
                lastBaseEventIndex = i;
                lastBaseEventEndTime = startInstanceList[i].startTime + startInstanceList[i].duration;
            }
            startInstanceList[i].baseEventIndex = lastBaseEventIndex;
Christiaan Janssen's avatar
Christiaan Janssen committed
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
            continue;
        }

        // general level
        if (endtimesPerLevel[level] > st) {
            level++;
        } else {
            while (level > Constants::QML_MIN_LEVEL && endtimesPerLevel[level-1] <= st)
                level--;
        }
        endtimesPerLevel[level] = st + startInstanceList[i].duration;

        // per type
        if (endtimesPerNestingLevel[type][nestingLevels[type]] > st) {
            nestingLevels[type]++;
        } else {
            while (nestingLevels[type] > Constants::QML_MIN_LEVEL &&
                   endtimesPerNestingLevel[type][nestingLevels[type]-1] <= st)
                nestingLevels[type]--;
        }
        endtimesPerNestingLevel[type][nestingLevels[type]] =
                st + startInstanceList[i].duration;

        startInstanceList[i].level = level;
        startInstanceList[i].nestingLevel = nestingLevels[type];

        if (level == Constants::QML_MIN_LEVEL) {
            qmlMeasuredTime += startInstanceList[i].duration;
1030
1031
1032
1033
            if (lastBaseEventEndTime < startInstanceList[i].startTime) {
                lastBaseEventIndex = i;
                lastBaseEventEndTime = startInstanceList[i].startTime + startInstanceList[i].duration;
            }
Christiaan Janssen's avatar
Christiaan Janssen committed
1034
        }
1035
        startInstanceList[i].baseEventIndex = lastBaseEventIndex;
Christiaan Janssen's avatar
Christiaan Janssen committed
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
    }
}

void QmlProfilerDataModel::QmlProfilerDataModelPrivate::computeNestingDepth()
{
    QHash<int, int> nestingDepth;
    for (int i = 0; i < endInstanceList.count(); i++) {
        int type = endInstanceList[i].description->eventType;
        int nestingInType = startInstanceList[endInstanceList[i].startTimeIndex].nestingLevel;
        if (!nestingDepth.contains(type))
            nestingDepth[type] = nestingInType;
        else {
            int nd = nestingDepth[type];
            nestingDepth[type] = nd > nestingInType ? nd : nestingInType;
        }

        startInstanceList[endInstanceList[i].startTimeIndex].nestingDepth = nestingDepth[type];
        if (nestingInType == Constants::QML_MIN_LEVEL)
            nestingDepth[type] = Constants::QML_MIN_LEVEL;
    }
}

void QmlProfilerDataModel::QmlProfilerDataModelPrivate::linkEndsToStarts()
{
    for (int i = 0; i < startInstanceList.count(); i++)
        endInstanceList[startInstanceList[i].endTimeIndex].startTimeIndex = i;
}

////////////////////////////////////////////////////////////////////////////////////

void QmlProfilerDataModel::compileStatistics(qint64 startTime, qint64 endTime)
{
    d->clearStatistics();
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
    if (traceDuration() > 0) {
        if (count() > 0) {
            d->redoTree(startTime, endTime);
            d->computeMedianTime(startTime, endTime);
            d->findBindingLoops(startTime, endTime);
        } else {
            d->insertQmlRootEvent();
            QmlRangeEventData *listedRootEvent = d->rangeEventDictionary.value(rootEventName());
            listedRootEvent->calls = 1;
            listedRootEvent->percentOfTime = 100;
        }
    }
Christiaan Janssen's avatar
Christiaan Janssen committed
1081
1082
1083
1084
1085
1086
1087
1088
}

void QmlProfilerDataModel::QmlProfilerDataModelPrivate::clearStatistics()
{
    // clear existing statistics
    foreach (QmlRangeEventData *eventDescription, rangeEventDictionary.values()) {
        eventDescription->calls = 0;
        // maximum possible value
1089
        eventDescription->minTime = traceEndTime;
Christiaan Janssen's avatar
Christiaan Janssen committed
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
        eventDescription->maxTime = 0;
        eventDescription->medianTime = 0;
        eventDescription->duration = 0;
        qDeleteAll(eventDescription->parentHash);
        qDeleteAll(eventDescription->childrenHash);
        eventDescription->parentHash.clear();
        eventDescription->childrenHash.clear();
    }
}

void QmlProfilerDataModel::QmlProfilerDataModelPrivate::redoTree(qint64 fromTime,
                                                                 qint64 toTime)
{
    double totalTime = 0;
    int fromIndex = q->findFirstIndex(fromTime);
    int toIndex = q->findLastIndex(toTime);

    QmlRangeEventData *listedRootEvent = rangeEventDictionary.value(rootEventName());
    QTC_ASSERT(listedRootEvent, /**/);

    // compute parent-child relationship and call count
    QHash<int, QmlRangeEventData*> lastParent;
    for (int index = fromIndex; index <= toIndex; index++) {
        QmlRangeEventData *eventDescription = startInstanceList[index].statsInfo;

        if (startInstanceList[index].startTime > toTime ||
                startInstanceList[index].startTime+startInstanceList[index].duration < fromTime) {
            continue;
        }

1120
        if (eventDescription->eventType == QmlDebug::Painting) {
Christiaan Janssen's avatar
Christiaan Janssen committed
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
1157
1158
1159
1160
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
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
            // skip animation/paint events
            continue;
        }

        eventDescription->calls++;
        qint64 duration = startInstanceList[index].duration;
        eventDescription->duration += duration;
        if (eventDescription->maxTime < duration)
            eventDescription->maxTime = duration;
        if (eventDescription->minTime > duration)
            eventDescription->minTime = duration;

        int level = startInstanceList[index].level;

        QmlRangeEventData *parentEvent = listedRootEvent;
        if (level > Constants::QML_MIN_LEVEL && lastParent.contains(level-1)) {
            parentEvent = lastParent[level-1];
        }

        if (!eventDescription->parentHash.contains(parentEvent->eventHashStr)) {
            QmlRangeEventRelative *newParentEvent = new QmlRangeEventRelative(parentEvent);
            newParentEvent->calls = 1;
            newParentEvent->duration = duration;

            eventDescription->parentHash.insert(parentEvent->eventHashStr, newParentEvent);
        } else {
            QmlRangeEventRelative *newParentEvent =
                    eventDescription->parentHash.value(parentEvent->eventHashStr);
            newParentEvent->duration += duration;
            newParentEvent->calls++;
        }

        if (!parentEvent->childrenHash.contains(eventDescription->eventHashStr)) {
            QmlRangeEventRelative *newChildEvent = new QmlRangeEventRelative(eventDescription);
            newChildEvent->calls = 1;
            newChildEvent->duration = duration;

            parentEvent->childrenHash.insert(eventDescription->eventHashStr, newChildEvent);
        } else {
            QmlRangeEventRelative *newChildEvent =
                    parentEvent->childrenHash.value(eventDescription->eventHashStr);
            newChildEvent->duration += duration;
            newChildEvent->calls++;
        }

        lastParent[level] = eventDescription;

        if (level == Constants::QML_MIN_LEVEL) {
            totalTime += duration;
        }
    }

    // fake rootEvent statistics
    // the +1 nanosecond is to force it to be on top of the sorted list
    listedRootEvent->duration = totalTime+1;
    listedRootEvent->minTime = totalTime+1;
    listedRootEvent->maxTime = totalTime+1;
    listedRootEvent->medianTime = totalTime+1;
    if (totalTime > 0)
        listedRootEvent->calls = 1;

    // copy to the global root reference
    qmlRootEvent = *listedRootEvent;

    // compute percentages
    foreach (QmlRangeEventData *binding, rangeEventDictionary.values()) {
        binding->percentOfTime = binding->duration * 100.0 / totalTime;
        binding->timePerCall = binding->calls > 0 ? double(binding->duration) / binding->calls : 0;
    }
}

void QmlProfilerDataModel::QmlProfilerDataModelPrivate::computeMedianTime(qint64 fromTime,
                                                                          qint64 toTime)
{
    int fromIndex = q->findFirstIndex(fromTime);
    int toIndex = q->findLastIndex(toTime);

    // compute median time
    QHash< QmlRangeEventData* , QList<qint64> > durationLists;
    for (int index = fromIndex; index <= toIndex; index++) {
        QmlRangeEventData *desc = startInstanceList[index].statsInfo;
        qint64 len = startInstanceList[index].duration;
        durationLists[desc].append(len);
    }
    QMutableHashIterator < QmlRangeEventData* , QList<qint64> > iter(durationLists);
    while (iter.hasNext()) {
        iter.next();
        if (!iter.value().isEmpty()) {
            qSort(iter.value());
            iter.key()->medianTime = iter.value().at(iter.value().count()/2);
        }
    }
}

void QmlProfilerDataModel::QmlProfilerDataModelPrivate::findBindingLoops(qint64 fromTime,
                                                                         qint64 toTime)
{
    int fromIndex = q->findFirstIndex(fromTime);
    int toIndex = q->findLastIndex(toTime);

    // first clear existing data
    foreach (QmlRangeEventData *event, rangeEventDictionary.values()) {
        event->isBindingLoop = false;
        foreach (QmlRangeEventRelative *parentEvent, event->parentHash.values())
            parentEvent->inLoopPath = false;
        foreach (QmlRangeEventRelative *childEvent, event->childrenHash.values())
            childEvent->inLoopPath = false;
    }

    QList<QmlRangeEventData *> stackRefs;
    QList<QmlRangeEventStartInstance *> stack;

    for (int i = 0; i < startInstanceList.count(); i++) {
        QmlRangeEventData *currentEvent = startInstanceList[i].statsInfo;
        QmlRangeEventStartInstance *inTimeEvent = &startInstanceList[i];
        inTimeEvent->bindingLoopHead = -1;

1238
1239
1240
1241
        // special: skip animation events (but not old paint events)
        if (inTimeEvent->statsInfo->eventType == Painting && inTimeEvent->animationCount >= 0)
            continue;

Christiaan Janssen's avatar
Christiaan Janssen committed
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
        // managing call stack
        for (int j = stack.count() - 1; j >= 0; j--) {
            if (stack[j]->startTime + stack[j]->duration <= inTimeEvent->startTime) {
                stack.removeAt(j);
                stackRefs.removeAt(j);
            }
        }

        bool loopDetected = stackRefs.contains(currentEvent);
        stack << inTimeEvent;
        stackRefs << currentEvent;

        if (loopDetected) {
            if (i >= fromIndex && i <= toIndex) {
                // for the statistics
                currentEvent->isBindingLoop = true;
                for (int j = stackRefs.indexOf(currentEvent); j < stackRefs.count()-1; j++) {
                    QmlRangeEventRelative *nextEventSub =
                            stackRefs[j]->childrenHash.value(stackRefs[j+1]->eventHashStr);
                    nextEventSub->inLoopPath = true;
                    QmlRangeEventRelative *prevEventSub =
                            stackRefs[j+1]->parentHash.value(stackRefs[j]->eventHashStr);
                    prevEventSub->inLoopPath = true;
                }
            }

            // use crossed references to find index in starttimesortedlist
            QmlRangeEventStartInstance *head = stack[stackRefs.indexOf(currentEvent)];
            inTimeEvent->bindingLoopHead = endInstanceList[head->endTimeIndex].startTimeIndex;
            startInstanceList[inTimeEvent->bindingLoopHead].bindingLoopHead = i;
        }
    }
}

////////////////////////////////////////////////////////////////////////////////////

void QmlProfilerDataModel::QmlProfilerDataModelPrivate::clearQmlRootEvent()
{
    qmlRootEvent.displayName = rootEventName();
    qmlRootEvent.location = QmlEventLocation();
    qmlRootEvent.eventHashStr = rootEventName();
    qmlRootEvent.details = rootEventDescription();
1284
    qmlRootEvent.eventType = QmlDebug::Binding;
Christiaan Janssen's avatar
Christiaan Janssen committed
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
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
    qmlRootEvent.duration = 0;
    qmlRootEvent.calls = 0;
    qmlRootEvent.minTime = 0;
    qmlRootEvent.maxTime = 0;
    qmlRootEvent.timePerCall = 0;
    qmlRootEvent.percentOfTime = 0;
    qmlRootEvent.medianTime = 0;
    qmlRootEvent.eventId = -1;

    qDeleteAll(qmlRootEvent.parentHash.values());
    qDeleteAll(qmlRootEvent.childrenHash.values());
    qmlRootEvent.parentHash.clear();
    qmlRootEvent.childrenHash.clear();
}

void QmlProfilerDataModel::QmlProfilerDataModelPrivate::insertQmlRootEvent()
{
    // create root event for statistics & insert into list
    clearQmlRootEvent();
    QmlRangeEventData *listedRootEvent = rangeEventDictionary.value(rootEventName());
    if (!listedRootEvent) {
        listedRootEvent = new QmlRangeEventData;
        rangeEventDictionary.insert(rootEventName(), listedRootEvent);
    }
    *listedRootEvent = qmlRootEvent;
}

void QmlProfilerDataModel::reloadDetails()
{
    // request binding/signal details from the AST
    foreach (QmlRangeEventData *event, d->rangeEventDictionary.values()) {
        if (event->eventType != Binding && event->eventType != HandlingSignal)
            continue;

        // This skips anonymous bindings in Qt4.8 (we don't have valid location data for them)
        if (event->location.filename.isEmpty())
            continue;

        // Skip non-anonymous bindings from Qt4.8 (we already have correct details for them)
        if (event->location.column == -1)
            continue;

        emit requestDetailsForLocation(event->eventType, event->location);
    }
    emit reloadDocumentsForDetails();
}

void QmlProfilerDataModel::rewriteDetailsString(int eventType,
1333
                                                const QmlDebug::QmlEventLocation &location,
Christiaan Janssen's avatar
Christiaan Janssen committed
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
                                                const QString &newString)
{
    QString eventHashStr = getHashStringForQmlEvent(location, eventType);
    QTC_ASSERT(d->rangeEventDictionary.contains(eventHashStr), return);
    d->rangeEventDictionary.value(eventHashStr)->details = newString;
    emit detailsChanged(d->rangeEventDictionary.value(eventHashStr)->eventId, newString);
}

void QmlProfilerDataModel::finishedRewritingDetails()
{
    emit reloadDetailLabels();
}

////////////////////////////////////////////////////////////////////////////////////

bool QmlProfilerDataModel::save(const QString &filename)
{
    if (isEmpty()) {
        emit error(tr("No data to save"));
        return false;
    }

    QFile file(filename);
    if (!file.open(QIODevice::WriteOnly)) {
        emit error(tr("Could not open %1 for writing").arg(filename));
        return false;
    }

    QXmlStreamWriter stream(&file);
    stream.setAutoFormatting(true);
    stream.writeStartDocument();

    stream.writeStartElement("trace");
    stream.writeAttribute("version", Constants::PROFILER_FILE_VERSION);

    stream.writeAttribute("traceStart", QString::number(traceStartTime()));
    stream.writeAttribute("traceEnd", QString::number(traceEndTime()));

    stream.writeStartElement("eventData");
    stream.writeAttribute("totalTime", QString::number(d->qmlMeasuredTime));

    foreach (const QmlRangeEventData *eventData, d->rangeEventDictionary.values()) {
        stream.writeStartElement("event");
        stream.writeAttribute("index", QString::number(d->rangeEventDictionary.keys().indexOf(eventData->eventHashStr)));
        stream.writeTextElement("displayname", eventData->displayName);
        stream.writeTextElement("type", qmlEventTypeAsString(eventData->eventType));
        if (!eventData->location.filename.isEmpty()) {
            stream.writeTextElement("filename", eventData->location.filename);
            stream.writeTextElement("line", QString::number(eventData->location.line));
            stream.writeTextElement("column", QString::number(eventData->location.column));
        }
        stream.writeTextElement("details", eventData->details);
1386
1387
        if (eventData->eventType == Binding)
            stream.writeTextElement("bindingType", QString::number((int)eventData->bindingType));
Christiaan Janssen's avatar
Christiaan Janssen committed
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
        stream.writeEndElement();
    }
    stream.writeEndElement(); // eventData

    stream.writeStartElement("profilerDataModel");
    foreach (const QmlRangeEventStartInstance &rangedEvent, d->startInstanceList) {
        stream.writeStartElement("range");
        stream.writeAttribute("startTime", QString::number(rangedEvent.startTime));
        stream.writeAttribute("duration", QString::number(rangedEvent.duration));
        stream.writeAttribute("eventIndex", QString::number(d->rangeEventDictionary.keys().indexOf(rangedEvent.statsInfo->eventHashStr)));
1398
        if (rangedEvent.statsInfo->eventType == QmlDebug::Painting && rangedEvent.animationCount >= 0) {
Christiaan Janssen's avatar
Christiaan Janssen committed
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
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
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
            // animation frame
            stream.writeAttribute("framerate", QString::number(rangedEvent.frameRate));
            stream.writeAttribute("animationcount", QString::number(rangedEvent.animationCount));
        }
        stream.writeEndElement();
    }
    stream.writeEndElement(); // profilerDataModel

    d->v8DataModel->save(stream);

    stream.writeEndElement(); // trace
    stream.writeEndDocument();

    file.close();
    return true;
}

void QmlProfilerDataModel::setFilename(const QString &filename)
{
    d->fileName = filename;
}

void QmlProfilerDataModel::load(const QString &filename)
{
    setFilename(filename);
    load();
}

// "be strict in your output but tolerant in your inputs"
void QmlProfilerDataModel::load()
{
    QString filename = d->fileName;

    QFile file(filename);

    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        emit error(tr("Could not open %1 for reading").arg(filename));
        return;
    }

    // erase current
    clear();

    setState(AcquiringData);

    bool readingQmlEvents = false;
    QHash<int, QmlRangeEventData *> descriptionBuffer;
    QmlRangeEventData *currentEvent = 0;
    bool startTimesAreSorted = true;
    bool validVersion = true;

    // time computation
    d->qmlMeasuredTime = 0;

    QXmlStreamReader stream(&file);

    while (validVersion && !stream.atEnd() && !stream.hasError()) {
        QXmlStreamReader::TokenType token = stream.readNext();
        QString elementName = stream.name().toString();
        switch (token) {
        case QXmlStreamReader::StartDocument :  continue;
        case QXmlStreamReader::StartElement : {
            if (elementName == "trace") {
                QXmlStreamAttributes attributes = stream.attributes();
                if (attributes.hasAttribute("version"))
                    validVersion = attributes.value("version").toString() == Constants::PROFILER_FILE_VERSION;
                else
                    validVersion = false;
                if (attributes.hasAttribute("traceStart"))
                    setTraceStartTime(attributes.value("traceStart").toString().toLongLong());
                if (attributes.hasAttribute("traceEnd"))
                    setTraceEndTime(attributes.value("traceEnd").toString().toLongLong());
            }
            if (elementName == "eventData") {
                readingQmlEvents = true;
                QXmlStreamAttributes attributes = stream.attributes();
                if (attributes.hasAttribute("totalTime"))
                    d->qmlMeasuredTime = attributes.value("totalTime").toString().toDouble();
                break;
            }
            if (elementName == "v8profile" && !readingQmlEvents) {
                d->v8DataModel->load(stream);
                break;
            }

            if (elementName == "trace") {
                QXmlStreamAttributes attributes = stream.attributes();
                if (attributes.hasAttribute("traceStart"))
                    setTraceStartTime(attributes.value("traceStart").toString().toLongLong());
                if (attributes.hasAttribute("traceEnd"))
                    setTraceEndTime(attributes.value("traceEnd").toString().toLongLong());
            }

            if (elementName == "range") {
                QmlRangeEventStartInstance rangedEvent;
                QXmlStreamAttributes attributes = stream.attributes();
                if (attributes.hasAttribute("startTime"))
                    rangedEvent.startTime = attributes.value("startTime").toString().toLongLong();
                if (attributes.hasAttribute("duration"))
                    rangedEvent.duration = attributes.value("duration").toString().toLongLong();
                if (attributes.hasAttribute("framerate"))
                    rangedEvent.frameRate = attributes.value("framerate").toString().toInt();
                if (attributes.hasAttribute("animationcount"))
                    rangedEvent.animationCount = attributes.value("animationcount").toString().toInt();
                else
                    rangedEvent.animationCount = -1;
                if (attributes.hasAttribute("eventIndex")) {
                    int ndx = attributes.value("eventIndex").toString().toInt();
                    if (!descriptionBuffer.value(ndx))
                        descriptionBuffer[ndx] = new QmlRangeEventData;
                    rangedEvent.statsInfo = descriptionBuffer.value(ndx);
                }
                rangedEvent.endTimeIndex = d->endInstanceList.count();

                if (!d->startInstanceList.isEmpty()
                        && rangedEvent.startTime < d->startInstanceList.last().startTime)
                    startTimesAreSorted = false;
                d->startInstanceList << rangedEvent;

                QmlRangeEventEndInstance endTimeEvent;
                endTimeEvent.endTime = rangedEvent.startTime + rangedEvent.duration;
                endTimeEvent.startTimeIndex = d->startInstanceList.count()-1;
                endTimeEvent.description = rangedEvent.statsInfo;
                d->endInstanceList << endTimeEvent;
                break;
            }

            if (readingQmlEvents) {
                if (elementName == "event") {
                    QXmlStreamAttributes attributes = stream.attributes();
                    if (attributes.hasAttribute("index")) {
                        int ndx = attributes.value("index").toString().toInt();
                        if (!descriptionBuffer.value(ndx))
                            descriptionBuffer[ndx] = new QmlRangeEventData;
                        currentEvent = descriptionBuffer[ndx];
1534
1535
                        // backwards compatibility: default bindingType
                        currentEvent->bindingType = QmlBinding;
Christiaan Janssen's avatar
Christiaan Janssen committed
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
1569
1570
1571
1572
1573
                    } else {
                        currentEvent = 0;
                    }
                    break;
                }

                // the remaining are eventdata or v8eventdata elements
                if (!currentEvent)
                    break;

                stream.readNext();
                if (stream.tokenType() != QXmlStreamReader::Characters)
                    break;
                QString readData = stream.text().toString();

                if (elementName == "displayname") {
                    currentEvent->displayName = readData;
                    break;
                }
                if (elementName == "type") {
                    currentEvent->eventType = qmlEventTypeAsEnum(readData);
                    break;
                }
                if (elementName == "filename") {
                    currentEvent->location.filename = readData;
                    break;
                }
                if (elementName == "line") {
                    currentEvent->location.line = readData.toInt();
                    break;
                }
                if (elementName == "column") {
                    currentEvent->location.column = readData.toInt();
                }
                if (elementName == "details") {
                    currentEvent->details = readData;
                    break;
                }
1574
1575
1576
1577
                if (elementName == "bindingType") {
                    currentEvent->bindingType = readData.toInt();
                    break;
                }
Christiaan Janssen's avatar
Christiaan Janssen committed
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
            }
            break;
        }
        case QXmlStreamReader::EndElement : {
            if (elementName == "event") {
                currentEvent = 0;
                break;
            }
            if (elementName == "eventData") {
                readingQmlEvents = false;
                break;
            }
        }
        default: break;
        }
    }

    file.close();

    if (stream.hasError()) {
        emit error(tr("Error while parsing %1").arg(filename));
        clear();
        return;
    }

    stream.clear();

    if (!validVersion) {
        clear();
        emit error(tr("Invalid version of QML Trace file."));
        return;
    }

    // move the buffered data to the details cache
    foreach (QmlRangeEventData *desc, descriptionBuffer.values()) {
        desc->eventHashStr = getHashStringForQmlEvent(desc->location, desc->eventType);;
        d->rangeEventDictionary[desc->eventHashStr] = desc;
    }

    // sort startTimeSortedList
    if (!startTimesAreSorted) {
        qSort(d->startInstanceList.begin(), d->startInstanceList.end(), compareStartTimes);
        for (int i = 0; i< d->startInstanceList.count(); i++) {
            QmlRangeEventStartInstance startTimeData = d->startInstanceList[i];
            d->endInstanceList[startTimeData.endTimeIndex].startTimeIndex = i;
        }
        qSort(d->endInstanceList.begin(), d->endInstanceList.end(), compareStartIndexes);
    }

    emit countChanged();

    descriptionBuffer.clear();

    setState(ProcessingData);
    d->postProcess();
}

////////////////////////////////////////////////////////////////////////////////////

QmlProfilerDataModel::State QmlProfilerDataModel::currentState() const
{
    return d->listState;
}

int QmlProfilerDataModel::getCurrentStateFromQml() const
{
    return (int)d->listState;
}

void QmlProfilerDataModel::setState(QmlProfilerDataModel::State state)
{
    // It's not an error, we are continuously calling "AcquiringData" for example
    if (d->listState == state)
        return;

    switch (state) {
        case Empty:
            // if it's not empty, complain but go on
            QTC_ASSERT(isEmpty(), /**/);
        break;
        case AcquiringData:
            // we're not supposed to receive new data while processing older data
            QTC_ASSERT(d->listState != ProcessingData, return);
        break;
        case ProcessingData:
            QTC_ASSERT(d->listState == AcquiringData, return);
        break;
        case Done:
            QTC_ASSERT(d->listState == ProcessingData || d->listState == Empty, return);
        break;
        default:
            emit error("Trying to set unknown state in events list");
        break;
    }

    d->listState = state;
    emit stateChanged();

    return;
}

} // namespace Internal
} // namespace QmlProfiler

QT_BEGIN_NAMESPACE
Q_DECLARE_TYPEINFO(QmlProfiler::Internal::QmlRangeEventData, Q_MOVABLE_TYPE);
Q_DECLARE_TYPEINFO(QmlProfiler::Internal::QmlRangeEventStartInstance, Q_MOVABLE_TYPE);
Q_DECLARE_TYPEINFO(QmlProfiler::Internal::QmlRangeEventEndInstance, Q_MOVABLE_TYPE);
Q_DECLARE_TYPEINFO(QmlProfiler::Internal::QmlRangeEventRelative, Q_MOVABLE_TYPE);
QT_END_NAMESPACE