qmlengine.cpp 28.8 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 "debuggerinternalconstants.h"
42
#include "debuggermainwindow.h"
hjk's avatar
hjk committed
43
#include "debuggerrunner.h"
44
#include "debuggerstringutils.h"
45
#include "debuggertooltipmanager.h"
46

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

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

60
#include <utils/environment.h>
61
#include <utils/qtcassert.h>
62
#include <utils/fileinprojectfinder.h>
63

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

#include <texteditor/itexteditor.h>
70

71 72 73 74 75 76 77 78 79 80
#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>
81
#include <QtGui/QPlainTextEdit>
82
#include <QtGui/QToolTip>
83
#include <QtGui/QTextDocument>
84 85

#include <QtNetwork/QTcpSocket>
86 87
#include <QtNetwork/QHostAddress>

88 89 90 91 92 93 94 95
#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
96 97
using namespace ProjectExplorer;

98 99 100
namespace Debugger {
namespace Internal {

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

106
private:
107
    friend class QmlEngine;
hjk's avatar
hjk committed
108 109
    QmlAdapter m_adapter;
    ApplicationLauncher m_applicationLauncher;
110
    Utils::FileInProjectFinder fileFinder;
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
};

117
QmlEnginePrivate::QmlEnginePrivate(QmlEngine *q)
118
    : m_adapter(q)
119 120
{}

121

122 123 124 125 126 127
///////////////////////////////////////////////////////////////////////
//
// QmlEngine
//
///////////////////////////////////////////////////////////////////////

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

    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,
152 153 154 155 156 157
        SIGNAL(appendMessage(QString, Utils::OutputFormat)),
        SLOT(appendMessage(QString, Utils::OutputFormat)));
    connect(&d->m_applicationLauncher,
            SIGNAL(processStarted()),
            &d->m_noDebugOutputTimer,
            SLOT(start()));
158

159 160 161 162 163 164 165 166
    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)));

167
    // Only wait 8 seconds for the 'Waiting for connection' on application ouput, then just try to connect
168 169 170 171
    // (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()));
172 173 174
}

QmlEngine::~QmlEngine()
hjk's avatar
hjk committed
175
{
176 177 178 179 180 181
    ExtensionSystem::PluginManager *pluginManager =
        ExtensionSystem::PluginManager::instance();

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

183 184 185 186 187 188 189 190 191 192
    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
193 194
    delete d;
}
195

hjk's avatar
hjk committed
196
void QmlEngine::setupInferior()
197
{
hjk's avatar
hjk committed
198
    QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
Lasse Holmstedt's avatar
Lasse Holmstedt committed
199

200
    if (startParameters().startMode == AttachToRemoteServer) {
201
        emit requestRemoteSetup();
202 203
        if (startParameters().qmlServerPort != quint16(-1))
            notifyInferiorSetupOk();
204 205 206
    } if (startParameters().startMode == AttachToQmlPort) {
            notifyInferiorSetupOk();

207 208 209 210 211 212
    } else {
        d->m_applicationLauncher.setEnvironment(startParameters().environment);
        d->m_applicationLauncher.setWorkingDirectory(startParameters().workingDirectory);

        notifyInferiorSetupOk();
    }
hjk's avatar
hjk committed
213
}
hjk's avatar
hjk committed
214

con's avatar
con committed
215
void QmlEngine::appendMessage(const QString &msg, Utils::OutputFormat /* format */)
hjk's avatar
hjk committed
216
{
217
    showMessage(msg, AppOutput); // FIXME: Redirect to RunControl
hjk's avatar
hjk committed
218 219
}

Lasse Holmstedt's avatar
Lasse Holmstedt committed
220 221 222 223
void QmlEngine::connectionEstablished()
{
    attemptBreakpointSynchronization();

224 225 226 227
    if (!watchHandler()->watcherNames().isEmpty()) {
        synchronizeWatchers();
    }
    connect(watchersModel(),SIGNAL(layoutChanged()),this,SLOT(synchronizeWatchers()));
Christiaan Janssen's avatar
Christiaan Janssen committed
228

229 230
    if (state() == EngineRunRequested)
        notifyEngineRunAndInferiorRunOk();
Lasse Holmstedt's avatar
Lasse Holmstedt committed
231
}
232

233 234 235 236
void QmlEngine::beginConnection()
{
    d->m_noDebugOutputTimer.stop();
    d->m_adapter.beginConnection();
Lasse Holmstedt's avatar
Lasse Holmstedt committed
237 238 239 240
}

void QmlEngine::connectionStartupFailed()
{
241 242 243 244 245 246 247 248
    if (isSlaveEngine()) {
        if (masterEngine()->state() != InferiorRunOk) {
            // we're right now debugging C++, just try longer ...
            beginConnection();
            return;
        }
    }

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

288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
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();
}

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

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

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

327 328 329 330 331
bool QmlEngine::canDisplayTooltip() const
{
    return state() == InferiorRunOk || state() == InferiorStopOk;
}

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

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

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

371 372
            updateEditor(editor, d->m_sourceDocuments.value(fileName));
        }
373
        editorManager->activateEditor(editor);
374

375 376 377 378 379
    } else {
        DebuggerEngine::gotoLocation(location);
    }
}

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

hjk's avatar
hjk committed
386 387 388
void QmlEngine::runEngine()
{
    QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());
Lasse Holmstedt's avatar
Lasse Holmstedt committed
389

390
    if (!isSlaveEngine() && startParameters().startMode != AttachToRemoteServer
391
            && startParameters().startMode != AttachToQmlPort)
392
        startApplicationLauncher();
393 394 395

    if (startParameters().startMode == AttachToQmlPort)
        beginConnection();
396 397 398 399 400
}

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

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

Christian Kandeler's avatar
Christian Kandeler committed
420
void QmlEngine::handleRemoteSetupDone(int gdbServerPort, int qmlPort)
421
{
Christian Kandeler's avatar
Christian Kandeler committed
422 423 424
    Q_UNUSED(gdbServerPort);
    if (qmlPort != -1)
        startParameters().qmlServerPort = qmlPort;
425 426 427 428 429 430 431 432 433 434
    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
435
void QmlEngine::shutdownInferior()
436
{
437 438 439 440
    d->m_noDebugOutputTimer.stop();

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

442 443
    if (isSlaveEngine()) {
        resetLocation();
Lasse Holmstedt's avatar
Lasse Holmstedt committed
444
    }
445
    stopApplicationLauncher();
446

hjk's avatar
hjk committed
447 448 449 450 451
    notifyInferiorShutdownOk();
}

void QmlEngine::shutdownEngine()
{
452
    closeConnection();
Lasse Holmstedt's avatar
Lasse Holmstedt committed
453

454 455
    // double check (ill engine?):
    stopApplicationLauncher();
Lasse Holmstedt's avatar
Lasse Holmstedt committed
456

457
    notifyEngineShutdownOk();
458 459
    if (!isSlaveEngine())
        showMessage(QString(), StatusBar);
460 461
}

hjk's avatar
hjk committed
462
void QmlEngine::setupEngine()
463
{
464 465 466
    connect(&d->m_applicationLauncher, SIGNAL(bringToForegroundRequested(qint64)),
            runControl(), SLOT(bringApplicationToForeground(qint64)),
            Qt::UniqueConnection);
Lasse Holmstedt's avatar
Lasse Holmstedt committed
467

468
    notifyEngineSetupOk();
469 470
}

471 472
void QmlEngine::continueInferior()
{
hjk's avatar
hjk committed
473
    QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
474 475 476
    if (d->m_adapter.activeDebuggerClient()) {
        d->m_adapter.activeDebuggerClient()->continueInferior();
    }
477
    resetLocation();
hjk's avatar
hjk committed
478 479
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
480 481 482 483
}

void QmlEngine::interruptInferior()
{
484 485 486
    if (d->m_adapter.activeDebuggerClient()) {
        d->m_adapter.activeDebuggerClient()->interruptInferior();
    }
487
    notifyInferiorStopOk();
488 489 490 491
}

void QmlEngine::executeStep()
{
492 493 494
    if (d->m_adapter.activeDebuggerClient()) {
        d->m_adapter.activeDebuggerClient()->executeStep();
    }
hjk's avatar
hjk committed
495 496
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
497 498 499 500
}

void QmlEngine::executeStepI()
{
501 502 503
    if (d->m_adapter.activeDebuggerClient()) {
        d->m_adapter.activeDebuggerClient()->executeStepI();
    }
hjk's avatar
hjk committed
504 505
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
506 507 508 509
}

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

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

void QmlEngine::executeNextI()
{
528
    executeNext();
529 530
}

531
void QmlEngine::executeRunToLine(const ContextData &data)
532
{
533 534 535 536 537 538 539
    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();
540 541 542 543 544 545 546 547
}

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

548
void QmlEngine::executeJumpToLine(const ContextData &data)
549
{
550
    Q_UNUSED(data)
551 552 553 554 555
    XSDEBUG("FIXME:  QmlEngine::executeJumpToLine()");
}

void QmlEngine::activateFrame(int index)
{
556 557 558
    if (state() != InferiorStopOk && state() != InferiorUnrunnable)
        return;

559 560 561
    if (d->m_adapter.activeDebuggerClient()) {
        d->m_adapter.activeDebuggerClient()->activateFrame(index);
    }
562
    gotoLocation(stackHandler()->frames().value(index));
563 564 565 566 567 568 569
}

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

570 571 572 573 574 575 576 577
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()) {
578
        d->m_adapter.activeDebuggerClient()->insertBreakpoint(id);
579 580
    } else {
        foreach (QmlDebuggerClient *client, d->m_adapter.debuggerClients()) {
581
            client->insertBreakpoint(id);
582 583 584 585 586 587 588 589 590 591 592 593
        }
    }
}

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

    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()) {
614
        d->m_adapter.activeDebuggerClient()->changeBreakpoint(id);
615 616
    } else {
        foreach (QmlDebuggerClient *client, d->m_adapter.debuggerClients()) {
617
            client->changeBreakpoint(id);
618 619 620 621 622 623 624 625
        }
    }

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

626 627
void QmlEngine::attemptBreakpointSynchronization()
{
628 629 630 631 632
    if (!stateAcceptsBreakpointChanges()) {
        showMessage(_("BREAKPOINT SYNCHRONIZATION NOT POSSIBLE IN CURRENT STATE"));
        return;
    }

hjk's avatar
hjk committed
633
    BreakHandler *handler = breakHandler();
634

635
    foreach (BreakpointModelId id, handler->unclaimedBreakpointIds()) {
636 637 638 639 640
        // Take ownership of the breakpoint. Requests insertion.
        if (acceptsBreakpoint(id))
            handler->setEngine(id, this);
    }

641
    foreach (BreakpointModelId id, handler->engineBreakpointIds(this)) {
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
        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;
662
        }
663
        QTC_ASSERT(false, qDebug() << "UNKNOWN STATE"  << id << state());
664 665
    }

666
    DebuggerEngine::attemptBreakpointSynchronization();
667

668
    if (d->m_adapter.activeDebuggerClient()) {
669
        d->m_adapter.activeDebuggerClient()->synchronizeBreakpoints();
670 671
    } else {
        foreach (QmlDebuggerClient *client, d->m_adapter.debuggerClients()) {
672
            client->synchronizeBreakpoints();
673
        }
674
    }
675 676
}

677
bool QmlEngine::acceptsBreakpoint(BreakpointModelId id) const
678
{
679 680 681 682 683 684
    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
685
    //This is because the older client does not support BreakpointOnQmlSignalHandler
686 687 688 689 690
    bool acceptBreakpoint = false;
    if (d->m_adapter.activeDebuggerClient()) {
        acceptBreakpoint = d->m_adapter.activeDebuggerClient()->acceptsBreakpoint(id);
    }
    return acceptBreakpoint;
691 692
}

693 694 695 696 697 698 699 700 701 702 703 704 705
void QmlEngine::loadSymbols(const QString &moduleName)
{
    Q_UNUSED(moduleName)
}

void QmlEngine::loadAllSymbols()
{
}

void QmlEngine::reloadModules()
{
}

706 707 708 709 710 711 712
void QmlEngine::reloadSourceFiles()
{
    if (d->m_adapter.activeDebuggerClient()) {
        d->m_adapter.activeDebuggerClient()->getSourceFiles();
    }
}

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

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

724
bool QmlEngine::setToolTipExpression(const QPoint &mousePos,
725
    TextEditor::ITextEditor *editor, const DebuggerToolTipContext &ctx)
726
{
727
    // This is processed by QML inspector, which has dependencies to
hjk's avatar
hjk committed
728
    // the qml js editor. Makes life easier.
729
    emit tooltipRequested(mousePos, editor, ctx.position);
730
    return true;
731 732 733 734 735 736 737 738
}

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

739
void QmlEngine::assignValueInDebugger(const WatchData *data,
hjk's avatar
hjk committed
740
    const QString &expression, const QVariant &valueV)
741
{
742
    quint64 objectId =  data->id;
743
    if (objectId > 0 && !expression.isEmpty() && d->m_adapter.activeDebuggerClient()) {
744
        d->m_adapter.activeDebuggerClient()->assignValueInDebugger(expression.toUtf8(), objectId, expression, valueV.toString());
745
    }
746 747
}

hjk's avatar
hjk committed
748 749
void QmlEngine::updateWatchData(const WatchData &data,
    const WatchUpdateFlags &)
750
{
Olivier Goffart's avatar
Olivier Goffart committed
751
//    qDebug() << "UPDATE WATCH DATA" << data.toString();
752
    //watchHandler()->rebuildModel();
753
    showStatusMessage(tr("Stopped."), 5000);
754

755 756
    if (!data.name.isEmpty() && d->m_adapter.activeDebuggerClient()) {
        if (data.isValueNeeded()) {
757
            d->m_adapter.activeDebuggerClient()->updateWatchData(data);
758 759 760 761 762
        }
        if (data.isChildrenNeeded()
                && watchHandler()->isExpandedIName(data.iname)) {
            d->m_adapter.activeDebuggerClient()->expandObject(data.iname, data.id);
        }
Christiaan Janssen's avatar
Christiaan Janssen committed
763 764 765
    }

    synchronizeWatchers();
766

Christiaan Janssen's avatar
Christiaan Janssen committed
767 768 769 770 771 772
    if (!data.isSomethingNeeded())
        watchHandler()->insertData(data);
}

void QmlEngine::synchronizeWatchers()
{
773
    QStringList watchedExpressions = watchHandler()->watchedExpressions();
774
    // send watchers list
775 776
    if (d->m_adapter.activeDebuggerClient()) {
        d->m_adapter.activeDebuggerClient()->synchronizeWatchers(watchedExpressions);
777
    } else {
778 779 780
        foreach (QmlDebuggerClient *client, d->m_adapter.debuggerClients())
            client->synchronizeWatchers(watchedExpressions);
    }
781 782
}

783
bool QmlEngine::hasCapability(unsigned cap) const
784
{
785
    return cap & (AddWatcherCapability
786
            | AddWatcherWhileRunningCapability
787
            | RunToLineCapability);
788 789 790 791 792 793 794 795 796
    /*ReverseSteppingCapability | SnapshotCapability
        | AutoDerefPointersCapability | DisassemblerCapability
        | RegisterCapability | ShowMemoryCapability
        | JumpToLineCapability | ReloadModuleCapability
        | ReloadModuleSymbolsCapability | BreakOnThrowAndCatchCapability
        | ReturnFromFunctionCapability
        | CreateFullBacktraceCapability
        | WatchpointCapability
        | AddWatcherCapability;*/
797 798
}

799
QString QmlEngine::toFileInProject(const QUrl &fileUrl)
800
{
801 802 803 804
    // make sure file finder is properly initialized
    d->fileFinder.setProjectDirectory(startParameters().projectSourceDirectory);
    d->fileFinder.setProjectFiles(startParameters().projectSourceFiles);
    d->fileFinder.setSysroot(startParameters().sysroot);
805

806
    return d->fileFinder.findFile(fileUrl);
807 808
}

809
void QmlEngine::inferiorSpontaneousStop()
810
{
811 812
    if (state() == InferiorRunOk)
        notifyInferiorSpontaneousStop();
813 814
}

815 816
void QmlEngine::disconnected()
{
817
    showMessage(tr("QML Debugger disconnected."), StatusBar);
818 819 820
    notifyInferiorExited();
}

821
void QmlEngine::wrongSetupMessageBoxFinished(int result)
822 823 824 825 826 827 828 829
{
    if (result == QMessageBox::Help) {
        Core::HelpManager *helpManager = Core::HelpManager::instance();
        helpManager->handleHelpRequest(
                    QLatin1String("qthelp://com.nokia.qtcreator/doc/creator-debugging-qml.html"));
    }
}

830 831
void QmlEngine::executeDebuggerCommand(const QString& command)
{
832 833 834
    if (d->m_adapter.activeDebuggerClient()) {
        d->m_adapter.activeDebuggerClient()->executeDebuggerCommand(command);
    }
835 836
}

837 838 839

QString QmlEngine::qmlImportPath() const
{
840
    return startParameters().environment.value(QLatin1String("QML_IMPORT_PATH"));
841 842
}

843
void QmlEngine::logMessage(const QString &service, LogDirection direction, const QString &message)
844
{
845
    QString msg = service;
846
    msg += direction == LogSend ? QLatin1String(": sending ") : QLatin1String(": receiving ");
847 848 849 850
    msg += message;
    showMessage(msg, LogDebug);
}

851 852 853 854 855 856 857 858 859 860
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);
861 862
    //update open editors

863 864 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 895 896 897 898 899 900 901 902 903 904 905
}

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 (!cursor.movePosition(QTextCursor::NextBlock))
            cursor.insertBlock();
    }
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

    //update open editors
    QString titlePattern = tr("JS Source for %1").arg(fileName);
    //Check if there are open editors with the same title
    QList<Core::IEditor *> editors = Core::EditorManager::instance()->openedEditors();
    foreach (Core::IEditor *editor, editors) {
        if (editor->displayName() == titlePattern) {
            updateEditor(editor, document);
            break;
        }
    }
}

void QmlEngine::updateEditor(Core::IEditor *editor, const QTextDocument *document)
{
    TextEditor::ITextEditor *textEditor = qobject_cast<TextEditor::ITextEditor*>(editor);
    if (!textEditor)
        return;

    QPlainTextEdit *plainTextEdit =
            qobject_cast<QPlainTextEdit *>(editor->widget());
    if (!plainTextEdit)
        return;
    plainTextEdit->setPlainText(document->toPlainText());
    plainTextEdit->setReadOnly(true);
931 932
}

933 934 935 936 937
QmlAdapter *QmlEngine::adapter() const
{
    return &d->m_adapter;
}

938
QmlEngine *createQmlEngine(const DebuggerStartParameters &sp,
939 940 941 942 943
    DebuggerEngine *masterEngine)
{
    return new QmlEngine(sp, masterEngine);
}

944
} // namespace Internal
945
} // namespace Debugger
946