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

#include "qmlinspectoragent.h"

#include "debuggeractions.h"
#include "debuggercore.h"
#include "debuggerengine.h"
#include "debuggerstringutils.h"
#include "watchhandler.h"

#include <qmldebug/qmldebugconstants.h>
#include <utils/qtcassert.h>
#include <utils/savedaction.h>
41
#include <QElapsedTimer>
42

Kai Koehne's avatar
Kai Koehne committed
43
using namespace QmlDebug;
44
using namespace QmlDebug::Constants;
Kai Koehne's avatar
Kai Koehne committed
45

46
47
48
49
50
51
52
53
54
55
56
57
namespace Debugger {
namespace Internal {

enum {
    debug = false
};

/*!
 * DebuggerAgent updates the watchhandler with the object tree data.
 */
QmlInspectorAgent::QmlInspectorAgent(DebuggerEngine *engine, QObject *parent)
    : QObject(parent)
58
    , m_debuggerEngine(engine)
59
60
61
62
    , m_engineClient(0)
    , m_engineQueryId(0)
    , m_rootContextQueryId(0)
    , m_objectToSelect(-1)
63
    , m_newObjectsCreated(false)
64
{
65
    m_debugIdToIname.insert(-1, QByteArray("inspect"));
66
67
    connect(debuggerCore()->action(ShowQmlObjectTree),
            SIGNAL(valueChanged(QVariant)), SLOT(updateStatus()));
68
    m_delayQueryTimer.setSingleShot(true);
69
    m_delayQueryTimer.setInterval(100);
70
    connect(&m_delayQueryTimer, SIGNAL(timeout()), SLOT(queryEngineContext()));
71
72
73
74
75
76
}

quint32 QmlInspectorAgent::queryExpressionResult(int debugId,
                                                 const QString &expression)
{
    if (debug)
77
78
        qDebug() << __FUNCTION__ << '(' << debugId << expression
                 << m_engine.debugId() << ')';
79
80

    return m_engineClient->queryExpressionResult(debugId, expression,
81
                                                 m_engine.debugId());
82
83
}

84
85
86
87
void QmlInspectorAgent::assignValue(const WatchData *data,
                                    const QString &expr, const QVariant &valueV)
{
    if (debug)
88
        qDebug() << __FUNCTION__ << '(' << data->id << ')' << data->iname;
89
90
91
92
93
94
95
96
97
98
99
100

    if (data->id) {
        QString val(valueV.toString());
        if (valueV.type() == QVariant::String) {
            val = val.replace(QLatin1Char('\"'), QLatin1String("\\\""));
            val = QLatin1Char('\"') + val + QLatin1Char('\"');
        }
        QString expression = QString(_("%1 = %2;")).arg(expr).arg(val);
        queryExpressionResult(data->id, expression);
    }
}

101
102
103
104
105
106
107
108
109
110
111
int parentIdForIname(const QByteArray &iname)
{
    // Extract the parent id
    int lastIndex = iname.lastIndexOf('.');
    int secondLastIndex = iname.lastIndexOf('.', lastIndex - 1);
    int parentId = -1;
    if (secondLastIndex != -1)
        parentId = iname.mid(secondLastIndex + 1, lastIndex - secondLastIndex - 1).toInt();
    return parentId;
}

112
113
114
void QmlInspectorAgent::updateWatchData(const WatchData &data)
{
    if (debug)
115
        qDebug() << __FUNCTION__ << '(' << data.id << ')';
116

hjk's avatar
hjk committed
117
    if (data.id && !m_fetchDataIds.contains(data.id)) {
118
        // objects
hjk's avatar
hjk committed
119
        m_fetchDataIds << data.id;
120
        fetchObject(data.id);
121
122
123
    }
}

124
125
126
127
128
129
130
void QmlInspectorAgent::watchDataSelected(const WatchData *data)
{
    if (debug)
        qDebug() << __FUNCTION__ << '(' << data->id << ')';

    if (data->id) {
        QTC_ASSERT(m_debugIdLocations.keys().contains(data->id), return);
Aurindam Jana's avatar
Aurindam Jana committed
131
        emit jumpToObjectDefinition(m_debugIdLocations.value(data->id), data->id);
132
133
134
    }
}

135
bool QmlInspectorAgent::selectObjectInTree(int debugId)
136
137
{
    if (debug) {
138
        qDebug() << __FUNCTION__ << '(' << debugId << ')';
139
140
141
142
143
144
145
146
147
        qDebug() << "  " << debugId << "already fetched? "
                 << m_debugIdToIname.contains(debugId);
    }

    if (m_debugIdToIname.contains(debugId)) {
        QByteArray iname = m_debugIdToIname.value(debugId);
        QTC_ASSERT(iname.startsWith("inspect."), qDebug() << iname);
        if (debug)
            qDebug() << "  selecting" << iname << "in tree";
148
        m_debuggerEngine->watchHandler()->setCurrentItem(iname);
149
        m_objectToSelect = 0;
150
        return true;
151
    } else {
152
        // we may have to fetch it
153
        m_objectToSelect = debugId;
154
155
156
157
158
159
160
161
        using namespace QmlDebug::Constants;
        if (m_engineClient->objectName() == QLatin1String(QDECLARATIVE_ENGINE)) {
            // reset current Selection
            QByteArray root = m_debuggerEngine->watchHandler()->watchData(QModelIndex())->iname;
            m_debuggerEngine->watchHandler()->setCurrentItem(root);
        } else {
            fetchObject(debugId);
        }
162
        return false;
163
164
165
166
167
168
169
170
171
172
173
    }
}

quint32 QmlInspectorAgent::setBindingForObject(int objectDebugId,
                                         const QString &propertyName,
                                         const QVariant &value,
                                         bool isLiteralValue,
                                         QString source,
                                         int line)
{
    if (debug)
174
175
        qDebug() << __FUNCTION__ << '(' << objectDebugId << propertyName
                 << value.toString() << isLiteralValue << source << line << ')';
176
177
178
179
180
181
182
183
184
185
186

    if (objectDebugId == -1)
        return 0;

    if (propertyName == QLatin1String("id"))
        return 0; // Crashes the QMLViewer.

    if (!isConnected()
            || !debuggerCore()->boolSetting(ShowQmlObjectTree))
        return 0;

187
    log(LogSend, QString::fromLatin1("SET_BINDING %1 %2 %3 %4").arg(
188
            QString::number(objectDebugId), propertyName, value.toString(),
189
            QString(isLiteralValue ? QLatin1String("true") : QLatin1String("false"))));
190
191
192
193
194
195

    quint32 queryId = m_engineClient->setBindingForObject(
                objectDebugId, propertyName, value.toString(), isLiteralValue,
                source, line);

    if (!queryId)
196
        log(LogSend, QLatin1String("SET_BINDING failed!"));
197
198
199
200
201
202
203
204
205

    return queryId;
}

quint32 QmlInspectorAgent::setMethodBodyForObject(int objectDebugId,
                                            const QString &methodName,
                                            const QString &methodBody)
{
    if (debug)
206
207
        qDebug() << __FUNCTION__ << '(' << objectDebugId
                 << methodName << methodBody << ')';
208
209
210
211
212
213
214
215

    if (objectDebugId == -1)
        return 0;

    if (!isConnected()
            || !debuggerCore()->boolSetting(ShowQmlObjectTree))
        return 0;

216
    log(LogSend, QString::fromLatin1("SET_METHOD_BODY %1 %2 %3").arg(
217
218
219
220
221
222
            QString::number(objectDebugId), methodName, methodBody));

    quint32 queryId = m_engineClient->setMethodBody(
                objectDebugId, methodName, methodBody);

    if (!queryId)
223
        log(LogSend, QLatin1String("failed!"));
224
225
226
227
228
229
230
231

    return queryId;
}

quint32 QmlInspectorAgent::resetBindingForObject(int objectDebugId,
                                           const QString &propertyName)
{
    if (debug)
232
233
        qDebug() << __FUNCTION__ << '(' << objectDebugId
                 << propertyName << ')';
234
235
236
237
238
239
240
241

    if (objectDebugId == -1)
        return 0;

    if (!isConnected()
            || !debuggerCore()->boolSetting(ShowQmlObjectTree))
        return 0;

242
    log(LogSend, QString::fromLatin1("RESET_BINDING %1 %2").arg(
243
244
245
246
247
248
            QString::number(objectDebugId), propertyName));

    quint32 queryId = m_engineClient->resetBindingForObject(
                objectDebugId, propertyName);

    if (!queryId)
249
        log(LogSend, QLatin1String("failed!"));
250
251
252
253

    return queryId;
}

254
ObjectReference QmlInspectorAgent::objectForName(
255
256
257
        const QString &objectId) const
{
    if (!objectId.isEmpty() && objectId[0].isLower()) {
258
        QHashIterator<int, QByteArray> iter(m_debugIdToIname);
Aurindam Jana's avatar
Aurindam Jana committed
259
        const WatchHandler *watchHandler = m_debuggerEngine->watchHandler();
260
261
        while (iter.hasNext()) {
            iter.next();
Aurindam Jana's avatar
Aurindam Jana committed
262
            const WatchData *wd = watchHandler->findData(iter.value());
263
            if (wd && wd->name == objectId)
264
                return ObjectReference(iter.key());
265
266
        }
    }
Kai Koehne's avatar
Kai Koehne committed
267
    return ObjectReference();
268
269
}

270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
ObjectReference QmlInspectorAgent::objectForId(int objectDebugId) const
{
    if (!m_debugIdToIname.contains(objectDebugId))
        return ObjectReference(objectDebugId);

    int line = -1;
    int column = -1;
    QString file;
    QHashIterator<QPair<QString, int>, QHash<QPair<int, int>, QList<int> > > iter(m_debugIdHash);
    while (iter.hasNext()) {
        iter.next();
        QHashIterator<QPair<int, int>, QList<int> > i(iter.value());
        while (i.hasNext()) {
            i.next();
            if (i.value().contains(objectDebugId)) {
                line = i.key().first;
                column = i.key().second;
                break;
            }
        }
        if (line != -1) {
            file = iter.key().first;
            break;
        }
    }
    // TODO: Set correct parentId
    return ObjectReference(objectDebugId, -1,
                           FileReference(QUrl::fromLocalFile(file), line, column));
}

300
int QmlInspectorAgent::objectIdForLocation(
301
302
        int line, int column) const
{
303
304
305
306
307
308
309
    QHashIterator<int, FileReference> iter(m_debugIdLocations);
    while (iter.hasNext()) {
        iter.next();
        const FileReference &ref = iter.value();
        if (ref.lineNumber() == line
                && ref.columnNumber() == column)
            return iter.key();
310
311
    }

312
313
314
315
316
317
    return -1;
}

QHash<int,QString> QmlInspectorAgent::rootObjectIds() const
{
    QHash<int,QString> rIds;
Aurindam Jana's avatar
Aurindam Jana committed
318
    const WatchHandler *watchHandler = m_debuggerEngine->watchHandler();
319
    foreach (const QByteArray &in, m_debugIdToIname) {
Aurindam Jana's avatar
Aurindam Jana committed
320
        const WatchData *data = watchHandler->findData(in);
321
322
        if (!data)
            continue;
323
        int debugId = data->id;
324
        QString className = QLatin1String(data->type);
325
326
327
        rIds.insert(debugId, className);
    }
     return rIds;
328
329
330
331
332
}

bool QmlInspectorAgent::addObjectWatch(int objectDebugId)
{
    if (debug)
333
        qDebug() << __FUNCTION__ << '(' << objectDebugId << ')';
334
335
336
337
338
339
340
341
342
343
344
345
346

    if (objectDebugId == -1)
        return false;

    if (!isConnected()
            || !debuggerCore()->boolSetting(ShowQmlObjectTree))
        return false;

    // already set
    if (m_objectWatches.contains(objectDebugId))
        return true;

    // is flooding the debugging output log!
347
    // log(LogSend, QString::fromLatin1("WATCH_PROPERTY %1").arg(objectDebugId));
348

349
    if (m_engineClient->addWatch(objectDebugId))
350
351
        m_objectWatches.append(objectDebugId);

352
    return true;
353
354
355
356
357
358
359
360
361
362
}

bool QmlInspectorAgent::isObjectBeingWatched(int objectDebugId)
{
    return m_objectWatches.contains(objectDebugId);
}

bool QmlInspectorAgent::removeObjectWatch(int objectDebugId)
{
    if (debug)
363
        qDebug() << __FUNCTION__ << '(' << objectDebugId << ')';
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392

    if (objectDebugId == -1)
        return false;

    if (!m_objectWatches.contains(objectDebugId))
        return false;

    if (!isConnected())
        return false;

    m_objectWatches.removeOne(objectDebugId);
    return true;
}

void QmlInspectorAgent::removeAllObjectWatches()
{
    if (debug)
        qDebug() << __FUNCTION__ << "()";

    foreach (int watchedObject, m_objectWatches)
        removeObjectWatch(watchedObject);
}

void QmlInspectorAgent::setEngineClient(BaseEngineDebugClient *client)
{
    if (m_engineClient == client)
        return;

    if (m_engineClient) {
Kai Koehne's avatar
Kai Koehne committed
393
        disconnect(m_engineClient, SIGNAL(newStatus(QmlDebug::ClientStatus)),
394
395
396
                   this, SLOT(updateStatus()));
        disconnect(m_engineClient, SIGNAL(result(quint32,QVariant,QByteArray)),
                   this, SLOT(onResult(quint32,QVariant,QByteArray)));
397
398
        disconnect(m_engineClient, SIGNAL(newObject(int,int,int)),
                   this, SLOT(newObject(int,int,int)));
399
400
        disconnect(m_engineClient, SIGNAL(valueChanged(int,QByteArray,QVariant)),
                   this, SLOT(onValueChanged(int,QByteArray,QVariant)));
401
402
403
404
405
    }

    m_engineClient = client;

    if (m_engineClient) {
Kai Koehne's avatar
Kai Koehne committed
406
        connect(m_engineClient, SIGNAL(newStatus(QmlDebug::ClientStatus)),
407
408
409
                this, SLOT(updateStatus()));
        connect(m_engineClient, SIGNAL(result(quint32,QVariant,QByteArray)),
                this, SLOT(onResult(quint32,QVariant,QByteArray)));
410
411
        connect(m_engineClient, SIGNAL(newObject(int,int,int)),
                this, SLOT(newObject(int,int,int)));
412
413
        connect(m_engineClient, SIGNAL(valueChanged(int,QByteArray,QVariant)),
                this, SLOT(onValueChanged(int,QByteArray,QVariant)));
414
415
416
417
418
    }

    updateStatus();
}

419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
QString QmlInspectorAgent::displayName(int objectDebugId) const
{
    if (!isConnected()
            || !debuggerCore()->boolSetting(ShowQmlObjectTree))
        return QString();

    if (m_debugIdToIname.contains(objectDebugId)) {
        const WatchData *data = m_debuggerEngine->watchHandler()->findData(
                    m_debugIdToIname.value(objectDebugId));
        QTC_ASSERT(data, return QString());
        return data->name;
    }
    return QString();
}

434
435
436
void QmlInspectorAgent::updateStatus()
{
    if (m_engineClient
Kai Koehne's avatar
Kai Koehne committed
437
            && (m_engineClient->status() == QmlDebug::Enabled)
438
439
440
            && debuggerCore()->boolSetting(ShowQmlObjectTree)) {
        reloadEngines();
    } else {
441
        clearObjectTree();
442
443
444
445
446
447
448
449
450
    }
}

void QmlInspectorAgent::onResult(quint32 queryId, const QVariant &value,
                                 const QByteArray &type)
{
    if (debug)
        qDebug() << __FUNCTION__ << "() ...";

451
    if (type == "FETCH_OBJECT_R") {
452
        log(LogReceive, _("FETCH_OBJECT_R %1").arg(
Kai Koehne's avatar
Kai Koehne committed
453
                qvariant_cast<ObjectReference>(value).idString()));
454
455
456
    } else if (type == "SET_BINDING_R"
               || type == "RESET_BINDING_R"
               || type == "SET_METHOD_BODY_R") {
457
        QString msg = QLatin1String(type) + tr("Success: ");
458
        msg += value.toBool() ? QLatin1Char('1') : QLatin1Char('0');
459
460
461
        if (!value.toBool())
            emit automaticUpdateFailed();
        log(LogReceive, msg);
462
463
464
465
466
    } else {
        log(LogReceive, QLatin1String(type));
    }

    if (m_objectTreeQueryIds.contains(queryId)) {
467
        m_objectTreeQueryIds.removeOne(queryId);
468
469
        if (value.type() == QVariant::List) {
            QVariantList objList = value.toList();
470
            foreach (const QVariant &var, objList) {
471
472
                // TODO: check which among the list is the actual
                // object that needs to be selected.
473
                verifyAndInsertObjectInTree(qvariant_cast<ObjectReference>(var));
474
475
            }
        } else {
476
            verifyAndInsertObjectInTree(qvariant_cast<ObjectReference>(value));
477
        }
478
479
480
481
482
483
484
485
486
487
    } else if (queryId == m_engineQueryId) {
        m_engineQueryId = 0;
        QList<EngineReference> engines = qvariant_cast<QList<EngineReference> >(value);
        QTC_ASSERT(engines.count(), return);
        // only care about first engine atm
        m_engine = engines.at(0);
        queryEngineContext();
    } else if (queryId == m_rootContextQueryId) {
        m_rootContextQueryId = 0;
        clearObjectTree();
488
        updateObjectTree(qvariant_cast<ContextReference>(value));
489
490
491
492
493
494
495
496
497
    } else {
        emit expressionResult(queryId, value);
    }

    if (debug)
        qDebug() << __FUNCTION__ << "done";

}

498
void QmlInspectorAgent::newObject(int engineId, int /*objectId*/, int /*parentId*/)
499
500
501
502
{
    if (debug)
        qDebug() << __FUNCTION__ << "()";

503
    log(LogReceive, QLatin1String("OBJECT_CREATED"));
504
505
506

    if (m_engine.debugId() != engineId)
        return;
507

508
509
    // TODO: FIX THIS for qt 5.x (Needs update in the qt side)
    m_delayQueryTimer.start();
510
511
}

512
513
514
515
516
void QmlInspectorAgent::onValueChanged(int debugId, const QByteArray &propertyName,
                                       const QVariant &value)
{
    const QByteArray iname = m_debugIdToIname.value(debugId) +
            ".[properties]." + propertyName;
Aurindam Jana's avatar
Aurindam Jana committed
517
518
    WatchHandler *watchHandler = m_debuggerEngine->watchHandler();
    const WatchData *data = watchHandler->findData(iname);
519
    if (debug)
520
        qDebug() << __FUNCTION__ << '(' << debugId << ')' << iname << value.toString();
521
522
523
    if (data) {
        WatchData d(*data);
        d.value = value.toString();
Aurindam Jana's avatar
Aurindam Jana committed
524
        watchHandler->insertData(d);
525
526
527
    }
}

528
529
530
531
532
533
534
535
536
537
538
539
540
void QmlInspectorAgent::reloadEngines()
{
    if (debug)
        qDebug() << __FUNCTION__ << "()";

    if (!isConnected())
        return;

    log(LogSend, _("LIST_ENGINES"));

    m_engineQueryId = m_engineClient->queryAvailableEngines();
}

541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
int QmlInspectorAgent::parentIdForObject(int objectDebugId)
{
    int pid = -1;

    if (m_debugIdToIname.contains(objectDebugId)) {
        QByteArray iname = m_debugIdToIname.value(objectDebugId);
        if (iname.count('.') > 1) {
            int offset = iname.lastIndexOf('.');
            QTC_ASSERT(offset > 0, return pid);
            iname = iname.left(offset);
            pid = m_debugIdToIname.key(iname);
        }
    }
    return pid;
}

557
void QmlInspectorAgent::queryEngineContext()
558
559
{
    if (debug)
560
        qDebug() << __FUNCTION__;
561
562
563
564
565

    if (!isConnected()
            || !debuggerCore()->boolSetting(ShowQmlObjectTree))
        return;

566
    log(LogSend, QLatin1String("LIST_OBJECTS"));
567
568

    m_rootContextQueryId
569
            = m_engineClient->queryRootContexts(m_engine);
570
571
}

572
void QmlInspectorAgent::fetchObject(int debugId)
573
574
{
    if (debug)
575
        qDebug() << __FUNCTION__ << '(' << debugId << ')';
576
577
578

    if (!isConnected()
            || !debuggerCore()->boolSetting(ShowQmlObjectTree))
579
        return;
580

581
    log(LogSend, QLatin1String("FETCH_OBJECT ") + QString::number(debugId));
582
    quint32 queryId = m_engineClient->queryObject(debugId);
583
    if (debug)
584
        qDebug() << __FUNCTION__ << '(' << debugId << ')'
585
                 << " - query id" << queryId;
586
    m_objectTreeQueryIds << queryId;
587
588
}

589
590
591
592
593
594
void QmlInspectorAgent::fetchContextObjectsForLocation(const QString &file,
                                     int lineNumber, int columnNumber)
{
    // This can be an expensive operation as it may return multiple
    // objects. Use fetchContextObject() where possible.
    if (debug)
595
596
        qDebug() << __FUNCTION__ << '(' << file << ':' << lineNumber
                 << ':' << columnNumber << ')';
597
598
599
600
601

    if (!isConnected()
            || !debuggerCore()->boolSetting(ShowQmlObjectTree))
        return;

602
    log(LogSend, QString::fromLatin1("FETCH_OBJECTS_FOR_LOCATION %1:%2:%3").arg(file)
603
604
605
606
        .arg(QString::number(lineNumber)).arg(QString::number(columnNumber)));
    quint32 queryId = m_engineClient->queryObjectsForLocation(QFileInfo(file).fileName(),
                                                             lineNumber, columnNumber);
    if (debug)
607
608
        qDebug() << __FUNCTION__ << '(' << file << ':' << lineNumber
                 << ':' << columnNumber << ')' << " - query id" << queryId;
609

610
    m_objectTreeQueryIds << queryId;
611
612
}

613
void QmlInspectorAgent::updateObjectTree(const ContextReference &context)
614
615
{
    if (debug)
616
        qDebug() << __FUNCTION__ << '(' << context << ')';
617
618
619
620
621

    if (!isConnected()
            || !debuggerCore()->boolSetting(ShowQmlObjectTree))
        return;

622
    foreach (const ObjectReference & obj, context.objects())
623
        verifyAndInsertObjectInTree(obj);
624

Kai Koehne's avatar
Kai Koehne committed
625
    foreach (const ContextReference &child, context.contexts())
626
        updateObjectTree(child);
627
628
}

629
void QmlInspectorAgent::verifyAndInsertObjectInTree(const ObjectReference &object)
630
631
{
    if (debug)
632
        qDebug() << __FUNCTION__ << '(' << object << ')';
633

634
635
    if (!object.isValid())
        return;
636

637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
    // Find out the correct position in the tree
    // Objects are inserted to the tree if they satisfy one of the two conditions.
    // Condition 1: Object is a root object i.e. parentId == -1.
    // Condition 2: Object has an expanded parent i.e. siblings are known.
    // If the two conditions are not met then we push the object to a stack and recursively
    // fetch parents till we find a previously expanded parent.

    WatchHandler *handler = m_debuggerEngine->watchHandler();
    const int parentId = object.parentId();
    const int objectDebugId = object.debugId();
    if (m_debugIdToIname.contains(parentId)) {
        QByteArray parentIname = m_debugIdToIname.value(parentId);
        if (parentId != -1 && !handler->isExpandedIName(parentIname)) {
            m_objectStack.push(object);
            handler->model()->fetchMore(handler->watchDataIndex(parentIname));
            return; // recursive
        }
        insertObjectInTree(object);
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
    } else {
        m_objectStack.push(object);
        fetchObject(parentId);
        return; // recursive
    }
    if (!m_objectStack.isEmpty()) {
        const ObjectReference &top = m_objectStack.top();
        // We want to expand only a particular branch and not the whole tree. Hence, we do not
        // expand siblings.
        if (object.children().contains(top)) {
            QByteArray objectIname = m_debugIdToIname.value(objectDebugId);
            if (!handler->isExpandedIName(objectIname)) {
                handler->model()->fetchMore(handler->watchDataIndex(objectIname));
            } else {
                verifyAndInsertObjectInTree(m_objectStack.pop());
                return; // recursive
            }
        }
    }
}

void QmlInspectorAgent::insertObjectInTree(const ObjectReference &object)
{
    if (debug)
        qDebug() << __FUNCTION__ << '(' << object << ')';
681

682
683
    const int objectDebugId = object.debugId();
    const int parentId = parentIdForIname(m_debugIdToIname.value(objectDebugId));
684

685
686
    QElapsedTimer timeElapsed;
    QList<WatchData> watchData;
687
688
689
690
691
692
693
694
695
696
697
698
    if (debug)
        timeElapsed.start();
    watchData.append(buildWatchData(object, m_debugIdToIname.value(parentId), true));
    if (debug)
        qDebug() << __FUNCTION__ << "Time: Build Watch Data took "
                 << timeElapsed.elapsed() << " ms";
    if (debug)
        timeElapsed.start();
    buildDebugIdHashRecursive(object);
    if (debug)
        qDebug() << __FUNCTION__ << "Time: Build Debug Id Hash took "
                 << timeElapsed.elapsed() << " ms";
699

Aurindam Jana's avatar
Aurindam Jana committed
700
    WatchHandler *watchHandler = m_debuggerEngine->watchHandler();
701
702
    if (debug)
        timeElapsed.start();
Aurindam Jana's avatar
Aurindam Jana committed
703
    watchHandler->insertData(watchData);
704
705
    if (debug)
        qDebug() << __FUNCTION__ << "Time: Insertion took " << timeElapsed.elapsed() << " ms";
706

707
    emit objectTreeUpdated();
708
    emit objectFetched(object);
709

710
    if (m_debugIdToIname.contains(m_objectToSelect)) {
711
        // select item in view
712
        QByteArray iname = m_debugIdToIname.value(m_objectToSelect);
713
714
        if (debug)
            qDebug() << "  selecting" << iname << "in tree";
Aurindam Jana's avatar
Aurindam Jana committed
715
        watchHandler->setCurrentItem(iname);
716
        m_objectToSelect = -1;
717
718
719
    }
}

Kai Koehne's avatar
Kai Koehne committed
720
void QmlInspectorAgent::buildDebugIdHashRecursive(const ObjectReference &ref)
721
722
{
    if (debug)
723
        qDebug() << __FUNCTION__ << '(' << ref << ')';
724
725
726
727
728
729
730
731

    QUrl fileUrl = ref.source().url();
    int lineNum = ref.source().lineNumber();
    int colNum = ref.source().columnNumber();
    int rev = 0;

    // handle the case where the url contains the revision number encoded.
    //(for object created by the debugger)
732
    static QRegExp rx(QLatin1String("(.*)_(\\d+):(\\d+)$"));
733
734
735
736
737
738
739
    if (rx.exactMatch(fileUrl.path())) {
        fileUrl.setPath(rx.cap(1));
        rev = rx.cap(2).toInt();
        lineNum += rx.cap(3).toInt() - 1;
    }

    const QString filePath
740
            = m_debuggerEngine->toFileInProject(fileUrl);
741
742
743
744
745
746

    // append the debug ids in the hash
    QPair<QString, int> file = qMakePair<QString, int>(filePath, rev);
    QPair<int, int> location = qMakePair<int, int>(lineNum, colNum);
    if (!m_debugIdHash[file][location].contains(ref.debugId()))
        m_debugIdHash[file][location].append(ref.debugId());
747
    m_debugIdLocations.insert(ref.debugId(), FileReference(filePath, lineNum, colNum));
748

Kai Koehne's avatar
Kai Koehne committed
749
    foreach (const ObjectReference &it, ref.children())
750
751
752
        buildDebugIdHashRecursive(it);
}

753
static QByteArray buildIName(const QByteArray &parentIname, int debugId)
754
{
755
    if (parentIname.isEmpty())
756
        return "inspect." + QByteArray::number(debugId);
757
    return parentIname + "." + QByteArray::number(debugId);
758
759
}

760
static QByteArray buildIName(const QByteArray &parentIname, const QString &name)
761
{
762
    return parentIname + "." + name.toLatin1();
763
764
}

Kai Koehne's avatar
Kai Koehne committed
765
QList<WatchData> QmlInspectorAgent::buildWatchData(const ObjectReference &obj,
766
767
                                       const QByteArray &parentIname,
                                       bool append)
768
769
{
    if (debug)
770
        qDebug() << __FUNCTION__ << '(' << obj << parentIname << ')';
771
772
773

    QList<WatchData> list;

774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
    int objDebugId = obj.debugId();
    QByteArray objIname = buildIName(parentIname, objDebugId);

    if (append) {
        WatchData objWatch;
        QString name = obj.idString();
        if (name.isEmpty())
            name = obj.className();

        if (name.isEmpty())
            return list;

        // object
        objWatch.id = objDebugId;
        objWatch.exp = name.toLatin1();
        objWatch.name = name;
        objWatch.iname = objIname;
        objWatch.type = obj.className().toLatin1();
        objWatch.value = _("object");
        objWatch.setHasChildren(true);
        objWatch.setAllUnneeded();

        list.append(objWatch);
        addObjectWatch(objWatch.id);
798
799
800
801
802
803
804
        if (m_debugIdToIname.contains(objDebugId)) {
            // The data needs to be removed since we now know the parent and
            // hence we can insert the data in the correct position
            const QByteArray oldIname = m_debugIdToIname.value(objDebugId);
            if (oldIname != objIname)
                m_debuggerEngine->watchHandler()->removeData(oldIname);
        }
805
        m_debugIdToIname.insert(objDebugId, objIname);
806
807
    }

Aurindam Jana's avatar
Aurindam Jana committed
808
    if (!m_debuggerEngine->watchHandler()->isExpandedIName(objIname)) {
809
810
        // we don't know the children yet. Not adding the 'properties'
        // element makes sure we're queried on expansion.
Aurindam Jana's avatar
Aurindam Jana committed
811
812
813
814
815
816
817
        if (obj.needsMoreData())
            return list;

        // To improve performance, we do not insert data for items
        // that have not been previously queried when the object tree is refreshed.
        if (m_newObjectsCreated)
            append = false;
818
819
    }

820
    // properties
821
    if (append && obj.properties().count()) {
822
        WatchData propertiesWatch;
823
        propertiesWatch.id = objDebugId;
824
        propertiesWatch.exp = "";
825
        propertiesWatch.name = tr("Properties");
826
        propertiesWatch.iname = objIname + ".[properties]";
827
828
829
830
831
832
833
834
835
        propertiesWatch.type = "";
        propertiesWatch.value = _("list");
        propertiesWatch.setHasChildren(true);
        propertiesWatch.setAllUnneeded();

        list.append(propertiesWatch);

        foreach (const PropertyReference &property, obj.properties()) {
            WatchData propertyWatch;
836
            propertyWatch.id = objDebugId;
837
838
839
840
841
842
843
844
845
            propertyWatch.exp = property.name().toLatin1();
            propertyWatch.name = property.name();
            propertyWatch.iname = buildIName(propertiesWatch.iname, property.name());
            propertyWatch.type = property.valueTypeName().toLatin1();
            propertyWatch.value = property.value().toString();
            propertyWatch.setAllUnneeded();
            propertyWatch.setHasChildren(false);
            list.append(propertyWatch);
        }
846
847
848
    }

    // recurse
Kai Koehne's avatar
Kai Koehne committed
849
    foreach (const ObjectReference &child, obj.children())
850
        list.append(buildWatchData(child, objIname, append));
851
852
853
854
855
856
857
858
859
860
861
862
863
    return list;
}

void QmlInspectorAgent::log(QmlInspectorAgent::LogDirection direction,
                            const QString &message)
{
    QString msg = _("Inspector");
    if (direction == LogSend)
        msg += _(" sending ");
    else
        msg += _(" receiving ");
    msg += message;

864
865
    if (m_debuggerEngine)
        m_debuggerEngine->showMessage(msg, LogDebug);
866
867
}

868
bool QmlInspectorAgent::isConnected() const
869
870
{
    return m_engineClient
Kai Koehne's avatar
Kai Koehne committed
871
            && (m_engineClient->status() == QmlDebug::Enabled);
872
873
}

874
875
void QmlInspectorAgent::clearObjectTree()
{
876
    m_debuggerEngine->watchHandler()->removeAllData(true);
877
    m_objectTreeQueryIds.clear();
878
    m_fetchDataIds.clear();
879
880
881
882
    int old_count = m_debugIdHash.count();
    m_debugIdHash.clear();
    m_debugIdHash.reserve(old_count + 1);
    m_debugIdToIname.clear();
883
    m_debugIdToIname.insert(-1, QByteArray("inspect"));
884
    m_objectStack.clear();
885
886
    // reset only for qt > 4.8.3.
    if (m_engineClient->objectName() != QLatin1String(QDECLARATIVE_ENGINE))
887
        m_newObjectsCreated = false;
888
889

    removeAllObjectWatches();
890
}
891
892
} // Internal
} // Debugger
893