qmlengine.cpp 25.6 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
/**************************************************************************
**
** 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"
Lasse Holmstedt's avatar
Lasse Holmstedt committed
31
#include "qmladapter.h"
32

33
#include "debuggeractions.h"
34
#include "debuggerconstants.h"
hjk's avatar
hjk committed
35
#include "debuggercore.h"
36
#include "debuggerdialogs.h"
hjk's avatar
hjk committed
37
#include "debuggerrunner.h"
38
#include "debuggerstringutils.h"
hjk's avatar
hjk committed
39
#include "debuggertooltip.h"
40
#include "debuggeruiswitcher.h"
41

42 43 44 45 46 47 48
#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
49
#include <extensionsystem/pluginmanager.h>
50
#include <projectexplorer/applicationlauncher.h>
51

52
#include <utils/environment.h>
53 54 55 56 57 58 59 60 61 62 63 64 65
#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>
66
#include <QtGui/QTextDocument>
67 68

#include <QtNetwork/QTcpSocket>
69 70
#include <QtNetwork/QHostAddress>

71 72 73 74 75 76 77 78
#define DEBUG_QML 1
#if DEBUG_QML
#   define SDEBUG(s) qDebug() << s
#else
#   define SDEBUG(s)
#endif
# define XSDEBUG(s) qDebug() << s

Lasse Holmstedt's avatar
Lasse Holmstedt committed
79 80
enum {
    MaxConnectionAttempts = 50,
81
    ConnectionAttemptDefaultInterval = 200
Lasse Holmstedt's avatar
Lasse Holmstedt committed
82
};
83

84 85 86
namespace Debugger {
namespace Internal {

87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
struct JSAgentBreakpointData
{
    QByteArray functionName;
    QByteArray fileName;
    qint32 lineNumber;
};

uint qHash(const JSAgentBreakpointData &b)
{
    return b.lineNumber ^ qHash(b.fileName);
}

QDataStream &operator<<(QDataStream &s, const JSAgentBreakpointData &data)
{
    return s << data.functionName << data.fileName << data.lineNumber;
}

QDataStream &operator>>(QDataStream &s, JSAgentBreakpointData &data)
{
    return s >> data.functionName >> data.fileName >> data.lineNumber;
}

bool operator==(const JSAgentBreakpointData &b1, const JSAgentBreakpointData &b2)
{
    return b1.lineNumber == b2.lineNumber && b1.fileName == b2.fileName;
}

typedef QSet<JSAgentBreakpointData> JSAgentBreakpoints;


117
static QDataStream &operator>>(QDataStream &s, WatchData &data)
118 119
{
    data = WatchData();
120 121 122 123 124 125 126 127
    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));
128
    data.setHasChildren(hasChildren);
129
    data.setAllUnneeded();
130 131 132
    return s;
}

133
static QDataStream &operator>>(QDataStream &s, StackFrame &frame)
134 135 136 137 138 139 140 141 142 143
{
    frame = StackFrame();
    QByteArray function;
    QByteArray file;
    s >> function >> file >> frame.line;
    frame.function = QString::fromUtf8(function);
    frame.file = QString::fromUtf8(file);
    return s;
}

144 145
} // namespace Internal

hjk's avatar
hjk committed
146 147
using namespace Internal;

hjk's avatar
hjk committed
148 149
struct QmlEnginePrivate
{
150 151 152 153 154 155 156 157 158 159
    explicit QmlEnginePrivate(QmlEngine *q);

    int m_ping;
    QmlAdapter *m_adapter;
    ProjectExplorer::ApplicationLauncher m_applicationLauncher;
    bool m_addedAdapterToObjectPool;
    bool m_attachToRunningExternalApp;
    bool m_hasShutdown;
};

hjk's avatar
hjk committed
160 161 162 163 164 165
QmlEnginePrivate::QmlEnginePrivate(QmlEngine *q)
    : m_ping(0)
    , m_adapter(new QmlAdapter(q))
    , m_addedAdapterToObjectPool(false)
    , m_attachToRunningExternalApp(false)
    , m_hasShutdown(false)
166 167 168
{
}

169 170 171 172 173 174
///////////////////////////////////////////////////////////////////////
//
// QmlEngine
//
///////////////////////////////////////////////////////////////////////

175
QmlEngine::QmlEngine(const DebuggerStartParameters &startParameters)
176
    : DebuggerEngine(startParameters), d(new QmlEnginePrivate(this))
177
{
Friedemann Kleint's avatar
Friedemann Kleint committed
178
    setObjectName(QLatin1String("QmlEngine"));
179 180 181 182 183 184
}

QmlEngine::~QmlEngine()
{
}

185 186
void QmlEngine::setAttachToRunningExternalApp(bool value)
{
187
    d->m_attachToRunningExternalApp = value;
188 189 190 191
}

void QmlEngine::pauseConnection()
{
192
    d->m_adapter->pauseConnection();
193 194
}

195 196 197 198 199 200 201 202 203 204
void QmlEngine::gotoLocation(const QString &fileName, int lineNumber, bool setMarker)
{
    QString processedFilename = fileName;

    if (isShadowBuildProject())
        processedFilename = fromShadowBuildFilename(fileName);

    DebuggerEngine::gotoLocation(processedFilename, lineNumber, setMarker);
}

hjk's avatar
hjk committed
205
void QmlEngine::gotoLocation(const StackFrame &frame, bool setMarker)
206
{
hjk's avatar
hjk committed
207
    StackFrame adjustedFrame = frame;
208 209 210 211 212 213
    if (isShadowBuildProject())
        adjustedFrame.file = fromShadowBuildFilename(frame.file);

    DebuggerEngine::gotoLocation(adjustedFrame, setMarker);
}

hjk's avatar
hjk committed
214
void QmlEngine::setupInferior()
215
{
hjk's avatar
hjk committed
216
    QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
Lasse Holmstedt's avatar
Lasse Holmstedt committed
217

218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
    if (startParameters().startMode == AttachToRemote) {
        emit remoteStartupRequested();
    } else {
        connect(&d->m_applicationLauncher, SIGNAL(processExited(int)),
                this, SLOT(disconnected()));
        connect(&d->m_applicationLauncher, SIGNAL(appendMessage(QString,bool)),
                runControl(), SLOT(emitAppendMessage(QString,bool)));
        connect(&d->m_applicationLauncher, SIGNAL(appendOutput(QString, bool)),
                runControl(), SLOT(emitAddToOutputWindow(QString, bool)));
        connect(&d->m_applicationLauncher, SIGNAL(bringToForegroundRequested(qint64)),
                runControl(), SLOT(bringApplicationToForeground(qint64)));

        d->m_applicationLauncher.setEnvironment(startParameters().environment);
        d->m_applicationLauncher.setWorkingDirectory(startParameters().workingDirectory);

        notifyInferiorSetupOk();
    }
hjk's avatar
hjk committed
235
}
hjk's avatar
hjk committed
236

Lasse Holmstedt's avatar
Lasse Holmstedt committed
237 238 239 240
void QmlEngine::connectionEstablished()
{
    attemptBreakpointSynchronization();

241 242
    ExtensionSystem::PluginManager *pluginManager =
        ExtensionSystem::PluginManager::instance();
243
    pluginManager->addObject(d->m_adapter);
244
    pluginManager->addObject(this);
245
    d->m_addedAdapterToObjectPool = true;
Lasse Holmstedt's avatar
Lasse Holmstedt committed
246

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

    notifyEngineRunAndInferiorRunOk();
}

void QmlEngine::connectionStartupFailed()
{
254 255 256 257
    QMessageBox::critical(0, tr("Failed to connect to debugger"),
        tr("Could not connect to QML debugger server at %1:%2.")
        .arg(startParameters().qmlServerAddress)
        .arg(startParameters().qmlServerPort));
Lasse Holmstedt's avatar
Lasse Holmstedt committed
258 259 260
    notifyEngineRunFailed();
}

261
void QmlEngine::connectionError(QAbstractSocket::SocketError socketError)
Lasse Holmstedt's avatar
Lasse Holmstedt committed
262
{
263
    if (socketError ==QAbstractSocket::RemoteHostClosedError)
264
        showMessage(tr("QML Debugger: Remote host closed connection."), StatusBar);
Lasse Holmstedt's avatar
Lasse Holmstedt committed
265 266
}

267 268 269

void QmlEngine::serviceConnectionError(const QString &serviceName)
{
270 271
    showMessage(tr("QML Debugger: Could not connect to service '%1'.")
        .arg(serviceName), StatusBar);
272 273
}

hjk's avatar
hjk committed
274 275 276
void QmlEngine::runEngine()
{
    QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());
Lasse Holmstedt's avatar
Lasse Holmstedt committed
277

278 279
    if (!d->m_attachToRunningExternalApp) {
        d->m_applicationLauncher.start(ProjectExplorer::ApplicationLauncher::Gui,
280 281 282
                                    startParameters().executable,
                                    startParameters().processArgs);
    }
Lasse Holmstedt's avatar
Lasse Holmstedt committed
283

284
    d->m_adapter->beginConnection();
hjk's avatar
hjk committed
285
    showMessage(tr("QML Debugger connecting..."), StatusBar);
286 287
}

288
void QmlEngine::handleRemoteSetupDone(int port)
289
{
290 291
    if (port != -1)
        startParameters().qmlServerPort = port;
292 293 294 295 296 297 298 299 300 301
    notifyInferiorSetupOk();
}

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

302 303 304
void QmlEngine::shutdownInferiorAsSlave()
{
    resetLocation();
305

306 307 308 309 310 311
    // This can be issued in almost any state. We assume, though,
    // that at this point of time the inferior is not running anymore,
    // even if stop notification were not issued or got lost.
    if (state() == InferiorRunOk) {
        setState(InferiorStopRequested);
        setState(InferiorStopOk);
312 313 314 315 316 317
        setState(InferiorShutdownRequested);
        setState(InferiorShutdownOk);
    } else {
        // force
        setState(InferiorShutdownRequested, true);
        setState(InferiorShutdownOk);
318 319 320 321 322
    }
}

void QmlEngine::shutdownEngineAsSlave()
{
323
    if (d->m_hasShutdown)
324 325
        return;

hjk's avatar
hjk committed
326 327
    disconnect(d->m_adapter, SIGNAL(connectionStartupFailed()),
        this, SLOT(connectionStartupFailed()));
328
    d->m_adapter->closeConnection();
329

330
    if (d->m_addedAdapterToObjectPool) {
hjk's avatar
hjk committed
331 332
        ExtensionSystem::PluginManager *pluginManager =
            ExtensionSystem::PluginManager::instance();
333
        pluginManager->removeObject(d->m_adapter);
334
        pluginManager->removeObject(this);
335 336
    }

337
    if (d->m_attachToRunningExternalApp) {
338 339 340 341
        setState(EngineShutdownRequested, true);
        setState(EngineShutdownOk, true);
        setState(DebuggerFinished, true);
    } else {
342
        if (d->m_applicationLauncher.isRunning()) {
343
            // should only happen if engine is ill
hjk's avatar
hjk committed
344 345
            disconnect(&d->m_applicationLauncher, SIGNAL(processExited(int)),
                this, SLOT(disconnected()));
346
            d->m_applicationLauncher.stop();
347 348
        }
    }
349
    d->m_hasShutdown = true;
350 351
}

hjk's avatar
hjk committed
352
void QmlEngine::shutdownInferior()
353
{
354
    // don't do normal shutdown if running as slave engine
355
    if (d->m_attachToRunningExternalApp)
356 357
        return;

hjk's avatar
hjk committed
358
    QTC_ASSERT(state() == InferiorShutdownRequested, qDebug() << state());
359
    if (!d->m_applicationLauncher.isRunning()) {
Lasse Holmstedt's avatar
Lasse Holmstedt committed
360 361
        showMessage(tr("Trying to stop while process is no longer running."), LogError);
    } else {
hjk's avatar
hjk committed
362 363
        disconnect(&d->m_applicationLauncher, SIGNAL(processExited(int)),
            this, SLOT(disconnected()));
364 365
        if (!d->m_attachToRunningExternalApp)
            d->m_applicationLauncher.stop();
Lasse Holmstedt's avatar
Lasse Holmstedt committed
366
    }
hjk's avatar
hjk committed
367 368 369 370 371 372
    notifyInferiorShutdownOk();
}

void QmlEngine::shutdownEngine()
{
    QTC_ASSERT(state() == EngineShutdownRequested, qDebug() << state());
Lasse Holmstedt's avatar
Lasse Holmstedt committed
373

374
    shutdownEngineAsSlave();
Lasse Holmstedt's avatar
Lasse Holmstedt committed
375

376
    notifyEngineShutdownOk();
377
    showMessage(QString(), StatusBar);
378 379
}

hjk's avatar
hjk committed
380
void QmlEngine::setupEngine()
381
{
382 383 384
    d->m_adapter->setMaxConnectionAttempts(MaxConnectionAttempts);
    d->m_adapter->setConnectionAttemptInterval(ConnectionAttemptDefaultInterval);
    connect(d->m_adapter, SIGNAL(connectionError(QAbstractSocket::SocketError)),
hjk's avatar
hjk committed
385 386 387 388 389 390 391
        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()));
Lasse Holmstedt's avatar
Lasse Holmstedt committed
392

393
    notifyEngineSetupOk();
394 395
}

396 397
void QmlEngine::continueInferior()
{
hjk's avatar
hjk committed
398
    QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
399 400 401 402
    QByteArray reply;
    QDataStream rs(&reply, QIODevice::WriteOnly);
    rs << QByteArray("CONTINUE");
    sendMessage(reply);
403
    resetLocation();
hjk's avatar
hjk committed
404 405
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
406 407 408 409
}

void QmlEngine::interruptInferior()
{
410 411 412 413
    QByteArray reply;
    QDataStream rs(&reply, QIODevice::WriteOnly);
    rs << QByteArray("INTERRUPT");
    sendMessage(reply);
414
    notifyInferiorStopOk();
415 416 417 418
}

void QmlEngine::executeStep()
{
419 420 421 422
    QByteArray reply;
    QDataStream rs(&reply, QIODevice::WriteOnly);
    rs << QByteArray("STEPINTO");
    sendMessage(reply);
hjk's avatar
hjk committed
423 424
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
425 426 427 428
}

void QmlEngine::executeStepI()
{
429 430 431 432
    QByteArray reply;
    QDataStream rs(&reply, QIODevice::WriteOnly);
    rs << QByteArray("STEPINTO");
    sendMessage(reply);
hjk's avatar
hjk committed
433 434
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
435 436 437 438
}

void QmlEngine::executeStepOut()
{
439 440 441 442
    QByteArray reply;
    QDataStream rs(&reply, QIODevice::WriteOnly);
    rs << QByteArray("STEPOUT");
    sendMessage(reply);
hjk's avatar
hjk committed
443 444
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
445 446 447 448
}

void QmlEngine::executeNext()
{
449 450 451 452
    QByteArray reply;
    QDataStream rs(&reply, QIODevice::WriteOnly);
    rs << QByteArray("STEPOVER");
    sendMessage(reply);
hjk's avatar
hjk committed
453 454
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
455 456 457 458
}

void QmlEngine::executeNextI()
{
459
    SDEBUG("QmlEngine::executeNextI()");
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
}

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)
{
484 485 486 487 488
    QByteArray reply;
    QDataStream rs(&reply, QIODevice::WriteOnly);
    rs << QByteArray("ACTIVATE_FRAME");
    rs << index;
    sendMessage(reply);
489
    gotoLocation(stackHandler()->frames().value(index), true);
490 491 492 493 494 495 496 497 498
}

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

void QmlEngine::attemptBreakpointSynchronization()
{
hjk's avatar
hjk committed
499
    BreakHandler *handler = breakHandler();
500
    //bool updateNeeded = false;
hjk's avatar
hjk committed
501 502 503
    JSAgentBreakpoints breakpoints;
    foreach (BreakpointId id, handler->engineBreakpointIds(this)) {
        QString processedFilename = handler->fileName(id);
504
        if (isShadowBuildProject())
hjk's avatar
hjk committed
505 506
            processedFilename = toShadowBuildFilename(handler->fileName(id));
        JSAgentBreakpointData bp;
507
        bp.fileName = processedFilename.toUtf8();
hjk's avatar
hjk committed
508 509
        bp.lineNumber = handler->lineNumber(id);
        bp.functionName = handler->functionName(id).toUtf8();
510
        breakpoints.insert(bp);
511 512 513 514 515
    }

    QByteArray reply;
    QDataStream rs(&reply, QIODevice::WriteOnly);
    rs << QByteArray("BREAKPOINTS");
516 517
    rs << breakpoints;
    //qDebug() << Q_FUNC_INFO << breakpoints;
518
    sendMessage(reply);
519 520
}

hjk's avatar
hjk committed
521
bool QmlEngine::acceptsBreakpoint(BreakpointId id)
522
{
hjk's avatar
hjk committed
523 524 525
    const QString fileName = breakHandler()->fileName(id);
    return fileName.endsWith(QLatin1String(".qml"))
        || fileName.endsWith(QLatin1String(".js"));
526 527
}

528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
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
//
//////////////////////////////////////////////////////////////////////

hjk's avatar
hjk committed
552 553
void QmlEngine::setToolTipExpression(const QPoint &mousePos,
    TextEditor::ITextEditor *editor, int cursorPos)
554
{
hjk's avatar
hjk committed
555 556
    // This is processed by QML inspector, which has dependencies to 
    // the qml js editor. Makes life easier.
557
    emit tooltipRequested(mousePos, editor, cursorPos);
558 559 560 561 562 563 564 565
}

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

hjk's avatar
hjk committed
566
void QmlEngine::assignValueInDebugger(const WatchData *,
hjk's avatar
hjk committed
567
    const QString &expression, const QVariant &valueV)
568
{
569 570 571 572 573 574 575 576 577
    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);
            rs << QByteArray("SET_PROPERTY");
578
            rs << expression.toUtf8() << objectId << property << valueV.toString();
579 580 581
            sendMessage(reply);
        }
    }
582 583
}

hjk's avatar
hjk committed
584 585
void QmlEngine::updateWatchData(const WatchData &data,
    const WatchUpdateFlags &)
586
{
Olivier Goffart's avatar
Olivier Goffart committed
587
//    qDebug() << "UPDATE WATCH DATA" << data.toString();
588
    //watchHandler()->rebuildModel();
589
    showStatusMessage(tr("Stopped."), 5000);
590

591
    if (!data.name.isEmpty() && data.isValueNeeded()) {
592 593 594 595 596 597 598
        QByteArray reply;
        QDataStream rs(&reply, QIODevice::WriteOnly);
        rs << QByteArray("EXEC");
        rs << data.iname << data.name;
        sendMessage(reply);
    }

599 600
    if (!data.name.isEmpty() && data.isChildrenNeeded()
            && watchHandler()->isExpandedIName(data.iname))
Arvid Ephraim Picciani's avatar
Arvid Ephraim Picciani committed
601
        expandObject(data.iname, data.id);
602

603 604 605 606 607 608 609
    {
        QByteArray reply;
        QDataStream rs(&reply, QIODevice::WriteOnly);
        rs << QByteArray("WATCH_EXPRESSIONS");
        rs << watchHandler()->watchedExpressions();
        sendMessage(reply);
    }
610 611 612

    if (!data.isSomethingNeeded())
        watchHandler()->insertData(data);
613 614
}

615 616 617 618 619 620 621 622 623
void QmlEngine::expandObject(const QByteArray& iname, quint64 objectId)
{
    QByteArray reply;
    QDataStream rs(&reply, QIODevice::WriteOnly);
    rs << QByteArray("EXPAND");
    rs << iname << objectId;
    sendMessage(reply);
}

624 625
void QmlEngine::sendPing()
{
626
    d->m_ping++;
627 628 629
    QByteArray reply;
    QDataStream rs(&reply, QIODevice::WriteOnly);
    rs << QByteArray("PING");
630
    rs << d->m_ping;
631 632 633
    sendMessage(reply);
}

634
namespace Internal {
635 636 637 638
DebuggerEngine *createQmlEngine(const DebuggerStartParameters &sp)
{
    return new QmlEngine(sp);
}
639
} // namespace Internal
640 641 642 643 644 645 646 647 648 649 650 651 652

unsigned QmlEngine::debuggerCapabilities() const
{
    return AddWatcherCapability;
    /*ReverseSteppingCapability | SnapshotCapability
        | AutoDerefPointersCapability | DisassemblerCapability
        | RegisterCapability | ShowMemoryCapability
        | JumpToLineCapability | ReloadModuleCapability
        | ReloadModuleSymbolsCapability | BreakOnThrowAndCatchCapability
        | ReturnFromFunctionCapability
        | CreateFullBacktraceCapability
        | WatchpointCapability
        | AddWatcherCapability;*/
653 654 655 656 657 658 659 660 661 662
}

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

    QByteArray command;
    stream >> command;

663
    showMessage(QLatin1String("RECEIVED RESPONSE: ")
hjk's avatar
hjk committed
664
        + quoteUnprintableLatin1(message));
665

666
    if (command == "STOPPED") {
667
        if (state() == InferiorRunOk)
668
            notifyInferiorSpontaneousStop();
669

hjk's avatar
hjk committed
670 671 672
        StackFrames stackFrames;
        QList<WatchData> watches;
        QList<WatchData> locals;
673
        stream >> stackFrames >> watches >> locals;
674

675 676
        for (int i = 0; i != stackFrames.size(); ++i)
            stackFrames[i].level = i + 1;
677 678 679 680 681

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

        watchHandler()->beginCycle();
682
        bool needPing = false;
683

hjk's avatar
hjk committed
684
        foreach (WatchData data, watches) {
685
            data.iname = watchHandler()->watcherName(data.exp);
686
            watchHandler()->insertData(data);
687

688 689
            if (watchHandler()->expandedINames().contains(data.iname)) {
                needPing = true;
Arvid Ephraim Picciani's avatar
Arvid Ephraim Picciani committed
690
                expandObject(data.iname, data.id);
691
            }
692 693
        }

hjk's avatar
hjk committed
694
        foreach (WatchData data, locals) {
695 696
            data.iname = "local." + data.exp;
            watchHandler()->insertData(data);
697

698 699
            if (watchHandler()->expandedINames().contains(data.iname)) {
                needPing = true;
Arvid Ephraim Picciani's avatar
Arvid Ephraim Picciani committed
700
                expandObject(data.iname, data.id);
701
            }
hjk's avatar
hjk committed
702 703
        }

704 705 706 707
        if (needPing)
            sendPing();
        else
            watchHandler()->endCycle();
708

709 710 711
        bool becauseOfException;
        stream >> becauseOfException;
        if (becauseOfException) {
712 713 714
            QString error;
            stream >> error;

715 716 717
            QString msg =
                tr("<p>An Uncaught Exception occured in <i>%1</i>:</p><p>%2</p>")
                    .arg(stackFrames.value(0).file, Qt::escape(error));
718
            showMessageBox(QMessageBox::Information, tr("Uncaught Exception"), msg);
719 720 721 722 723
        } else {
            //
            // Make breakpoint non-pending
            //
            QString file;
724
            QString function;
725 726 727 728 729
            int line = -1;

            if (!stackFrames.isEmpty()) {
                file = stackFrames.at(0).file;
                line = stackFrames.at(0).line;
730
                function = stackFrames.at(0).function;
731 732 733 734 735

                if (isShadowBuildProject()) {
                    file = fromShadowBuildFilename(file);
                }
            }
736

hjk's avatar
hjk committed
737 738 739 740 741 742 743 744 745 746
            BreakHandler *handler = breakHandler();
            foreach (BreakpointId id, handler->engineBreakpointIds(this)) {
                QString processedFilename = handler->fileName(id);
                if (processedFilename == file && handler->lineNumber(id) == line) {
                    handler->setState(id, BreakpointInserted);
                    BreakpointResponse br = handler->response(id);
                    br.bpFileName = file;
                    br.bpLineNumber = line;
                    br.bpFuncName = function;
                    handler->setResponse(id, br);
747 748 749
                }
            }
        }
750
    } else if (command == "RESULT") {
hjk's avatar
hjk committed
751
        WatchData data;
752 753 754
        QByteArray iname;
        stream >> iname >> data;
        data.iname = iname;
755 756 757
        if (iname.startsWith("watch.")) {
            watchHandler()->insertData(data);
        } else if(iname == "console") {
758
            showMessage(data.value, ScriptConsoleOutput);
759 760 761
        } else {
            qWarning() << "QmlEngine: Unexcpected result: " << iname << data.value;
        }
762
    } else if (command == "EXPANDED") {
hjk's avatar
hjk committed
763
        QList<WatchData> result;
764 765
        QByteArray iname;
        stream >> iname >> result;
766
        bool needPing = false;
hjk's avatar
hjk committed
767
        foreach (WatchData data, result) {
768 769 770
            data.iname = iname + '.' + data.exp;
            watchHandler()->insertData(data);

771 772
            if (watchHandler()->expandedINames().contains(data.iname)) {
                needPing = true;
Arvid Ephraim Picciani's avatar
Arvid Ephraim Picciani committed
773
                expandObject(data.iname, data.id);
774
            }
775
        }
776 777
        if (needPing)
            sendPing();
778
    } else if (command == "LOCALS") {
hjk's avatar
hjk committed
779
        QList<WatchData> locals;
780 781 782
        int frameId;
        stream >> frameId >> locals;
        watchHandler()->beginCycle();
783
        bool needPing = false;
hjk's avatar
hjk committed
784
        foreach (WatchData data, locals) {
785 786
            data.iname = "local." + data.exp;
            watchHandler()->insertData(data);
787 788
            if (watchHandler()->expandedINames().contains(data.iname)) {
                needPing = true;
Arvid Ephraim Picciani's avatar
Arvid Ephraim Picciani committed
789
                expandObject(data.iname, data.id);
790
            }
791
        }
792 793 794 795 796 797 798 799
        if (needPing)
            sendPing();
        else
            watchHandler()->endCycle();

    } else if (command == "PONG") {
        int ping;
        stream >> ping;
800
        if (ping == d->m_ping)
801
            watchHandler()->endCycle();
802 803 804 805 806
    } else {
        qDebug() << Q_FUNC_INFO << "Unknown command: " << command;
    }
}

807 808
void QmlEngine::disconnected()
{
809
    showMessage(tr("QML Debugger disconnected."), StatusBar);
810 811 812
    notifyInferiorExited();
}

813 814 815 816 817 818 819 820 821
void QmlEngine::executeDebuggerCommand(const QString& command)
{
    QByteArray reply;
    QDataStream rs(&reply, QIODevice::WriteOnly);
    rs << QByteArray("EXEC");
    rs << QByteArray("console") << command;
    sendMessage(reply);
}

822 823
bool QmlEngine::isShadowBuildProject() const
{
hjk's avatar
hjk committed
824 825
    return !startParameters().projectBuildDir.isEmpty()
        && startParameters().projectDir != startParameters().projectBuildDir;
826 827 828 829 830 831
}

QString QmlEngine::qmlImportPath() const
{
    const QString qmlImportPathPrefix("QML_IMPORT_PATH=");
    QStringList env = startParameters().environment;
hjk's avatar
hjk committed
832 833 834
    foreach (const QString &envStr, env) {
        if (envStr.startsWith(qmlImportPathPrefix))
            return envStr.mid(qmlImportPathPrefix.length());
835
    }
hjk's avatar
hjk committed
836
    return QString();
837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
}

QString QmlEngine::toShadowBuildFilename(const QString &filename) const
{
    QString newFilename = filename;
    QString importPath = qmlImportPath();

    newFilename = mangleFilenamePaths(filename, startParameters().projectDir, startParameters().projectBuildDir);
    if (newFilename == filename && !importPath.isEmpty()) {
        newFilename = mangleFilenamePaths(filename, startParameters().projectDir, importPath);
    }

    return newFilename;
}

hjk's avatar
hjk committed
852 853
QString QmlEngine::mangleFilenamePaths(const QString &filename,
    const QString &oldBasePath, const QString &newBasePath) const
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
{
    QDir oldBaseDir(oldBasePath);
    QDir newBaseDir(newBasePath);
    QFileInfo fileInfo(filename);

    if (oldBaseDir.exists() && newBaseDir.exists() && fileInfo.exists()) {
        if (fileInfo.absoluteFilePath().startsWith(oldBaseDir.canonicalPath())) {
            QString fileRelativePath = fileInfo.canonicalFilePath().mid(oldBasePath.length());
            QFileInfo projectFile(newBaseDir.canonicalPath() + QLatin1Char('/') + fileRelativePath);

            if (projectFile.exists())
                return projectFile.canonicalFilePath();
        }
    }
    return filename;
}

QString QmlEngine::fromShadowBuildFilename(const QString &filename) const
{
    QString newFilename = filename;
    QString importPath = qmlImportPath();

    newFilename = mangleFilenamePaths(filename, startParameters().projectBuildDir, startParameters().projectDir);
    if (newFilename == filename && !importPath.isEmpty()) {
        newFilename = mangleFilenamePaths(filename, startParameters().projectBuildDir, importPath);
    }

    return newFilename;
}
883

884
} // namespace Debugger
885