qmlengine.cpp 97.5 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 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
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 connect();
    void disconnect();

    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);
    void frame(int number = -1);
    void scope(int number = -1, int frameNumber = -1);
    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 version();
    void clearCache();

    void sendAndLogV8Request(const QJsonObject &request);

    QByteArray packMessage(const QByteArray &type, const QByteArray &message = QByteArray());
    QJsonObject initObject();

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

164 165 166 167 168
    void handleBacktrace(const QVariant &bodyVal, const QVariant &refsVal);
    void handleLookup(const QVariant &bodyVal, const QVariant &refsVal);
    void handleEvaluate(int sequence, bool success, const QVariant &bodyVal, const QVariant &refsVal);
    void handleFrame(const QVariant &bodyVal, const QVariant &refsVal);
    void handleScope(const QVariant &bodyVal, const QVariant &refsVal);
hjk's avatar
hjk committed
169 170 171 172
    StackFrame extractStackFrame(const QVariant &bodyVal, const QVariant &refsVal);

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

hjk's avatar
hjk committed
174 175 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
public:
    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;
210
};
211

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

hjk's avatar
hjk committed
218

219 220 221 222 223 224
///////////////////////////////////////////////////////////////////////
//
// QmlEngine
//
///////////////////////////////////////////////////////////////////////

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

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

hjk's avatar
hjk committed
234 235 236 237 238
    connect(stackHandler(), &StackHandler::stackChanged,
            this, &QmlEngine::updateCurrentContext);
    connect(stackHandler(), &StackHandler::currentIndexChanged,
            this, &QmlEngine::updateCurrentContext);
    connect(inspectorView(), SIGNAL(currentIndexChanged(QModelIndex)),
239
            SLOT(updateCurrentContext()));
hjk's avatar
hjk committed
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
    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);
257

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

hjk's avatar
hjk committed
264 265 266
    if (auto mmIface = ModelManagerInterface::instance()) {
        connect(mmIface, &ModelManagerInterface::documentUpdated,
                this, &QmlEngine::documentUpdated);
267
    }
268
    // we won't get any debug output
269
    if (startParameters.useTerminal) {
hjk's avatar
hjk committed
270 271 272
        d->noDebugOutputTimer.setInterval(0);
        d->retryOnConnectFail = true;
        d->automaticConnect = true;
273
    }
hjk's avatar
hjk committed
274 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

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

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

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

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

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

323
    notifyInferiorSetupOk();
324

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    infoBox->show();
}

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

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

    notifyEngineRunFailed();
}

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

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

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

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

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

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

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

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

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

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

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

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

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

573
        notifyEngineSetupOk();
574

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

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

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

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

hjk's avatar
hjk committed
607
void QmlEngine::shutdownInferior()
608
{
hjk's avatar
hjk committed
609 610
    // End session.
    d->disconnect();
611

612
    if (isSlaveEngine())
613 614
        resetLocation();
    stopApplicationLauncher();
615
    closeConnection();
616

hjk's avatar
hjk committed
617 618 619 620 621
    notifyInferiorShutdownOk();
}

void QmlEngine::shutdownEngine()
{
hjk's avatar
hjk committed
622
    clearExceptionSelection();
623

hjk's avatar
hjk committed
624 625 626
    if (auto consoleManager = ConsoleManagerInterface::instance())
        consoleManager->setScriptEvaluator(0);
    d->noDebugOutputTimer.stop();
627 628

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

631
    notifyEngineShutdownOk();
632 633
    if (!isSlaveEngine())
        showMessage(QString(), StatusBar);
634 635
}

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

645
        // We can't do this in the constructore because runControl() isn't yet defined
hjk's avatar
hjk committed
646 647
        connect(&d->applicationLauncher, &ApplicationLauncher::bringToForegroundRequested,
                runControl(), &RunControl::bringApplicationToForeground,
648 649 650 651
                Qt::UniqueConnection);

        notifyEngineSetupOk();
    }
652 653
}

654 655
void QmlEngine::continueInferior()
{
hjk's avatar
hjk committed
656
    QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
hjk's avatar
hjk committed
657 658
    clearExceptionSelection();
    d->continueDebugging(Continue);
659
    resetLocation();
hjk's avatar
hjk committed
660 661
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
662 663 664 665
}

void QmlEngine::interruptInferior()
{
hjk's avatar
hjk committed
666 667
    showMessage(_(INTERRUPT), LogInput);
    d->sendMessage(d->packMessage(INTERRUPT));
668
    notifyInferiorStopOk();
669 670 671 672
}

void QmlEngine::executeStep()
{
hjk's avatar
hjk committed
673 674
    clearExceptionSelection();
    d->continueDebugging(StepIn);
hjk's avatar
hjk committed
675 676
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
677 678 679 680
}

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

void QmlEngine::executeStepOut()
{
hjk's avatar
hjk committed
689 690
    clearExceptionSelection();
    d->continueDebugging(StepOut);
hjk's avatar
hjk committed
691 692
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
693 694 695 696
}

void QmlEngine::executeNext()
{
hjk's avatar
hjk committed
697 698
    clearExceptionSelection();
    d->continueDebugging(Next);
hjk's avatar
hjk committed
699 700
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
701 702 703 704
}

void QmlEngine::executeNextI()
{
705
    executeNext();
706 707
}

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

724 725
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
726 727 728 729 730 731 732 733
}

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

734
void QmlEngine::executeJumpToLine(const ContextData &data)
735
{
736
    Q_UNUSED(data)
737 738 739 740 741
    XSDEBUG("FIXME:  QmlEngine::executeJumpToLine()");
}

void QmlEngine::activateFrame(int index)
{
742 743 744
    if (state() != InferiorStopOk && state() != InferiorUnrunnable)
        return;

hjk's avatar
hjk committed
745 746 747 748
    if (index != stackHandler()->currentIndex())
        d->frame(d->stackIndexLookup.value(index));

    stackHandler()->setCurrentIndex(index);
749
    gotoLocation(stackHandler()->frames().value(index));
750 751
}

hjk's avatar
hjk committed
752
void QmlEngine::selectThread(ThreadId threadId)
753
{
hjk's avatar
hjk committed
754
    Q_UNUSED(threadId)
755 756
}

757
void QmlEngine::insertBreakpoint(Breakpoint bp)
758
{
759 760 761
    BreakpointState state = bp.state();
    QTC_ASSERT(state == BreakpointInsertRequested, qDebug() << bp << this << state);
    bp.notifyBreakpointInsertProceeding();
762

763
    const BreakpointParameters &params = bp.parameters();
764 765 766 767 768 769
    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
770
            d->pendingBreakpoints.insertMulti(params.fileName, bp);
771 772 773 774 775 776
            return;
        }
        if (!valid)
            return;
    }

hjk's avatar
hjk committed
777 778 779 780 781 782 783 784 785 786 787 788
    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();
789
    }
hjk's avatar
hjk committed
790 791

    d->breakpointsSync.insert(d->sequence, bp.id());
792 793
}

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

809 810 811
    BreakpointState state = bp.state();
    QTC_ASSERT(state == BreakpointRemoveRequested, qDebug() << bp << this << state);
    bp.notifyBreakpointRemoveProceeding();
812

hjk's avatar
hjk committed
813 814 815 816 817 818 819 820 821
    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);
822

823 824
    if (bp.state() == BreakpointRemoveProceeding)
        bp.notifyBreakpointRemoveOk();
825 826
}

827
void QmlEngine::changeBreakpoint(Breakpoint bp)
828
{
829 830 831
    BreakpointState state = bp.state();
    QTC_ASSERT(state == BreakpointChangeRequested, qDebug() << bp << this << state);
    bp.notifyBreakpointChangeProceeding();
832

hjk's avatar
hjk committed
833 834 835 836 837 838 839 840 841 842 843
    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);
844
    } else {
hjk's avatar
hjk committed
845 846 847 848 849 850
        //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);
851 852
    }

853 854
    if (bp.state() == BreakpointChangeProceeding)
        bp.notifyBreakpointChangeOk();
855 856
}

857 858
void QmlEngine::attemptBreakpointSynchronization()
{
859 860 861 862 863
    if (!stateAcceptsBreakpointChanges()) {
        showMessage(_("BREAKPOINT SYNCHRONIZATION NOT POSSIBLE IN CURRENT STATE"));
        return;
    }

hjk's avatar
hjk committed
864
    BreakHandler *handler = breakHandler();
865

866
    DebuggerEngine *bpOwner = isSlaveEngine() ? masterEngine() : this;
867
    foreach (Breakpoint bp, handler->unclaimedBreakpoints()) {
868
        // Take ownership of the breakpoint. Requests insertion.
869 870
        if (acceptsBreakpoint(bp))
            bp.setEngine(bpOwner);
871 872
    }

873 874
    foreach (Breakpoint bp, handler->engineBreakpoints(bpOwner)) {
        switch (bp.state()) {
875 876 877 878 879
        case BreakpointNew:
            // Should not happen once claimed.
            QTC_CHECK(false);
            continue;
        case BreakpointInsertRequested:
880
            insertBreakpoint(bp);
881 882
            continue;
        case BreakpointChangeRequested:
883
            changeBreakpoint(bp);
884 885
            continue;
        case BreakpointRemoveRequested: