qmlengine.cpp 94.3 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 34

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

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

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

#include <projectexplorer/applicationlauncher.h>
57

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

62 63
#include <texteditor/textdocument.h>
#include <texteditor/texteditor.h>
hjk's avatar
hjk committed
64 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

hjk's avatar
hjk committed
86 87 88
using namespace Core;
using namespace ProjectExplorer;
using namespace QmlDebug;
89
using namespace QmlJS;
hjk's avatar
hjk committed
90
using namespace TextEditor;
hjk's avatar
hjk committed
91

92 93 94
namespace Debugger {
namespace Internal {

hjk's avatar
hjk committed
95
enum Exceptions
96
{
hjk's avatar
hjk committed
97 98 99 100
    NoExceptions,
    UncaughtExceptions,
    AllExceptions
};
101

hjk's avatar
hjk committed
102
enum StepAction
103
{
hjk's avatar
hjk committed
104 105 106 107 108
    Continue,
    StepIn,
    StepOut,
    Next
};
109

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

hjk's avatar
hjk committed
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
class QmlEnginePrivate : QmlDebugClient
{
public:
    QmlEnginePrivate(QmlEngine *engine_, QmlDebugConnection *connection_)
        : QmlDebugClient(QLatin1String("V8Debugger"), connection_),
          engine(engine_),
          inspectorAdapter(engine, connection_),
          connection(connection_)
    {}

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

    void continueDebugging(StepAction stepAction);

    void evaluate(const QString expr, bool global = false, bool disableBreak = false,
                  int frame = -1, bool addContext = false);
    void lookup(const QList<int> handles, bool includeSource = false);
    void backtrace(int fromFrame = -1, int toFrame = -1, bool bottom = false);
139 140
    void frame(int number);
    void scope(int number, int frameNumber = -1);
hjk's avatar
hjk committed
141 142 143 144 145 146 147 148 149 150 151 152 153 154
    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 clearCache();

    void expandObject(const QByteArray &iname, quint64 objectId);
    void flushSendBuffer();

155 156 157 158 159 160
    void handleBacktrace(const QVariant &bodyVal);
    void handleLookup(const QVariant &bodyVal);
    void handleEvaluate(int sequence, bool success, const QVariant &bodyVal);
    void handleFrame(const QVariant &bodyVal);
    void handleScope(const QVariant &bodyVal);
    StackFrame extractStackFrame(const QVariant &bodyVal);
hjk's avatar
hjk committed
161 162 163

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

165
    void runCommand(const DebuggerCommand &command);
166
    void runDirectCommand(const QByteArray &type, const QByteArray &msg = QByteArray());
167

168 169 170 171 172 173
    void clearRefs() { refVals.clear(); }
    void memorizeRefs(const QVariant &refs);
    QmlV8ObjectData extractData(const QVariant &data) const;
    void insertSubItems(WatchItem *parent, const QVariantList &properties);
    ConsoleItem *constructLogItemTree(ConsoleItem *parent, const QmlV8ObjectData &objectData);

hjk's avatar
hjk committed
174
public:
175
    QHash<int, QmlV8ObjectData> refVals; // The mapping of target object handles to retrieved values.
hjk's avatar
hjk committed
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
    int sequence = -1;
    QmlEngine *engine;
    QHash<BreakpointModelId, int> breakpoints;
    QHash<int, BreakpointModelId> breakpointsSync;
    QList<int> breakpointsTemp;

    QHash<int, QString> evaluatingExpression;
    QHash<int, QByteArray> localsAndWatchers;
    QList<int> updateLocalsAndWatchers;
    QList<int> debuggerCommands;

    //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;
    QmlInspectorAdapter inspectorAdapter;
    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;
211
};
212

hjk's avatar
hjk committed
213
static void updateDocument(IDocument *document, const QTextDocument *textDocument)
214
{
hjk's avatar
hjk committed
215 216
    if (auto baseTextDocument = qobject_cast<TextDocument *>(document))
        baseTextDocument->document()->setPlainText(textDocument->toPlainText());
217 218
}

hjk's avatar
hjk committed
219

220 221 222 223 224 225
///////////////////////////////////////////////////////////////////////
//
// QmlEngine
//
///////////////////////////////////////////////////////////////////////

226
QmlEngine::QmlEngine(const DebuggerRunParameters &startParameters, DebuggerEngine *masterEngine)
hjk's avatar
hjk committed
227 228
  : DebuggerEngine(startParameters),
    d(new QmlEnginePrivate(this, new QmlDebugConnection(this)))
229
{
Friedemann Kleint's avatar
Friedemann Kleint committed
230
    setObjectName(QLatin1String("QmlEngine"));
231

Aurindam Jana's avatar
Aurindam Jana committed
232 233 234
    if (masterEngine)
        setMasterEngine(masterEngine);

hjk's avatar
hjk committed
235 236 237 238 239
    connect(stackHandler(), &StackHandler::stackChanged,
            this, &QmlEngine::updateCurrentContext);
    connect(stackHandler(), &StackHandler::currentIndexChanged,
            this, &QmlEngine::updateCurrentContext);
    connect(inspectorView(), SIGNAL(currentIndexChanged(QModelIndex)),
240
            SLOT(updateCurrentContext()));
hjk's avatar
hjk committed
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
    connect(d->inspectorAdapter.agent(), &QmlInspectorAgent::expressionResult,
            this, &QmlEngine::expressionEvaluated);

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

Kai Koehne's avatar
Kai Koehne committed
259 260
    // 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
261 262 263
    d->noDebugOutputTimer.setSingleShot(true);
    d->noDebugOutputTimer.setInterval(8000);
    connect(&d->noDebugOutputTimer, SIGNAL(timeout()), this, SLOT(tryToConnect()));
264

hjk's avatar
hjk committed
265 266 267
    if (auto mmIface = ModelManagerInterface::instance()) {
        connect(mmIface, &ModelManagerInterface::documentUpdated,
                this, &QmlEngine::documentUpdated);
268
    }
269
    // we won't get any debug output
270
    if (startParameters.useTerminal) {
hjk's avatar
hjk committed
271 272 273
        d->noDebugOutputTimer.setInterval(0);
        d->retryOnConnectFail = true;
        d->automaticConnect = true;
274
    }
hjk's avatar
hjk committed
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302

    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);
303 304 305
}

QmlEngine::~QmlEngine()
hjk's avatar
hjk committed
306
{
hjk's avatar
hjk committed
307
    QSet<IDocument *> documentsToClose;
308

hjk's avatar
hjk committed
309 310 311
    QHash<QString, QWeakPointer<BaseTextEditor> >::iterator iter;
    for (iter = d->sourceEditors.begin(); iter != d->sourceEditors.end(); ++iter) {
        QWeakPointer<BaseTextEditor> textEditPtr = iter.value();
312
        if (textEditPtr)
313
            documentsToClose << textEditPtr.data()->document();
314
    }
hjk's avatar
hjk committed
315 316 317
    EditorManager::closeDocuments(documentsToClose.toList());

    delete d;
hjk's avatar
hjk committed
318
}
319

hjk's avatar
hjk committed
320
void QmlEngine::setupInferior()
321
{
hjk's avatar
hjk committed
322
    QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
Lasse Holmstedt's avatar
Lasse Holmstedt committed
323

324
    notifyInferiorSetupOk();
325

hjk's avatar
hjk committed
326
    if (d->automaticConnect)
327
        beginConnection();
hjk's avatar
hjk committed
328
}
hjk's avatar
hjk committed
329

con's avatar
con committed
330
void QmlEngine::appendMessage(const QString &msg, Utils::OutputFormat /* format */)
hjk's avatar
hjk committed
331
{
332
    showMessage(msg, AppOutput); // FIXME: Redirect to RunControl
hjk's avatar
hjk committed
333 334
}

Lasse Holmstedt's avatar
Lasse Holmstedt committed
335 336 337 338
void QmlEngine::connectionEstablished()
{
    attemptBreakpointSynchronization();

339
    if (!watchHandler()->watcherNames().isEmpty())
340
        synchronizeWatchers();
hjk's avatar
hjk committed
341 342
    connect(watchModel(), &QAbstractItemModel::layoutChanged,
            this, &QmlEngine::synchronizeWatchers);
Christiaan Janssen's avatar
Christiaan Janssen committed
343

344 345
    if (state() == EngineRunRequested)
        notifyEngineRunAndInferiorRunOk();
Lasse Holmstedt's avatar
Lasse Holmstedt committed
346
}
347

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

369
void QmlEngine::beginConnection(quint16 port)
370
{
hjk's avatar
hjk committed
371
    d->noDebugOutputTimer.stop();
372

hjk's avatar
hjk committed
373
    if (state() != EngineRunRequested && d->retryOnConnectFail)
374 375
        return;

376
    QTC_ASSERT(state() == EngineRunRequested, return);
377

378
    QString host =  runParameters().qmlServerAddress;
379 380 381 382
    // Use localhost as default
    if (host.isEmpty())
        host = QLatin1String("localhost");

383 384 385 386 387 388 389 390 391 392 393
    /*
     * 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).
     */
394 395
    if (runParameters().qmlServerPort > 0)
        port = runParameters().qmlServerPort;
396

hjk's avatar
hjk committed
397 398
    if (!d->connection || d->connection->isOpen())
        return;
Lasse Holmstedt's avatar
Lasse Holmstedt committed
399

hjk's avatar
hjk committed
400 401 402 403 404
    d->connection->connectToHost(host, port);

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

406
void QmlEngine::connectionStartupFailed()
Lasse Holmstedt's avatar
Lasse Holmstedt committed
407
{
hjk's avatar
hjk committed
408
    if (d->retryOnConnectFail) {
409 410
        // retry after 3 seconds ...
        QTimer::singleShot(3000, this, SLOT(beginConnection()));
411 412
        return;
    }
413

hjk's avatar
hjk committed
414
    QMessageBox *infoBox = new QMessageBox(ICore::mainWindow());
415 416
    infoBox->setIcon(QMessageBox::Critical);
    infoBox->setWindowTitle(tr("Qt Creator"));
417 418 419 420 421
    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);
422 423
    infoBox->setModal(true);

hjk's avatar
hjk committed
424 425
    connect(infoBox, &QDialog::finished,
            this, &QmlEngine::errorMessageBoxFinished);
426 427 428 429

    infoBox->show();
}

430 431
void QmlEngine::appStartupFailed(const QString &errorMessage)
{
432 433 434 435
    QString error = tr("Could not connect to the in-process QML debugger."
                       "\n%1").arg(errorMessage);

    if (isMasterEngine()) {
hjk's avatar
hjk committed
436
        QMessageBox *infoBox = new QMessageBox(ICore::mainWindow());
437 438 439 440 441
        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
442 443
        connect(infoBox, &QDialog::finished,
                this, &QmlEngine::errorMessageBoxFinished);
444 445 446 447
        infoBox->show();
    } else {
        showMessage(error, StatusBar);
    }
448 449 450 451

    notifyEngineRunFailed();
}

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

hjk's avatar
hjk committed
474
void QmlEngine::filterApplicationMessage(const QString &output, int /*channel*/) const
Lasse Holmstedt's avatar
Lasse Holmstedt committed
475
{
hjk's avatar
hjk committed
476
    d->outputParser.processOutput(output);
477 478 479 480
}

void QmlEngine::showMessage(const QString &msg, int channel, int timeout) const
{
481
    if (channel == AppOutput || channel == AppError)
hjk's avatar
hjk committed
482
        filterApplicationMessage(msg, channel);
483 484 485
    DebuggerEngine::showMessage(msg, channel, timeout);
}

486 487 488
void QmlEngine::gotoLocation(const Location &location)
{
    const QString fileName = location.fileName();
489
    if (QUrl(fileName).isLocalFile()) {
490
        // internal file from source files -> show generated .js
hjk's avatar
hjk committed
491
        QTC_ASSERT(d->sourceDocuments.contains(fileName), return);
492

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

514 515
void QmlEngine::closeConnection()
{
hjk's avatar
hjk committed
516 517 518 519 520 521 522 523 524
    disconnect(watchModel(), &QAbstractItemModel::layoutChanged,
               this, &QmlEngine::synchronizeWatchers);

    if (d->connectionTimer.isActive()) {
        d->connectionTimer.stop();
    } else {
        if (d->connection)
            d->connection->close();
    }
525 526
}

hjk's avatar
hjk committed
527 528 529
void QmlEngine::runEngine()
{
    QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());
Lasse Holmstedt's avatar
Lasse Holmstedt committed
530

531
    if (!isSlaveEngine()) {
532
        if (runParameters().startMode == AttachToRemoteServer)
hjk's avatar
hjk committed
533
            d->noDebugOutputTimer.start();
534
        else if (runParameters().startMode == AttachToRemoteProcess)
535 536
            beginConnection();
        else
537
            startApplicationLauncher();
538
    } else {
hjk's avatar
hjk committed
539
        d->noDebugOutputTimer.start();
540
    }
541 542 543 544
}

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

557 558
void QmlEngine::stopApplicationLauncher()
{
hjk's avatar
hjk committed
559 560 561 562
    if (d->applicationLauncher.isRunning()) {
        disconnect(&d->applicationLauncher, &ApplicationLauncher::processExited,
                   this, &QmlEngine::disconnected);
        d->applicationLauncher.stop();
563
    }
564 565
}

566
void QmlEngine::notifyEngineRemoteSetupFinished(const RemoteSetupResult &result)
567
{
568
    DebuggerEngine::notifyEngineRemoteSetupFinished(result);
569

570 571
    if (result.success) {
        if (result.qmlServerPort != InvalidPort)
572
            runParameters().qmlServerPort = result.qmlServerPort;
573

574
        notifyEngineSetupOk();
575

576 577 578
        // 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
579 580
        // In case we get an output the d->outputParser will start the connection.
        d->noDebugOutputTimer.setInterval(60000);
581 582 583
    }
    else {
        if (isMasterEngine())
hjk's avatar
hjk committed
584
            QMessageBox::critical(ICore::dialogParent(), tr("Failed to start application"),
585 586 587
                                  tr("Application startup failed: %1").arg(result.reason));
        notifyEngineSetupFailed();
    }
588 589
}

Aurindam Jana's avatar
Aurindam Jana committed
590 591 592 593 594
void QmlEngine::notifyEngineRemoteServerRunning(const QByteArray &serverChannel, int pid)
{
    bool ok = false;
    quint16 qmlPort = serverChannel.toUInt(&ok);
    if (ok)
595
        runParameters().qmlServerPort = qmlPort;
Aurindam Jana's avatar
Aurindam Jana committed
596
    else
Friedemann Kleint's avatar
Friedemann Kleint committed
597
        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
598 599 600 601 602

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

    // The remote setup can take a while especially with mixed debugging.
hjk's avatar
hjk committed
603 604 605
    // 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
606 607
}

hjk's avatar
hjk committed
608
void QmlEngine::shutdownInferior()
609
{
hjk's avatar
hjk committed
610
    // End session.
611 612 613 614 615
    //    { "seq"     : <number>,
    //      "type"    : "request",
    //      "command" : "disconnect",
    //    }
    d->runCommand(DISCONNECT);
616

617
    if (isSlaveEngine())
618 619
        resetLocation();
    stopApplicationLauncher();
620
    closeConnection();
621

hjk's avatar
hjk committed
622 623 624 625 626
    notifyInferiorShutdownOk();
}

void QmlEngine::shutdownEngine()
{
hjk's avatar
hjk committed
627
    clearExceptionSelection();
628

hjk's avatar
hjk committed
629 630 631
    if (auto consoleManager = ConsoleManagerInterface::instance())
        consoleManager->setScriptEvaluator(0);
    d->noDebugOutputTimer.stop();
632 633

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

636
    notifyEngineShutdownOk();
637 638
    if (!isSlaveEngine())
        showMessage(QString(), StatusBar);
639 640
}

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

650
        // We can't do this in the constructore because runControl() isn't yet defined
hjk's avatar
hjk committed
651 652
        connect(&d->applicationLauncher, &ApplicationLauncher::bringToForegroundRequested,
                runControl(), &RunControl::bringApplicationToForeground,
653 654 655 656
                Qt::UniqueConnection);

        notifyEngineSetupOk();
    }
657 658
}

659 660
void QmlEngine::continueInferior()
{
hjk's avatar
hjk committed
661
    QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
hjk's avatar
hjk committed
662 663
    clearExceptionSelection();
    d->continueDebugging(Continue);
664
    resetLocation();
hjk's avatar
hjk committed
665 666
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
667 668 669 670
}

void QmlEngine::interruptInferior()
{
hjk's avatar
hjk committed
671
    showMessage(_(INTERRUPT), LogInput);
672
    d->runDirectCommand(INTERRUPT);
673
    notifyInferiorStopOk();
674 675 676 677
}

void QmlEngine::executeStep()
{
hjk's avatar
hjk committed
678 679
    clearExceptionSelection();
    d->continueDebugging(StepIn);
hjk's avatar
hjk committed
680 681
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
682 683 684 685
}

void QmlEngine::executeStepI()
{
hjk's avatar
hjk committed
686 687
    clearExceptionSelection();
    d->continueDebugging(StepIn);
hjk's avatar
hjk committed
688 689
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
690 691 692 693
}

void QmlEngine::executeStepOut()
{
hjk's avatar
hjk committed
694 695
    clearExceptionSelection();
    d->continueDebugging(StepOut);
hjk's avatar
hjk committed
696 697
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
698 699 700 701
}

void QmlEngine::executeNext()
{
hjk's avatar
hjk committed
702 703
    clearExceptionSelection();
    d->continueDebugging(Next);
hjk's avatar
hjk committed
704 705
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
706 707 708 709
}

void QmlEngine::executeNextI()
{
710
    executeNext();
711 712
}

713
void QmlEngine::executeRunToLine(const ContextData &data)
714
{
715
    QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
Jarek Kobus's avatar
Jarek Kobus committed
716
    showStatusMessage(tr("Run to line %1 (%2) requested...").arg(data.lineNumber).arg(data.fileName), 5000);
717
    resetLocation();
718 719 720 721 722 723
    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
724 725 726 727 728
    d->setBreakpoint(QString(_(SCRIPTREGEXP)), modifiedData.fileName,
                     true, modifiedData.lineNumber);
    clearExceptionSelection();
    d->continueDebugging(Continue);

729 730
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
731 732 733 734 735 736 737 738
}

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

739
void QmlEngine::executeJumpToLine(const ContextData &data)
740
{
741
    Q_UNUSED(data)
742 743 744 745 746
    XSDEBUG("FIXME:  QmlEngine::executeJumpToLine()");
}

void QmlEngine::activateFrame(int index)
{
747 748 749
    if (state() != InferiorStopOk && state() != InferiorUnrunnable)
        return;

hjk's avatar
hjk committed
750 751 752 753
    if (index != stackHandler()->currentIndex())
        d->frame(d->stackIndexLookup.value(index));

    stackHandler()->setCurrentIndex(index);
754
    gotoLocation(stackHandler()->frames().value(index));
755 756
}

hjk's avatar
hjk committed
757
void QmlEngine::selectThread(ThreadId threadId)
758
{
hjk's avatar
hjk committed
759
    Q_UNUSED(threadId)
760 761
}

762
void QmlEngine::insertBreakpoint(Breakpoint bp)
763
{
764 765 766
    BreakpointState state = bp.state();
    QTC_ASSERT(state == BreakpointInsertRequested, qDebug() << bp << this << state);
    bp.notifyBreakpointInsertProceeding();
767

768
    const BreakpointParameters &params = bp.parameters();
769 770 771 772 773 774
    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
775
            d->pendingBreakpoints.insertMulti(params.fileName, bp);
776 777 778 779 780 781
            return;
        }
        if (!valid)
            return;
    }

hjk's avatar
hjk committed
782 783 784 785 786 787 788 789 790 791 792 793
    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();
794
    }
hjk's avatar
hjk committed
795 796

    d->breakpointsSync.insert(d->sequence, bp.id());
797 798
}

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

814 815 816
    BreakpointState state = bp.state();
    QTC_ASSERT(state == BreakpointRemoveRequested, qDebug() << bp << this << state);
    bp.notifyBreakpointRemoveProceeding();
817

hjk's avatar
hjk committed
818 819 820 821 822 823 824 825 826
    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);
827

828 829
    if (bp.state() == BreakpointRemoveProceeding)
        bp.notifyBreakpointRemoveOk();
830 831
}

832
void QmlEngine::changeBreakpoint(Breakpoint bp)
833
{
834 835 836
    BreakpointState state = bp.state();
    QTC_ASSERT(state == BreakpointChangeRequested, qDebug() << bp << this << state);
    bp.notifyBreakpointChangeProceeding();
837

hjk's avatar
hjk committed
838 839 840 841 842 843 844 845 846 847 848
    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);
849
    } else {
hjk's avatar
hjk committed
850 851 852 853 854 855
        //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);
856 857
    }

858 859
    if (bp.state() == BreakpointChangeProceeding)
        bp.notifyBreakpointChangeOk();
860 861
}

862 863
void QmlEngine::attemptBreakpointSynchronization()
{
864 865 866 867 868
    if (!stateAcceptsBreakpointChanges()) {
        showMessage(_("BREAKPOINT SYNCHRONIZATION NOT POSSIBLE IN CURRENT STATE"));
        return;
    }

hjk's avatar
hjk committed
869
    BreakHandler *handler = breakHandler();
870

871
    DebuggerEngine *bpOwner = isSlaveEngine() ? masterEngine() : this;
872
    foreach (Breakpoint bp, handler->unclaimedBreakpoints()) {
873
        // Take ownership of the breakpoint. Requests insertion.
874 875
        if (acceptsBreakpoint(bp))
            bp.setEngine(bpOwner);
Christiaan Janssen's avatar