qmlengine.cpp 24.5 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).
**
7
** Contact: Nokia Corporation (qt-info@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
29
** Nokia at qt-info@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
#include <qmljsdebugclient/qdeclarativeoutputparser.h>
56

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

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

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

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

80 81 82 83 84 85 86 87
#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
88 89
using namespace ProjectExplorer;

90 91 92
namespace Debugger {
namespace Internal {

93 94
class QmlEnginePrivate
{
95
public:
96 97
    explicit QmlEnginePrivate(QmlEngine *q);

98
private:
99
    friend class QmlEngine;
hjk's avatar
hjk committed
100 101
    QmlAdapter m_adapter;
    ApplicationLauncher m_applicationLauncher;
102
    Utils::FileInProjectFinder fileFinder;
103
    QTimer m_noDebugOutputTimer;
104
    QmlJsDebugClient::QDeclarativeOutputParser m_outputParser;
105 106
};

107
QmlEnginePrivate::QmlEnginePrivate(QmlEngine *q)
108
    : m_adapter(q)
109 110
{}

111

112 113 114 115 116 117
///////////////////////////////////////////////////////////////////////
//
// QmlEngine
//
///////////////////////////////////////////////////////////////////////

118 119
QmlEngine::QmlEngine(const DebuggerStartParameters &startParameters,
        DebuggerEngine *masterEngine)
120
  : DebuggerEngine(startParameters, QmlLanguage, masterEngine),
121
    d(new QmlEnginePrivate(this))
122
{
Friedemann Kleint's avatar
Friedemann Kleint committed
123
    setObjectName(QLatin1String("QmlEngine"));
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141

    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,
142 143 144 145 146 147
        SIGNAL(appendMessage(QString, Utils::OutputFormat)),
        SLOT(appendMessage(QString, Utils::OutputFormat)));
    connect(&d->m_applicationLauncher,
            SIGNAL(processStarted()),
            &d->m_noDebugOutputTimer,
            SLOT(start()));
148

149 150 151 152 153 154 155 156
    d->m_outputParser.setNoOutputText(ApplicationLauncher::msgWinCannotRetrieveDebuggingOutput());
    connect(&d->m_outputParser, SIGNAL(waitingForConnectionMessage()),
            this, SLOT(beginConnection()));
    connect(&d->m_outputParser, SIGNAL(noOutputMessage()),
            this, SLOT(beginConnection()));
    connect(&d->m_outputParser, SIGNAL(errorMessage(QString)),
            this, SLOT(wrongSetupMessageBox(QString)));

157
    // Only wait 8 seconds for the 'Waiting for connection' on application ouput, then just try to connect
158 159 160 161
    // (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()));
162 163 164
}

QmlEngine::~QmlEngine()
hjk's avatar
hjk committed
165
{
166 167 168 169 170 171
    ExtensionSystem::PluginManager *pluginManager =
        ExtensionSystem::PluginManager::instance();

    if (pluginManager->allObjects().contains(this)) {
        pluginManager->removeObject(this);
    }
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
172

hjk's avatar
hjk committed
173 174
    delete d;
}
175

hjk's avatar
hjk committed
176
void QmlEngine::setupInferior()
177
{
hjk's avatar
hjk committed
178
    QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
Lasse Holmstedt's avatar
Lasse Holmstedt committed
179

180
    if (startParameters().startMode == AttachToRemoteServer) {
181
        emit requestRemoteSetup();
182 183
        if (startParameters().qmlServerPort != quint16(-1))
            notifyInferiorSetupOk();
184 185 186
    } if (startParameters().startMode == AttachToQmlPort) {
            notifyInferiorSetupOk();

187 188 189 190 191 192
    } else {
        d->m_applicationLauncher.setEnvironment(startParameters().environment);
        d->m_applicationLauncher.setWorkingDirectory(startParameters().workingDirectory);

        notifyInferiorSetupOk();
    }
hjk's avatar
hjk committed
193
}
hjk's avatar
hjk committed
194

con's avatar
con committed
195
void QmlEngine::appendMessage(const QString &msg, Utils::OutputFormat /* format */)
hjk's avatar
hjk committed
196
{
197
    showMessage(msg, AppOutput); // FIXME: Redirect to RunControl
hjk's avatar
hjk committed
198 199
}

Lasse Holmstedt's avatar
Lasse Holmstedt committed
200 201 202 203
void QmlEngine::connectionEstablished()
{
    attemptBreakpointSynchronization();

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

206 207 208 209
    if (!watchHandler()->watcherNames().isEmpty()) {
        synchronizeWatchers();
    }
    connect(watchersModel(),SIGNAL(layoutChanged()),this,SLOT(synchronizeWatchers()));
Christiaan Janssen's avatar
Christiaan Janssen committed
210

211 212
    if (state() == EngineRunRequested)
        notifyEngineRunAndInferiorRunOk();
Lasse Holmstedt's avatar
Lasse Holmstedt committed
213
}
214

215 216 217
void QmlEngine::beginConnection()
{
    d->m_noDebugOutputTimer.stop();
218
    showMessage(tr("QML Debugger connecting..."), StatusBar);
219
    d->m_adapter.beginConnection();
Lasse Holmstedt's avatar
Lasse Holmstedt committed
220 221 222 223
}

void QmlEngine::connectionStartupFailed()
{
224 225 226 227 228 229 230 231
    if (isSlaveEngine()) {
        if (masterEngine()->state() != InferiorRunOk) {
            // we're right now debugging C++, just try longer ...
            beginConnection();
            return;
        }
    }

232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
    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) {
251
    case QMessageBox::Retry: {
252
        beginConnection();
253 254 255 256 257
        break;
    }
    case QMessageBox::Help: {
        Core::HelpManager *helpManager = Core::HelpManager::instance();
        helpManager->handleHelpRequest("qthelp://com.nokia.qtcreator/doc/creator-debugging-qml.html");
258
        // fall through
259 260
    }
    default:
261 262 263 264
        if (state() == InferiorRunOk) {
            notifyInferiorSpontaneousStop();
            notifyInferiorIll();
        } else {
265
        notifyEngineRunFailed();
266
        }
Kai Koehne's avatar
Kai Koehne committed
267
        break;
268
    }
Lasse Holmstedt's avatar
Lasse Holmstedt committed
269 270
}

271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
void QmlEngine::wrongSetupMessageBox(const QString &errorMessage)
{
    d->m_noDebugOutputTimer.stop();
    notifyEngineRunFailed();

    Core::ICore * const core = Core::ICore::instance();
    QMessageBox *infoBox = new QMessageBox(core->mainWindow());
    infoBox->setIcon(QMessageBox::Critical);
    infoBox->setWindowTitle(tr("Qt Creator"));
    //: %1 is detailed error message
    infoBox->setText(tr("Could not connect to the in-process QML debugger:\n%1")
                     .arg(errorMessage));
    infoBox->setStandardButtons(QMessageBox::Ok | QMessageBox::Help);
    infoBox->setDefaultButton(QMessageBox::Ok);
    infoBox->setModal(true);

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

    infoBox->show();
}

293
void QmlEngine::connectionError(QAbstractSocket::SocketError socketError)
Lasse Holmstedt's avatar
Lasse Holmstedt committed
294
{
hjk's avatar
hjk committed
295
    if (socketError == QAbstractSocket::RemoteHostClosedError)
296
        showMessage(tr("QML Debugger: Remote host closed connection."), StatusBar);
297

298 299 300 301
    if (!isSlaveEngine()) { // normal flow for slave engine when gdb exits
        notifyInferiorSpontaneousStop();
        notifyInferiorIll();
    }
Lasse Holmstedt's avatar
Lasse Holmstedt committed
302 303
}

304 305
void QmlEngine::serviceConnectionError(const QString &serviceName)
{
306 307
    showMessage(tr("QML Debugger: Could not connect to service '%1'.")
        .arg(serviceName), StatusBar);
308 309
}

310 311 312 313 314
bool QmlEngine::canDisplayTooltip() const
{
    return state() == InferiorRunOk || state() == InferiorStopOk;
}

315
void QmlEngine::filterApplicationMessage(const QString &output, int /*channel*/)
316
{
317
    d->m_outputParser.processOutput(output);
318 319 320 321 322 323 324 325 326 327
}

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);
}

328 329
void QmlEngine::closeConnection()
{
330
    disconnect(watchersModel(),SIGNAL(layoutChanged()),this,SLOT(synchronizeWatchers()));
331
    d->m_adapter.closeConnection();
332 333
}

hjk's avatar
hjk committed
334 335 336
void QmlEngine::runEngine()
{
    QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());
Lasse Holmstedt's avatar
Lasse Holmstedt committed
337

338
    if (!isSlaveEngine() && startParameters().startMode != AttachToRemoteServer
339
            && startParameters().startMode != AttachToQmlPort)
340
        startApplicationLauncher();
341 342 343

    if (startParameters().startMode == AttachToQmlPort)
        beginConnection();
344 345 346 347 348
}

void QmlEngine::startApplicationLauncher()
{
    if (!d->m_applicationLauncher.isRunning()) {
349 350 351 352
        appendMessage(tr("Starting %1 %2").arg(
                          QDir::toNativeSeparators(startParameters().executable),
                          startParameters().processArgs)
                      + QLatin1Char('\n')
con's avatar
con committed
353
                     , Utils::NormalMessageFormat);
hjk's avatar
hjk committed
354
        d->m_applicationLauncher.start(ApplicationLauncher::Gui,
355 356 357
                                    startParameters().executable,
                                    startParameters().processArgs);
    }
358
}
Lasse Holmstedt's avatar
Lasse Holmstedt committed
359

360 361 362 363 364 365
void QmlEngine::stopApplicationLauncher()
{
    if (d->m_applicationLauncher.isRunning()) {
        disconnect(&d->m_applicationLauncher, SIGNAL(processExited(int)), this, SLOT(disconnected()));
        d->m_applicationLauncher.stop();
    }
366 367
}

Christian Kandeler's avatar
Christian Kandeler committed
368
void QmlEngine::handleRemoteSetupDone(int gdbServerPort, int qmlPort)
369
{
Christian Kandeler's avatar
Christian Kandeler committed
370 371 372
    Q_UNUSED(gdbServerPort);
    if (qmlPort != -1)
        startParameters().qmlServerPort = qmlPort;
373 374 375 376 377 378 379 380 381 382
    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
383
void QmlEngine::shutdownInferior()
384
{
385 386 387 388
    d->m_noDebugOutputTimer.stop();

    if (d->m_adapter.activeDebuggerClient())
        d->m_adapter.activeDebuggerClient()->endSession();
389

390 391
    if (isSlaveEngine()) {
        resetLocation();
Lasse Holmstedt's avatar
Lasse Holmstedt committed
392
    }
393
    stopApplicationLauncher();
394

hjk's avatar
hjk committed
395 396 397 398 399
    notifyInferiorShutdownOk();
}

void QmlEngine::shutdownEngine()
{
400
    closeConnection();
Lasse Holmstedt's avatar
Lasse Holmstedt committed
401

402 403
    // double check (ill engine?):
    stopApplicationLauncher();
Lasse Holmstedt's avatar
Lasse Holmstedt committed
404

405
    notifyEngineShutdownOk();
406 407
    if (!isSlaveEngine())
        showMessage(QString(), StatusBar);
408 409
}

hjk's avatar
hjk committed
410
void QmlEngine::setupEngine()
411
{
412 413 414
    connect(&d->m_applicationLauncher, SIGNAL(bringToForegroundRequested(qint64)),
            runControl(), SLOT(bringApplicationToForeground(qint64)),
            Qt::UniqueConnection);
Lasse Holmstedt's avatar
Lasse Holmstedt committed
415

416
    notifyEngineSetupOk();
417 418
}

419 420
void QmlEngine::continueInferior()
{
hjk's avatar
hjk committed
421
    QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
422 423 424 425
    if (d->m_adapter.activeDebuggerClient()) {
        logMessage(LogSend, "CONTINUE");
        d->m_adapter.activeDebuggerClient()->continueInferior();
    }
426
    resetLocation();
hjk's avatar
hjk committed
427 428
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
429 430 431 432
}

void QmlEngine::interruptInferior()
{
433 434 435 436
    if (d->m_adapter.activeDebuggerClient()) {
        logMessage(LogSend, "INTERRUPT");
        d->m_adapter.activeDebuggerClient()->interruptInferior();
    }
437
    notifyInferiorStopOk();
438 439 440 441
}

void QmlEngine::executeStep()
{
442 443 444 445
    if (d->m_adapter.activeDebuggerClient()) {
        logMessage(LogSend, "STEPINTO");
        d->m_adapter.activeDebuggerClient()->executeStep();
    }
hjk's avatar
hjk committed
446 447
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
448 449 450 451
}

void QmlEngine::executeStepI()
{
452 453 454 455
    if (d->m_adapter.activeDebuggerClient()) {
        logMessage(LogSend, "STEPINTO");
        d->m_adapter.activeDebuggerClient()->executeStepI();
    }
hjk's avatar
hjk committed
456 457
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
458 459 460 461
}

void QmlEngine::executeStepOut()
{
462 463 464 465
    if (d->m_adapter.activeDebuggerClient()) {
        logMessage(LogSend, "STEPOUT");
        d->m_adapter.activeDebuggerClient()->executeStepOut();
    }
hjk's avatar
hjk committed
466 467
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
468 469 470 471
}

void QmlEngine::executeNext()
{
472 473 474 475
    if (d->m_adapter.activeDebuggerClient()) {
        logMessage(LogSend, "STEPOVER");
        d->m_adapter.activeDebuggerClient()->executeNext();
    }
hjk's avatar
hjk committed
476 477
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
478 479 480 481
}

void QmlEngine::executeNextI()
{
482
    executeNext();
483 484
}

485
void QmlEngine::executeRunToLine(const ContextData &data)
486
{
487
    Q_UNUSED(data)
488 489 490 491 492 493 494 495 496
    SDEBUG("FIXME:  QmlEngine::executeRunToLine()");
}

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

497
void QmlEngine::executeJumpToLine(const ContextData &data)
498
{
499
    Q_UNUSED(data)
500 501 502 503 504
    XSDEBUG("FIXME:  QmlEngine::executeJumpToLine()");
}

void QmlEngine::activateFrame(int index)
{
505 506 507
    if (state() != InferiorStopOk && state() != InferiorUnrunnable)
        return;

508 509 510 511
    if (d->m_adapter.activeDebuggerClient()) {
        logMessage(LogSend, QString("%1 %2").arg(QString("ACTIVATE_FRAME"), QString::number(index)));
        d->m_adapter.activeDebuggerClient()->activateFrame(index);
    }
512
    gotoLocation(stackHandler()->frames().value(index));
513 514 515 516 517 518 519
}

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

520 521 522 523 524 525 526 527
void QmlEngine::insertBreakpoint(BreakpointModelId id)
{
    BreakHandler *handler = breakHandler();
    BreakpointState state = handler->state(id);
    QTC_ASSERT(state == BreakpointInsertRequested, qDebug() << id << this << state);
    handler->notifyBreakpointInsertProceeding(id);

    if (d->m_adapter.activeDebuggerClient()) {
528
        d->m_adapter.activeDebuggerClient()->insertBreakpoint(id);
529 530
    } else {
        foreach (QmlDebuggerClient *client, d->m_adapter.debuggerClients()) {
531
            client->insertBreakpoint(id);
532 533 534 535 536 537 538 539 540 541 542 543
        }
    }
}

void QmlEngine::removeBreakpoint(BreakpointModelId id)
{
    BreakHandler *handler = breakHandler();
    BreakpointState state = handler->state(id);
    QTC_ASSERT(state == BreakpointRemoveRequested, qDebug() << id << this << state);
    handler->notifyBreakpointRemoveProceeding(id);

    if (d->m_adapter.activeDebuggerClient()) {
544
        d->m_adapter.activeDebuggerClient()->removeBreakpoint(id);
545 546
    } else {
        foreach (QmlDebuggerClient *client, d->m_adapter.debuggerClients()) {
547
            client->removeBreakpoint(id);
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
        }
    }

    if (handler->state(id) == BreakpointRemoveProceeding) {
        handler->notifyBreakpointRemoveOk(id);
    }
}

void QmlEngine::changeBreakpoint(BreakpointModelId id)
{
    BreakHandler *handler = breakHandler();
    BreakpointState state = handler->state(id);
    QTC_ASSERT(state == BreakpointChangeRequested, qDebug() << id << this << state);
    handler->notifyBreakpointChangeProceeding(id);

    if (d->m_adapter.activeDebuggerClient()) {
564
        d->m_adapter.activeDebuggerClient()->changeBreakpoint(id);
565 566
    } else {
        foreach (QmlDebuggerClient *client, d->m_adapter.debuggerClients()) {
567
            client->changeBreakpoint(id);
568 569 570 571 572 573 574 575
        }
    }

    if (handler->state(id) == BreakpointChangeProceeding) {
        handler->notifyBreakpointChangeOk(id);
    }
}

576 577
void QmlEngine::attemptBreakpointSynchronization()
{
578 579 580 581 582
    if (!stateAcceptsBreakpointChanges()) {
        showMessage(_("BREAKPOINT SYNCHRONIZATION NOT POSSIBLE IN CURRENT STATE"));
        return;
    }

hjk's avatar
hjk committed
583
    BreakHandler *handler = breakHandler();
584

585
    foreach (BreakpointModelId id, handler->unclaimedBreakpointIds()) {
586 587 588 589 590
        // Take ownership of the breakpoint. Requests insertion.
        if (acceptsBreakpoint(id))
            handler->setEngine(id, this);
    }

591
    foreach (BreakpointModelId id, handler->engineBreakpointIds(this)) {
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
        switch (handler->state(id)) {
        case BreakpointNew:
            // Should not happen once claimed.
            QTC_CHECK(false);
            continue;
        case BreakpointInsertRequested:
            insertBreakpoint(id);
            continue;
        case BreakpointChangeRequested:
            changeBreakpoint(id);
            continue;
        case BreakpointRemoveRequested:
            removeBreakpoint(id);
            continue;
        case BreakpointChangeProceeding:
        case BreakpointInsertProceeding:
        case BreakpointRemoveProceeding:
        case BreakpointInserted:
        case BreakpointDead:
            continue;
612
        }
613
        QTC_ASSERT(false, qDebug() << "UNKNOWN STATE"  << id << state());
614 615
    }

616
    DebuggerEngine::attemptBreakpointSynchronization();
617

618
    if (d->m_adapter.activeDebuggerClient()) {
619
        d->m_adapter.activeDebuggerClient()->synchronizeBreakpoints();
620 621
    } else {
        foreach (QmlDebuggerClient *client, d->m_adapter.debuggerClients()) {
622
            client->synchronizeBreakpoints();
623
        }
624
    }
625 626
}

627
bool QmlEngine::acceptsBreakpoint(BreakpointModelId id) const
628
{
629 630 631 632 633 634
    if (!DebuggerEngine::isCppBreakpoint(breakHandler()->breakpointData(id)))
            return true;

    //If it is a Cpp Breakpoint query if the type can be also handled by the debugger client
    //TODO: enable setting of breakpoints before start of debug session
    //For now, the event breakpoint can be set after the activeDebuggerClient is known
635
    //This is because the older client does not support BreakpointOnQmlSignalHandler
636 637 638 639 640
    bool acceptBreakpoint = false;
    if (d->m_adapter.activeDebuggerClient()) {
        acceptBreakpoint = d->m_adapter.activeDebuggerClient()->acceptsBreakpoint(id);
    }
    return acceptBreakpoint;
641 642
}

643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
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
//
//////////////////////////////////////////////////////////////////////

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

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

682
void QmlEngine::assignValueInDebugger(const WatchData *data,
hjk's avatar
hjk committed
683
    const QString &expression, const QVariant &valueV)
684
{
685
    quint64 objectId =  data->id;
686
    if (objectId > 0 && !expression.isEmpty() && d->m_adapter.activeDebuggerClient()) {
687
        logMessage(LogSend, QString("%1 %2 %3 %4 %5").arg(
688 689
                       QString("SET_PROPERTY"), QString::number(objectId), QString(expression),
                       valueV.toString()));
690
        d->m_adapter.activeDebuggerClient()->assignValueInDebugger(expression.toUtf8(), objectId, expression, valueV.toString());
691
    }
692 693
}

hjk's avatar
hjk committed
694 695
void QmlEngine::updateWatchData(const WatchData &data,
    const WatchUpdateFlags &)
696
{
Olivier Goffart's avatar
Olivier Goffart committed
697
//    qDebug() << "UPDATE WATCH DATA" << data.toString();
698
    //watchHandler()->rebuildModel();
699
    showStatusMessage(tr("Stopped."), 5000);
700

701 702 703 704
    if (!data.name.isEmpty() && d->m_adapter.activeDebuggerClient()) {
        if (data.isValueNeeded()) {
            logMessage(LogSend, QString("%1 %2 %3").arg(QString("EXEC"), QString(data.iname),
                                                        QString(data.name)));
705
            d->m_adapter.activeDebuggerClient()->updateWatchData(data);
706 707 708 709 710
        }
        if (data.isChildrenNeeded()
                && watchHandler()->isExpandedIName(data.iname)) {
            d->m_adapter.activeDebuggerClient()->expandObject(data.iname, data.id);
        }
Christiaan Janssen's avatar
Christiaan Janssen committed
711 712 713
    }

    synchronizeWatchers();
714

Christiaan Janssen's avatar
Christiaan Janssen committed
715 716 717 718 719 720
    if (!data.isSomethingNeeded())
        watchHandler()->insertData(data);
}

void QmlEngine::synchronizeWatchers()
{
721
    QStringList watchedExpressions = watchHandler()->watchedExpressions();
722 723
    // send watchers list
    logMessage(LogSend, QString("%1 %2").arg(
724 725 726
                   QString("WATCH_EXPRESSIONS"), watchedExpressions.join(", ")));
    if (d->m_adapter.activeDebuggerClient()) {
        d->m_adapter.activeDebuggerClient()->synchronizeWatchers(watchedExpressions);
727
    } else {
728 729 730
        foreach (QmlDebuggerClient *client, d->m_adapter.debuggerClients())
            client->synchronizeWatchers(watchedExpressions);
    }
731 732
}

733 734
unsigned QmlEngine::debuggerCapabilities() const
{
735
    return AddWatcherCapability|AddWatcherWhileRunningCapability;
736 737 738 739 740 741 742 743 744
    /*ReverseSteppingCapability | SnapshotCapability
        | AutoDerefPointersCapability | DisassemblerCapability
        | RegisterCapability | ShowMemoryCapability
        | JumpToLineCapability | ReloadModuleCapability
        | ReloadModuleSymbolsCapability | BreakOnThrowAndCatchCapability
        | ReturnFromFunctionCapability
        | CreateFullBacktraceCapability
        | WatchpointCapability
        | AddWatcherCapability;*/
745 746
}

747
QString QmlEngine::toFileInProject(const QUrl &fileUrl)
748
{
749 750 751 752
    // make sure file finder is properly initialized
    d->fileFinder.setProjectDirectory(startParameters().projectSourceDirectory);
    d->fileFinder.setProjectFiles(startParameters().projectSourceFiles);
    d->fileFinder.setSysroot(startParameters().sysroot);
753

754
    return d->fileFinder.findFile(fileUrl);
755 756
}

757
void QmlEngine::inferiorSpontaneousStop()
758
{
759 760
    if (state() == InferiorRunOk)
        notifyInferiorSpontaneousStop();
761 762
}

763 764
void QmlEngine::disconnected()
{
765
    showMessage(tr("QML Debugger disconnected."), StatusBar);
766 767 768
    notifyInferiorExited();
}

769
void QmlEngine::wrongSetupMessageBoxFinished(int result)
770 771 772 773 774 775 776 777
{
    if (result == QMessageBox::Help) {
        Core::HelpManager *helpManager = Core::HelpManager::instance();
        helpManager->handleHelpRequest(
                    QLatin1String("qthelp://com.nokia.qtcreator/doc/creator-debugging-qml.html"));
    }
}

778 779
void QmlEngine::executeDebuggerCommand(const QString& command)
{
780 781 782 783 784
    if (d->m_adapter.activeDebuggerClient()) {
        logMessage(LogSend, QString("%1 %2 %3").arg(QString("EXEC"), QString("console"),
                                                          QString(command)));
        d->m_adapter.activeDebuggerClient()->executeDebuggerCommand(command);
    }
785 786
}

787 788 789

QString QmlEngine::qmlImportPath() const
{
790
    return startParameters().environment.value("QML_IMPORT_PATH");
791 792
}

793 794
void QmlEngine::logMessage(LogDirection direction, const QString &message)
{
795
    QString msg = "QmlDebugger";
796 797 798 799 800 801 802 803 804
    if (direction == LogSend) {
        msg += " sending ";
    } else {
        msg += " receiving ";
    }
    msg += message;
    showMessage(msg, LogDebug);
}

805 806 807 808 809
QmlAdapter *QmlEngine::adapter() const
{
    return &d->m_adapter;
}

810
QmlEngine *createQmlEngine(const DebuggerStartParameters &sp,
811 812 813 814 815
    DebuggerEngine *masterEngine)
{
    return new QmlEngine(sp, masterEngine);
}

816
} // namespace Internal
817
} // namespace Debugger
818