qmlengine.cpp 34.6 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
#include <qmljsdebugclient/qdebugmessageclient.h>
62

63
#include <utils/environment.h>
64
#include <utils/qtcassert.h>
65
#include <utils/fileinprojectfinder.h>
66

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

#include <texteditor/itexteditor.h>
73

74 75 76 77 78
#include <QDateTime>
#include <QDebug>
#include <QDir>
#include <QFileInfo>
#include <QTimer>
79

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

88 89
#include <QTcpSocket>
#include <QHostAddress>
90

91 92 93 94 95 96 97 98
#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
99 100
using namespace ProjectExplorer;

101 102 103
namespace Debugger {
namespace Internal {

104 105
class QmlEnginePrivate
{
106
public:
107 108
    explicit QmlEnginePrivate(QmlEngine *q);

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

122
QmlEnginePrivate::QmlEnginePrivate(QmlEngine *q)
123 124
    : m_adapter(q),
      m_validContext(false)
125 126
{}

127

128 129 130 131 132 133
///////////////////////////////////////////////////////////////////////
//
// QmlEngine
//
///////////////////////////////////////////////////////////////////////

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

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

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

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 175 176 177 178 179 180 181
    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)));

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

    qtMessageLogHandler()->setHasEditableRow(true);
189 190 191
}

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

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

200 201 202 203 204 205 206 207 208 209
    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
210 211
    delete d;
}
212

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

217
    notifyInferiorSetupOk();
hjk's avatar
hjk committed
218
}
hjk's avatar
hjk committed
219

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

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

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

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

238 239 240 241
void QmlEngine::beginConnection()
{
    d->m_noDebugOutputTimer.stop();
    d->m_adapter.beginConnection();
Lasse Holmstedt's avatar
Lasse Holmstedt committed
242 243 244 245
}

void QmlEngine::connectionStartupFailed()
{
246 247 248 249 250 251 252 253
    if (isSlaveEngine()) {
        if (masterEngine()->state() != InferiorRunOk) {
            // we're right now debugging C++, just try longer ...
            beginConnection();
            return;
        }
    }

hjk's avatar
hjk committed
254
    QMessageBox *infoBox = new QMessageBox(Core::ICore::mainWindow());
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
    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) {
272
    case QMessageBox::Retry: {
273
        beginConnection();
274 275 276 277
        break;
    }
    case QMessageBox::Help: {
        Core::HelpManager *helpManager = Core::HelpManager::instance();
278
        helpManager->handleHelpRequest(QLatin1String("qthelp://com.nokia.qtcreator/doc/creator-debugging-qml.html"));
279
        // fall through
280 281
    }
    default:
282 283 284 285
        if (state() == InferiorRunOk) {
            notifyInferiorSpontaneousStop();
            notifyInferiorIll();
        } else {
286
        notifyEngineRunFailed();
287
        }
Kai Koehne's avatar
Kai Koehne committed
288
        break;
289
    }
Lasse Holmstedt's avatar
Lasse Holmstedt committed
290 291
}

292 293 294 295 296
void QmlEngine::wrongSetupMessageBox(const QString &errorMessage)
{
    d->m_noDebugOutputTimer.stop();
    notifyEngineRunFailed();

hjk's avatar
hjk committed
297
    QMessageBox *infoBox = new QMessageBox(Core::ICore::mainWindow());
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
    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();
}

313
void QmlEngine::connectionError(QAbstractSocket::SocketError socketError)
Lasse Holmstedt's avatar
Lasse Holmstedt committed
314
{
hjk's avatar
hjk committed
315
    if (socketError == QAbstractSocket::RemoteHostClosedError)
316
        showMessage(tr("QML Debugger: Remote host closed connection."), StatusBar);
317

318 319 320 321
    if (!isSlaveEngine()) { // normal flow for slave engine when gdb exits
        notifyInferiorSpontaneousStop();
        notifyInferiorIll();
    }
Lasse Holmstedt's avatar
Lasse Holmstedt committed
322 323
}

324 325
void QmlEngine::serviceConnectionError(const QString &serviceName)
{
326 327
    showMessage(tr("QML Debugger: Could not connect to service '%1'.")
        .arg(serviceName), StatusBar);
328 329
}

330 331 332 333 334
bool QmlEngine::canDisplayTooltip() const
{
    return state() == InferiorRunOk || state() == InferiorStopOk;
}

335
void QmlEngine::filterApplicationMessage(const QString &output, int /*channel*/)
336
{
337
    d->m_outputParser.processOutput(output);
338 339 340 341 342 343 344 345 346 347
}

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

348 349 350
void QmlEngine::gotoLocation(const Location &location)
{
    const QString fileName = location.fileName();
Daniel Molkentin's avatar
Daniel Molkentin committed
351 352
    // TODO: QUrl::isLocalFile() once we depend on Qt 4.8
    if (QUrl(fileName).scheme().compare(QLatin1String("file"), Qt::CaseInsensitive) == 0) {
353 354 355 356 357
        // 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
358 359 360 361 362 363 364 365 366 367
        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) {
368 369 370 371 372 373
            editor = editorManager->openEditorWithContents(QmlJSEditor::Constants::C_QMLJSEDITOR_ID,
                                                           &titlePattern);
            if (editor) {
                editor->setProperty(Constants::OPENED_BY_DEBUGGER, true);
            }

374 375
            updateEditor(editor, d->m_sourceDocuments.value(fileName));
        }
376
        editorManager->activateEditor(editor);
377

378 379 380 381 382
    } else {
        DebuggerEngine::gotoLocation(location);
    }
}

383 384
void QmlEngine::closeConnection()
{
385
    disconnect(watchersModel(),SIGNAL(layoutChanged()),this,SLOT(synchronizeWatchers()));
386
    d->m_adapter.closeConnection();
387 388
}

hjk's avatar
hjk committed
389 390 391
void QmlEngine::runEngine()
{
    QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());
Lasse Holmstedt's avatar
Lasse Holmstedt committed
392

393 394 395 396 397 398
    if (!isSlaveEngine()) {
        if (startParameters().startMode != AttachToRemoteServer)
            startApplicationLauncher();
        else
            beginConnection();
    }
399 400 401 402 403
}

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

415 416 417 418 419 420
void QmlEngine::stopApplicationLauncher()
{
    if (d->m_applicationLauncher.isRunning()) {
        disconnect(&d->m_applicationLauncher, SIGNAL(processExited(int)), this, SLOT(disconnected()));
        d->m_applicationLauncher.stop();
    }
421 422
}

Christian Kandeler's avatar
Christian Kandeler committed
423
void QmlEngine::handleRemoteSetupDone(int gdbServerPort, int qmlPort)
424
{
Christian Kandeler's avatar
Christian Kandeler committed
425
    Q_UNUSED(gdbServerPort);
426

Christian Kandeler's avatar
Christian Kandeler committed
427 428
    if (qmlPort != -1)
        startParameters().qmlServerPort = qmlPort;
429 430

    notifyEngineRemoteSetupDone();
431
    notifyEngineSetupOk();
432 433 434 435
}

void QmlEngine::handleRemoteSetupFailed(const QString &message)
{
436 437 438
    if (isMasterEngine())
        QMessageBox::critical(0,tr("Failed to start application"),
            tr("Application startup failed: %1").arg(message));
439 440

    notifyEngineRemoteSetupFailed();
441
    notifyEngineSetupFailed();
442 443
}

hjk's avatar
hjk committed
444
void QmlEngine::shutdownInferior()
445
{
446 447 448 449
    d->m_noDebugOutputTimer.stop();

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

451 452
    if (isSlaveEngine()) {
        resetLocation();
Lasse Holmstedt's avatar
Lasse Holmstedt committed
453
    }
454
    stopApplicationLauncher();
455

hjk's avatar
hjk committed
456 457 458 459 460
    notifyInferiorShutdownOk();
}

void QmlEngine::shutdownEngine()
{
461
    closeConnection();
Lasse Holmstedt's avatar
Lasse Holmstedt committed
462

463 464
    // double check (ill engine?):
    stopApplicationLauncher();
Lasse Holmstedt's avatar
Lasse Holmstedt committed
465

466
    notifyEngineShutdownOk();
467 468
    if (!isSlaveEngine())
        showMessage(QString(), StatusBar);
469 470
}

hjk's avatar
hjk committed
471
void QmlEngine::setupEngine()
472
{
473
    if (startParameters().requestRemoteSetup) {
474
        // we need to get the port first
475
        notifyEngineRequestRemoteSetup();
476 477 478
    } else {
        d->m_applicationLauncher.setEnvironment(startParameters().environment);
        d->m_applicationLauncher.setWorkingDirectory(startParameters().workingDirectory);
Lasse Holmstedt's avatar
Lasse Holmstedt committed
479

480 481 482 483 484 485 486
        // 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();
    }
487 488
}

489 490
void QmlEngine::continueInferior()
{
hjk's avatar
hjk committed
491
    QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
492 493 494
    if (d->m_adapter.activeDebuggerClient()) {
        d->m_adapter.activeDebuggerClient()->continueInferior();
    }
495
    resetLocation();
hjk's avatar
hjk committed
496 497
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
498 499 500 501
}

void QmlEngine::interruptInferior()
{
502 503 504
    if (d->m_adapter.activeDebuggerClient()) {
        d->m_adapter.activeDebuggerClient()->interruptInferior();
    }
505
    notifyInferiorStopOk();
506 507 508 509
}

void QmlEngine::executeStep()
{
510 511 512
    if (d->m_adapter.activeDebuggerClient()) {
        d->m_adapter.activeDebuggerClient()->executeStep();
    }
hjk's avatar
hjk committed
513 514
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
515 516 517 518
}

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

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

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

void QmlEngine::executeNextI()
{
546
    executeNext();
547 548
}

549
void QmlEngine::executeRunToLine(const ContextData &data)
550
{
551 552 553 554 555 556 557
    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();
558 559 560 561 562 563 564 565
}

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

566
void QmlEngine::executeJumpToLine(const ContextData &data)
567
{
568
    Q_UNUSED(data)
569 570 571 572 573
    XSDEBUG("FIXME:  QmlEngine::executeJumpToLine()");
}

void QmlEngine::activateFrame(int index)
{
574 575 576
    if (state() != InferiorStopOk && state() != InferiorUnrunnable)
        return;

577 578 579
    if (d->m_adapter.activeDebuggerClient()) {
        d->m_adapter.activeDebuggerClient()->activateFrame(index);
    }
580
    gotoLocation(stackHandler()->frames().value(index));
581 582 583 584 585 586 587
}

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

588 589 590 591 592 593 594 595
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()) {
596
        d->m_adapter.activeDebuggerClient()->insertBreakpoint(id);
597 598
    } else {
        foreach (QmlDebuggerClient *client, d->m_adapter.debuggerClients()) {
599
            client->insertBreakpoint(id);
600 601 602 603 604 605 606 607 608 609 610 611
        }
    }
}

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()) {
612
        d->m_adapter.activeDebuggerClient()->removeBreakpoint(id);
613 614
    } else {
        foreach (QmlDebuggerClient *client, d->m_adapter.debuggerClients()) {
615
            client->removeBreakpoint(id);
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
        }
    }

    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()) {
632
        d->m_adapter.activeDebuggerClient()->changeBreakpoint(id);
633 634
    } else {
        foreach (QmlDebuggerClient *client, d->m_adapter.debuggerClients()) {
635
            client->changeBreakpoint(id);
636 637 638 639 640 641 642 643
        }
    }

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

644 645
void QmlEngine::attemptBreakpointSynchronization()
{
646 647 648 649 650
    if (!stateAcceptsBreakpointChanges()) {
        showMessage(_("BREAKPOINT SYNCHRONIZATION NOT POSSIBLE IN CURRENT STATE"));
        return;
    }

hjk's avatar
hjk committed
651
    BreakHandler *handler = breakHandler();
652

653
    foreach (BreakpointModelId id, handler->unclaimedBreakpointIds()) {
654 655 656 657 658
        // Take ownership of the breakpoint. Requests insertion.
        if (acceptsBreakpoint(id))
            handler->setEngine(id, this);
    }

659
    foreach (BreakpointModelId id, handler->engineBreakpointIds(this)) {
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
        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;
680
        }
681
        QTC_ASSERT(false, qDebug() << "UNKNOWN STATE"  << id << state());
682 683
    }

684
    DebuggerEngine::attemptBreakpointSynchronization();
685

686
    if (d->m_adapter.activeDebuggerClient()) {
687
        d->m_adapter.activeDebuggerClient()->synchronizeBreakpoints();
688 689
    } else {
        foreach (QmlDebuggerClient *client, d->m_adapter.debuggerClients()) {
690
            client->synchronizeBreakpoints();
691
        }
692
    }
693 694
}

695
bool QmlEngine::acceptsBreakpoint(BreakpointModelId id) const
696
{
697
    if (!breakHandler()->breakpointData(id).isCppBreakpoint())
698 699 700 701 702
            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
703
    //This is because the older client does not support BreakpointOnQmlSignalHandler
704 705 706 707 708
    bool acceptBreakpoint = false;
    if (d->m_adapter.activeDebuggerClient()) {
        acceptBreakpoint = d->m_adapter.activeDebuggerClient()->acceptsBreakpoint(id);
    }
    return acceptBreakpoint;
709 710
}

711 712 713 714 715 716 717 718 719 720 721 722 723
void QmlEngine::loadSymbols(const QString &moduleName)
{
    Q_UNUSED(moduleName)
}

void QmlEngine::loadAllSymbols()
{
}

void QmlEngine::reloadModules()
{
}

724 725 726 727 728 729 730
void QmlEngine::reloadSourceFiles()
{
    if (d->m_adapter.activeDebuggerClient()) {
        d->m_adapter.activeDebuggerClient()->getSourceFiles();
    }
}

731 732 733 734 735 736 737 738 739 740 741
void QmlEngine::requestModuleSymbols(const QString &moduleName)
{
    Q_UNUSED(moduleName)
}

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

742
bool QmlEngine::setToolTipExpression(const QPoint &mousePos,
743
    TextEditor::ITextEditor *editor, const DebuggerToolTipContext &ctx)
744
{
745
    // This is processed by QML inspector, which has dependencies to
hjk's avatar
hjk committed
746
    // the qml js editor. Makes life easier.
747
    emit tooltipRequested(mousePos, editor, ctx.position);
748
    return true;
749 750 751 752 753 754 755 756
}

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

757
void QmlEngine::assignValueInDebugger(const WatchData *data,
hjk's avatar
hjk committed
758
    const QString &expression, const QVariant &valueV)
759
{
760
    quint64 objectId =  data->id;
761
    if (objectId > 0 && !expression.isEmpty() && d->m_adapter.activeDebuggerClient()) {
762
        d->m_adapter.activeDebuggerClient()->assignValueInDebugger(expression.toUtf8(), objectId, expression, valueV.toString());
763
    }
764 765
}

hjk's avatar
hjk committed
766 767
void QmlEngine::updateWatchData(const WatchData &data,
    const WatchUpdateFlags &)
768
{
Olivier Goffart's avatar
Olivier Goffart committed
769
//    qDebug() << "UPDATE WATCH DATA" << data.toString();
770
    //watchHandler()->rebuildModel();
771
    showStatusMessage(tr("Stopped."), 5000);
772

773 774
    if (!data.name.isEmpty() && d->m_adapter.activeDebuggerClient()) {
        if (data.isValueNeeded()) {
775
            d->m_adapter.activeDebuggerClient()->updateWatchData(data);
776 777 778 779 780
        }
        if (data.isChildrenNeeded()
                && watchHandler()->isExpandedIName(data.iname)) {
            d->m_adapter.activeDebuggerClient()->expandObject(data.iname, data.id);
        }
Christiaan Janssen's avatar
Christiaan Janssen committed
781 782 783
    }

    synchronizeWatchers();
784

Christiaan Janssen's avatar
Christiaan Janssen committed
785 786 787 788 789 790
    if (!data.isSomethingNeeded())
        watchHandler()->insertData(data);
}

void QmlEngine::synchronizeWatchers()
{
791
    QStringList watchedExpressions = watchHandler()->watchedExpressions();
792
    // send watchers list
793 794
    if (d->m_adapter.activeDebuggerClient()) {
        d->m_adapter.activeDebuggerClient()->synchronizeWatchers(watchedExpressions);
795
    } else {
796 797 798
        foreach (QmlDebuggerClient *client, d->m_adapter.debuggerClients())
            client->synchronizeWatchers(watchedExpressions);
    }
799 800
}

801 802 803 804 805 806
void QmlEngine::onDebugQueryStateChanged(
        QmlJsDebugClient::QDeclarativeDebugQuery::State state)
{
    QmlJsDebugClient::QDeclarativeDebugExpressionQuery *query =
            qobject_cast<QmlJsDebugClient::QDeclarativeDebugExpressionQuery *>(
                sender());
807 808 809 810 811
    if (query && state != QmlJsDebugClient::QDeclarativeDebugQuery::Error) {
        QtMessageLogItem *item = constructLogItemTree(query->result());
        if (item)
            qtMessageLogHandler()->appendItem(item);
    } else
812 813 814 815 816 817
        qtMessageLogHandler()->
                appendItem(new QtMessageLogItem(QtMessageLogHandler::ErrorType,
                                             _("Error evaluating expression.")));
    delete query;
}

818
bool QmlEngine::hasCapability(unsigned cap) const
819
{
820
    return cap & (AddWatcherCapability
821
            | AddWatcherWhileRunningCapability
822
            | RunToLineCapability);
823 824 825 826 827 828 829 830 831
    /*ReverseSteppingCapability | SnapshotCapability
        | AutoDerefPointersCapability | DisassemblerCapability
        | RegisterCapability | ShowMemoryCapability
        | JumpToLineCapability | ReloadModuleCapability
        | ReloadModuleSymbolsCapability | BreakOnThrowAndCatchCapability
        | ReturnFromFunctionCapability
        | CreateFullBacktraceCapability
        | WatchpointCapability
        | AddWatcherCapability;*/
832 833
}

834
QString QmlEngine::toFileInProject(const QUrl &fileUrl)
835
{
836 837 838 839
    // make sure file finder is properly initialized
    d->fileFinder.setProjectDirectory(startParameters().projectSourceDirectory);
    d->fileFinder.setProjectFiles(startParameters().projectSourceFiles);
    d->fileFinder.setSysroot(startParameters().sysroot);
840

841
    return d->fileFinder.findFile(fileUrl);
842 843
}

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

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

856
void QmlEngine::wrongSetupMessageBoxFinished(int result)
857 858 859 860 861 862 863 864
{
    if (result == QMessageBox::Help) {
        Core::HelpManager *helpManager = Core::HelpManager::instance();
        helpManager->handleHelpRequest(
                    QLatin1String("qthelp://com.nokia.qtcreator/doc/creator-debugging-qml.html"));
    }
}

865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
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);
}

void QmlEngine::appendDebugOutput(QtMsgType type, const QString &message)
{
    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;
    }
    qtMessageLogHandler()->appendItem(new QtMessageLogItem(itemType, message));
}

895 896
void QmlEngine::executeDebuggerCommand(const QString& command)
{
897 898 899
    if (d->m_adapter.activeDebuggerClient()) {
        d->m_adapter.activeDebuggerClient()->executeDebuggerCommand(command);
    }
900 901
}

902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
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;
}
950 951 952

QString QmlEngine::qmlImportPath() const
{
953
    return startParameters().environment.value(QLatin1String("QML_IMPORT_PATH"));
954 955
}

956
void QmlEngine::logMessage(const QString &service, LogDirection direction, const QString &message)
957
{
958
    QString msg = service;
959
    msg += direction == LogSend ? QLatin1String(": sending ") : QLatin1String(": receiving ");
960 961 962 963
    msg += message;
    showMessage(msg, LogDebug);
}

964 965 966 967 968 969 970 971 972 973
void QmlEngine::setSourceFiles(const QStringList &fileNames)
{
    QMap<QString,QString> files;
    foreach (const QString &file, fileNames) {
        QString shortName = file;
        QString fullName = d->fileFinder.findFile(file);
        files.insert(shortName, fullName);
    }

    sourceFilesHandler()->setSourceFiles(files);
974 975
    //update open editors

976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
}

void QmlEngine::updateScriptSource(const QString &fileName, int lineOffset, int columnOffset,
                                   const QString &source)
{
    QTextDocument *document = 0;
    if (d->m_sourceDocuments.contains(fileName)) {
        document = d->m_sourceDocuments.value(fileName);
    } else {
        document = new QTextDocument(this);
        d->m_sourceDocuments.insert(fileName, document);
    }

    // We're getting an unordered set of snippets that can even interleave
    // Therefore we've to carefully update the existing document

    QTextCursor cursor(document);
    for (int i = 0; i < lineOffset; ++i) {
        if (!cursor.movePosition(QTextCursor::NextBlock))
            cursor.insertBlock();
    }
    QTC_CHECK(cursor.blockNumber() == lineOffset);

    for (int i = 0; i < columnOffset; ++i) {
        if (!cursor.movePosition(QTextCursor::NextCharacter))
            cursor.insertText(QLatin1String(" "));
    }
    QTC_CHECK(cursor.positionInBlock() == columnOffset);

    QStringList lines = source.split(QLatin1Char('\n'));
    foreach (QString line, lines) {
        if (line.endsWith(QLatin1Char('\r')))
            line.remove(line.size() -1, 1);

        // line already there?
        QTextCursor existingCursor(cursor);
        existingCursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
        if (existingCursor.selectedText() != line)
            cursor.insertText(line);

        if (