qmlengine.cpp 94.9 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
2
**
Eike Ziller's avatar
Eike Ziller committed
3 4
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
7
**
hjk's avatar
hjk committed
8 9 10 11
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
Eike Ziller's avatar
Eike Ziller committed
12 13
** a written agreement between you and The Qt Company.  For licensing terms and
** conditions see http://www.qt.io/terms-conditions.  For further information
Eike Ziller's avatar
Eike Ziller committed
14
** use the contact form at http://www.qt.io/contact-us.
15 16
**
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
** Alternatively, this file may be used under the terms of the GNU Lesser
Eike Ziller's avatar
Eike Ziller committed
18 19 20 21 22 23
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
hjk's avatar
hjk committed
24
**
Eike Ziller's avatar
Eike Ziller committed
25 26
** In addition, as a special exception, The Qt Company gives you certain additional
** rights.  These rights are described in The Qt Company LGPL Exception
con's avatar
con committed
27 28
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
29
****************************************************************************/
30 31

#include "qmlengine.h"
hjk's avatar
hjk committed
32 33

#include "interactiveinterpreter.h"
34
#include "qmlinspectoragent.h"
hjk's avatar
hjk committed
35 36
#include "qmlv8debuggerclientconstants.h"
#include "qmlengineutils.h"
37

hjk's avatar
hjk committed
38
#include <debugger/breakhandler.h>
39 40 41
#include <debugger/debuggeractions.h>
#include <debugger/debuggercore.h>
#include <debugger/debuggerinternalconstants.h>
42
#include <debugger/debuggerruncontrol.h>
43 44
#include <debugger/debuggerstringutils.h>
#include <debugger/debuggertooltipmanager.h>
hjk's avatar
hjk committed
45 46
#include <debugger/sourcefileshandler.h>
#include <debugger/stackhandler.h>
Christian Kandeler's avatar
Christian Kandeler committed
47
#include <debugger/threaddata.h>
hjk's avatar
hjk committed
48
#include <debugger/watchhandler.h>
49
#include <debugger/watchwindow.h>
50

hjk's avatar
hjk committed
51 52 53 54 55
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/helpmanager.h>
#include <coreplugin/icore.h>

#include <projectexplorer/applicationlauncher.h>
56

57
#include <qmljseditor/qmljseditorconstants.h>
58
#include <qmljs/qmljsmodelmanagerinterface.h>
59
#include <qmljs/consolemanagerinterface.h>
60

61 62
#include <texteditor/textdocument.h>
#include <texteditor/texteditor.h>
hjk's avatar
hjk committed
63

64
#include <utils/treemodel.h>
hjk's avatar
hjk committed
65
#include <utils/qtcassert.h>
66

67 68
#include <QDebug>
#include <QDir>
69
#include <QDockWidget>
hjk's avatar
hjk committed
70 71 72 73
#include <QFileInfo>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
74 75
#include <QMessageBox>
#include <QPlainTextEdit>
hjk's avatar
hjk committed
76
#include <QTimer>
77

hjk's avatar
hjk committed
78
#define DEBUG_QML 0
79 80 81 82 83 84 85
#if DEBUG_QML
#   define SDEBUG(s) qDebug() << s
#else
#   define SDEBUG(s)
#endif
# define XSDEBUG(s) qDebug() << s

86 87
#define CB(callback) [this](const QVariantMap &r) { callback(r); }

hjk's avatar
hjk committed
88 89 90
using namespace Core;
using namespace ProjectExplorer;
using namespace QmlDebug;
91
using namespace QmlJS;
hjk's avatar
hjk committed
92
using namespace TextEditor;
93
using namespace Utils;
hjk's avatar
hjk committed
94

95 96 97
namespace Debugger {
namespace Internal {

hjk's avatar
hjk committed
98
enum Exceptions
99
{
hjk's avatar
hjk committed
100 101 102 103
    NoExceptions,
    UncaughtExceptions,
    AllExceptions
};
104

hjk's avatar
hjk committed
105
enum StepAction
106
{
hjk's avatar
hjk committed
107 108 109 110 111
    Continue,
    StepIn,
    StepOut,
    Next
};
112

hjk's avatar
hjk committed
113 114 115 116 117 118 119 120
struct QmlV8ObjectData
{
    int handle;
    QByteArray name;
    QByteArray type;
    QVariant value;
    QVariantList properties;
};
121

122 123
typedef std::function<void(const QVariantMap &)> QmlCallback;

124 125 126 127 128 129 130 131
struct LookupData
{
    QByteArray iname;
    QString name;
};

typedef QMultiHash<int, LookupData> LookupItems; // id -> (iname, exp)

hjk's avatar
hjk committed
132 133 134 135 136 137
class QmlEnginePrivate : QmlDebugClient
{
public:
    QmlEnginePrivate(QmlEngine *engine_, QmlDebugConnection *connection_)
        : QmlDebugClient(QLatin1String("V8Debugger"), connection_),
          engine(engine_),
138
          inspectorAgent(engine, connection_),
hjk's avatar
hjk committed
139 140 141 142 143 144 145 146 147
          connection(connection_)
    {}

    void sendMessage(const QByteArray &msg);
    void messageReceived(const QByteArray &data);
    void stateChanged(State state);

    void continueDebugging(StepAction stepAction);

148 149
    void evaluate(const QString expr, const QmlCallback &cb);
    void lookup(const LookupItems &items);
150
    void backtrace();
151
    void updateLocals();
152
    void scope(int number, int frameNumber = -1);
hjk's avatar
hjk committed
153 154 155 156 157 158 159 160 161 162 163
    void scripts(int types = 4, const QList<int> ids = QList<int>(),
                 bool includeSource = false, const QVariant filter = QVariant());

    void setBreakpoint(const QString type, const QString target,
                       bool enabled = true,int line = 0, int column = 0,
                       const QString condition = QString(), int ignoreCount = -1);
    void clearBreakpoint(int breakpoint);
    void setExceptionBreak(Exceptions type, bool enabled = false);

    void flushSendBuffer();

164 165
    void handleBacktrace(const QVariantMap &response);
    void handleLookup(const QVariantMap &response);
166
    void handleExecuteDebuggerCommand(const QVariantMap &response);
167
    void handleEvaluateExpression(const QVariantMap &response, const QByteArray &iname, const QString &expr);
168 169 170
    void handleFrame(const QVariantMap &response);
    void handleScope(const QVariantMap &response);
    void handleVersion(const QVariantMap &response);
171
    StackFrame extractStackFrame(const QVariant &bodyVal);
hjk's avatar
hjk committed
172 173 174

    bool canEvaluateScript(const QString &script);
    void updateScriptSource(const QString &fileName, int lineOffset, int columnOffset, const QString &source);
175

176
    void runCommand(const DebuggerCommand &command, const QmlCallback &cb = QmlCallback());
177
    void runDirectCommand(const QByteArray &type, const QByteArray &msg = QByteArray());
178

179 180 181 182
    void clearRefs() { refVals.clear(); }
    void memorizeRefs(const QVariant &refs);
    QmlV8ObjectData extractData(const QVariant &data) const;
    void insertSubItems(WatchItem *parent, const QVariantList &properties);
183
    void checkForFinishedUpdate();
184
    ConsoleItem *constructLogItemTree(const QmlV8ObjectData &objectData);
185

hjk's avatar
hjk committed
186
public:
187
    QHash<int, QmlV8ObjectData> refVals; // The mapping of target object handles to retrieved values.
hjk's avatar
hjk committed
188 189 190 191 192 193
    int sequence = -1;
    QmlEngine *engine;
    QHash<BreakpointModelId, int> breakpoints;
    QHash<int, BreakpointModelId> breakpointsSync;
    QList<int> breakpointsTemp;

194
    LookupItems currentlyLookingUp; // Id -> inames
hjk's avatar
hjk committed
195 196 197 198 199 200 201 202 203 204 205 206 207

    //Cache
    QList<int> currentFrameScopes;
    QHash<int, int> stackIndexLookup;

    StepAction previousStepAction = Continue;

    QList<QByteArray> sendBuffer;

    QHash<QString, QTextDocument*> sourceDocuments;
    QHash<QString, QWeakPointer<BaseTextEditor> > sourceEditors;
    InteractiveInterpreter interpreter;
    ApplicationLauncher applicationLauncher;
208
    QmlInspectorAgent inspectorAgent;
hjk's avatar
hjk committed
209 210 211 212 213 214 215 216 217 218 219
    QmlOutputParser outputParser;

    QTimer noDebugOutputTimer;
    QHash<QString,Breakpoint> pendingBreakpoints;
    QList<quint32> queryIds;
    bool retryOnConnectFail = false;
    bool automaticConnect = false;

    QTimer connectionTimer;
    QmlDebug::QmlDebugConnection *connection;
    QmlDebug::QDebugMessageClient *msgClient = 0;
220 221

    QHash<int, QmlCallback> callbackForToken;
222 223 224 225
private:
    ConsoleItem *constructLogItemTree(const QmlV8ObjectData &objectData, QList<int> &seenHandles);
    void constructChildLogItems(ConsoleItem *item, const QmlV8ObjectData &objectData,
                             QList<int> &seenHandles);
226
};
227

hjk's avatar
hjk committed
228
static void updateDocument(IDocument *document, const QTextDocument *textDocument)
229
{
hjk's avatar
hjk committed
230 231
    if (auto baseTextDocument = qobject_cast<TextDocument *>(document))
        baseTextDocument->document()->setPlainText(textDocument->toPlainText());
232 233
}

hjk's avatar
hjk committed
234

235 236 237 238 239 240
///////////////////////////////////////////////////////////////////////
//
// QmlEngine
//
///////////////////////////////////////////////////////////////////////

241
QmlEngine::QmlEngine(const DebuggerRunParameters &startParameters, DebuggerEngine *masterEngine)
hjk's avatar
hjk committed
242 243
  : DebuggerEngine(startParameters),
    d(new QmlEnginePrivate(this, new QmlDebugConnection(this)))
244
{
Friedemann Kleint's avatar
Friedemann Kleint committed
245
    setObjectName(QLatin1String("QmlEngine"));
246

Aurindam Jana's avatar
Aurindam Jana committed
247 248 249
    if (masterEngine)
        setMasterEngine(masterEngine);

hjk's avatar
hjk committed
250 251 252 253 254
    connect(stackHandler(), &StackHandler::stackChanged,
            this, &QmlEngine::updateCurrentContext);
    connect(stackHandler(), &StackHandler::currentIndexChanged,
            this, &QmlEngine::updateCurrentContext);
    connect(inspectorView(), SIGNAL(currentIndexChanged(QModelIndex)),
255
            SLOT(updateCurrentContext()));
hjk's avatar
hjk committed
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270

    connect(&d->applicationLauncher, &ApplicationLauncher::processExited,
            this, &QmlEngine::disconnected);
    connect(&d->applicationLauncher, &ApplicationLauncher::appendMessage,
            this, &QmlEngine::appendMessage);
    connect(&d->applicationLauncher, &ApplicationLauncher::processStarted,
            &d->noDebugOutputTimer, static_cast<void(QTimer::*)()>(&QTimer::start));

    d->outputParser.setNoOutputText(ApplicationLauncher::msgWinCannotRetrieveDebuggingOutput());
    connect(&d->outputParser, &QmlOutputParser::waitingForConnectionOnPort,
            this, &QmlEngine::beginConnection);
    connect(&d->outputParser, &QmlOutputParser::noOutputMessage,
            this, [this] { tryToConnect(); });
    connect(&d->outputParser, &QmlOutputParser::errorMessage,
            this, &QmlEngine::appStartupFailed);
271

Kai Koehne's avatar
Kai Koehne committed
272 273
    // Only wait 8 seconds for the 'Waiting for connection' on application output,
    // then just try to connect (application output might be redirected / blocked)
hjk's avatar
hjk committed
274 275 276
    d->noDebugOutputTimer.setSingleShot(true);
    d->noDebugOutputTimer.setInterval(8000);
    connect(&d->noDebugOutputTimer, SIGNAL(timeout()), this, SLOT(tryToConnect()));
277

hjk's avatar
hjk committed
278 279 280
    if (auto mmIface = ModelManagerInterface::instance()) {
        connect(mmIface, &ModelManagerInterface::documentUpdated,
                this, &QmlEngine::documentUpdated);
281
    }
282
    // we won't get any debug output
283
    if (startParameters.useTerminal) {
hjk's avatar
hjk committed
284 285 286
        d->noDebugOutputTimer.setInterval(0);
        d->retryOnConnectFail = true;
        d->automaticConnect = true;
287
    }
hjk's avatar
hjk committed
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315

    if (auto consoleManager = ConsoleManagerInterface::instance())
        consoleManager->setScriptEvaluator(this);


    d->connectionTimer.setInterval(4000);
    d->connectionTimer.setSingleShot(true);
    connect(&d->connectionTimer, &QTimer::timeout,
            this, &QmlEngine::checkConnectionState);

    connect(d->connection, &QmlDebugConnection::stateMessage,
            this, &QmlEngine::showConnectionStateMessage);
    connect(d->connection, &QmlDebugConnection::errorMessage,
            this, &QmlEngine::showConnectionErrorMessage);
    connect(d->connection, &QmlDebugConnection::error,
            this, &QmlEngine::connectionErrorOccurred);
    connect(d->connection, &QmlDebugConnection::opened,
            &d->connectionTimer, &QTimer::stop);
    connect(d->connection, &QmlDebugConnection::opened,
            this, &QmlEngine::connectionEstablished);
    connect(d->connection, &QmlDebugConnection::closed,
            this, &QmlEngine::disconnected);

    d->msgClient = new QDebugMessageClient(d->connection);
    connect(d->msgClient, &QDebugMessageClient::newState,
            this, &QmlEngine::clientStateChanged);
    connect(d->msgClient, &QDebugMessageClient::message,
            this, &appendDebugOutput);
316 317 318
}

QmlEngine::~QmlEngine()
hjk's avatar
hjk committed
319
{
hjk's avatar
hjk committed
320
    QSet<IDocument *> documentsToClose;
321

hjk's avatar
hjk committed
322 323 324
    QHash<QString, QWeakPointer<BaseTextEditor> >::iterator iter;
    for (iter = d->sourceEditors.begin(); iter != d->sourceEditors.end(); ++iter) {
        QWeakPointer<BaseTextEditor> textEditPtr = iter.value();
325
        if (textEditPtr)
326
            documentsToClose << textEditPtr.data()->document();
327
    }
hjk's avatar
hjk committed
328 329 330
    EditorManager::closeDocuments(documentsToClose.toList());

    delete d;
hjk's avatar
hjk committed
331
}
332

hjk's avatar
hjk committed
333
void QmlEngine::setupInferior()
334
{
hjk's avatar
hjk committed
335
    QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
Lasse Holmstedt's avatar
Lasse Holmstedt committed
336

337
    notifyInferiorSetupOk();
338

hjk's avatar
hjk committed
339
    if (d->automaticConnect)
340
        beginConnection();
hjk's avatar
hjk committed
341
}
hjk's avatar
hjk committed
342

con's avatar
con committed
343
void QmlEngine::appendMessage(const QString &msg, Utils::OutputFormat /* format */)
hjk's avatar
hjk committed
344
{
345
    showMessage(msg, AppOutput); // FIXME: Redirect to RunControl
hjk's avatar
hjk committed
346 347
}

Lasse Holmstedt's avatar
Lasse Holmstedt committed
348 349 350 351
void QmlEngine::connectionEstablished()
{
    attemptBreakpointSynchronization();

352 353
    if (state() == EngineRunRequested)
        notifyEngineRunAndInferiorRunOk();
Lasse Holmstedt's avatar
Lasse Holmstedt committed
354
}
355

356 357
void QmlEngine::tryToConnect(quint16 port)
{
358
    showMessage(QLatin1String("QML Debugger: No application output received in time, trying to connect ..."), LogStatus);
hjk's avatar
hjk committed
359
    d->retryOnConnectFail = true;
360 361 362
    if (state() == EngineRunRequested) {
        if (isSlaveEngine()) {
            // Probably cpp is being debugged and hence we did not get the output yet.
363
            if (!masterEngine()->isDying()) {
hjk's avatar
hjk committed
364 365
                d->noDebugOutputTimer.setInterval(4000);
                d->noDebugOutputTimer.start();
366
            }
367 368 369 370 371 372
            else
                appStartupFailed(tr("No application output received in time"));
        } else {
            beginConnection(port);
        }
    } else {
hjk's avatar
hjk committed
373
        d->automaticConnect = true;
374
    }
375 376
}

377
void QmlEngine::beginConnection(quint16 port)
378
{
hjk's avatar
hjk committed
379
    d->noDebugOutputTimer.stop();
380

hjk's avatar
hjk committed
381
    if (state() != EngineRunRequested && d->retryOnConnectFail)
382 383
        return;

384
    QTC_ASSERT(state() == EngineRunRequested, return);
385

386
    QString host =  runParameters().qmlServerAddress;
387 388 389 390
    // Use localhost as default
    if (host.isEmpty())
        host = QLatin1String("localhost");

391 392 393 394 395 396 397 398 399 400 401
    /*
     * Let plugin-specific code override the port printed by the application. This is necessary
     * in the case of port forwarding, when the port the application listens on is not the same that
     * we want to connect to.
     * NOTE: It is still necessary to wait for the output in that case, because otherwise we cannot
     * be sure that the port is already open. The usual method of trying to connect repeatedly
     * will not work, because the intermediate port is already open. So the connection
     * will be accepted on that port but the forwarding to the target port will fail and
     * the connection will be closed again (instead of returning the "connection refused"
     * error that we expect).
     */
402 403
    if (runParameters().qmlServerPort > 0)
        port = runParameters().qmlServerPort;
404

hjk's avatar
hjk committed
405 406
    if (!d->connection || d->connection->isOpen())
        return;
Lasse Holmstedt's avatar
Lasse Holmstedt committed
407

hjk's avatar
hjk committed
408 409 410 411 412
    d->connection->connectToHost(host, port);

    //A timeout to check the connection state
    d->connectionTimer.start();
}
413

414
void QmlEngine::connectionStartupFailed()
Lasse Holmstedt's avatar
Lasse Holmstedt committed
415
{
hjk's avatar
hjk committed
416
    if (d->retryOnConnectFail) {
417 418
        // retry after 3 seconds ...
        QTimer::singleShot(3000, this, SLOT(beginConnection()));
419 420
        return;
    }
421

hjk's avatar
hjk committed
422
    QMessageBox *infoBox = new QMessageBox(ICore::mainWindow());
423 424
    infoBox->setIcon(QMessageBox::Critical);
    infoBox->setWindowTitle(tr("Qt Creator"));
425 426 427 428 429
    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);
430 431
    infoBox->setModal(true);

hjk's avatar
hjk committed
432 433
    connect(infoBox, &QDialog::finished,
            this, &QmlEngine::errorMessageBoxFinished);
434 435 436 437

    infoBox->show();
}

438 439
void QmlEngine::appStartupFailed(const QString &errorMessage)
{
440 441 442 443
    QString error = tr("Could not connect to the in-process QML debugger."
                       "\n%1").arg(errorMessage);

    if (isMasterEngine()) {
hjk's avatar
hjk committed
444
        QMessageBox *infoBox = new QMessageBox(ICore::mainWindow());
445 446 447 448 449
        infoBox->setIcon(QMessageBox::Critical);
        infoBox->setWindowTitle(tr("Qt Creator"));
        infoBox->setText(error);
        infoBox->setStandardButtons(QMessageBox::Ok | QMessageBox::Help);
        infoBox->setDefaultButton(QMessageBox::Ok);
hjk's avatar
hjk committed
450 451
        connect(infoBox, &QDialog::finished,
                this, &QmlEngine::errorMessageBoxFinished);
452 453 454 455
        infoBox->show();
    } else {
        showMessage(error, StatusBar);
    }
456 457 458 459

    notifyEngineRunFailed();
}

460
void QmlEngine::errorMessageBoxFinished(int result)
461 462
{
    switch (result) {
463
    case QMessageBox::Retry: {
464
        beginConnection();
465 466 467
        break;
    }
    case QMessageBox::Help: {
hjk's avatar
hjk committed
468
        HelpManager::handleHelpRequest(QLatin1String("qthelp://org.qt-project.qtcreator/doc/creator-debugging-qml.html"));
469
        // fall through
470 471
    }
    default:
472 473 474
        if (state() == InferiorRunOk) {
            notifyInferiorSpontaneousStop();
            notifyInferiorIll();
475
        } else if (state() == EngineRunRequested) {
476
            notifyEngineRunFailed();
477
        }
Kai Koehne's avatar
Kai Koehne committed
478
        break;
479
    }
Lasse Holmstedt's avatar
Lasse Holmstedt committed
480 481
}

hjk's avatar
hjk committed
482
void QmlEngine::filterApplicationMessage(const QString &output, int /*channel*/) const
Lasse Holmstedt's avatar
Lasse Holmstedt committed
483
{
hjk's avatar
hjk committed
484
    d->outputParser.processOutput(output);
485 486 487 488
}

void QmlEngine::showMessage(const QString &msg, int channel, int timeout) const
{
489
    if (channel == AppOutput || channel == AppError)
hjk's avatar
hjk committed
490
        filterApplicationMessage(msg, channel);
491 492 493
    DebuggerEngine::showMessage(msg, channel, timeout);
}

494 495 496
void QmlEngine::gotoLocation(const Location &location)
{
    const QString fileName = location.fileName();
497
    if (QUrl(fileName).isLocalFile()) {
498
        // internal file from source files -> show generated .js
hjk's avatar
hjk committed
499
        QTC_ASSERT(d->sourceDocuments.contains(fileName), return);
500

Aurindam Jana's avatar
Aurindam Jana committed
501
        QString titlePattern = tr("JS Source for %1").arg(fileName);
502
        //Check if there are open documents with the same title
hjk's avatar
hjk committed
503
        foreach (IDocument *document, DocumentModel::openedDocuments()) {
504
            if (document->displayName() == titlePattern) {
hjk's avatar
hjk committed
505
                EditorManager::activateEditorForDocument(document);
506
                return;
Aurindam Jana's avatar
Aurindam Jana committed
507 508
            }
        }
hjk's avatar
hjk committed
509
        IEditor *editor = EditorManager::openEditorWithContents(
510 511 512
                    QmlJSEditor::Constants::C_QMLJSEDITOR_ID, &titlePattern);
        if (editor) {
            editor->document()->setProperty(Constants::OPENED_BY_DEBUGGER, true);
hjk's avatar
hjk committed
513
            if (auto plainTextEdit = qobject_cast<QPlainTextEdit *>(editor->widget()))
514
                plainTextEdit->setReadOnly(true);
hjk's avatar
hjk committed
515
            updateDocument(editor->document(), d->sourceDocuments.value(fileName));
516
        }
517 518 519 520 521
    } else {
        DebuggerEngine::gotoLocation(location);
    }
}

522 523
void QmlEngine::closeConnection()
{
hjk's avatar
hjk committed
524 525 526 527 528 529
    if (d->connectionTimer.isActive()) {
        d->connectionTimer.stop();
    } else {
        if (d->connection)
            d->connection->close();
    }
530 531
}

hjk's avatar
hjk committed
532 533 534
void QmlEngine::runEngine()
{
    QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());
Lasse Holmstedt's avatar
Lasse Holmstedt committed
535

536
    if (!isSlaveEngine()) {
537
        if (runParameters().startMode == AttachToRemoteServer)
hjk's avatar
hjk committed
538
            d->noDebugOutputTimer.start();
539
        else if (runParameters().startMode == AttachToRemoteProcess)
540 541
            beginConnection();
        else
542
            startApplicationLauncher();
543
    } else {
hjk's avatar
hjk committed
544
        d->noDebugOutputTimer.start();
545
    }
546 547 548 549
}

void QmlEngine::startApplicationLauncher()
{
hjk's avatar
hjk committed
550
    if (!d->applicationLauncher.isRunning()) {
551
        appendMessage(tr("Starting %1 %2").arg(
552 553
                          QDir::toNativeSeparators(runParameters().executable),
                          runParameters().processArgs)
554
                      + QLatin1Char('\n')
con's avatar
con committed
555
                     , Utils::NormalMessageFormat);
hjk's avatar
hjk committed
556
        d->applicationLauncher.start(ApplicationLauncher::Gui,
557 558
                                    runParameters().executable,
                                    runParameters().processArgs);
559
    }
560
}
Lasse Holmstedt's avatar
Lasse Holmstedt committed
561

562 563
void QmlEngine::stopApplicationLauncher()
{
hjk's avatar
hjk committed
564 565 566 567
    if (d->applicationLauncher.isRunning()) {
        disconnect(&d->applicationLauncher, &ApplicationLauncher::processExited,
                   this, &QmlEngine::disconnected);
        d->applicationLauncher.stop();
568
    }
569 570
}

571
void QmlEngine::notifyEngineRemoteSetupFinished(const RemoteSetupResult &result)
572
{
573
    DebuggerEngine::notifyEngineRemoteSetupFinished(result);
574

575 576
    if (result.success) {
        if (result.qmlServerPort != InvalidPort)
577
            runParameters().qmlServerPort = result.qmlServerPort;
578

579
        notifyEngineSetupOk();
580

581 582 583
        // The remote setup can take while especialy with mixed debugging.
        // Just waiting for 8 seconds is not enough. Increase the timeout
        // to 60 s
hjk's avatar
hjk committed
584 585
        // In case we get an output the d->outputParser will start the connection.
        d->noDebugOutputTimer.setInterval(60000);
586 587 588
    }
    else {
        if (isMasterEngine())
hjk's avatar
hjk committed
589
            QMessageBox::critical(ICore::dialogParent(), tr("Failed to start application"),
590 591 592
                                  tr("Application startup failed: %1").arg(result.reason));
        notifyEngineSetupFailed();
    }
593 594
}

Aurindam Jana's avatar
Aurindam Jana committed
595 596 597 598 599
void QmlEngine::notifyEngineRemoteServerRunning(const QByteArray &serverChannel, int pid)
{
    bool ok = false;
    quint16 qmlPort = serverChannel.toUInt(&ok);
    if (ok)
600
        runParameters().qmlServerPort = qmlPort;
Aurindam Jana's avatar
Aurindam Jana committed
601
    else
Friedemann Kleint's avatar
Friedemann Kleint committed
602
        qWarning() << tr("QML debugging port not set: Unable to convert %1 to unsigned int.").arg(QString::fromLatin1(serverChannel));
Aurindam Jana's avatar
Aurindam Jana committed
603 604 605 606 607

    DebuggerEngine::notifyEngineRemoteServerRunning(serverChannel, pid);
    notifyEngineSetupOk();

    // The remote setup can take a while especially with mixed debugging.
hjk's avatar
hjk committed
608 609 610
    // Just waiting for 8 seconds is not enough. Increase the timeout to 60 s.
    // In case we get an output the d->outputParser will start the connection.
    d->noDebugOutputTimer.setInterval(60000);
Aurindam Jana's avatar
Aurindam Jana committed
611 612
}

hjk's avatar
hjk committed
613
void QmlEngine::shutdownInferior()
614
{
hjk's avatar
hjk committed
615
    // End session.
616 617 618 619 620
    //    { "seq"     : <number>,
    //      "type"    : "request",
    //      "command" : "disconnect",
    //    }
    d->runCommand(DISCONNECT);
621

622
    if (isSlaveEngine())
623 624
        resetLocation();
    stopApplicationLauncher();
625
    closeConnection();
626

hjk's avatar
hjk committed
627 628 629 630 631
    notifyInferiorShutdownOk();
}

void QmlEngine::shutdownEngine()
{
hjk's avatar
hjk committed
632
    clearExceptionSelection();
633

hjk's avatar
hjk committed
634 635 636
    if (auto consoleManager = ConsoleManagerInterface::instance())
        consoleManager->setScriptEvaluator(0);
    d->noDebugOutputTimer.stop();
637 638

   // double check (ill engine?):
639
    stopApplicationLauncher();
Lasse Holmstedt's avatar
Lasse Holmstedt committed
640

641
    notifyEngineShutdownOk();
642 643
    if (!isSlaveEngine())
        showMessage(QString(), StatusBar);
644 645
}

hjk's avatar
hjk committed
646
void QmlEngine::setupEngine()
647
{
648
    if (runParameters().remoteSetupNeeded) {
649
        // we need to get the port first
650
        notifyEngineRequestRemoteSetup();
651
    } else {
hjk's avatar
hjk committed
652 653
        d->applicationLauncher.setEnvironment(runParameters().environment);
        d->applicationLauncher.setWorkingDirectory(runParameters().workingDirectory);
Lasse Holmstedt's avatar
Lasse Holmstedt committed
654

655
        // We can't do this in the constructore because runControl() isn't yet defined
hjk's avatar
hjk committed
656 657
        connect(&d->applicationLauncher, &ApplicationLauncher::bringToForegroundRequested,
                runControl(), &RunControl::bringApplicationToForeground,
658 659 660 661
                Qt::UniqueConnection);

        notifyEngineSetupOk();
    }
662 663
}

664 665
void QmlEngine::continueInferior()
{
hjk's avatar
hjk committed
666
    QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
hjk's avatar
hjk committed
667 668
    clearExceptionSelection();
    d->continueDebugging(Continue);
669
    resetLocation();
hjk's avatar
hjk committed
670 671
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
672 673 674 675
}

void QmlEngine::interruptInferior()
{
hjk's avatar
hjk committed
676
    showMessage(_(INTERRUPT), LogInput);
677
    d->runDirectCommand(INTERRUPT);
678
    notifyInferiorStopOk();
679 680 681 682
}

void QmlEngine::executeStep()
{
hjk's avatar
hjk committed
683 684
    clearExceptionSelection();
    d->continueDebugging(StepIn);
hjk's avatar
hjk committed
685 686
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
687 688 689 690
}

void QmlEngine::executeStepI()
{
hjk's avatar
hjk committed
691 692
    clearExceptionSelection();
    d->continueDebugging(StepIn);
hjk's avatar
hjk committed
693 694
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
695 696 697 698
}

void QmlEngine::executeStepOut()
{
hjk's avatar
hjk committed
699 700
    clearExceptionSelection();
    d->continueDebugging(StepOut);
hjk's avatar
hjk committed
701 702
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
703 704 705 706
}

void QmlEngine::executeNext()
{
hjk's avatar
hjk committed
707 708
    clearExceptionSelection();
    d->continueDebugging(Next);
hjk's avatar
hjk committed
709 710
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
711 712 713 714
}

void QmlEngine::executeNextI()
{
715
    executeNext();
716 717
}

718
void QmlEngine::executeRunToLine(const ContextData &data)
719
{
720
    QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
Jarek Kobus's avatar
Jarek Kobus committed
721
    showStatusMessage(tr("Run to line %1 (%2) requested...").arg(data.lineNumber).arg(data.fileName), 5000);
722
    resetLocation();
723 724 725 726 727 728
    ContextData modifiedData = data;
    quint32 line = data.lineNumber;
    quint32 column;
    bool valid;
    if (adjustBreakpointLineAndColumn(data.fileName, &line, &column, &valid))
        modifiedData.lineNumber = line;
hjk's avatar
hjk committed
729 730 731 732 733
    d->setBreakpoint(QString(_(SCRIPTREGEXP)), modifiedData.fileName,
                     true, modifiedData.lineNumber);
    clearExceptionSelection();
    d->continueDebugging(Continue);

734 735
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
736 737 738 739 740 741 742 743
}

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

744
void QmlEngine::executeJumpToLine(const ContextData &data)
745
{
746
    Q_UNUSED(data)
747 748 749 750 751
    XSDEBUG("FIXME:  QmlEngine::executeJumpToLine()");
}

void QmlEngine::activateFrame(int index)
{
752 753 754
    if (state() != InferiorStopOk && state() != InferiorUnrunnable)
        return;

hjk's avatar
hjk committed
755
    stackHandler()->setCurrentIndex(index);
756
    gotoLocation(stackHandler()->frames().value(index));
757 758

    d->updateLocals();
759 760
}

hjk's avatar
hjk committed
761
void QmlEngine::selectThread(ThreadId threadId)
762
{
hjk's avatar
hjk committed
763
    Q_UNUSED(threadId)
764 765
}

766
void QmlEngine::insertBreakpoint(Breakpoint bp)
767
{
768 769 770
    BreakpointState state = bp.state();
    QTC_ASSERT(state == BreakpointInsertRequested, qDebug() << bp << this << state);
    bp.notifyBreakpointInsertProceeding();
771

772
    const BreakpointParameters &params = bp.parameters();
773 774 775 776 777 778
    quint32 line = params.lineNumber;
    quint32 column = 0;
    if (params.type == BreakpointByFileAndLine) {
        bool valid = false;
        if (!adjustBreakpointLineAndColumn(params.fileName, &line, &column,
                                           &valid)) {
hjk's avatar
hjk committed
779
            d->pendingBreakpoints.insertMulti(params.fileName, bp);
780 781 782 783 784 785
            return;
        }
        if (!valid)
            return;
    }

hjk's avatar
hjk committed
786 787 788 789 790 791 792 793 794 795 796 797
    if (params.type == BreakpointAtJavaScriptThrow) {
        bp.notifyBreakpointInsertOk();
        d->setExceptionBreak(AllExceptions, params.enabled);

    } else if (params.type == BreakpointByFileAndLine) {
        d->setBreakpoint(QString(_(SCRIPTREGEXP)), params.fileName,
                         params.enabled, line, column,
                         QLatin1String(params.condition), params.ignoreCount);

    } else if (params.type == BreakpointOnQmlSignalEmit) {
        d->setBreakpoint(QString(_(EVENT)), params.functionName, params.enabled);
        bp.notifyBreakpointInsertOk();
798
    }
hjk's avatar
hjk committed
799 800

    d->breakpointsSync.insert(d->sequence, bp.id());
801 802
}

803
void QmlEngine::removeBreakpoint(Breakpoint bp)
804
{
805
    const BreakpointParameters &params = bp.parameters();
806
    if (params.type == BreakpointByFileAndLine &&
hjk's avatar
hjk committed
807 808 809
            d->pendingBreakpoints.contains(params.fileName)) {
        auto it = d->pendingBreakpoints.find(params.fileName);
        while (it != d->pendingBreakpoints.end() && it.key() == params.fileName) {
810
            if (it.value() == bp.id()) {
hjk's avatar
hjk committed
811
                d->pendingBreakpoints.erase(it);
812 813
                return;
            }
814
            ++it;
815 816 817
        }
    }

818 819 820
    BreakpointState state = bp.state();
    QTC_ASSERT(state == BreakpointRemoveRequested, qDebug() << bp << this << state);
    bp.notifyBreakpointRemoveProceeding();
821

hjk's avatar
hjk committed
822 823 824 825 826 827 828 829 830
    int breakpoint = d->breakpoints.value(bp.id());
    d->breakpoints.remove(bp.id());

    if (params.type == BreakpointAtJavaScriptThrow)
        d->setExceptionBreak(AllExceptions);
    else if (params.type == BreakpointOnQmlSignalEmit)
        d->setBreakpoint(QString(_(EVENT)), params.functionName, false);
    else
        d->clearBreakpoint(breakpoint);
831

832 833
    if (bp.state() == BreakpointRemoveProceeding)
        bp.notifyBreakpointRemoveOk();
834 835
}

836
void QmlEngine::changeBreakpoint(Breakpoint bp)
837
{
838 839 840
    BreakpointState state = bp.state();
    QTC_ASSERT(state == BreakpointChangeRequested, qDebug() << bp << this << state);
    bp.notifyBreakpointChangeProceeding();
841

hjk's avatar
hjk committed
842 843 844 845 846 847 848 849 850 851 852
    const BreakpointParameters &params = bp.parameters();

    BreakpointResponse br = bp.response();
    if (params.type == BreakpointAtJavaScriptThrow) {
        d->setExceptionBreak(AllExceptions, params.enabled);
        br.enabled = params.enabled;
        bp.setResponse(br);
    } else if (params.type == BreakpointOnQmlSignalEmit) {
        d->setBreakpoint(QString(_(EVENT)), params.functionName, params.enabled);
        br.enabled = params.enabled;
        bp.setResponse(br);
853
    } else {
hjk's avatar
hjk committed
854 855 856 857 858 859
        //V8 supports only minimalistic changes in breakpoint
        //Remove the breakpoint and add again
        bp.notifyBreakpointChangeOk();
        bp.removeBreakpoint();
        BreakHandler *handler = d->engine->breakHandler();
        handler->appendBreakpoint(params);
860 861
    }

862 863
    if (bp.state() == BreakpointChangeProceeding)
        bp.notifyBreakpointChangeOk();
864 865
}

866 867
void QmlEngine::attemptBreakpointSynchronization()
{
868 869 870 871 872
    if (!stateAcceptsBreakpointChanges()) {
        showMessage(_("BREAKPOINT SYNCHRONIZATION NOT POSSIBLE IN CURRENT STATE"));
        return;
    }

hjk's avatar
hjk committed
873
    BreakHandler *handler = breakHandler();
874

875
    DebuggerEngine *bpOwner = isSlaveEngine() ? masterEngine() : this;
876
    foreach (Breakpoint bp, handler->unclaimedBreakpoints()) {
877
        // Take ownership of the breakpoint. Requests insertion.
878 879
        if (acceptsBreakpoint(bp))
            bp.setEngine(bpOwner);
880 881
    }

882 883
    foreach (Breakpoint bp, handler->engineBreakpoints