qmlengine.cpp 32.1 KB
Newer Older
1 2 3 4 5 6
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
hjk's avatar
hjk committed
7
** Contact: Nokia Corporation (info@qt.nokia.com)
8 9 10 11
**
**
** GNU Lesser General Public License Usage
**
hjk's avatar
hjk committed
12 13 14 15 16 17
** 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.
18
**
con's avatar
con committed
19
** In addition, as a special exception, Nokia gives you certain additional
hjk's avatar
hjk committed
20
** rights. These rights are described in the Nokia Qt LGPL Exception
con's avatar
con committed
21 22
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
23 24 25 26 27
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
con's avatar
con committed
28
** If you have questions regarding the use of this file, please contact
Tobias Hunger's avatar
Tobias Hunger committed
29
** Nokia at info@qt.nokia.com.
30 31 32 33
**
**************************************************************************/

#include "qmlengine.h"
Lasse Holmstedt's avatar
Lasse Holmstedt committed
34
#include "qmladapter.h"
35

Friedemann Kleint's avatar
Friedemann Kleint committed
36
#include "debuggerstartparameters.h"
37
#include "debuggeractions.h"
38
#include "debuggerconstants.h"
hjk's avatar
hjk committed
39
#include "debuggercore.h"
40
#include "debuggerdialogs.h"
41
#include "debuggermainwindow.h"
hjk's avatar
hjk committed
42
#include "debuggerrunner.h"
43
#include "debuggerstringutils.h"
44
#include "debuggertooltipmanager.h"
45

46 47 48 49 50 51 52
#include "breakhandler.h"
#include "moduleshandler.h"
#include "registerhandler.h"
#include "stackhandler.h"
#include "watchhandler.h"
#include "watchutils.h"

Lasse Holmstedt's avatar
Lasse Holmstedt committed
53
#include <extensionsystem/pluginmanager.h>
54
#include <projectexplorer/applicationlauncher.h>
55

56
#include <utils/environment.h>
57
#include <utils/qtcassert.h>
58
#include <utils/fileinprojectfinder.h>
59

60
#include <coreplugin/icore.h>
61 62
#include <coreplugin/helpmanager.h>

63 64 65 66 67 68 69 70 71 72 73
#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>
74
#include <QtGui/QTextDocument>
75 76

#include <QtNetwork/QTcpSocket>
77 78
#include <QtNetwork/QHostAddress>

79 80 81 82 83 84 85 86
#define DEBUG_QML 1
#if DEBUG_QML
#   define SDEBUG(s) qDebug() << s
#else
#   define SDEBUG(s)
#endif
# define XSDEBUG(s) qDebug() << s

hjk's avatar
hjk committed
87 88
using namespace ProjectExplorer;

89 90 91
namespace Debugger {
namespace Internal {

92 93 94
struct JSAgentBreakpointData
{
    QByteArray functionName;
95 96 97 98 99 100 101 102
    QByteArray fileUrl;
    qint32 lineNumber;
};

struct JSAgentStackData
{
    QByteArray functionName;
    QByteArray fileUrl;
103 104 105 106 107
    qint32 lineNumber;
};

uint qHash(const JSAgentBreakpointData &b)
{
108
    return b.lineNumber ^ qHash(b.fileUrl);
109 110 111 112
}

QDataStream &operator<<(QDataStream &s, const JSAgentBreakpointData &data)
{
113 114 115 116 117 118
    return s << data.functionName << data.fileUrl << data.lineNumber;
}

QDataStream &operator<<(QDataStream &s, const JSAgentStackData &data)
{
    return s << data.functionName << data.fileUrl << data.lineNumber;
119 120 121 122
}

QDataStream &operator>>(QDataStream &s, JSAgentBreakpointData &data)
{
123 124 125 126 127 128
    return s >> data.functionName >> data.fileUrl >> data.lineNumber;
}

QDataStream &operator>>(QDataStream &s, JSAgentStackData &data)
{
    return s >> data.functionName >> data.fileUrl >> data.lineNumber;
129 130 131 132
}

bool operator==(const JSAgentBreakpointData &b1, const JSAgentBreakpointData &b2)
{
133
    return b1.lineNumber == b2.lineNumber && b1.fileUrl == b2.fileUrl;
134 135 136
}

typedef QSet<JSAgentBreakpointData> JSAgentBreakpoints;
137
typedef QList<JSAgentStackData> JSAgentStackFrames;
138 139


140
static QDataStream &operator>>(QDataStream &s, WatchData &data)
141 142
{
    data = WatchData();
143 144 145 146 147 148 149 150
    QByteArray name;
    QByteArray value;
    QByteArray type;
    bool hasChildren = false;
    s >> data.exp >> name >> value >> type >> hasChildren >> data.id;
    data.name = QString::fromUtf8(name);
    data.setType(type, false);
    data.setValue(QString::fromUtf8(value));
151
    data.setHasChildren(hasChildren);
152
    data.setAllUnneeded();
153 154 155
    return s;
}

156 157
class QmlEnginePrivate
{
158
public:
159 160
    explicit QmlEnginePrivate(QmlEngine *q);

161
private:
162
    friend class QmlEngine;
163
    int m_ping;
hjk's avatar
hjk committed
164 165
    QmlAdapter m_adapter;
    ApplicationLauncher m_applicationLauncher;
166
    Utils::FileInProjectFinder fileFinder;
167
    QTimer m_noDebugOutputTimer;
168 169
};

170
QmlEnginePrivate::QmlEnginePrivate(QmlEngine *q)
hjk's avatar
hjk committed
171
    : m_ping(0), m_adapter(q)
172 173
{}

174

175 176 177 178 179 180
///////////////////////////////////////////////////////////////////////
//
// QmlEngine
//
///////////////////////////////////////////////////////////////////////

181 182 183 184
QmlEngine::QmlEngine(const DebuggerStartParameters &startParameters,
        DebuggerEngine *masterEngine)
  : DebuggerEngine(startParameters, masterEngine),
    d(new QmlEnginePrivate(this))
185
{
Friedemann Kleint's avatar
Friedemann Kleint committed
186
    setObjectName(QLatin1String("QmlEngine"));
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206

    ExtensionSystem::PluginManager *pluginManager =
        ExtensionSystem::PluginManager::instance();
    pluginManager->addObject(this);

    connect(&d->m_adapter, SIGNAL(connectionError(QAbstractSocket::SocketError)),
        SLOT(connectionError(QAbstractSocket::SocketError)));
    connect(&d->m_adapter, SIGNAL(serviceConnectionError(QString)),
        SLOT(serviceConnectionError(QString)));
    connect(&d->m_adapter, SIGNAL(connected()),
        SLOT(connectionEstablished()));
    connect(&d->m_adapter, SIGNAL(connectionStartupFailed()),
        SLOT(connectionStartupFailed()));

    connect(&d->m_applicationLauncher,
        SIGNAL(processExited(int)),
        SLOT(disconnected()));
    connect(&d->m_applicationLauncher,
        SIGNAL(appendMessage(QString,Utils::OutputFormat)),
        SLOT(appendMessage(QString,Utils::OutputFormat)));
207 208 209 210 211 212

// Only wait 8 seconds for the 'Waiting for connection' on application ouput, then just try to connect
    // (application output might be redirected / blocked)
    d->m_noDebugOutputTimer.setSingleShot(true);
    d->m_noDebugOutputTimer.setInterval(8000);
    connect(&d->m_noDebugOutputTimer, SIGNAL(timeout()), this, SLOT(beginConnection()));
213 214 215
}

QmlEngine::~QmlEngine()
216 217 218 219 220 221 222 223
{
    ExtensionSystem::PluginManager *pluginManager =
        ExtensionSystem::PluginManager::instance();

    if (pluginManager->allObjects().contains(this)) {
        pluginManager->removeObject(this);
    }
}
224

hjk's avatar
hjk committed
225
void QmlEngine::setupInferior()
226
{
hjk's avatar
hjk committed
227
    QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
Lasse Holmstedt's avatar
Lasse Holmstedt committed
228

229
    if (startParameters().startMode == AttachToRemote) {
230 231 232 233
        if (startParameters().qmlServerPort != quint16(-1))
            notifyInferiorSetupOk();
        else
            emit requestRemoteSetup();
234 235 236 237 238 239
    } else {
        d->m_applicationLauncher.setEnvironment(startParameters().environment);
        d->m_applicationLauncher.setWorkingDirectory(startParameters().workingDirectory);

        notifyInferiorSetupOk();
    }
hjk's avatar
hjk committed
240
}
hjk's avatar
hjk committed
241

con's avatar
con committed
242
void QmlEngine::appendMessage(const QString &msg, Utils::OutputFormat /* format */)
hjk's avatar
hjk committed
243
{
244
    showMessage(msg, AppOutput); // FIXME: Redirect to RunControl
hjk's avatar
hjk committed
245 246
}

Lasse Holmstedt's avatar
Lasse Holmstedt committed
247 248 249 250
void QmlEngine::connectionEstablished()
{
    attemptBreakpointSynchronization();

251
    showMessage(tr("QML Debugger connected."), StatusBar);
Lasse Holmstedt's avatar
Lasse Holmstedt committed
252

253 254 255 256
    if (!watchHandler()->watcherNames().isEmpty()) {
        synchronizeWatchers();
    }
    connect(watchersModel(),SIGNAL(layoutChanged()),this,SLOT(synchronizeWatchers()));
Christiaan Janssen's avatar
Christiaan Janssen committed
257

Lasse Holmstedt's avatar
Lasse Holmstedt committed
258 259 260
    notifyEngineRunAndInferiorRunOk();
}

261 262 263 264 265 266
void QmlEngine::beginConnection()
{
    d->m_noDebugOutputTimer.stop();
    d->m_adapter.beginConnection();
}

Lasse Holmstedt's avatar
Lasse Holmstedt committed
267 268
void QmlEngine::connectionStartupFailed()
{
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
    Core::ICore * const core = Core::ICore::instance();
    QMessageBox *infoBox = new QMessageBox(core->mainWindow());
    infoBox->setIcon(QMessageBox::Critical);
    infoBox->setWindowTitle(tr("Qt Creator"));
    infoBox->setText(tr("Could not connect to the in-process QML debugger.\n"
                        "Do you want to retry?"));
    infoBox->setStandardButtons(QMessageBox::Retry | QMessageBox::Cancel | QMessageBox::Help);
    infoBox->setDefaultButton(QMessageBox::Retry);
    infoBox->setModal(true);

    connect(infoBox, SIGNAL(finished(int)),
            this, SLOT(retryMessageBoxFinished(int)));

    infoBox->show();
}

void QmlEngine::retryMessageBoxFinished(int result)
{
    switch (result) {
288
    case QMessageBox::Retry: {
289
        beginConnection();
290 291 292 293 294
        break;
    }
    case QMessageBox::Help: {
        Core::HelpManager *helpManager = Core::HelpManager::instance();
        helpManager->handleHelpRequest("qthelp://com.nokia.qtcreator/doc/creator-debugging-qml.html");
295
        // fall through
296 297 298
    }
    default:
        notifyEngineRunFailed();
Kai Koehne's avatar
Kai Koehne committed
299
        break;
300
    }
Lasse Holmstedt's avatar
Lasse Holmstedt committed
301 302
}

303
void QmlEngine::connectionError(QAbstractSocket::SocketError socketError)
Lasse Holmstedt's avatar
Lasse Holmstedt committed
304
{
hjk's avatar
hjk committed
305
    if (socketError == QAbstractSocket::RemoteHostClosedError)
306
        showMessage(tr("QML Debugger: Remote host closed connection."), StatusBar);
Lasse Holmstedt's avatar
Lasse Holmstedt committed
307 308
}

309 310
void QmlEngine::serviceConnectionError(const QString &serviceName)
{
311 312
    showMessage(tr("QML Debugger: Could not connect to service '%1'.")
        .arg(serviceName), StatusBar);
313 314
}

315 316 317 318 319
bool QmlEngine::canDisplayTooltip() const
{
    return state() == InferiorRunOk || state() == InferiorStopOk;
}

320 321
void QmlEngine::filterApplicationMessage(const QString &msg, int /*channel*/)
{
Friedemann Kleint's avatar
Friedemann Kleint committed
322
    static const QString qddserver = QLatin1String("QDeclarativeDebugServer: ");
323
    static const QString cannotRetrieveDebuggingOutput = ApplicationLauncher::msgWinCannotRetrieveDebuggingOutput();
324

325
    const int index = msg.indexOf(qddserver);
326
    if (index != -1) {
327 328 329
        // we're actually getting debug output
        d->m_noDebugOutputTimer.stop();

330 331 332
        QString status = msg;
        status.remove(0, index + qddserver.length()); // chop of 'QDeclarativeDebugServer: '

333 334 335
        static QString waitingForConnection = QLatin1String("Waiting for connection ");
        static QString unableToListen = QLatin1String("Unable to listen ");
        static QString debuggingNotEnabled = QLatin1String("Ignoring \"-qmljsdebugger=");
336
        static QString debuggingNotEnabled2 = QLatin1String("Ignoring\"-qmljsdebugger="); // There is (was?) a bug in one of the error strings - safest to handle both
337 338 339 340
        static QString connectionEstablished = QLatin1String("Connection established");

        QString errorMessage;
        if (status.startsWith(waitingForConnection)) {
341
            beginConnection();
342
        } else if (status.startsWith(unableToListen)) {
343
            //: Error message shown after 'Could not connect ... debugger:"
344
            errorMessage = tr("The port seems to be in use.");
345
        } else if (status.startsWith(debuggingNotEnabled) || status.startsWith(debuggingNotEnabled2)) {
346 347
            //: Error message shown after 'Could not connect ... debugger:"
            errorMessage = tr("The application is not set up for QML/JS debugging.");
348 349 350 351 352 353 354 355 356 357 358 359 360
        } else if (status.startsWith(connectionEstablished)) {
            // nothing to do
        } else {
            qWarning() << "Unknown QDeclarativeDebugServer status message: " << status;
        }

        if (!errorMessage.isEmpty()) {
            notifyEngineRunFailed();

            Core::ICore * const core = Core::ICore::instance();
            QMessageBox *infoBox = new QMessageBox(core->mainWindow());
            infoBox->setIcon(QMessageBox::Critical);
            infoBox->setWindowTitle(tr("Qt Creator"));
Friedemann Kleint's avatar
Friedemann Kleint committed
361 362
            //: %1 is detailed error message
            infoBox->setText(tr("Could not connect to the in-process QML debugger:\n%1")
363 364 365 366 367 368
                             .arg(errorMessage));
            infoBox->setStandardButtons(QMessageBox::Ok | QMessageBox::Help);
            infoBox->setDefaultButton(QMessageBox::Ok);
            infoBox->setModal(true);

            connect(infoBox, SIGNAL(finished(int)),
369
                    this, SLOT(wrongSetupMessageBoxFinished(int)));
370 371 372

            infoBox->show();
        }
Friedemann Kleint's avatar
Friedemann Kleint committed
373
    } else if (msg.contains(cannotRetrieveDebuggingOutput)) {
374
        // we won't get debugging output, so just try to connect ...
375
        beginConnection();
376 377 378 379 380 381 382 383 384 385 386
    }
}

void QmlEngine::showMessage(const QString &msg, int channel, int timeout) const
{
    if (channel == AppOutput || channel == AppError) {
        const_cast<QmlEngine*>(this)->filterApplicationMessage(msg, channel);
    }
    DebuggerEngine::showMessage(msg, channel, timeout);
}

387 388 389 390 391
bool QmlEngine::acceptsWatchesWhileRunning() const
{
    return true;
}

392 393
void QmlEngine::closeConnection()
{
394
    disconnect(watchersModel(),SIGNAL(layoutChanged()),this,SLOT(synchronizeWatchers()));
395
    d->m_adapter.closeConnection();
396 397
}

hjk's avatar
hjk committed
398 399 400
void QmlEngine::runEngine()
{
    QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());
Lasse Holmstedt's avatar
Lasse Holmstedt committed
401

402
    if (!isSlaveEngine() && startParameters().startMode != AttachToRemote)
403
        startApplicationLauncher();
404
    d->m_noDebugOutputTimer.start();
405 406 407 408 409
}

void QmlEngine::startApplicationLauncher()
{
    if (!d->m_applicationLauncher.isRunning()) {
410 411 412 413
        appendMessage(tr("Starting %1 %2").arg(
                          QDir::toNativeSeparators(startParameters().executable),
                          startParameters().processArgs)
                      + QLatin1Char('\n')
con's avatar
con committed
414
                     , Utils::NormalMessageFormat);
hjk's avatar
hjk committed
415
        d->m_applicationLauncher.start(ApplicationLauncher::Gui,
416 417 418
                                    startParameters().executable,
                                    startParameters().processArgs);
    }
419
}
Lasse Holmstedt's avatar
Lasse Holmstedt committed
420

421 422 423 424 425 426
void QmlEngine::stopApplicationLauncher()
{
    if (d->m_applicationLauncher.isRunning()) {
        disconnect(&d->m_applicationLauncher, SIGNAL(processExited(int)), this, SLOT(disconnected()));
        d->m_applicationLauncher.stop();
    }
427 428
}

Christian Kandeler's avatar
Christian Kandeler committed
429
void QmlEngine::handleRemoteSetupDone(int gdbServerPort, int qmlPort)
430
{
Christian Kandeler's avatar
Christian Kandeler committed
431 432 433
    Q_UNUSED(gdbServerPort);
    if (qmlPort != -1)
        startParameters().qmlServerPort = qmlPort;
434 435 436 437 438 439 440 441 442 443
    notifyInferiorSetupOk();
}

void QmlEngine::handleRemoteSetupFailed(const QString &message)
{
    QMessageBox::critical(0,tr("Failed to start application"),
        tr("Application startup failed: %1").arg(message));
    notifyInferiorSetupFailed();
}

hjk's avatar
hjk committed
444
void QmlEngine::shutdownInferior()
445
{
446 447
    if (isSlaveEngine()) {
        resetLocation();
Lasse Holmstedt's avatar
Lasse Holmstedt committed
448
    }
449
    stopApplicationLauncher();
hjk's avatar
hjk committed
450 451 452 453 454
    notifyInferiorShutdownOk();
}

void QmlEngine::shutdownEngine()
{
455
    closeConnection();
Lasse Holmstedt's avatar
Lasse Holmstedt committed
456

457 458
    // double check (ill engine?):
    stopApplicationLauncher();
Lasse Holmstedt's avatar
Lasse Holmstedt committed
459

460
    notifyEngineShutdownOk();
461 462
    if (!isSlaveEngine())
        showMessage(QString(), StatusBar);
463 464
}

hjk's avatar
hjk committed
465
void QmlEngine::setupEngine()
466
{
467
    d->m_ping = 0;
468 469 470 471

    connect(&d->m_applicationLauncher, SIGNAL(bringToForegroundRequested(qint64)),
            runControl(), SLOT(bringApplicationToForeground(qint64)),
            Qt::UniqueConnection);
Lasse Holmstedt's avatar
Lasse Holmstedt committed
472

473
    notifyEngineSetupOk();
474 475
}

476 477
void QmlEngine::continueInferior()
{
hjk's avatar
hjk committed
478
    QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
479 480
    QByteArray reply;
    QDataStream rs(&reply, QIODevice::WriteOnly);
481 482 483
    QByteArray cmd = "CONTINUE";
    rs << cmd;
    logMessage(LogSend, cmd);
484
    sendMessage(reply);
485
    resetLocation();
hjk's avatar
hjk committed
486 487
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
488 489 490 491
}

void QmlEngine::interruptInferior()
{
492 493
    QByteArray reply;
    QDataStream rs(&reply, QIODevice::WriteOnly);
494 495 496
    QByteArray cmd = "INTERRUPT";
    rs << cmd;
    logMessage(LogSend, cmd);
497
    sendMessage(reply);
498
    notifyInferiorStopOk();
499 500 501 502
}

void QmlEngine::executeStep()
{
503 504
    QByteArray reply;
    QDataStream rs(&reply, QIODevice::WriteOnly);
505 506 507
    QByteArray cmd = "STEPINTO";
    rs << cmd;
    logMessage(LogSend, cmd);
508
    sendMessage(reply);
509
    resetLocation();
hjk's avatar
hjk committed
510 511
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
512 513 514 515
}

void QmlEngine::executeStepI()
{
516 517
    QByteArray reply;
    QDataStream rs(&reply, QIODevice::WriteOnly);
518 519 520
    QByteArray cmd = "STEPINTO";
    rs << cmd;
    logMessage(LogSend, cmd);
521
    sendMessage(reply);
522
    resetLocation();
hjk's avatar
hjk committed
523 524
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
525 526 527 528
}

void QmlEngine::executeStepOut()
{
529 530
    QByteArray reply;
    QDataStream rs(&reply, QIODevice::WriteOnly);
531 532 533
    QByteArray cmd = "STEPOUT";
    rs << cmd;
    logMessage(LogSend, cmd);
534
    sendMessage(reply);
535
    resetLocation();
hjk's avatar
hjk committed
536 537
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
538 539 540 541
}

void QmlEngine::executeNext()
{
542 543
    QByteArray reply;
    QDataStream rs(&reply, QIODevice::WriteOnly);
544 545 546
    QByteArray cmd = "STEPOVER";
    rs << cmd;
    logMessage(LogSend, cmd);
547
    sendMessage(reply);
548
    resetLocation();
hjk's avatar
hjk committed
549 550
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
551 552 553 554
}

void QmlEngine::executeNextI()
{
555
    SDEBUG("QmlEngine::executeNextI()");
556 557
}

558
void QmlEngine::executeRunToLine(const ContextData &data)
559
{
560
    Q_UNUSED(data)
561 562 563 564 565 566 567 568 569
    SDEBUG("FIXME:  QmlEngine::executeRunToLine()");
}

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

570
void QmlEngine::executeJumpToLine(const ContextData &data)
571
{
572
    Q_UNUSED(data)
573 574 575 576 577
    XSDEBUG("FIXME:  QmlEngine::executeJumpToLine()");
}

void QmlEngine::activateFrame(int index)
{
578 579
    QByteArray reply;
    QDataStream rs(&reply, QIODevice::WriteOnly);
580 581 582 583
    QByteArray cmd = "ACTIVATE_FRAME";
    rs << cmd
       << index;
    logMessage(LogSend, QString("%1 %2").arg(QString(cmd), QString::number(index)));
584
    sendMessage(reply);
585
    gotoLocation(stackHandler()->frames().value(index));
586 587 588 589 590 591 592 593 594
}

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

void QmlEngine::attemptBreakpointSynchronization()
{
hjk's avatar
hjk committed
595
    BreakHandler *handler = breakHandler();
596

597
    foreach (BreakpointModelId id, handler->unclaimedBreakpointIds()) {
598 599 600 601 602
        // Take ownership of the breakpoint. Requests insertion.
        if (acceptsBreakpoint(id))
            handler->setEngine(id, this);
    }

hjk's avatar
hjk committed
603
    JSAgentBreakpoints breakpoints;
604
    foreach (BreakpointModelId id, handler->engineBreakpointIds(this)) {
605 606 607 608 609 610 611 612
        if (handler->state(id) == BreakpointRemoveRequested) {
            handler->notifyBreakpointRemoveProceeding(id);
            handler->notifyBreakpointRemoveOk(id);
        } else {
            if (handler->state(id) == BreakpointInsertRequested) {
                handler->notifyBreakpointInsertProceeding(id);
            }
            JSAgentBreakpointData bp;
613
            bp.fileUrl = QUrl::fromLocalFile(handler->fileName(id)).toString().toUtf8();
614 615 616 617 618 619 620
            bp.lineNumber = handler->lineNumber(id);
            bp.functionName = handler->functionName(id).toUtf8();
            breakpoints.insert(bp);
            if (handler->state(id) == BreakpointInsertProceeding) {
                handler->notifyBreakpointInsertOk(id);
            }
        }
621 622 623 624
    }

    QByteArray reply;
    QDataStream rs(&reply, QIODevice::WriteOnly);
625 626 627 628 629 630 631
    QByteArray cmd = "BREAKPOINTS";
    rs << cmd
       << breakpoints;

    QStringList breakPointsStr;
    foreach (const JSAgentBreakpointData &bp, breakpoints) {
        breakPointsStr << QString("('%1' '%2' %3)").arg(QString(bp.functionName),
632
                                  QString(bp.fileUrl), QString::number(bp.lineNumber));
633 634 635
    }
    logMessage(LogSend, QString("%1 [%2]").arg(QString(cmd), breakPointsStr.join(", ")));

636
    sendMessage(reply);
637 638
}

639
bool QmlEngine::acceptsBreakpoint(BreakpointModelId id) const
640
{
641
    return !DebuggerEngine::isCppBreakpoint(breakHandler()->breakpointData(id));
642 643
}

644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
void QmlEngine::loadSymbols(const QString &moduleName)
{
    Q_UNUSED(moduleName)
}

void QmlEngine::loadAllSymbols()
{
}

void QmlEngine::reloadModules()
{
}

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

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

668
bool QmlEngine::setToolTipExpression(const QPoint &mousePos,
669
    TextEditor::ITextEditor *editor, const DebuggerToolTipContext &ctx)
670
{
hjk's avatar
hjk committed
671 672
    // This is processed by QML inspector, which has dependencies to 
    // the qml js editor. Makes life easier.
673
    emit tooltipRequested(mousePos, editor, ctx.position);
674
    return true;
675 676 677 678 679 680 681 682
}

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

hjk's avatar
hjk committed
683
void QmlEngine::assignValueInDebugger(const WatchData *,
hjk's avatar
hjk committed
684
    const QString &expression, const QVariant &valueV)
685
{
686 687 688 689 690 691 692 693
    QRegExp inObject("@([0-9a-fA-F]+)->(.+)");
    if (inObject.exactMatch(expression)) {
        bool ok = false;
        quint64 objectId = inObject.cap(1).toULongLong(&ok, 16);
        QString property = inObject.cap(2);
        if (ok && objectId > 0 && !property.isEmpty()) {
            QByteArray reply;
            QDataStream rs(&reply, QIODevice::WriteOnly);
694 695
            QByteArray cmd = "SET_PROPERTY";
            rs << cmd;
696
            rs << expression.toUtf8() << objectId << property << valueV.toString();
697 698 699
            logMessage(LogSend, QString("%1 %2 %3 %4 %5").arg(
                                 QString(cmd), QString::number(objectId), QString(property),
                                 valueV.toString()));
700 701 702
            sendMessage(reply);
        }
    }
703 704
}

hjk's avatar
hjk committed
705 706
void QmlEngine::updateWatchData(const WatchData &data,
    const WatchUpdateFlags &)
707
{
Olivier Goffart's avatar
Olivier Goffart committed
708
//    qDebug() << "UPDATE WATCH DATA" << data.toString();
709
    //watchHandler()->rebuildModel();
710
    showStatusMessage(tr("Stopped."), 5000);
711

712
    if (!data.name.isEmpty() && data.isValueNeeded()) {
713 714
        QByteArray reply;
        QDataStream rs(&reply, QIODevice::WriteOnly);
715 716
        QByteArray cmd = "EXEC";
        rs << cmd;
717
        rs << data.iname << data.name;
718 719
        logMessage(LogSend, QString("%1 %2 %3").arg(QString(cmd), QString(data.iname),
                                                          QString(data.name)));
720 721 722
        sendMessage(reply);
    }

723
    if (!data.name.isEmpty() && data.isChildrenNeeded()
Christiaan Janssen's avatar
Christiaan Janssen committed
724
            && watchHandler()->isExpandedIName(data.iname)) {
Arvid Ephraim Picciani's avatar
Arvid Ephraim Picciani committed
725
        expandObject(data.iname, data.id);
Christiaan Janssen's avatar
Christiaan Janssen committed
726 727 728
    }

    synchronizeWatchers();
729

Christiaan Janssen's avatar
Christiaan Janssen committed
730 731 732 733 734 735
    if (!data.isSomethingNeeded())
        watchHandler()->insertData(data);
}

void QmlEngine::synchronizeWatchers()
{
736 737 738 739 740 741 742 743 744
    // send watchers list
    QByteArray reply;
    QDataStream rs(&reply, QIODevice::WriteOnly);
    QByteArray cmd = "WATCH_EXPRESSIONS";
    rs << cmd;
    rs << watchHandler()->watchedExpressions();
    logMessage(LogSend, QString("%1 %2").arg(
                   QString(cmd), watchHandler()->watchedExpressions().join(", ")));
    sendMessage(reply);
745 746
}

747
void QmlEngine::expandObject(const QByteArray &iname, quint64 objectId)
748 749 750
{
    QByteArray reply;
    QDataStream rs(&reply, QIODevice::WriteOnly);
751 752
    QByteArray cmd = "EXPAND";
    rs << cmd;
753
    rs << iname << objectId;
754 755
    logMessage(LogSend, QString("%1 %2 %3").arg(QString(cmd), QString(iname),
                                                      QString::number(objectId)));
756 757 758
    sendMessage(reply);
}

759 760
void QmlEngine::sendPing()
{
761
    d->m_ping++;
762 763
    QByteArray reply;
    QDataStream rs(&reply, QIODevice::WriteOnly);
764 765
    QByteArray cmd = "PING";
    rs << cmd;
766
    rs << d->m_ping;
767
    logMessage(LogSend, QString("%1 %2").arg(QString(cmd), QString::number(d->m_ping)));
768 769 770
    sendMessage(reply);
}

771 772 773 774 775 776 777 778 779 780 781 782
unsigned QmlEngine::debuggerCapabilities() const
{
    return AddWatcherCapability;
    /*ReverseSteppingCapability | SnapshotCapability
        | AutoDerefPointersCapability | DisassemblerCapability
        | RegisterCapability | ShowMemoryCapability
        | JumpToLineCapability | ReloadModuleCapability
        | ReloadModuleSymbolsCapability | BreakOnThrowAndCatchCapability
        | ReturnFromFunctionCapability
        | CreateFullBacktraceCapability
        | WatchpointCapability
        | AddWatcherCapability;*/
783 784
}

785
QString QmlEngine::toFileInProject(const QUrl &fileUrl)
786
{
787 788 789
    if (d->fileFinder.projectDirectory().isEmpty()) {
        d->fileFinder.setProjectDirectory(startParameters().projectSourceDirectory);
        d->fileFinder.setProjectFiles(startParameters().projectSourceFiles);
790 791
    }

792
    return d->fileFinder.findFile(fileUrl);
793 794
}

795 796 797 798 799 800 801 802
void QmlEngine::messageReceived(const QByteArray &message)
{
    QByteArray rwData = message;
    QDataStream stream(&rwData, QIODevice::ReadOnly);

    QByteArray command;
    stream >> command;

803
    if (command == "STOPPED") {
804
        //qDebug() << command << this << state();
hjk's avatar
hjk committed
805
        if (state() == InferiorRunOk)
806
            notifyInferiorSpontaneousStop();
807

hjk's avatar
hjk committed
808
        QString logString = QString::fromLatin1(command);
809

810
        JSAgentStackFrames stackFrames;
hjk's avatar
hjk committed
811 812
        QList<WatchData> watches;
        QList<WatchData> locals;
813
        stream >> stackFrames >> watches >> locals;
814

815 816
        logString += QString::fromLatin1(" (%1 stack frames) (%2 watches)  (%3 locals)").
                     arg(stackFrames.size()).arg(watches.size()).arg(locals.size());
817

818 819 820 821 822
        StackFrames ideStackFrames;
        for (int i = 0; i != stackFrames.size(); ++i) {
            StackFrame frame;
            frame.line = stackFrames.at(i).lineNumber;
            frame.function = stackFrames.at(i).functionName;
823
            frame.file = toFileInProject(QUrl(stackFrames.at(i).fileUrl));
824 825 826 827
            frame.usable = QFileInfo(frame.file).isReadable();
            frame.level = i + 1;
            ideStackFrames << frame;
        }
828

829 830 831
        if (ideStackFrames.size() && ideStackFrames.back().function == "<global>")
            ideStackFrames.takeLast();
        stackHandler()->setFrames(ideStackFrames);
832 833

        watchHandler()->beginCycle();
834
        bool needPing = false;
835

hjk's avatar
hjk committed
836
        foreach (WatchData data, watches) {
837
            data.iname = watchHandler()->watcherName(data.exp);
838
            watchHandler()->insertData(data);
839

840 841
            if (watchHandler()->expandedINames().contains(data.iname)) {
                needPing = true;
Arvid Ephraim Picciani's avatar
Arvid Ephraim Picciani committed
842
                expandObject(data.iname, data.id);
843
            }
844 845
        }

hjk's avatar
hjk committed
846
        foreach (WatchData data, locals) {
847 848
            data.iname = "local." + data.exp;
            watchHandler()->insertData(data);
849

850 851
            if (watchHandler()->expandedINames().contains(data.iname)) {
                needPing = true;
Arvid Ephraim Picciani's avatar
Arvid Ephraim Picciani committed
852
                expandObject(data.iname, data.id);
853
            }
hjk's avatar
hjk committed
854 855
        }

856
        if (needPing) {
857
            sendPing();
858
        } else {
859
            watchHandler()->endCycle();
860
        }
861

862 863
        bool becauseOfException;
        stream >> becauseOfException;
864 865 866

        logString += becauseOfException ? " exception" : " no_exception";

867
        if (becauseOfException) {
868 869 870
            QString error;
            stream >> error;

Friedemann Kleint's avatar
Friedemann Kleint committed
871 872
            logString += QLatin1Char(' ');
            logString += error;
873 874
            logMessage(LogReceive, logString);

875
            QString msg = stackFrames.isEmpty()
Friedemann Kleint's avatar
Friedemann Kleint committed
876
                ? tr("<p>An uncaught exception occurred:</p><p>%1</p>")
877
                    .arg(Qt::escape(error))