qmlengine.cpp 35 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
#include "interactiveinterpreter.h"
36

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

48 49 50 51 52
#include "breakhandler.h"
#include "moduleshandler.h"
#include "registerhandler.h"
#include "stackhandler.h"
#include "watchhandler.h"
53
#include "sourcefileshandler.h"
54
#include "watchutils.h"
55
#include "qtmessageloghandler.h"
56

Lasse Holmstedt's avatar
Lasse Holmstedt committed
57
#include <extensionsystem/pluginmanager.h>
58
#include <projectexplorer/applicationlauncher.h>
59
#include <qmljsdebugclient/qdeclarativeoutputparser.h>
60
#include <qmljseditor/qmljseditorconstants.h>
61

62
#include <utils/environment.h>
63 64
#include <utils/qtcassert.h>

65 66
#include <coreplugin/coreconstants.h>
#include <coreplugin/editormanager/editormanager.h>
67
#include <coreplugin/helpmanager.h>
68 69 70
#include <coreplugin/icore.h>

#include <texteditor/itexteditor.h>
71

72 73 74 75 76
#include <QDateTime>
#include <QDebug>
#include <QDir>
#include <QFileInfo>
#include <QTimer>
77

78 79 80 81 82 83 84
#include <QAction>
#include <QApplication>
#include <QMainWindow>
#include <QMessageBox>
#include <QPlainTextEdit>
#include <QToolTip>
#include <QTextDocument>
85

86 87
#include <QTcpSocket>
#include <QHostAddress>
88

89 90 91 92 93 94 95 96
#define DEBUG_QML 1
#if DEBUG_QML
#   define SDEBUG(s) qDebug() << s
#else
#   define SDEBUG(s)
#endif
# define XSDEBUG(s) qDebug() << s

hjk's avatar
hjk committed
97 98
using namespace ProjectExplorer;

99 100 101
namespace Debugger {
namespace Internal {

102 103
class QmlEnginePrivate
{
104
public:
105 106
    explicit QmlEnginePrivate(QmlEngine *q);

107
private:
108
    friend class QmlEngine;
hjk's avatar
hjk committed
109 110
    QmlAdapter m_adapter;
    ApplicationLauncher m_applicationLauncher;
111
    QTimer m_noDebugOutputTimer;
112
    QmlJsDebugClient::QDeclarativeOutputParser m_outputParser;
113 114
    QHash<QString, QTextDocument*> m_sourceDocuments;
    QHash<QString, QWeakPointer<TextEditor::ITextEditor> > m_sourceEditors;
115 116
    InteractiveInterpreter m_interpreter;
    bool m_validContext;
117 118
};

119
QmlEnginePrivate::QmlEnginePrivate(QmlEngine *q)
120 121
    : m_adapter(q),
      m_validContext(false)
122 123
{}

124

125 126 127 128 129 130
///////////////////////////////////////////////////////////////////////
//
// QmlEngine
//
///////////////////////////////////////////////////////////////////////

131 132
QmlEngine::QmlEngine(const DebuggerStartParameters &startParameters,
        DebuggerEngine *masterEngine)
133
  : DebuggerEngine(startParameters, QmlLanguage, masterEngine),
134
    d(new QmlEnginePrivate(this))
135
{
Friedemann Kleint's avatar
Friedemann Kleint committed
136
    setObjectName(QLatin1String("QmlEngine"));
137 138 139 140 141 142 143 144 145 146 147 148 149 150

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

151 152 153 154 155 156
    connect(this, SIGNAL(stateChanged(Debugger::DebuggerState)),
            SLOT(updateCurrentContext()));
    connect(this->stackHandler(), SIGNAL(currentIndexChanged()),
            SLOT(updateCurrentContext()));
    connect(&d->m_adapter, SIGNAL(selectionChanged()),
            SLOT(updateCurrentContext()));
157 158 159 160 161
    connect(d->m_adapter.messageClient(),
            SIGNAL(message(QtMsgType,QString,
                           QmlJsDebugClient::QDebugContextInfo)),
            SLOT(appendDebugOutput(QtMsgType,QString,
                                   QmlJsDebugClient::QDebugContextInfo)));
162

163 164 165 166
    connect(&d->m_applicationLauncher,
        SIGNAL(processExited(int)),
        SLOT(disconnected()));
    connect(&d->m_applicationLauncher,
167 168 169 170 171 172
        SIGNAL(appendMessage(QString, Utils::OutputFormat)),
        SLOT(appendMessage(QString, Utils::OutputFormat)));
    connect(&d->m_applicationLauncher,
            SIGNAL(processStarted()),
            &d->m_noDebugOutputTimer,
            SLOT(start()));
173

174
    d->m_outputParser.setNoOutputText(ApplicationLauncher::msgWinCannotRetrieveDebuggingOutput());
175 176 177
    connect(&d->m_outputParser, SIGNAL(waitingForConnectionOnPort(quint16)),
            this, SLOT(beginConnection(quint16)));
    connect(&d->m_outputParser, SIGNAL(waitingForConnectionViaOst()),
178 179 180 181
            this, SLOT(beginConnection()));
    connect(&d->m_outputParser, SIGNAL(noOutputMessage()),
            this, SLOT(beginConnection()));
    connect(&d->m_outputParser, SIGNAL(errorMessage(QString)),
182
            this, SLOT(connectionStartupFailed(QString)));
183

184
    // Only wait 8 seconds for the 'Waiting for connection' on application ouput, then just try to connect
185 186 187 188
    // (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()));
189 190

    qtMessageLogHandler()->setHasEditableRow(true);
191 192 193
}

QmlEngine::~QmlEngine()
hjk's avatar
hjk committed
194
{
195 196 197 198 199 200
    ExtensionSystem::PluginManager *pluginManager =
        ExtensionSystem::PluginManager::instance();

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

202 203 204 205 206 207 208 209 210 211
    QList<Core::IEditor *> editorsToClose;

    QHash<QString, QWeakPointer<TextEditor::ITextEditor> >::iterator iter;
    for (iter = d->m_sourceEditors.begin(); iter != d->m_sourceEditors.end(); ++iter) {
        QWeakPointer<TextEditor::ITextEditor> textEditPtr = iter.value();
        if (textEditPtr)
            editorsToClose << textEditPtr.data();
    }
    Core::EditorManager::instance()->closeEditors(editorsToClose);

hjk's avatar
hjk committed
212 213
    delete d;
}
214

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

219
    notifyInferiorSetupOk();
hjk's avatar
hjk committed
220
}
hjk's avatar
hjk committed
221

con's avatar
con committed
222
void QmlEngine::appendMessage(const QString &msg, Utils::OutputFormat /* format */)
hjk's avatar
hjk committed
223
{
224
    showMessage(msg, AppOutput); // FIXME: Redirect to RunControl
hjk's avatar
hjk committed
225 226
}

Lasse Holmstedt's avatar
Lasse Holmstedt committed
227 228 229 230
void QmlEngine::connectionEstablished()
{
    attemptBreakpointSynchronization();

231 232 233 234
    if (!watchHandler()->watcherNames().isEmpty()) {
        synchronizeWatchers();
    }
    connect(watchersModel(),SIGNAL(layoutChanged()),this,SLOT(synchronizeWatchers()));
Christiaan Janssen's avatar
Christiaan Janssen committed
235

236 237
    if (state() == EngineRunRequested)
        notifyEngineRunAndInferiorRunOk();
Lasse Holmstedt's avatar
Lasse Holmstedt committed
238
}
239

240
void QmlEngine::beginConnection(quint16 port)
241 242
{
    d->m_noDebugOutputTimer.stop();
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
    if (port > 0) {
        QTC_CHECK(startParameters().communicationChannel
                  == DebuggerStartParameters::CommunicationChannelTcpIp);
        QTC_ASSERT(startParameters().connParams.port == 0
                   || startParameters().connParams.port == port,
                   qWarning() << "Port " << port << "from application output does not match"
                   << startParameters().connParams.port << "from start parameters.")
        d->m_adapter.beginConnectionTcp(startParameters().qmlServerAddress, port);
        return;
    }
    if (startParameters().communicationChannel
           == DebuggerStartParameters::CommunicationChannelTcpIp) {
        // no port from application output, use the one from start parameters ...
        d->m_adapter.beginConnectionTcp(startParameters().qmlServerAddress,
                                        startParameters().qmlServerPort);
    } else {
        QTC_CHECK(startParameters().communicationChannel
                  == DebuggerStartParameters::CommunicationChannelUsb);
        d->m_adapter.beginConnectionOst(startParameters().remoteChannel);
    }
Lasse Holmstedt's avatar
Lasse Holmstedt committed
263 264
}

265
void QmlEngine::connectionStartupFailed(const QString &errorMessage)
Lasse Holmstedt's avatar
Lasse Holmstedt committed
266
{
267 268 269 270 271 272 273 274
    if (isSlaveEngine()) {
        if (masterEngine()->state() != InferiorRunOk) {
            // we're right now debugging C++, just try longer ...
            beginConnection();
            return;
        }
    }

hjk's avatar
hjk committed
275
    QMessageBox *infoBox = new QMessageBox(Core::ICore::mainWindow());
276 277
    infoBox->setIcon(QMessageBox::Critical);
    infoBox->setWindowTitle(tr("Qt Creator"));
278 279 280 281 282 283 284 285 286 287 288 289 290
    if (qobject_cast<QmlAdapter *>(sender())) {
        infoBox->setText(tr("Could not connect to the in-process QML debugger."
                            "\nDo you want to retry?"));
        infoBox->setStandardButtons(QMessageBox::Retry | QMessageBox::Cancel |
                                    QMessageBox::Help);
        infoBox->setDefaultButton(QMessageBox::Retry);
    }
    if (qobject_cast<QmlJsDebugClient::QDeclarativeOutputParser *>(sender())) {
        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);
    }
291 292 293
    infoBox->setModal(true);

    connect(infoBox, SIGNAL(finished(int)),
294
            this, SLOT(errorMessageBoxFinished(int)));
295 296 297 298

    infoBox->show();
}

299
void QmlEngine::errorMessageBoxFinished(int result)
300 301
{
    switch (result) {
302
    case QMessageBox::Retry: {
303
        beginConnection();
304 305 306 307
        break;
    }
    case QMessageBox::Help: {
        Core::HelpManager *helpManager = Core::HelpManager::instance();
308
        helpManager->handleHelpRequest(QLatin1String("qthelp://com.nokia.qtcreator/doc/creator-debugging-qml.html"));
309
        // fall through
310 311
    }
    default:
312 313 314 315
        if (state() == InferiorRunOk) {
            notifyInferiorSpontaneousStop();
            notifyInferiorIll();
        } else {
316
            notifyEngineRunFailed();
317
        }
Kai Koehne's avatar
Kai Koehne committed
318
        break;
319
    }
Lasse Holmstedt's avatar
Lasse Holmstedt committed
320 321
}

322
void QmlEngine::connectionError(QAbstractSocket::SocketError socketError)
Lasse Holmstedt's avatar
Lasse Holmstedt committed
323
{
hjk's avatar
hjk committed
324
    if (socketError == QAbstractSocket::RemoteHostClosedError)
325
        showMessage(tr("QML Debugger: Remote host closed connection."), StatusBar);
326

327 328 329 330
    if (!isSlaveEngine()) { // normal flow for slave engine when gdb exits
        notifyInferiorSpontaneousStop();
        notifyInferiorIll();
    }
Lasse Holmstedt's avatar
Lasse Holmstedt committed
331 332
}

333 334
void QmlEngine::serviceConnectionError(const QString &serviceName)
{
335 336
    showMessage(tr("QML Debugger: Could not connect to service '%1'.")
        .arg(serviceName), StatusBar);
337 338
}

339 340 341 342 343
bool QmlEngine::canDisplayTooltip() const
{
    return state() == InferiorRunOk || state() == InferiorStopOk;
}

344
void QmlEngine::filterApplicationMessage(const QString &output, int /*channel*/)
345
{
346
    d->m_outputParser.processOutput(output);
347 348 349 350 351 352 353 354 355 356
}

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

357 358 359
void QmlEngine::gotoLocation(const Location &location)
{
    const QString fileName = location.fileName();
Daniel Molkentin's avatar
Daniel Molkentin committed
360 361
    // TODO: QUrl::isLocalFile() once we depend on Qt 4.8
    if (QUrl(fileName).scheme().compare(QLatin1String("file"), Qt::CaseInsensitive) == 0) {
362 363 364 365 366
        // internal file from source files -> show generated .js
        QTC_ASSERT(d->m_sourceDocuments.contains(fileName), return);
        Core::IEditor *editor = 0;

        Core::EditorManager *editorManager = Core::EditorManager::instance();
Aurindam Jana's avatar
Aurindam Jana committed
367 368 369 370 371 372 373 374 375 376
        QString titlePattern = tr("JS Source for %1").arg(fileName);
        //Check if there are open editors with the same title
        QList<Core::IEditor *> editors = editorManager->openedEditors();
        foreach (Core::IEditor *ed, editors) {
            if (ed->displayName() == titlePattern) {
                editor = ed;
                break;
            }
        }
        if (!editor) {
377 378 379 380 381 382
            editor = editorManager->openEditorWithContents(QmlJSEditor::Constants::C_QMLJSEDITOR_ID,
                                                           &titlePattern);
            if (editor) {
                editor->setProperty(Constants::OPENED_BY_DEBUGGER, true);
            }

383 384
            updateEditor(editor, d->m_sourceDocuments.value(fileName));
        }
385
        editorManager->activateEditor(editor);
386

387 388 389 390 391
    } else {
        DebuggerEngine::gotoLocation(location);
    }
}

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()) {
403 404 405
        if (startParameters().startMode == AttachToRemoteServer)
            beginConnection();
        else
406 407
            startApplicationLauncher();
    }
408 409 410 411 412
}

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

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

Christian Kandeler's avatar
Christian Kandeler committed
432
void QmlEngine::handleRemoteSetupDone(int gdbServerPort, int qmlPort)
433
{
Christian Kandeler's avatar
Christian Kandeler committed
434
    Q_UNUSED(gdbServerPort);
435

Christian Kandeler's avatar
Christian Kandeler committed
436 437
    if (qmlPort != -1)
        startParameters().qmlServerPort = qmlPort;
438 439

    notifyEngineRemoteSetupDone();
440
    notifyEngineSetupOk();
441 442 443 444
}

void QmlEngine::handleRemoteSetupFailed(const QString &message)
{
445 446 447
    if (isMasterEngine())
        QMessageBox::critical(0,tr("Failed to start application"),
            tr("Application startup failed: %1").arg(message));
448 449

    notifyEngineRemoteSetupFailed();
450
    notifyEngineSetupFailed();
451 452
}

hjk's avatar
hjk committed
453
void QmlEngine::shutdownInferior()
454
{
455 456 457 458
    d->m_noDebugOutputTimer.stop();

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

460 461
    if (isSlaveEngine()) {
        resetLocation();
Lasse Holmstedt's avatar
Lasse Holmstedt committed
462
    }
463
    stopApplicationLauncher();
464

hjk's avatar
hjk committed
465 466 467 468 469
    notifyInferiorShutdownOk();
}

void QmlEngine::shutdownEngine()
{
470
    closeConnection();
Lasse Holmstedt's avatar
Lasse Holmstedt committed
471

472 473
    // double check (ill engine?):
    stopApplicationLauncher();
Lasse Holmstedt's avatar
Lasse Holmstedt committed
474

475
    notifyEngineShutdownOk();
476 477
    if (!isSlaveEngine())
        showMessage(QString(), StatusBar);
478 479
}

hjk's avatar
hjk committed
480
void QmlEngine::setupEngine()
481
{
482
    if (startParameters().requestRemoteSetup) {
483
        // we need to get the port first
484
        notifyEngineRequestRemoteSetup();
485 486 487
    } else {
        d->m_applicationLauncher.setEnvironment(startParameters().environment);
        d->m_applicationLauncher.setWorkingDirectory(startParameters().workingDirectory);
Lasse Holmstedt's avatar
Lasse Holmstedt committed
488

489 490 491 492 493 494 495
        // We can't do this in the constructore because runControl() isn't yet defined
        connect(&d->m_applicationLauncher, SIGNAL(bringToForegroundRequested(qint64)),
                runControl(), SLOT(bringApplicationToForeground(qint64)),
                Qt::UniqueConnection);

        notifyEngineSetupOk();
    }
496 497
}

498 499
void QmlEngine::continueInferior()
{
hjk's avatar
hjk committed
500
    QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
501 502 503
    if (d->m_adapter.activeDebuggerClient()) {
        d->m_adapter.activeDebuggerClient()->continueInferior();
    }
504
    resetLocation();
hjk's avatar
hjk committed
505 506
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
507 508 509 510
}

void QmlEngine::interruptInferior()
{
511 512 513
    if (d->m_adapter.activeDebuggerClient()) {
        d->m_adapter.activeDebuggerClient()->interruptInferior();
    }
514
    notifyInferiorStopOk();
515 516 517 518
}

void QmlEngine::executeStep()
{
519 520 521
    if (d->m_adapter.activeDebuggerClient()) {
        d->m_adapter.activeDebuggerClient()->executeStep();
    }
hjk's avatar
hjk committed
522 523
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
524 525 526 527
}

void QmlEngine::executeStepI()
{
528 529 530
    if (d->m_adapter.activeDebuggerClient()) {
        d->m_adapter.activeDebuggerClient()->executeStepI();
    }
hjk's avatar
hjk committed
531 532
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
533 534 535 536
}

void QmlEngine::executeStepOut()
{
537 538 539
    if (d->m_adapter.activeDebuggerClient()) {
        d->m_adapter.activeDebuggerClient()->executeStepOut();
    }
hjk's avatar
hjk committed
540 541
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
542 543 544 545
}

void QmlEngine::executeNext()
{
546 547 548
    if (d->m_adapter.activeDebuggerClient()) {
        d->m_adapter.activeDebuggerClient()->executeNext();
    }
hjk's avatar
hjk committed
549 550
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
551 552 553 554
}

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

558
void QmlEngine::executeRunToLine(const ContextData &data)
559
{
560 561 562 563 564 565 566
    QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
    showStatusMessage(tr("Run to line  %1 (%2) requested...").arg(data.lineNumber).arg(data.fileName), 5000);
    resetLocation();
    if (d->m_adapter.activeDebuggerClient())
        d->m_adapter.activeDebuggerClient()->executeRunToLine(data);
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
567 568 569 570 571 572 573 574
}

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

575
void QmlEngine::executeJumpToLine(const ContextData &data)
576
{
577
    Q_UNUSED(data)
578 579 580 581 582
    XSDEBUG("FIXME:  QmlEngine::executeJumpToLine()");
}

void QmlEngine::activateFrame(int index)
{
583 584 585
    if (state() != InferiorStopOk && state() != InferiorUnrunnable)
        return;

586 587 588
    if (d->m_adapter.activeDebuggerClient()) {
        d->m_adapter.activeDebuggerClient()->activateFrame(index);
    }
589
    gotoLocation(stackHandler()->frames().value(index));
590 591 592 593 594 595 596
}

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

597 598 599 600 601 602 603 604
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()) {
605
        d->m_adapter.activeDebuggerClient()->insertBreakpoint(id);
606 607
    } else {
        foreach (QmlDebuggerClient *client, d->m_adapter.debuggerClients()) {
608
            client->insertBreakpoint(id);
609 610 611 612 613 614 615 616 617 618 619 620
        }
    }
}

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()) {
621
        d->m_adapter.activeDebuggerClient()->removeBreakpoint(id);
622 623
    } else {
        foreach (QmlDebuggerClient *client, d->m_adapter.debuggerClients()) {
624
            client->removeBreakpoint(id);
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
        }
    }

    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()) {
641
        d->m_adapter.activeDebuggerClient()->changeBreakpoint(id);
642 643
    } else {
        foreach (QmlDebuggerClient *client, d->m_adapter.debuggerClients()) {
644
            client->changeBreakpoint(id);
645 646 647 648 649 650 651 652
        }
    }

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

653 654
void QmlEngine::attemptBreakpointSynchronization()
{
655 656 657 658 659
    if (!stateAcceptsBreakpointChanges()) {
        showMessage(_("BREAKPOINT SYNCHRONIZATION NOT POSSIBLE IN CURRENT STATE"));
        return;
    }

hjk's avatar
hjk committed
660
    BreakHandler *handler = breakHandler();
661

662
    foreach (BreakpointModelId id, handler->unclaimedBreakpointIds()) {
663 664 665 666 667
        // Take ownership of the breakpoint. Requests insertion.
        if (acceptsBreakpoint(id))
            handler->setEngine(id, this);
    }

668
    foreach (BreakpointModelId id, handler->engineBreakpointIds(this)) {
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
        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;
689
        }
690
        QTC_ASSERT(false, qDebug() << "UNKNOWN STATE"  << id << state());
691 692
    }

693
    DebuggerEngine::attemptBreakpointSynchronization();
694

695
    if (d->m_adapter.activeDebuggerClient()) {
696
        d->m_adapter.activeDebuggerClient()->synchronizeBreakpoints();
697 698
    } else {
        foreach (QmlDebuggerClient *client, d->m_adapter.debuggerClients()) {
699
            client->synchronizeBreakpoints();
700
        }
701
    }
702 703
}

704
bool QmlEngine::acceptsBreakpoint(BreakpointModelId id) const
705
{
706
    if (!breakHandler()->breakpointData(id).isCppBreakpoint())
707 708 709 710 711
            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
712
    //This is because the older client does not support BreakpointOnQmlSignalHandler
713 714 715 716 717
    bool acceptBreakpoint = false;
    if (d->m_adapter.activeDebuggerClient()) {
        acceptBreakpoint = d->m_adapter.activeDebuggerClient()->acceptsBreakpoint(id);
    }
    return acceptBreakpoint;
718 719
}

720 721 722 723 724 725 726 727 728 729 730 731 732
void QmlEngine::loadSymbols(const QString &moduleName)
{
    Q_UNUSED(moduleName)
}

void QmlEngine::loadAllSymbols()
{
}

void QmlEngine::reloadModules()
{
}

733 734 735 736 737 738 739
void QmlEngine::reloadSourceFiles()
{
    if (d->m_adapter.activeDebuggerClient()) {
        d->m_adapter.activeDebuggerClient()->getSourceFiles();
    }
}

740 741 742 743 744 745 746 747 748 749 750
void QmlEngine::requestModuleSymbols(const QString &moduleName)
{
    Q_UNUSED(moduleName)
}

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

751
bool QmlEngine::setToolTipExpression(const QPoint &mousePos,
752
    TextEditor::ITextEditor *editor, const DebuggerToolTipContext &ctx)
753
{
754
    // This is processed by QML inspector, which has dependencies to
hjk's avatar
hjk committed
755
    // the qml js editor. Makes life easier.
756
    emit tooltipRequested(mousePos, editor, ctx.position);
757
    return true;
758 759 760 761 762 763 764 765
}

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

766
void QmlEngine::assignValueInDebugger(const WatchData *data,
hjk's avatar
hjk committed
767
    const QString &expression, const QVariant &valueV)
768
{
769
    quint64 objectId =  data->id;
770
    if (objectId > 0 && !expression.isEmpty() && d->m_adapter.activeDebuggerClient()) {
771
        d->m_adapter.activeDebuggerClient()->assignValueInDebugger(expression.toUtf8(), objectId, expression, valueV.toString());
772
    }
773 774
}

hjk's avatar
hjk committed
775 776
void QmlEngine::updateWatchData(const WatchData &data,
    const WatchUpdateFlags &)
777
{
Olivier Goffart's avatar
Olivier Goffart committed
778
//    qDebug() << "UPDATE WATCH DATA" << data.toString();
779
    //watchHandler()->rebuildModel();
780
    showStatusMessage(tr("Stopped."), 5000);
781

782 783
    if (!data.name.isEmpty() && d->m_adapter.activeDebuggerClient()) {
        if (data.isValueNeeded()) {
784
            d->m_adapter.activeDebuggerClient()->updateWatchData(data);
785 786 787 788 789
        }
        if (data.isChildrenNeeded()
                && watchHandler()->isExpandedIName(data.iname)) {
            d->m_adapter.activeDebuggerClient()->expandObject(data.iname, data.id);
        }
Christiaan Janssen's avatar
Christiaan Janssen committed
790 791 792
    }

    synchronizeWatchers();
793

Christiaan Janssen's avatar
Christiaan Janssen committed
794 795 796 797 798 799
    if (!data.isSomethingNeeded())
        watchHandler()->insertData(data);
}

void QmlEngine::synchronizeWatchers()
{
800
    QStringList watchedExpressions = watchHandler()->watchedExpressions();
801
    // send watchers list
802 803
    if (d->m_adapter.activeDebuggerClient()) {
        d->m_adapter.activeDebuggerClient()->synchronizeWatchers(watchedExpressions);
804
    } else {
805 806 807
        foreach (QmlDebuggerClient *client, d->m_adapter.debuggerClients())
            client->synchronizeWatchers(watchedExpressions);
    }
808 809
}

810 811 812 813 814 815
void QmlEngine::onDebugQueryStateChanged(
        QmlJsDebugClient::QDeclarativeDebugQuery::State state)
{
    QmlJsDebugClient::QDeclarativeDebugExpressionQuery *query =
            qobject_cast<QmlJsDebugClient::QDeclarativeDebugExpressionQuery *>(
                sender());
816 817 818 819 820
    if (query && state != QmlJsDebugClient::QDeclarativeDebugQuery::Error) {
        QtMessageLogItem *item = constructLogItemTree(query->result());
        if (item)
            qtMessageLogHandler()->appendItem(item);
    } else
821 822 823 824 825 826
        qtMessageLogHandler()->
                appendItem(new QtMessageLogItem(QtMessageLogHandler::ErrorType,
                                             _("Error evaluating expression.")));
    delete query;
}

827
bool QmlEngine::hasCapability(unsigned cap) const
828
{
829
    return cap & (AddWatcherCapability
830
            | AddWatcherWhileRunningCapability
831
            | RunToLineCapability);
832 833 834 835 836 837 838 839 840
    /*ReverseSteppingCapability | SnapshotCapability
        | AutoDerefPointersCapability | DisassemblerCapability
        | RegisterCapability | ShowMemoryCapability
        | JumpToLineCapability | ReloadModuleCapability
        | ReloadModuleSymbolsCapability | BreakOnThrowAndCatchCapability
        | ReturnFromFunctionCapability
        | CreateFullBacktraceCapability
        | WatchpointCapability
        | AddWatcherCapability;*/
841 842
}

843
void QmlEngine::inferiorSpontaneousStop()
844
{
845 846
    if (state() == InferiorRunOk)
        notifyInferiorSpontaneousStop();
847 848
}

849 850
void QmlEngine::disconnected()
{
851
    showMessage(tr("QML Debugger disconnected."), StatusBar);
852 853 854
    notifyInferiorExited();
}

855 856 857 858 859 860 861 862 863
void QmlEngine::updateCurrentContext()
{
    const QString context = state() == InferiorStopOk ?
                stackHandler()->currentFrame().function :
                d->m_adapter.currentSelectedDisplayName();
    d->m_validContext = !context.isEmpty();
    showMessage(tr("Context: ").append(context), QtMessageLogStatus);
}

864 865
void QmlEngine::appendDebugOutput(QtMsgType type, const QString &message,
                                  const QmlJsDebugClient::QDebugContextInfo &info)
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882
{
    QtMessageLogHandler::ItemType itemType;
    switch (type) {
    case QtDebugMsg:
        itemType = QtMessageLogHandler::DebugType;
        break;
    case QtWarningMsg:
        itemType = QtMessageLogHandler::WarningType;
        break;
    case QtCriticalMsg:
    case QtFatalMsg:
        itemType = QtMessageLogHandler::ErrorType;
        break;
    default:
        //This case is not possible
        return;
    }
883 884 885 886
    QtMessageLogItem *item = new QtMessageLogItem(itemType, message);
    item->file = info.file;
    item->line = info.line;
    qtMessageLogHandler()->appendItem(item);
887 888
}

889 890
void QmlEngine::executeDebuggerCommand(const QString& command)
{
891 892 893
    if (d->m_adapter.activeDebuggerClient()) {
        d->m_adapter.activeDebuggerClient()->executeDebuggerCommand(command);
    }
894 895
}

896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
bool QmlEngine::evaluateScriptExpression(const QString& expression)
{
    bool didEvaluate = true;
    //Check if string is only white spaces
    if (!expression.trimmed().isEmpty()) {
        //Check for a valid context
        if (d->m_validContext) {
            //check if it can be evaluated
            if (canEvaluateScript(expression)) {
                //Evaluate expression based on engine state
                //When engine->state() == InferiorStopOk, the expression
                //is sent to V8DebugService. In all other cases, the
                //expression is evaluated by QDeclarativeEngine.
                if (state() != InferiorStopOk) {
                    QDeclarativeEngineDebug *engineDebug =
                            d->m_adapter.engineDebugClient();

                    int id = d->m_adapter.currentSelectedDebugId();
                    if (engineDebug && id != -1) {
                        QDeclarativeDebugExpressionQuery *query =
                                engineDebug->queryExpressionResult(id, expression);
                        connect(query,
                                SIGNAL(stateChanged(
                                           QmlJsDebugClient::QDeclarativeDebugQuery
                                           ::State)),
                                this,
                                SLOT(onDebugQueryStateChanged(
                                         QmlJsDebugClient::QDeclarativeDebugQuery
                                         ::State)));
                    }
                } else {
                    executeDebuggerCommand(expression);
                }
            } else {
                didEvaluate = false;
            }
        } else {
            //Incase of invalid context, show Error message
            qtMessageLogHandler()->
                            appendItem(new QtMessageLogItem(
                                           QtMessageLogHandler::ErrorType,
                                           _("Cannot evaluate without"
                                             "a valid QML/JS Context.")),
                                       qtMessageLogHandler()->rowCount());
        }
    }
    return didEvaluate;
}
944 945 946

QString QmlEngine::qmlImportPath() const
{
947
    return startParameters().environment.value(QLatin1String("QML_IMPORT_PATH"));
948 949
}

950
void QmlEngine::logMessage(const QString &service, LogDirection direction, const QString &message)
951
{
952
    QString msg = service;
953
    msg += direction == LogSend ? QLatin1String(": sending ") : QLatin1String(": receiving ");
954 955 956 957
    msg += message;
    showMessage(msg, LogDebug);
}

958 959 960 961 962
void QmlEngine::setSourceFiles(const QStringList &fileNames)
{
    QMap<QString,QString> files;
    foreach (const QString &file, fileNames) {
        QString shortName = file;
963
        QString fullName = toFileInProject(file);
964 965 966 967
        files.insert(shortName, fullName);
    }

    sourceFilesHandler()->setSourceFiles(files);
968 969
    //update open editors

970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997