qmlengine.cpp 56.8 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "qmlengine.h"

32
#include "debuggerconstants.h"
33
#include "debuggerplugin.h"
34
#include "debuggerdialogs.h"
35
36
#include "debuggerstringutils.h"

37
38
39
40
41
42
43
#include "breakhandler.h"
#include "moduleshandler.h"
#include "registerhandler.h"
#include "stackhandler.h"
#include "watchhandler.h"
#include "watchutils.h"

44
45
46
47
#include "canvasframerate.h"

#include <projectexplorer/environment.h>

48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <utils/qtcassert.h>

#include <QtCore/QDateTime>
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QTimer>

#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QMainWindow>
#include <QtGui/QMessageBox>
#include <QtGui/QToolTip>

#include <QtNetwork/QTcpSocket>
63
64
65
66
#include <QtNetwork/QHostAddress>

#include <private/qdeclarativedebug_p.h>
#include <private/qdeclarativedebugclient_p.h>
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

#define DEBUG_QML 1
#if DEBUG_QML
#   define SDEBUG(s) qDebug() << s
#else
#   define SDEBUG(s)
#endif
# define XSDEBUG(s) qDebug() << s

#define CB(callback) &QmlEngine::callback, STRINGIFY(callback)

//#define USE_CONGESTION_CONTROL


namespace Debugger {
namespace Internal {


class QmlResponse
{
public:
    QmlResponse() {}
    QmlResponse(const QByteArray &data_) : data(data_) {}

    QString toString() const { return data; }

    QByteArray data;
};


97
98
99
100
101
102
103
104
105
106
107
108
///////////////////////////////////////////////////////////////////////
//
// QmlDebuggerClient
//
///////////////////////////////////////////////////////////////////////

class QmlDebuggerClient : public QDeclarativeDebugClient
{
    Q_OBJECT

public:
    QmlDebuggerClient(QDeclarativeDebugConnection *connection, QmlEngine *engine)
109
        : QDeclarativeDebugClient(QLatin1String("QDeclarativeEngine"), connection)
110
111
112
113
114
        , m_connection(connection), m_engine(engine)
    {
        setEnabled(true);
    }

115
116
117
118
119
120
121
    void sendMessage(const QByteArray &msg)
    {
        QTC_ASSERT(isConnected(), /**/);
        qDebug() << "SENDING: " << quoteUnprintableLatin1(msg);
        QDeclarativeDebugClient::sendMessage(msg);
    }

122
123
124
125
126
127
128
129
130
131
132
    void messageReceived(const QByteArray &data)
    {
        m_engine->messageReceived(data);
    }


    QDeclarativeDebugConnection *m_connection;
    QmlEngine *m_engine;
};


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
class QmlFrameRateClient : public QDeclarativeDebugClient
{
    Q_OBJECT

public:
    QmlFrameRateClient(QDeclarativeDebugConnection *connection, QmlEngine *engine)
        : QDeclarativeDebugClient(QLatin1String("CanvasFrameRate"), connection)
        , m_connection(connection), m_engine(engine)
    {
        setEnabled(true);
    }

    void messageReceived(const QByteArray &data)
    {
        Q_UNUSED(data);
        // FIXME
        //qDebug() << "CANVAS FRAME RATE: " << data.size();
        //m_engine->messageReceived(data);
    }


    QDeclarativeDebugConnection *m_connection;
    QmlEngine *m_engine;
};


159

160
161
162
163
164
165
///////////////////////////////////////////////////////////////////////
//
// QmlEngine
//
///////////////////////////////////////////////////////////////////////

166
167
QmlEngine::QmlEngine(const DebuggerStartParameters &startParameters)
    : DebuggerEngine(startParameters)
168
{
169
170
    m_conn = 0;
    m_client = 0;
hjk's avatar
hjk committed
171
    m_engineDebugInterface = 0;
172
    m_frameRate = 0;
hjk's avatar
hjk committed
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191

    /*
    m_watchTableModel = new Internal::WatchTableModel(0, this);

    m_objectTreeWidget = new Internal::ObjectTree;
    m_propertiesWidget = new Internal::ObjectPropertiesView(m_watchTableModel);
    m_watchTableView = new Internal::WatchTableView(m_watchTableModel);
    m_expressionWidget = new Internal::ExpressionQueryWidget(Internal::ExpressionQueryWidget::SeparateEntryMode);
//    m_frameRateWidget = new Internal::CanvasFrameRate;
//    m_frameRateWidget->setObjectName(QLatin1String("QmlDebugFrameRate"));

    connect(Debugger::DebuggerPlugin::instance(),
        SIGNAL(stateChanged(int)), this, SLOT(debuggerStateChanged(int)));

    m_editablePropertyTypes = QStringList() << "qreal" << "bool" << "QString"
                                            << "int" << "QVariant" << "QUrl" << "QColor";

    connect(m_connectionTimer, SIGNAL(timeout()), SLOT(pollInspector()));
    */
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
}

QmlEngine::~QmlEngine()
{
}

void QmlEngine::executeDebuggerCommand(const QString &command)
{
    QByteArray cmd = command.toUtf8();
    cmd = cmd.mid(cmd.indexOf(' ') + 1);
    QByteArray null;
    null.append('\0');
    // FIXME: works for single-digit escapes only
    cmd.replace("\\0", null);
    cmd.replace("\\1", "\1");
    cmd.replace("\\3", "\3");
208
209
210
    //QmlCommand tcf;
    //tcf.command = cmd;
    //enqueueCommand(tcf);
211
212
213
214
215
}

void QmlEngine::shutdown()
{
    exitDebugger();
hjk's avatar
hjk committed
216
217
218
219

    //m_objectTreeWidget->saveSettings(m_settings);
    //m_propertiesWidget->saveSettings(m_settings);
    //m_settings.saveSettings(Core::ICore::instance()->settings());
220
221
222
223
224
225
226
}

void QmlEngine::exitDebugger()
{
    SDEBUG("QmlEngine::exitDebugger()");
}

227
228
const int serverPort = 3768;

229
void QmlEngine::startEngine()
230
{
231
    QTC_ASSERT(state() == EngineStarting, qDebug() << state());
232
    const DebuggerStartParameters &sp = startParameters();
233
234
235
    const int pos = sp.remoteChannel.indexOf(QLatin1Char(':'));
    const QString host = sp.remoteChannel.left(pos);
    const quint16 port = sp.remoteChannel.mid(pos + 1).toInt();
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
    qDebug() << "STARTING QML ENGINE" <<  host << port << sp.remoteChannel
        << sp.executable << sp.processArgs << sp.workingDirectory;
  
    ProjectExplorer::Environment env = ProjectExplorer::Environment::systemEnvironment(); // empty env by default
    env.set("QML_DEBUG_SERVER_PORT", QString::number(serverPort));

    connect(&m_proc, SIGNAL(error(QProcess::ProcessError)),
        SLOT(handleProcError(QProcess::ProcessError)));
    connect(&m_proc, SIGNAL(finished(int, QProcess::ExitStatus)),
        SLOT(handleProcFinished(int, QProcess::ExitStatus)));
    connect(&m_proc, SIGNAL(readyReadStandardOutput()),
        SLOT(readProcStandardOutput()));
    connect(&m_proc, SIGNAL(readyReadStandardError()),
        SLOT(readProcStandardError()));

    m_proc.setEnvironment(env.toStringList());
    m_proc.setWorkingDirectory(sp.workingDirectory);
    m_proc.start(sp.executable, sp.processArgs);

    if (!m_proc.waitForStarted()) {
256
        setState(EngineStartFailed);
257
258
259
        startFailed();
        return;
    }
260
    setState(EngineStarted);
261
    startSuccessful();
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
    setState(InferiorStarting);

    //m_frameRate = new CanvasFrameRate(0);
    //m_frameRate->show();
}

void QmlEngine::setupConnection()
{
    QTC_ASSERT(m_conn == 0, /**/);
    m_conn = new QDeclarativeDebugConnection(this);

    connect(m_conn, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
            SLOT(connectionStateChanged()));
    connect(m_conn, SIGNAL(error(QAbstractSocket::SocketError)),
            SLOT(connectionError()));
    connect(m_conn, SIGNAL(connected()),
            SLOT(connectionConnected()));

    QTC_ASSERT(m_client == 0, /**/);
    m_client = new QmlDebuggerClient(m_conn, this);
282
    (void) new QmlFrameRateClient(m_conn, this);
283
284


hjk's avatar
hjk committed
285
286
287
288
289
290
291
292
293
    QTC_ASSERT(m_engineDebugInterface == 0, /**/);
    m_engineDebugInterface = new QDeclarativeEngineDebug(m_conn, this);

    //m_objectTreeWidget->setEngineDebug(m_engineDebugInterface);
    //m_propertiesWidget->setEngineDebug(m_engineDebugInterface);
    //m_watchTableModel->setEngineDebug(m_engineDebugInterface);
    //m_expressionWidget->setEngineDebug(m_engineDebugInterface);
    //resetViews();
    //m_frameRateWidget->reset(m_conn);
294
295
296
297
298
299
300
301
302
303
304
305
306
307

    QHostAddress ha(QHostAddress::LocalHost);

    qDebug() << "CONNECTING TO " << ha.toString() << serverPort;
    m_conn->connectToHost(ha, serverPort);

    if (!m_conn->waitForConnected()) {
        qDebug() << "CONNECTION FAILED";
        setState(InferiorStartFailed);
        startFailed();
        return;
    }

    qDebug() << "CONNECTION SUCCESSFUL";
308
    setState(InferiorRunningRequested);
309
    setState(InferiorRunning);
hjk's avatar
hjk committed
310
311

    reloadEngines();
312
313
314
315
316
}

void QmlEngine::continueInferior()
{
    SDEBUG("QmlEngine::continueInferior()");
317
318
319
320
321
322
    QByteArray reply;
    QDataStream rs(&reply, QIODevice::WriteOnly);
    rs << QByteArray("CONTINUE");
    sendMessage(reply);
    setState(InferiorRunningRequested);
    setState(InferiorRunning);
323
324
325
326
327
328
329
330
}

void QmlEngine::runInferior()
{
}

void QmlEngine::interruptInferior()
{
331
    qDebug() << "INTERRUPT";
332
333
334
335
    QByteArray reply;
    QDataStream rs(&reply, QIODevice::WriteOnly);
    rs << QByteArray("INTERRUPT");
    sendMessage(reply);
336
337
338
339
}

void QmlEngine::executeStep()
{
340
341
342
343
344
345
346
    SDEBUG("QmlEngine::executeStep()");
    QByteArray reply;
    QDataStream rs(&reply, QIODevice::WriteOnly);
    rs << QByteArray("STEPINTO");
    sendMessage(reply);
    setState(InferiorRunningRequested);
    setState(InferiorRunning);
347
348
349
350
}

void QmlEngine::executeStepI()
{
351
352
353
354
355
356
357
    SDEBUG("QmlEngine::executeStepI()");
    QByteArray reply;
    QDataStream rs(&reply, QIODevice::WriteOnly);
    rs << QByteArray("STEPINTO");
    sendMessage(reply);
    setState(InferiorRunningRequested);
    setState(InferiorRunning);
358
359
360
361
}

void QmlEngine::executeStepOut()
{
362
363
364
365
366
367
368
    SDEBUG("QmlEngine::executeStepOut()");
    QByteArray reply;
    QDataStream rs(&reply, QIODevice::WriteOnly);
    rs << QByteArray("STEPOUT");
    sendMessage(reply);
    setState(InferiorRunningRequested);
    setState(InferiorRunning);
369
370
371
372
}

void QmlEngine::executeNext()
{
373
374
375
376
377
378
379
    QByteArray reply;
    QDataStream rs(&reply, QIODevice::WriteOnly);
    rs << QByteArray("STEPOVER");
    sendMessage(reply);
    setState(InferiorRunningRequested);
    setState(InferiorRunning);
    SDEBUG("QmlEngine::nextExec()");
380
381
382
383
}

void QmlEngine::executeNextI()
{
384
    SDEBUG("QmlEngine::executeNextI()");
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
}

void QmlEngine::executeRunToLine(const QString &fileName, int lineNumber)
{
    Q_UNUSED(fileName)
    Q_UNUSED(lineNumber)
    SDEBUG("FIXME:  QmlEngine::executeRunToLine()");
}

void QmlEngine::executeRunToFunction(const QString &functionName)
{
    Q_UNUSED(functionName)
    XSDEBUG("FIXME:  QmlEngine::executeRunToFunction()");
}

void QmlEngine::executeJumpToLine(const QString &fileName, int lineNumber)
{
    Q_UNUSED(fileName)
    Q_UNUSED(lineNumber)
    XSDEBUG("FIXME:  QmlEngine::executeJumpToLine()");
}

void QmlEngine::activateFrame(int index)
{
    Q_UNUSED(index)
410
411
    qDebug() << Q_FUNC_INFO << index;
    gotoLocation(stackHandler()->frames().value(index), true);
412
413
414
415
416
417
418
419
420
}

void QmlEngine::selectThread(int index)
{
    Q_UNUSED(index)
}

void QmlEngine::attemptBreakpointSynchronization()
{
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
    BreakHandler *handler = breakHandler();
    //bool updateNeeded = false;
    QSet< QPair<QString, qint32> > breakList;
    for (int index = 0; index != handler->size(); ++index) {
        BreakpointData *data = handler->at(index);
        breakList << qMakePair(data->fileName, data->lineNumber.toInt());
    }

    {
    QByteArray reply;
    QDataStream rs(&reply, QIODevice::WriteOnly);
    rs << QByteArray("BREAKPOINTS");
    rs << breakList;
    //qDebug() << Q_FUNC_INFO << breakList;
    sendMessage(reply);
    }
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
}

void QmlEngine::loadSymbols(const QString &moduleName)
{
    Q_UNUSED(moduleName)
}

void QmlEngine::loadAllSymbols()
{
}

void QmlEngine::reloadModules()
{
}

void QmlEngine::requestModuleSymbols(const QString &moduleName)
{
    Q_UNUSED(moduleName)
}

457
458
459
460
461
462
void QmlEngine::sendMessage(const QByteArray &msg)
{
    QTC_ASSERT(m_client, return);
    m_client->sendMessage(msg);
}

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

//////////////////////////////////////////////////////////////////////
//
// Tooltip specific stuff
//
//////////////////////////////////////////////////////////////////////

static WatchData m_toolTip;
static QPoint m_toolTipPos;
static QHash<QString, WatchData> m_toolTipCache;

void QmlEngine::setToolTipExpression(const QPoint &mousePos, TextEditor::ITextEditor *editor, int cursorPos)
{
    Q_UNUSED(mousePos)
    Q_UNUSED(editor)
    Q_UNUSED(cursorPos)
}

//////////////////////////////////////////////////////////////////////
//
// Watch specific stuff
//
//////////////////////////////////////////////////////////////////////

void QmlEngine::assignValueInDebugger(const QString &expression,
    const QString &value)
{
    XSDEBUG("ASSIGNING: " << expression + '=' + value);
    updateLocals();
}

void QmlEngine::updateLocals()
{
hjk's avatar
hjk committed
496
    qDebug() << "UPDATE LOCALS";
497
498
}

499
void QmlEngine::updateWatchData(const WatchData &data)
500
{
hjk's avatar
hjk committed
501
    qDebug() << "UPDATE WATCH DATA" << data.toString();
502
    //watchHandler()->rebuildModel();
503
    showStatusMessage(tr("Stopped."), 5000);
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519

    if (!data.name.isEmpty()) {
        QByteArray reply;
        QDataStream rs(&reply, QIODevice::WriteOnly);
        rs << QByteArray("EXEC");
        rs << data.iname << data.name;
        sendMessage(reply);
    }

    {
        QByteArray reply;
        QDataStream rs(&reply, QIODevice::WriteOnly);
        rs << QByteArray("WATCH_EXPRESSIONS");
        rs << watchHandler()->watchedExpressions();
        sendMessage(reply);
    }
520
521
522
523
524
525
526
527
}

void QmlEngine::updateSubItem(const WatchData &data0)
{
    Q_UNUSED(data0)
    QTC_ASSERT(false, return);
}

528
DebuggerEngine *createQmlEngine(const DebuggerStartParameters &sp)
529
{
530
    return new QmlEngine(sp);
531
532
}

533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
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
unsigned QmlEngine::debuggerCapabilities() const
{
    return AddWatcherCapability;
    /*ReverseSteppingCapability | SnapshotCapability
        | AutoDerefPointersCapability | DisassemblerCapability
        | RegisterCapability | ShowMemoryCapability
        | JumpToLineCapability | ReloadModuleCapability
        | ReloadModuleSymbolsCapability | BreakOnThrowAndCatchCapability
        | ReturnFromFunctionCapability
        | CreateFullBacktraceCapability
        | WatchpointCapability
        | AddWatcherCapability;*/
}

static void updateWatchDataFromVariant(const QVariant &value,  WatchData &data)
{
    switch (value.userType()) {
        case QVariant::Bool:
            data.setType(QLatin1String("Bool"), false);
            data.setValue(value.toBool() ? QLatin1String("true") : QLatin1String("false"));
            data.setHasChildren(false);
            break;
        case QVariant::Date:
        case QVariant::DateTime:
        case QVariant::Time:
            data.setType(QLatin1String("Date"), false);
            data.setValue(value.toDateTime().toString());
            data.setHasChildren(false);
            break;
        /*} else if (ob.isError()) {
            data.setType(QLatin1String("Error"), false);
            data.setValue(QString(QLatin1Char(' ')));
        } else if (ob.isFunction()) {
            data.setType(QLatin1String("Function"), false);
            data.setValue(QString(QLatin1Char(' ')));*/
        case QVariant::Invalid:{
            const QString nullValue = QLatin1String("<null>");
            data.setType(nullValue, false);
            data.setValue(nullValue);
            break;}
        case QVariant::UInt:
        case QVariant::Int:
        case QVariant::Double:
        //FIXME FLOAT
            data.setType(QLatin1String("Number"), false);
            data.setValue(QString::number(value.toDouble()));
            data.setHasChildren(false);
            break;
/*                } else if (ob.isObject()) {
            data.setType(QLatin1String("Object"), false);
            data.setValue(QString(QLatin1Char(' ')));
        } else if (ob.isQMetaObject()) {
            data.setType(QLatin1String("QMetaObject"), false);
            data.setValue(QString(QLatin1Char(' ')));
        } else if (ob.isQObject()) {
            data.setType(QLatin1String("QObject"), false);
            data.setValue(QString(QLatin1Char(' ')));
        } else if (ob.isRegExp()) {
            data.setType(QLatin1String("RegExp"), false);
            data.setValue(ob.toRegExp().pattern());
        } else if (ob.isString()) {*/
        case QVariant::String:
            data.setType(QLatin1String("String"), false);
            data.setValue(value.toString());
/*                } else if (ob.isVariant()) {
            data.setType(QLatin1String("Variant"), false);
            data.setValue(QString(QLatin1Char(' ')));
        } else if (ob.isUndefined()) {
            data.setType(QLatin1String("<undefined>"), false);
            data.setValue(QLatin1String("<unknown>"));
            data.setHasChildren(false);
        } else {*/
        default:{
            const QString unknown = QLatin1String("<unknown>");
            data.setType(unknown, false);
            data.setValue(unknown);
            data.setHasChildren(false);
        }
    }
}

void QmlEngine::messageReceived(const QByteArray &message)
{
    QByteArray rwData = message;
    QDataStream stream(&rwData, QIODevice::ReadOnly);

    QByteArray command;
    stream >> command;

622
623
    qDebug() << "RECEIVED COMMAND: " << command;

624
    showMessage(_("RECEIVED RESPONSE: ") + quoteUnprintableLatin1(message));
625
626
627
628
    if (command == "STOPPED") {
        setState(InferiorStopping);
        setState(InferiorStopped);

629
630
631
632
        QList<QPair<QString, QPair<QString, qint32> > > backtrace;
        QList<QPair<QString, QVariant> > watches;
        stream >> backtrace >> watches;

633
        StackFrames stackFrames;
634
635
636
637
638
639
        typedef QPair<QString, QPair<QString, qint32> > Iterator;
        foreach (const Iterator &it, backtrace) {
            StackFrame frame;
            frame.file = it.second.first;
            frame.line = it.second.second;
            frame.function = it.first;
640
            stackFrames.append(frame);
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
        }

        gotoLocation(stackFrames.value(0), true);
        stackHandler()->setFrames(stackFrames);

        watchHandler()->beginCycle();

        typedef QPair<QString, QVariant > Iterator2;
        foreach (const Iterator2 &it, watches) {
            WatchData data;
            data.name = it.first;
            data.exp = it.first.toUtf8();
            data.iname = watchHandler()->watcherName(data.exp);
            updateWatchDataFromVariant(it.second,  data);
            watchHandler()->insertData(data);
        }

        watchHandler()->endCycle();

hjk's avatar
hjk committed
660
661
662
663
664
665
666
667
        foreach (QDeclarativeDebugWatch *watch, m_watches) {
            qDebug() << "WATCH"
                << watch->objectName()
                << watch->queryId()
                << watch->state()
                << watch->objectDebugId();
        }

668
669
670
671
672
673
674
675
676
677
678
679
680
681
    } else if (command == "RESULT") {
        WatchData data;
        QVariant variant;
        stream >> data.iname >> data.name >> variant;
        data.exp = data.name.toUtf8();
        updateWatchDataFromVariant(variant,  data);
        qDebug() << Q_FUNC_INFO << this << data.name << data.iname << variant;
        watchHandler()->insertData(data);
    } else {
        qDebug() << Q_FUNC_INFO << "Unknown command: " << command;
    }

}

682
683
684
685
686
687
688
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
QString QmlEngine::errorMessage(QProcess::ProcessError error)
{
    switch (error) {
        case QProcess::FailedToStart:
            return tr("The Gdb process failed to start. Either the "
                "invoked program is missing, or you may have insufficient "
                "permissions to invoke the program.");
        case QProcess::Crashed:
            return tr("The Gdb process crashed some time after starting "
                "successfully.");
        case QProcess::Timedout:
            return tr("The last waitFor...() function timed out. "
                "The state of QProcess is unchanged, and you can try calling "
                "waitFor...() again.");
        case QProcess::WriteError:
            return tr("An error occurred when attempting to write "
                "to the Gdb process. For example, the process may not be running, "
                "or it may have closed its input channel.");
        case QProcess::ReadError:
            return tr("An error occurred when attempting to read from "
                "the Gdb process. For example, the process may not be running.");
        default:
            return tr("An unknown error in the Gdb process occurred. ");
    }
}

void QmlEngine::handleProcError(QProcess::ProcessError error)
{
    showMessage(_("HANDLE QML ERROR"));
    switch (error) {
    case QProcess::Crashed:
        break; // will get a processExited() as well
    // impossible case QProcess::FailedToStart:
    case QProcess::ReadError:
    case QProcess::WriteError:
    case QProcess::Timedout:
    default:
        m_proc.kill();
        setState(EngineShuttingDown, true);
        plugin()->showMessageBox(QMessageBox::Critical, tr("Gdb I/O Error"),
                       errorMessage(error));
        break;
    }
}

void QmlEngine::handleProcFinished(int code, QProcess::ExitStatus type)
{
    showMessage(_("QML VIEWER PROCESS FINISHED, status %1, code %2").arg(type).arg(code));
    setState(DebuggerNotReady, true);
}

void QmlEngine::readProcStandardError()
{
735
    QString msg = QString::fromUtf8(m_proc.readAllStandardError());
736
737
    if (!m_conn)
        setupConnection();
738
739
    qDebug() << "STD ERR" << msg;
    showMessage(msg, AppError);
740
741
742
743
}

void QmlEngine::readProcStandardOutput()
{
744
745
746
    QString msg = QString::fromUtf8(m_proc.readAllStandardOutput());
    qDebug() << "STD OUT" << msg;
    showMessage(msg, AppOutput);
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
}

void QmlEngine::connectionStateChanged()
{
    QTC_ASSERT(m_conn, return);
    QAbstractSocket::SocketState state = m_conn->state();
    qDebug() << "CONNECTION STATE: " << state;
    switch (state) {
        case QAbstractSocket::UnconnectedState:
        {
            showStatusMessage(tr("[QmlEngine] disconnected.\n\n"));
//            resetViews();

//            updateMenuActions();

            break;
        }
        case QAbstractSocket::HostLookupState:
            showStatusMessage(tr("[QmlEngine] resolving host..."));
            break;
        case QAbstractSocket::ConnectingState:
            showStatusMessage(tr("[QmlEngine] connecting to debug server..."));
            break;
        case QAbstractSocket::ConnectedState:
            showStatusMessage(tr("[QmlEngine] connected.\n"));
            //setupConnection()
            break;
        case QAbstractSocket::ClosingState:
            showStatusMessage(tr("[QmlEngine] closing..."));
            break;
        case QAbstractSocket::BoundState:
            showStatusMessage(tr("[QmlEngine] bound state"));
            break;
        case QAbstractSocket::ListeningState:
            showStatusMessage(tr("[QmlEngine] listening state"));
            break;
        default:
            showStatusMessage(tr("[QmlEngine] unknown state: %1").arg(state));
            break;
    }
}

void QmlEngine::connectionError()
{
    QTC_ASSERT(m_conn, return);
    showStatusMessage(tr("[QmlEngine] error: (%1) %2", "%1=error code, %2=error message")
            .arg(m_conn->error()).arg(m_conn->errorString()));
}

void QmlEngine::connectionConnected()
{
    QTC_ASSERT(m_conn, return);
    showStatusMessage(tr("[QmlEngine] error: (%1) %2", "%1=error code, %2=error message")
            .arg(m_conn->error()).arg(m_conn->errorString()));
}


hjk's avatar
hjk committed
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
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
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
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
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
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
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
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
#if 0
class EngineComboBox : public QComboBox
{
    Q_OBJECT
public:
    struct EngineInfo
    {
        QString name;
        int id;
    };

    EngineComboBox(QWidget *parent = 0);

    void addEngine(int engine, const QString &name);
    void clearEngines();

protected:

private:
    QList<EngineInfo> m_engines;
};

EngineComboBox::EngineComboBox(QWidget *parent)
    : QComboBox(parent)
{
    setEnabled(false);
    setEditable(false);
}

void EngineComboBox::addEngine(int engine, const QString &name)
{
    EngineInfo info;
    info.id = engine;
    if (name.isEmpty())
        info.name = tr("Engine %1", "engine number").arg(engine);
    else
        info.name = name;
    m_engines << info;

    addItem(info.name);
}

void EngineComboBox::clearEngines()
{
    m_engines.clear();
    clear();
}


bool QmlEngine::setDebugConfigurationDataFromProject(ProjectExplorer::Project *projectToDebug)
{
    if (!projectToDebug) {
        emit statusMessage(tr("Invalid project, debugging canceled."));
        return false;
    }

    QmlProjectManager::QmlProjectRunConfiguration* config =
            qobject_cast<QmlProjectManager::QmlProjectRunConfiguration*>(projectToDebug->activeTarget()->activeRunConfiguration());
    if (!config) {
        emit statusMessage(tr("Cannot find project run configuration, debugging canceled."));
        return false;
    }
    m_runConfigurationDebugData.serverAddress = config->debugServerAddress();
    m_runConfigurationDebugData.serverPort = config->debugServerPort();
    m_connectionTimer->setInterval(ConnectionAttemptDefaultInterval);

    return true;
}

void QmlEngine::startQmlProjectDebugger()
{
    m_simultaneousCppAndQmlDebugMode = false;
    m_connectionTimer->start();
}

bool QmlEngine::connectToViewer()
{
    if (m_conn && m_conn->state() != QAbstractSocket::UnconnectedState)
        return false;

    delete m_engineDebugInterface; m_engineDebugInterface = 0;

    if (m_conn) {
        m_conn->disconnectFromHost();
        delete m_conn;
        m_conn = 0;
    }

    QString host = m_runConfigurationDebugData.serverAddress;
    quint16 port = quint16(m_runConfigurationDebugData.serverPort);

    m_conn = new QDeclarativeDebugConnection(this);
    connect(m_conn, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
            SLOT(connectionStateChanged()));
    connect(m_conn, SIGNAL(error(QAbstractSocket::SocketError)),
            SLOT(connectionError()));

    emit statusMessage(tr("[Inspector] set to connect to debug server %1:%2").arg(host).arg(port));
    m_conn->connectToHost(host, port);
    // blocks until connected; if no connection is available, will fail immediately

    if (!m_conn->waitForConnected())
        return false;

    QTC_ASSERT(m_debuggerRunControl, return false);
    QmlEngine *engine = qobject_cast<QmlEngine *>(m_debuggerRunControl->engine());
    QTC_ASSERT(engine, return false);

    (void) new DebuggerClient(m_conn, engine);

    return true;
}

void QmlEngine::disconnectFromViewer()
{
    m_conn->disconnectFromHost();
    updateMenuActions();
}

void QmlEngine::connectionStateChanged()
{
    switch (m_conn->state()) {
        case QAbstractSocket::UnconnectedState:
        {
            emit statusMessage(tr("[Inspector] disconnected.\n\n"));
            resetViews();
            updateMenuActions();
            break;
        }
        case QAbstractSocket::HostLookupState:
            emit statusMessage(tr("[Inspector] resolving host..."));
            break;
        case QAbstractSocket::ConnectingState:
            emit statusMessage(tr("[Inspector] connecting to debug server..."));
            break;
        case QAbstractSocket::ConnectedState:
        {
            emit statusMessage(tr("[Inspector] connected.\n"));

            resetViews();
//            m_frameRateWidget->reset(m_conn);

            break;
        }
        case QAbstractSocket::ClosingState:
            emit statusMessage(tr("[Inspector] closing..."));
            break;
        case QAbstractSocket::BoundState:
        case QAbstractSocket::ListeningState:
            break;
    }
}

void QmlEngine::resetViews()
{
    m_objectTreeWidget->cleanup();
    m_propertiesWidget->clear();
    m_expressionWidget->clear();
    m_watchTableModel->removeAllWatches();
}

void QmlEngine::createDockWidgets()
{

    m_engineComboBox = new Internal::EngineComboBox;
    m_engineComboBox->setEnabled(false);
    connect(m_engineComboBox, SIGNAL(currentIndexChanged(int)),
            SLOT(queryEngineContext(int)));

    // FancyMainWindow uses widgets' window titles for tab labels
//    m_frameRateWidget->setWindowTitle(tr("Frame rate"));

    Utils::StyledBar *treeOptionBar = new Utils::StyledBar;
    QHBoxLayout *treeOptionBarLayout = new QHBoxLayout(treeOptionBar);
    treeOptionBarLayout->setContentsMargins(5, 0, 5, 0);
    treeOptionBarLayout->setSpacing(5);
    treeOptionBarLayout->addWidget(new QLabel(tr("QML engine:")));
    treeOptionBarLayout->addWidget(m_engineComboBox);

    QWidget *treeWindow = new QWidget;
    treeWindow->setObjectName(QLatin1String("QmlDebugTree"));
    treeWindow->setWindowTitle(tr("Object Tree"));
    QVBoxLayout *treeWindowLayout = new QVBoxLayout(treeWindow);
    treeWindowLayout->setMargin(0);
    treeWindowLayout->setSpacing(0);
    treeWindowLayout->setContentsMargins(0,0,0,0);
    treeWindowLayout->addWidget(treeOptionBar);
    treeWindowLayout->addWidget(m_objectTreeWidget);


    m_watchTableView->setModel(m_watchTableModel);
    Internal::WatchTableHeaderView *header = new Internal::WatchTableHeaderView(m_watchTableModel);
    m_watchTableView->setHorizontalHeader(header);

    connect(m_objectTreeWidget, SIGNAL(activated(QDeclarativeDebugObjectReference)),
            this, SLOT(treeObjectActivated(QDeclarativeDebugObjectReference)));

    connect(m_objectTreeWidget, SIGNAL(currentObjectChanged(QDeclarativeDebugObjectReference)),
            m_propertiesWidget, SLOT(reload(QDeclarativeDebugObjectReference)));

    connect(m_objectTreeWidget, SIGNAL(expressionWatchRequested(QDeclarativeDebugObjectReference,QString)),
            m_watchTableModel, SLOT(expressionWatchRequested(QDeclarativeDebugObjectReference,QString)));

    connect(m_propertiesWidget, SIGNAL(watchToggleRequested(QDeclarativeDebugObjectReference,QDeclarativeDebugPropertyReference)),
            m_watchTableModel, SLOT(togglePropertyWatch(QDeclarativeDebugObjectReference,QDeclarativeDebugPropertyReference)));

    connect(m_watchTableModel, SIGNAL(watchCreated(QDeclarativeDebugWatch*)),
            m_propertiesWidget, SLOT(watchCreated(QDeclarativeDebugWatch*)));

    connect(m_watchTableModel, SIGNAL(rowsInserted(QModelIndex,int,int)),
            m_watchTableView, SLOT(scrollToBottom()));

    connect(m_watchTableView, SIGNAL(objectActivated(int)),
            m_objectTreeWidget, SLOT(setCurrentObject(int)));

    connect(m_objectTreeWidget, SIGNAL(currentObjectChanged(QDeclarativeDebugObjectReference)),
            m_expressionWidget, SLOT(setCurrentObject(QDeclarativeDebugObjectReference)));


    Core::MiniSplitter *propSplitter = new Core::MiniSplitter(Qt::Horizontal);
    Core::MiniSplitter *propWatcherSplitter = new Core::MiniSplitter(Qt::Vertical);
    propWatcherSplitter->addWidget(m_propertiesWidget);
    propWatcherSplitter->addWidget(m_watchTableView);
    propWatcherSplitter->setStretchFactor(0, 2);
    propWatcherSplitter->setStretchFactor(1, 1);
    propWatcherSplitter->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Expanding);

    propSplitter->setWindowTitle(tr("Properties and Watchers"));
    propSplitter->setObjectName(QLatin1String("QmlDebugProperties"));
    propSplitter->addWidget(m_objectTreeWidget);
    propSplitter->addWidget(propWatcherSplitter);
    propSplitter->setStretchFactor(0, 1);
    propSplitter->setStretchFactor(1, 3);

    InspectorOutputWidget *inspectorOutput = new InspectorOutputWidget();
    inspectorOutput->setObjectName(QLatin1String("QmlDebugInspectorOutput"));
    connect(this, SIGNAL(statusMessage(QString)),
            inspectorOutput, SLOT(addInspectorStatus(QString)));

    Debugger::DebuggerUISwitcher *uiSwitcher = Debugger::DebuggerUISwitcher::instance();

    m_watchTableView->hide();
//    m_objectTreeDock = uiSwitcher->createDockWidget(Qml::Constants::LANG_QML,
//                                                            treeWindow, Qt::BottomDockWidgetArea);
//    m_frameRateDock = uiSwitcher->createDockWidget(Qml::Constants::LANG_QML,
//                                                            m_frameRateWidget, Qt::BottomDockWidgetArea);
    m_propertyWatcherDock = uiSwitcher->createDockWidget(Qml::Constants::LANG_QML,
                                                            propSplitter, Qt::BottomDockWidgetArea);
    m_inspectorOutputDock = uiSwitcher->createDockWidget(Qml::Constants::LANG_QML,
                                                            inspectorOutput, Qt::BottomDockWidgetArea);

    m_expressionWidget->setWindowTitle(tr("Script Console"));
    m_expressionQueryDock = uiSwitcher->createDockWidget(Qml::Constants::LANG_QML,
                                                         m_expressionWidget, Qt::BottomDockWidgetArea);

    m_inspectorOutputDock->setToolTip(tr("Output of the QML inspector, such as information on connecting to the server."));

    m_dockWidgets << /*m_objectTreeDock << *//*m_frameRateDock << */ m_propertyWatcherDock
                  << m_inspectorOutputDock << m_expressionQueryDock;

    m_context = new Internal::InspectorContext(m_objectTreeWidget);
    m_propWatcherContext = new Internal::InspectorContext(m_propertyWatcherDock);

    Core::ICore *core = Core::ICore::instance();
    core->addContextObject(m_propWatcherContext);
    core->addContextObject(m_context);

    m_simultaneousDebugAction = new QAction(this);
    m_simultaneousDebugAction->setText(tr("Start Debugging C++ and QML Simultaneously..."));
    connect(m_simultaneousDebugAction, SIGNAL(triggered()),
        this, SLOT(simultaneouslyDebugQmlCppApplication()));

    Core::ActionManager *am = core->actionManager();
    Core::ActionContainer *mstart = am->actionContainer(ProjectExplorer::Constants::M_DEBUG_STARTDEBUGGING);
    Core::Command *cmd = am->registerAction(m_simultaneousDebugAction, Constants::M_DEBUG_SIMULTANEOUSLY,
                                            m_context->context());
    cmd->setAttribute(Core::Command::CA_Hide);
    mstart->addAction(cmd, Core::Constants::G_DEFAULT_ONE);

    m_settings.readSettings(core->settings());
    m_objectTreeWidget->readSettings(m_settings);
    m_propertiesWidget->readSettings(m_settings);

    connect(m_objectTreeWidget, SIGNAL(contextHelpIdChanged(QString)), m_context,
            SLOT(setContextHelpId(QString)));
    connect(m_watchTableView, SIGNAL(contextHelpIdChanged(QString)), m_propWatcherContext,
            SLOT(setContextHelpId(QString)));
    connect(m_propertiesWidget, SIGNAL(contextHelpIdChanged(QString)), m_propWatcherContext,
            SLOT(setContextHelpId(QString)));
    connect(m_expressionWidget, SIGNAL(contextHelpIdChanged(QString)), m_propWatcherContext,
            SLOT(setContextHelpId(QString)));
}

void QmlEngine::simultaneouslyDebugQmlCppApplication()
{
    QString errorMessage;
    ProjectExplorer::ProjectExplorerPlugin *pex = ProjectExplorer::ProjectExplorerPlugin::instance();
    ProjectExplorer::Project *project = pex->startupProject();

    if (!project)
         errorMessage = QString(tr("No project was found."));
    else {
        if (project->id() == "QmlProjectManager.QmlProject")
            errorMessage = attachToQmlViewerAsExternalApp(project);
        else {
            errorMessage = attachToExternalCppAppWithQml(project);
        }
    }

    if (!errorMessage.isEmpty())
        QMessageBox::warning(Core::ICore::instance()->mainWindow(), "Failed to debug C++ and QML", errorMessage);
}

QString QmlEngine::attachToQmlViewerAsExternalApp(ProjectExplorer::Project *project)
{
    m_debugMode = QmlProjectWithCppPlugins;

    QmlProjectManager::QmlProjectRunConfiguration* runConfig =
                qobject_cast<QmlProjectManager::QmlProjectRunConfiguration*>(project->activeTarget()->activeRunConfiguration());

    if (!runConfig)
        return QString(tr("No run configurations were found for the project '%1'.").arg(project->displayName()));

    Internal::StartExternalQmlDialog dlg(Debugger::DebuggerUISwitcher::instance()->mainWindow());

    QString importPathArgument = "-I";
    QString execArgs;
    if (runConfig->viewerArguments().contains(importPathArgument))
        execArgs = runConfig->viewerArguments().join(" ");
    else {
        QFileInfo qmlFileInfo(runConfig->viewerArguments().last());
        importPathArgument.append(" " + qmlFileInfo.absolutePath() + " ");
        execArgs = importPathArgument + runConfig->viewerArguments().join(" ");
    }


    dlg.setPort(runConfig->debugServerPort());
    dlg.setDebuggerUrl(runConfig->debugServerAddress());
    dlg.setProjectDisplayName(project->displayName());
    dlg.setDebugMode(Internal::StartExternalQmlDialog::QmlProjectWithCppPlugins);
    dlg.setQmlViewerArguments(execArgs);
    dlg.setQmlViewerPath(runConfig->viewerPath());

    if (dlg.exec() != QDialog::Accepted)
        return QString();

    m_runConfigurationDebugData.serverAddress = dlg.debuggerUrl();
    m_runConfigurationDebugData.serverPort = dlg.port();
    m_settings.setExternalPort(dlg.port());
    m_settings.setExternalUrl(dlg.debuggerUrl());

    ProjectExplorer::Environment customEnv = ProjectExplorer::Environment::systemEnvironment(); // empty env by default
    customEnv.set(QmlProjectManager::Constants::E_QML_DEBUG_SERVER_PORT, QString::number(m_settings.externalPort()));

    Debugger::DebuggerRunControl *debuggableRunControl =
     createDebuggerRunControl(runConfig, dlg.qmlViewerPath(), dlg.qmlViewerArguments());

    return executeDebuggerRunControl(debuggableRunControl, &customEnv);
}

QString QmlEngine::attachToExternalCppAppWithQml(ProjectExplorer::Project *project)
{
    m_debugMode = CppProjectWithQmlEngines;

    ProjectExplorer::LocalApplicationRunConfiguration* runConfig =
                qobject_cast<ProjectExplorer::LocalApplicationRunConfiguration*>(project->activeTarget()->activeRunConfiguration());

    if (!project->activeTarget() || !project->activeTarget()->activeRunConfiguration())
        return QString(tr("No run configurations were found for the project '%1'.").arg(project->displayName()));
    else if (!runConfig)
        return QString(tr("No valid run configuration was found for the project %1. "
                                  "Only locally runnable configurations are supported.\n"
                                  "Please check your project settings.").arg(project->displayName()));

    Internal::StartExternalQmlDialog dlg(Debugger::DebuggerUISwitcher::instance()->mainWindow());

    dlg.setPort(m_settings.externalPort());
    dlg.setDebuggerUrl(m_settings.externalUrl());
    dlg.setProjectDisplayName(project->displayName());
    dlg.setDebugMode(Internal::StartExternalQmlDialog::CppProjectWithQmlEngine);
    if (dlg.exec() != QDialog::Accepted)
        return QString();

    m_runConfigurationDebugData.serverAddress = dlg.debuggerUrl();
    m_runConfigurationDebugData.serverPort = dlg.port();
    m_settings.setExternalPort(dlg.port());
    m_settings.setExternalUrl(dlg.debuggerUrl());

    ProjectExplorer::Environment customEnv = runConfig->environment();
    customEnv.set(QmlProjectManager::Constants::E_QML_DEBUG_SERVER_PORT, QString::number(m_settings.externalPort()));
    Debugger::DebuggerRunControl *debuggableRunControl = createDebuggerRunControl(runConfig);
    return executeDebuggerRunControl(debuggableRunControl, &customEnv);
}

QString QmlEngine::executeDebuggerRunControl(Debugger::DebuggerRunControl *debuggableRunControl, ProjectExplorer::Environment *environment)
{
    ProjectExplorer::ProjectExplorerPlugin *pex = ProjectExplorer::ProjectExplorerPlugin::instance();

    // to make sure we have a valid, debuggable run control, find the correct factory for it
    if (debuggableRunControl) {

        // modify the env
        debuggableRunControl->setCustomEnvironment(*environment);

        pex->startRunControl(debuggableRunControl, ProjectExplorer::Constants::DEBUGMODE);
        m_simultaneousCppAndQmlDebugMode = true;

        return QString();
    }
    return QString(tr("A valid run control was not registered in Qt Creator for this project run configuration."));;
}

Debugger::DebuggerRunControl *QmlEngine::createDebuggerRunControl(ProjectExplorer::RunConfiguration *runConfig,
                                                                     const QString &executableFile, const QString &executableArguments)
{
    ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
    const QList<Debugger::DebuggerRunControlFactory *> factories = pm->getObjects<Debugger::DebuggerRunControlFactory>();
    ProjectExplorer::RunControl *runControl = 0;

    if (m_debugMode == QmlProjectWithCppPlugins) {
        Debugger::DebuggerStartParameters sp;
        sp.startMode = Debugger::StartExternal;
        sp.executable = executableFile;
        sp.processArgs = executableArguments.split(QLatin1Char(' '));
        runControl = factories.first()->create(sp);
        return qobject_cast<Debugger::DebuggerRunControl *>(runControl);
    }

    if (m_debugMode == CppProjectWithQmlEngines) {
        if (factories.length() && factories.first()->canRun(runConfig, ProjectExplorer::Constants::DEBUGMODE)) {
            runControl = factories.first()->create(runConfig, ProjectExplorer::Constants::DEBUGMODE);
            return qobject_cast<Debugger::DebuggerRunControl *>(runControl);
        }
    }

    return 0;
}

void QmlEngine::updateMenuActions()
{

    bool enabled = true;
    if (m_simultaneousCppAndQmlDebugMode)
        enabled = (m_cppDebuggerState == Debugger::DebuggerNotReady && (!m_conn || m_conn->state() == QAbstractSocket::UnconnectedState));
    else
        enabled = (!m_conn || m_conn->state() == QAbstractSocket::UnconnectedState);

    m_simultaneousDebugAction->setEnabled(enabled);
}


void QmlEngine::debuggerStateChanged(int newState)
{
    if (m_simultaneousCppAndQmlDebugMode) {

        switch(newState) {
        case Debugger::EngineStarting:
            {
                m_connectionInitialized = false;
                break;
            }
        case Debugger::AdapterStartFailed:
        case Debugger::InferiorStartFailed:
            emit statusMessage(QString(tr("Debugging failed: could not start C++ debugger.")));
            break;
        case Debugger::InferiorRunningRequested:
            {
                if (m_cppDebuggerState == Debugger::InferiorStopped) {
                    // re-enable UI again
                    m_objectTreeWidget->setEnabled(true);
                    m_propertiesWidget->setEnabled(true);
                    m_expressionWidget->setEnabled(true);
                }
                break;
            }
        case Debugger::InferiorRunning:
            {
                if (!m_connectionInitialized) {
                    m_connectionInitialized = true;
                    m_connectionTimer->setInterval(ConnectionAttemptSimultaneousInterval);
                    m_connectionTimer->start();
                }
                break;
            }
        case Debugger::InferiorStopped:
            {
                m_objectTreeWidget->setEnabled(false);
                m_propertiesWidget->setEnabled(false);
                m_expressionWidget->setEnabled(false);
                break;
            }
        case Debugger::EngineShuttingDown:
            {
                m_connectionInitialized = false;
                // here it's safe to enable the debugger windows again -
                // disabled ones look ugly.
                m_objectTreeWidget->setEnabled(true);
                m_propertiesWidget->setEnabled(true);
                m_expressionWidget->setEnabled(true);
                m_simultaneousCppAndQmlDebugMode = false;
                break;
            }
        default:
            break;
        }
    }

    m_cppDebuggerState = newState;
    updateMenuActions();
}


void QmlEngine::setSimpleDockWidgetArrangement()
{
    Utils::FancyMainWindow *mainWindow = Debugger::DebuggerUISwitcher::instance()->mainWindow();

    mainWindow->setTrackingEnabled(false);
    QList<QDockWidget *> dockWidgets = mainWindow->dockWidgets();
    foreach (QDockWidget *dockWidget, dockWidgets) {
        if (m_dockWidgets.contains(dockWidget)) {
            dockWidget->setFloating(false);
            mainWindow->removeDockWidget(dockWidget);
        }
    }

    foreach (QDockWidget *dockWidget, dockWidgets) {
        if (m_dockWidgets.contains(dockWidget)) {
            mainWindow->addDockWidget(Qt::BottomDockWidgetArea, dockWidget);
            dockWidget->show();
        }
    }
    mainWindow->splitDockWidget(mainWindow->toolBarDockWidget(), m_propertyWatcherDock, Qt::Vertical);
    //mainWindow->tabifyDockWidget(m_frameRateDock, m_propertyWatcherDock);
    mainWindow->tabifyDockWidget(m_propertyWatcherDock, m_expressionQueryDock);
    mainWindow->tabifyDockWidget(m_propertyWatcherDock, m_inspectorOutputDock);
    m_propertyWatcherDock->raise();

    m_inspectorOutputDock->setVisible(false);

    mainWindow->setTrackingEnabled(true);
}
#endif

void QmlEngine::reloadEngines()
{
    //m_engineComboBox->setEnabled(false);

    QDeclarativeDebugEnginesQuery *query =
           m_engineDebugInterface->queryAvailableEngines(this);
    if (!query->isWaiting())
        enginesChanged(query);
    else
        QObject::connect(query, SIGNAL(stateChanged(QDeclarativeDebugQuery::State)),
                         this, SLOT(enginesChanged()));
}

void QmlEngine::enginesChanged()
{
    enginesChanged(qobject_cast<QDeclarativeDebugEnginesQuery *>(sender()));
}

void QmlEngine::enginesChanged(QDeclarativeDebugEnginesQuery *query)
{
    //m_engineComboBox->clearEngines();
    QList<QDeclarativeDebugEngineReference> engines = query->engines();
    if (engines.isEmpty())
1370
        qWarning("QMLDEBUGGER: NO ENGINES FOUND!");
hjk's avatar
hjk committed
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
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
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
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
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745

    //m_engineComboBox->setEnabled(true);

    for (int i = 0; i < engines.count(); ++i)
        qDebug() << "ENGINE: "  <<  engines.at(i).debugId() << engines.at(i).name();
    //    m_engineComboBox->addEngine(engines.at(i).debugId(), engines.at(i).name());

    if (engines.count() > 0) {
    //    m_engineComboBox->setCurrentIndex(engines.at(0).debugId());
        queryEngineContext(engines.at(0));
    }
}

void QmlEngine::queryEngineContext(const QDeclarativeDebugEngineReference &engine)
{
    QDeclarativeDebugRootContextQuery *query =
        m_engineDebugInterface->queryRootContexts(engine, this);

    if (!query->isWaiting())
        contextChanged();
    else
        QObject::connect(query, SIGNAL(stateChanged(QDeclarativeDebugQuery::State)),
                         this, SLOT(contextChanged()));
}

void QmlEngine::contextChanged()
{
    contextChanged(qobject_cast<QDeclarativeDebugRootContextQuery *>(sender()));
}

void QmlEngine::contextChanged(QDeclarativeDebugRootContextQuery *query)
{
    QTC_ASSERT(query, return);
    //dump(query->rootContext(), 0);
    foreach (const QDeclarativeDebugObjectReference &object, query->rootContext().objects())
        reloadObject(object);
}

void QmlEngine::reloadObject(const QDeclarativeDebugObjectReference &object)
{
    qDebug() << "RELOAD OBJECT: " << object.debugId() << object.idString()
            << object.className();
    QDeclarativeDebugObjectQuery *query =
        m_engineDebugInterface->queryObjectRecursive(object, this);
    if (!query->isWaiting())
        objectFetched(query, QDeclarativeDebugQuery::Completed);
    else
        QObject::connect(query, SIGNAL(stateChanged(QDeclarativeDebugQuery::State)),
                         this, SLOT(objectFetched(QDeclarativeDebugQuery::State)));
}

void QmlEngine::objectFetched(QDeclarativeDebugQuery::State state)
{
    objectFetched(qobject_cast<QDeclarativeDebugObjectQuery *>(sender()), state);
}

void QmlEngine::objectFetched(QDeclarativeDebugObjectQuery *query,
    QDeclarativeDebugQuery::State state)
{
    QTC_ASSERT(query, return);
    QTC_ASSERT(state == QDeclarativeDebugQuery::Completed, return);
    //dump(m_query->object(), 0);

    m_watches.clear();
    buildTree(query->object(), "local");

    qDebug() << "WATCHES CREATED: " << m_watches.size();
    //watchHandler()->beginCycle();
    //watchHandler()->insertBulkData(list);
    //watchHandler()->endCycle();
    //setCurrentItem(topLevelItem(0));

    // this ugly hack is needed if user wants to see internal structs
    // on startup - debugger does not load them until towards the end,
    // so essentially loading twice gives us the full list as everything
    // is already loaded.
    //if (m_showUninspectableItems && !m_showUninspectableOnInitDone) {
    //    m_showUninspectableOnInitDone = true;
    //    reloadObject(m_currentObjectDebugId);
    //}
}

void QmlEngine::buildTree(const QDeclarativeDebugObjectReference &obj,
    const QByteArray &iname)
{
    //QTC_ASSERT(obj.contextDebugId() >= 0, return);
    WatchData data;
    data.iname = iname;

    if (obj.idString().isEmpty())
        data.name = QString("<%1>").arg(obj.className());
    else
        data.name = obj.idString();

    data.value = "?";
    data.type = "?";
    data.setHasChildren(!obj.children().isEmpty());
    data.setAllUnneeded();
    qDebug() << "CREATED ITEM " << data.iname << data.name;
    m_watches.append(m_engineDebugInterface->addWatch(obj, data.name, 0));
    //QDeclarativeDebugPropertyWatch *QDeclarativeEngineDebug::addWatch(const QDeclarativeDebugPropertyReference &property, QObject *parent)

    //data.userRole = qVariantFromValue(obj);
    /*
    if (parent && obj.contextDebugId() >= 0
            && obj.contextDebugId() != parent->data(0, Qt::UserRole
                    ).value<QDeclarativeDebugObjectReference>().contextDebugId())
    {

        QDeclarativeDebugFileReference source = obj.source();
        if (!source.url().isEmpty()) {
            QString toolTipString = QLatin1String("URL: ") + source.url().toString();
            item->setToolTip(0, toolTipString);
        }

    } else {
        item->setExpanded(true);
    }

    if (obj.contextDebugId() < 0)
        item->setHasValidDebugId(false);
*/

    for (int i = 0; i < obj.children().size(); ++i)
        buildTree(obj.children().at(i), iname + '.' + QByteArray::number(i));
}

#if 0
void QmlEngine::treeObjectActivated(const QDeclarativeDebugObjectReference &obj)
{
    QDeclarativeDebugFileReference source = obj.source();
    QString fileName = source.url().toLocalFile();

    if (source.lineNumber() < 0 || !QFile::exists(fileName))
        return;

    Core::EditorManager *editorManager = Core::EditorManager::instance();
    Core::IEditor *editor = editorManager->openEditor(fileName, QString(), Core::EditorManager::NoModeSwitch);
    TextEditor::ITextEditor *textEditor = qobject_cast<TextEditor::ITextEditor*>(editor);

    if (textEditor) {
        editorManager->addCurrentPositionToNavigationHistory();
        textEditor->gotoLine(source.lineNumber());
        textEditor->widget()->setFocus();
    }
}

bool QmlEngine::canEditProperty(const QString &propertyType)
{
    return m_editablePropertyTypes.contains(propertyType);
}

QDeclarativeDebugExpressionQuery *QmlEngine::executeExpression(int objectDebugId, const QString &objectId,
                                                                  const QString &propertyName, const QVariant &value)
{
    //qDebug() << entity.property << entity.title << entity.objectId;
    if (objectId.length()) {

        QString quoteWrappedValue = value.toString();
        if (addQuotesForData(value))
            quoteWrappedValue = QString("'%1'").arg(quoteWrappedValue);

        QString constructedExpression = objectId + "." + propertyName + "=" + quoteWrappedValue;
        //qDebug() << "EXPRESSION:" << constructedExpression;
        return m_client->queryExpressionResult(objectDebugId, constructedExpression, this);
    }

    return 0;
}

bool QmlEngine::addQuotesForData(const QVariant &value) const
{
    switch (value.type()) {
    case QVariant::String:
    case QVariant::Color:
    case QVariant::Date:
        return true;
    default:
        break;
    }

    return false;
}

ObjectTree::ObjectTree(QDeclarativeEngineDebug *client, QWidget *parent)
    : QTreeWidget(parent),
      m_client(client),
      m_query(0), m_clickedItem(0), m_showUninspectableItems(false),
      m_currentObjectDebugId(0), m_showUninspectableOnInitDone(false)
{
    setAttribute(Qt::WA_MacShowFocusRect, false);
    setFrameStyle(QFrame::NoFrame);
    setHeaderHidden(true);
    setExpandsOnDoubleClick(false);

    m_addWatchAction = new QAction(tr("Add watch expression..."), this);
    m_toggleUninspectableItemsAction = new QAction(tr("Show uninspectable items"), this);
    m_toggleUninspectableItemsAction->setCheckable(true);
    m_goToFileAction = new QAction(tr("Go to file"), this);
    connect(m_toggleUninspectableItemsAction, SIGNAL(triggered()), SLOT(toggleUninspectableItems()));
    connect(m_addWatchAction, SIGNAL(triggered()), SLOT(addWatch()));
    connect(m_goToFileAction, SIGNAL(triggered()), SLOT(goToFile()));

    connect(this, SIGNAL(currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)),
            SLOT(currentItemChanged(QTreeWidgetItem *)));
    connect(this, SIGNAL(itemActivated(QTreeWidgetItem *, int)),
            SLOT(activated(QTreeWidgetItem *)));
    connect(this, SIGNAL(itemSelectionChanged()), SLOT(selectionChanged()));
}

void ObjectTree::readSettings(const InspectorSettings &settings)
{
    if (settings.showUninspectableItems() != m_showUninspectableItems)
        toggleUninspectableItems();
}
void ObjectTree::saveSettings(InspectorSettings &settings)
{
    settings.setShowUninspectableItems(m_showUninspectableItems);
}

void ObjectTree::setEngineDebug(QDeclarativeEngineDebug *client)
{
    m_client = client;
}

void ObjectTree::toggleUninspectableItems()
{
    m_showUninspectableItems = !m_showUninspectableItems;
    m_toggleUninspectableItemsAction->setChecked(m_showUninspectableItems);
    reload(m_currentObjectDebugId);
}

void ObjectTree::selectionChanged()
{
    if (selectedItems().isEmpty())
        return;

    QTreeWidgetItem *item = selectedItems().first();
    if (item)
        emit contextHelpIdChanged(InspectorContext::contextHelpIdForItem(item->text(0)));
}


void ObjectTree::setCurrentObject(int debugId)
{
    QTreeWidgetItem *item = findItemByObjectId(debugId);
    if (item) {
        setCurrentItem(item);
        scrollToItem(item);
        item->setExpanded(true);
    }


}

{
    if (!item)
        return;

    QDeclarativeDebugObjectReference obj = item->data(0, Qt::UserRole).value<QDeclarativeDebugObjectReference>();
    if (obj.debugId() >= 0)
        emit currentObjectChanged(obj);
}

void ObjectTree::activated(QTreeWidgetItem *item)
{
    if (!item)
        return;

    QDeclarativeDebugObjectReference obj = item->data(0, Qt::UserRole).value<QDeclarativeDebugObjectReference>();
    if (obj.debugId() >= 0)
        emit activated(obj);
}

void ObjectTree::cleanup()
{
    m_showUninspectableOnInitDone = false;
    clear();
}

void ObjectTree::dump(const QDeclarativeDebugContextReference &ctxt, int ind)
{
    QByteArray indent(ind * 4, ' ');
    qWarning().nospace() << indent.constData() << ctxt.debugId() << " "
                         << qPrintable(ctxt.name());

    for (int ii = 0; ii < ctxt.contexts().count(); ++ii)
        dump(ctxt.contexts().at(ii), ind + 1);

    for (int ii = 0; ii < ctxt.objects().count(); ++ii)
        dump(ctxt.objects().at(ii), ind);
}

void ObjectTree::dump(const QDeclarativeDebugObjectReference &obj, int ind)
{
    QByteArray indent(ind * 4, ' ');
    qWarning().nospace() << indent.constData() << qPrintable(obj.className())
                         << " " << qPrintable(obj.idString()) << " "
                         << obj.debugId();

    for (int ii = 0; ii < obj.children().count(); ++ii)
        dump(obj.children().at(ii), ind + 1);
}

QTreeWidgetItem *ObjectTree::findItemByObjectId(int debugId) const
{
    for (int i=0; i<topLevelItemCount(); ++i) {
        QTreeWidgetItem *item = findItem(topLevelItem(i), debugId);
        if (item)
            return item;
    }

    return 0;
}

QTreeWidgetItem *ObjectTree::findItem(QTreeWidgetItem *item, int debugId) const
{
    if (item->data(0, Qt::UserRole).value<QDeclarativeDebugObjectReference>().debugId() == debugId)
        return item;

    QTreeWidgetItem *child;
    for (int i=0; i<item->childCount(); ++i) {
        child = findItem(item->child(i), debugId);
        if (child)
            return child;
    }

    return 0;
}

void ObjectTree::addWatch()
{
    QDeclarativeDebugObjectReference obj =
            currentItem()->data(0, Qt::UserRole).value<QDeclarativeDebugObjectReference>();

    bool ok = false;
    QString watch = QInputDialog::getText(this, tr("Watch expression"),
            tr("Expression:"), QLineEdit::Normal, QString(), &ok);
    if (ok && !watch.isEmpty())
        emit expressionWatchRequested(obj, watch);

}

void ObjectTree::goToFile()
{
    QDeclarativeDebugObjectReference obj =
            currentItem()->data(0, Qt::UserRole).value<QDeclarativeDebugObjectReference>();

    if (obj.debugId() >= 0)
        emit activated(obj);
}

void ObjectTree::contextMenuEvent(QContextMenuEvent *event)
{

    m_clickedItem = itemAt(QPoint(event->pos().x(),
                                  event->pos().y() ));
    if (!m_clickedItem)
        return;

    QMenu menu;
    menu.addAction(m_addWatchAction);
    menu.addAction(m_goToFileAction);
    if (m_currentObjectDebugId) {
        menu.addSeparator();
        menu.addAction(m_toggleUninspectableItemsAction);
    }

    menu.exec(event->globalPos());
}

} // Internal
} // Qml
#endif

1746
1747
} // namespace Internal
} // namespace Debugger
1748
1749

#include "qmlengine.moc"