qmlengine.cpp 44.8 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"
32
#include "baseqmldebuggerclient.h"
33
#include "qmlinspectoragent.h"
34

35 36 37 38
#include <debugger/debuggeractions.h>
#include <debugger/debuggercore.h>
#include <debugger/debuggerinternalconstants.h>
#include <debugger/debuggermainwindow.h>
39 40
#include <debugger/debuggerruncontrol.h>
#include <debugger/debuggerstartparameters.h>
41 42 43
#include <debugger/debuggerstringutils.h>
#include <debugger/debuggertooltipmanager.h>
#include <debugger/localsandexpressionswindow.h>
Christian Kandeler's avatar
Christian Kandeler committed
44
#include <debugger/threaddata.h>
45
#include <debugger/watchwindow.h>
46

47 48 49 50
#include <debugger/breakhandler.h>
#include <debugger/stackhandler.h>
#include <debugger/watchhandler.h>
#include <debugger/sourcefileshandler.h>
51

52
#include <qmljseditor/qmljseditorconstants.h>
53 54
#include <qmljs/parser/qmljsast_p.h>
#include <qmljs/qmljsmodelmanagerinterface.h>
55
#include <qmljs/consolemanagerinterface.h>
56

57 58
#include <utils/qtcassert.h>

59 60
#include <texteditor/textdocument.h>
#include <texteditor/texteditor.h>
61
#include <coreplugin/editormanager/editormanager.h>
62
#include <coreplugin/helpmanager.h>
63 64
#include <coreplugin/icore.h>

65 66
#include <QDebug>
#include <QDir>
67
#include <QDockWidget>
68 69
#include <QMessageBox>
#include <QPlainTextEdit>
70

71 72 73 74 75 76 77 78
#define DEBUG_QML 1
#if DEBUG_QML
#   define SDEBUG(s) qDebug() << s
#else
#   define SDEBUG(s)
#endif
# define XSDEBUG(s) qDebug() << s

79 80
using namespace QmlJS;
using namespace AST;
hjk's avatar
hjk committed
81

82 83 84
namespace Debugger {
namespace Internal {

85 86
static QTreeView *inspectorTreeView()
{
87
    return Internal::inspectorView();
88 89
}

Kai Koehne's avatar
Kai Koehne committed
90
class ASTWalker : public Visitor
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
{
public:
    void operator()(Node *ast, quint32 *l, quint32 *c)
    {
        done = false;
        line = l;
        column = c;
        Node::accept(ast, this);
    }

    bool preVisit(Node *ast)
    {
        return ast->lastSourceLocation().startLine >= *line && !done;
    }

    //Case 1: Breakpoint is between sourceStart(exclusive) and
    //        sourceEnd(inclusive) --> End tree walk.
    //Case 2: Breakpoint is on sourceStart --> Check for the start
    //        of the first executable code. Set the line number and
    //        column number. End tree walk.
    //Case 3: Breakpoint is on "unbreakable" code --> Find the next "breakable"
    //        code and check for Case 2. End tree walk.

    //Add more types when suitable.

    bool visit(UiScriptBinding *ast)
    {
Aurindam Jana's avatar
Aurindam Jana committed
118 119 120
        if (!ast->statement)
            return true;

121 122 123 124 125 126 127 128 129 130 131
        quint32 sourceStartLine = ast->firstSourceLocation().startLine;
        quint32 statementStartLine;
        quint32 statementColumn;

        if (ast->statement->kind == Node::Kind_ExpressionStatement) {
            statementStartLine = ast->statement->firstSourceLocation().
                    startLine;
            statementColumn = ast->statement->firstSourceLocation().startColumn;

        } else if (ast->statement->kind == Node::Kind_Block) {
            Block *block = static_cast<Block *>(ast->statement);
Aurindam Jana's avatar
Aurindam Jana committed
132 133
            if (!block || !block->statements)
                return true;
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 164 165 166 167 168 169 170 171 172 173 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 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
            statementStartLine = block->statements->firstSourceLocation().
                    startLine;
            statementColumn = block->statements->firstSourceLocation().
                    startColumn;

        } else {
            return true;
        }


        //Case 1
        //Check for possible relocation within the binding statement

        //Rewritten to (function <token>() { { }})
        //The offset 16 is position of inner lbrace without token length.
        const int offset = 16;

        //Case 2
        if (statementStartLine == *line) {
            if (sourceStartLine == *line)
                *column = offset + ast->qualifiedId->identifierToken.length;
            done = true;
        }

        //Case 3
        if (statementStartLine > *line) {
            *line = statementStartLine;
            if (sourceStartLine == *line)
                *column = offset + ast->qualifiedId->identifierToken.length;
            else
                *column = statementColumn;
            done = true;
        }
        return true;
    }

    bool visit(FunctionDeclaration *ast) {
        quint32 sourceStartLine = ast->firstSourceLocation().startLine;
        quint32 sourceStartColumn = ast->firstSourceLocation().startColumn;
        quint32 statementStartLine = ast->body->firstSourceLocation().startLine;
        quint32 statementColumn = ast->body->firstSourceLocation().startColumn;

        //Case 1
        //Check for possible relocation within the function declaration

        //Case 2
        if (statementStartLine == *line) {
            if (sourceStartLine == *line)
                *column = statementColumn - sourceStartColumn + 1;
            done = true;
        }

        //Case 3
        if (statementStartLine > *line) {
            *line = statementStartLine;
            if (sourceStartLine == *line)
                *column = statementColumn - sourceStartColumn + 1;
            else
                *column = statementColumn;
            done = true;
        }
        return true;
    }

    bool visit(EmptyStatement *ast)
    {
        *line = ast->lastSourceLocation().startLine + 1;
        return true;
    }

    bool visit(VariableStatement *ast) { test(ast); return true; }
    bool visit(VariableDeclarationList *ast) { test(ast); return true; }
    bool visit(VariableDeclaration *ast) { test(ast); return true; }
    bool visit(ExpressionStatement *ast) { test(ast); return true; }
    bool visit(IfStatement *ast) { test(ast); return true; }
    bool visit(DoWhileStatement *ast) { test(ast); return true; }
    bool visit(WhileStatement *ast) { test(ast); return true; }
    bool visit(ForStatement *ast) { test(ast); return true; }
    bool visit(LocalForStatement *ast) { test(ast); return true; }
    bool visit(ForEachStatement *ast) { test(ast); return true; }
    bool visit(LocalForEachStatement *ast) { test(ast); return true; }
    bool visit(ContinueStatement *ast) { test(ast); return true; }
    bool visit(BreakStatement *ast) { test(ast); return true; }
    bool visit(ReturnStatement *ast) { test(ast); return true; }
    bool visit(WithStatement *ast) { test(ast); return true; }
    bool visit(SwitchStatement *ast) { test(ast); return true; }
    bool visit(CaseBlock *ast) { test(ast); return true; }
    bool visit(CaseClauses *ast) { test(ast); return true; }
    bool visit(CaseClause *ast) { test(ast); return true; }
    bool visit(DefaultClause *ast) { test(ast); return true; }
    bool visit(LabelledStatement *ast) { test(ast); return true; }
    bool visit(ThrowStatement *ast) { test(ast); return true; }
    bool visit(TryStatement *ast) { test(ast); return true; }
    bool visit(Catch *ast) { test(ast); return true; }
    bool visit(Finally *ast) { test(ast); return true; }
    bool visit(FunctionExpression *ast) { test(ast); return true; }
    bool visit(DebuggerStatement *ast) { test(ast); return true; }

    void test(Node *ast)
    {
        quint32 statementStartLine = ast->firstSourceLocation().startLine;
        //Case 1/2
        if (statementStartLine <= *line &&
                *line <= ast->lastSourceLocation().startLine)
            done = true;

        //Case 3
        if (statementStartLine > *line) {
            *line = statementStartLine;
            *column = ast->firstSourceLocation().startColumn;
            done = true;
        }
    }

    bool done;
    quint32 *line;
    quint32 *column;
};
252

253
ConsoleManagerInterface *qmlConsoleManager()
254
{
255
    return ConsoleManagerInterface::instance();
256 257
}

258 259 260 261 262 263
///////////////////////////////////////////////////////////////////////
//
// QmlEngine
//
///////////////////////////////////////////////////////////////////////

Aurindam Jana's avatar
Aurindam Jana committed
264
QmlEngine::QmlEngine(const DebuggerStartParameters &startParameters, DebuggerEngine *masterEngine)
265
  : DebuggerEngine(startParameters)
Kai Koehne's avatar
Kai Koehne committed
266 267 268 269
  , m_adapter(this)
  , m_inspectorAdapter(&m_adapter, this)
  , m_retryOnConnectFail(false)
  , m_automaticConnect(false)
270
{
Friedemann Kleint's avatar
Friedemann Kleint committed
271
    setObjectName(QLatin1String("QmlEngine"));
272

Aurindam Jana's avatar
Aurindam Jana committed
273 274 275
    if (masterEngine)
        setMasterEngine(masterEngine);

276 277
    connect(&m_adapter, SIGNAL(connectionError(QDebugSupport::Error)),
        SLOT(connectionError(QDebugSupport::Error)));
Kai Koehne's avatar
Kai Koehne committed
278
    connect(&m_adapter, SIGNAL(serviceConnectionError(QString)),
279
        SLOT(serviceConnectionError(QString)));
Kai Koehne's avatar
Kai Koehne committed
280
    connect(&m_adapter, SIGNAL(connected()),
281
        SLOT(connectionEstablished()));
Kai Koehne's avatar
Kai Koehne committed
282
    connect(&m_adapter, SIGNAL(connectionStartupFailed()),
283 284
        SLOT(connectionStartupFailed()));

Aurindam Jana's avatar
Aurindam Jana committed
285
    connect(stackHandler(), SIGNAL(stackChanged()),
286
            SLOT(updateCurrentContext()));
Aurindam Jana's avatar
Aurindam Jana committed
287
    connect(stackHandler(), SIGNAL(currentIndexChanged()),
288
            SLOT(updateCurrentContext()));
289
    connect(inspectorTreeView(), SIGNAL(currentIndexChanged(QModelIndex)),
290
            SLOT(updateCurrentContext()));
Kai Koehne's avatar
Kai Koehne committed
291
    connect(m_inspectorAdapter.agent(), SIGNAL(
292 293
                expressionResult(quint32,QVariant)),
            SLOT(expressionEvaluated(quint32,QVariant)));
Kai Koehne's avatar
Kai Koehne committed
294
    connect(m_adapter.messageClient(),
295
            SIGNAL(message(QtMsgType,QString,
296
                           QmlDebug::QDebugContextInfo)),
297
            SLOT(appendDebugOutput(QtMsgType,QString,
298
                                   QmlDebug::QDebugContextInfo)));
299

300

Kai Koehne's avatar
Kai Koehne committed
301
    connect(&m_applicationLauncher,
Robert Loehning's avatar
Robert Loehning committed
302
        SIGNAL(processExited(int,QProcess::ExitStatus)),
303
        SLOT(disconnected()));
Kai Koehne's avatar
Kai Koehne committed
304
    connect(&m_applicationLauncher,
Robert Loehning's avatar
Robert Loehning committed
305 306
        SIGNAL(appendMessage(QString,Utils::OutputFormat)),
        SLOT(appendMessage(QString,Utils::OutputFormat)));
Kai Koehne's avatar
Kai Koehne committed
307
    connect(&m_applicationLauncher,
308
            SIGNAL(processStarted()),
Kai Koehne's avatar
Kai Koehne committed
309
            &m_noDebugOutputTimer,
310
            SLOT(start()));
311

Kai Koehne's avatar
Kai Koehne committed
312 313 314
    m_outputParser.setNoOutputText(ProjectExplorer::ApplicationLauncher
                                   ::msgWinCannotRetrieveDebuggingOutput());
    connect(&m_outputParser, SIGNAL(waitingForConnectionOnPort(quint16)),
315
            this, SLOT(beginConnection(quint16)));
Kai Koehne's avatar
Kai Koehne committed
316
    connect(&m_outputParser, SIGNAL(noOutputMessage()),
317
            this, SLOT(tryToConnect()));
Kai Koehne's avatar
Kai Koehne committed
318
    connect(&m_outputParser, SIGNAL(errorMessage(QString)),
319
            this, SLOT(appStartupFailed(QString)));
320

Kai Koehne's avatar
Kai Koehne committed
321 322 323 324 325
    // Only wait 8 seconds for the 'Waiting for connection' on application output,
    // then just try to connect (application output might be redirected / blocked)
    m_noDebugOutputTimer.setSingleShot(true);
    m_noDebugOutputTimer.setInterval(8000);
    connect(&m_noDebugOutputTimer, SIGNAL(timeout()), this, SLOT(tryToConnect()));
326

327 328 329 330 331
    ModelManagerInterface *mmIface = ModelManagerInterface::instance();
    if (mmIface) {
        connect(ModelManagerInterface::instance(), SIGNAL(documentUpdated(QmlJS::Document::Ptr)),
                this, SLOT(documentUpdated(QmlJS::Document::Ptr)));
    }
332
    // we won't get any debug output
333
    if (startParameters.useTerminal) {
Kai Koehne's avatar
Kai Koehne committed
334 335 336
        m_noDebugOutputTimer.setInterval(0);
        m_retryOnConnectFail = true;
        m_automaticConnect = true;
337
    }
338 339
    if (qmlConsoleManager())
        qmlConsoleManager()->setScriptEvaluator(this);
340 341 342
}

QmlEngine::~QmlEngine()
hjk's avatar
hjk committed
343
{
344
    QSet<Core::IDocument *> documentsToClose;
345

346
    QHash<QString, QWeakPointer<TextEditor::BaseTextEditor> >::iterator iter;
Kai Koehne's avatar
Kai Koehne committed
347
    for (iter = m_sourceEditors.begin(); iter != m_sourceEditors.end(); ++iter) {
348
        QWeakPointer<TextEditor::BaseTextEditor> textEditPtr = iter.value();
349
        if (textEditPtr)
350
            documentsToClose << textEditPtr.data()->document();
351
    }
352
    Core::EditorManager::closeDocuments(documentsToClose.toList());
hjk's avatar
hjk committed
353
}
354

hjk's avatar
hjk committed
355
void QmlEngine::setupInferior()
356
{
hjk's avatar
hjk committed
357
    QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
Lasse Holmstedt's avatar
Lasse Holmstedt committed
358

359
    notifyInferiorSetupOk();
360

Kai Koehne's avatar
Kai Koehne committed
361
    if (m_automaticConnect)
362
        beginConnection();
hjk's avatar
hjk committed
363
}
hjk's avatar
hjk committed
364

con's avatar
con committed
365
void QmlEngine::appendMessage(const QString &msg, Utils::OutputFormat /* format */)
hjk's avatar
hjk committed
366
{
367
    showMessage(msg, AppOutput); // FIXME: Redirect to RunControl
hjk's avatar
hjk committed
368 369
}

Lasse Holmstedt's avatar
Lasse Holmstedt committed
370 371 372 373
void QmlEngine::connectionEstablished()
{
    attemptBreakpointSynchronization();

374
    if (!watchHandler()->watcherNames().isEmpty())
375
        synchronizeWatchers();
hjk's avatar
hjk committed
376
    connect(watchModel(),SIGNAL(layoutChanged()),this,SLOT(synchronizeWatchers()));
Christiaan Janssen's avatar
Christiaan Janssen committed
377

378 379
    if (state() == EngineRunRequested)
        notifyEngineRunAndInferiorRunOk();
Lasse Holmstedt's avatar
Lasse Holmstedt committed
380
}
381

382 383
void QmlEngine::tryToConnect(quint16 port)
{
384
    showMessage(QLatin1String("QML Debugger: No application output received in time, trying to connect ..."), LogStatus);
Kai Koehne's avatar
Kai Koehne committed
385
    m_retryOnConnectFail = true;
386 387 388
    if (state() == EngineRunRequested) {
        if (isSlaveEngine()) {
            // Probably cpp is being debugged and hence we did not get the output yet.
389 390
            if (!masterEngine()->isDying()) {
                m_noDebugOutputTimer.setInterval(4000);
391
                m_noDebugOutputTimer.start();
392
            }
393 394 395 396 397 398
            else
                appStartupFailed(tr("No application output received in time"));
        } else {
            beginConnection(port);
        }
    } else {
Kai Koehne's avatar
Kai Koehne committed
399
        m_automaticConnect = true;
400
    }
401 402
}

403
void QmlEngine::beginConnection(quint16 port)
404
{
Kai Koehne's avatar
Kai Koehne committed
405
    m_noDebugOutputTimer.stop();
406

Kai Koehne's avatar
Kai Koehne committed
407
    if (state() != EngineRunRequested && m_retryOnConnectFail)
408 409
        return;

410
    QTC_ASSERT(state() == EngineRunRequested, return);
411

412 413 414 415 416
    QString host =  startParameters().qmlServerAddress;
    // Use localhost as default
    if (host.isEmpty())
        host = QLatin1String("localhost");

417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
    /*
     * 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).
     */
    if (startParameters().qmlServerPort > 0)
        port = startParameters().qmlServerPort;

    m_adapter.beginConnectionTcp(host, port);
Lasse Holmstedt's avatar
Lasse Holmstedt committed
432 433
}

434

435
void QmlEngine::connectionStartupFailed()
Lasse Holmstedt's avatar
Lasse Holmstedt committed
436
{
Kai Koehne's avatar
Kai Koehne committed
437
    if (m_retryOnConnectFail) {
438 439
        // retry after 3 seconds ...
        QTimer::singleShot(3000, this, SLOT(beginConnection()));
440 441
        return;
    }
442

hjk's avatar
hjk committed
443
    QMessageBox *infoBox = new QMessageBox(Core::ICore::mainWindow());
444 445
    infoBox->setIcon(QMessageBox::Critical);
    infoBox->setWindowTitle(tr("Qt Creator"));
446 447 448 449 450
    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);
451 452 453
    infoBox->setModal(true);

    connect(infoBox, SIGNAL(finished(int)),
454
            this, SLOT(errorMessageBoxFinished(int)));
455 456 457 458

    infoBox->show();
}

459 460
void QmlEngine::appStartupFailed(const QString &errorMessage)
{
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
    QString error = tr("Could not connect to the in-process QML debugger."
                       "\n%1").arg(errorMessage);

    if (isMasterEngine()) {
        QMessageBox *infoBox = new QMessageBox(Core::ICore::mainWindow());
        infoBox->setIcon(QMessageBox::Critical);
        infoBox->setWindowTitle(tr("Qt Creator"));
        infoBox->setText(error);
        infoBox->setStandardButtons(QMessageBox::Ok | QMessageBox::Help);
        infoBox->setDefaultButton(QMessageBox::Ok);
        connect(infoBox, SIGNAL(finished(int)),
                this, SLOT(errorMessageBoxFinished(int)));
        infoBox->show();
    } else {
        showMessage(error, StatusBar);
    }
477 478 479 480

    notifyEngineRunFailed();
}

481
void QmlEngine::errorMessageBoxFinished(int result)
482 483
{
    switch (result) {
484
    case QMessageBox::Retry: {
485
        beginConnection();
486 487 488
        break;
    }
    case QMessageBox::Help: {
489
        Core::HelpManager::handleHelpRequest(QLatin1String("qthelp://org.qt-project.qtcreator/doc/creator-debugging-qml.html"));
490
        // fall through
491 492
    }
    default:
493 494 495
        if (state() == InferiorRunOk) {
            notifyInferiorSpontaneousStop();
            notifyInferiorIll();
496
        } else if (state() == EngineRunRequested) {
497
            notifyEngineRunFailed();
498
        }
Kai Koehne's avatar
Kai Koehne committed
499
        break;
500
    }
Lasse Holmstedt's avatar
Lasse Holmstedt committed
501 502
}

503
void QmlEngine::connectionError(QDebugSupport::Error error)
Lasse Holmstedt's avatar
Lasse Holmstedt committed
504
{
505
    if (error == QDebugSupport::RemoteClosedConnectionError)
506
        showMessage(tr("QML Debugger: Remote host closed connection."), StatusBar);
507

508 509 510 511
    if (!isSlaveEngine()) { // normal flow for slave engine when gdb exits
        notifyInferiorSpontaneousStop();
        notifyInferiorIll();
    }
Lasse Holmstedt's avatar
Lasse Holmstedt committed
512 513
}

514 515
void QmlEngine::serviceConnectionError(const QString &serviceName)
{
516
    showMessage(tr("QML Debugger: Could not connect to service \"%1\".")
517
        .arg(serviceName), StatusBar);
518 519
}

520 521
bool QmlEngine::canDisplayTooltip() const
{
522
    return false;
523 524
}

525
void QmlEngine::filterApplicationMessage(const QString &output, int /*channel*/)
526
{
Kai Koehne's avatar
Kai Koehne committed
527
    m_outputParser.processOutput(output);
528 529 530 531
}

void QmlEngine::showMessage(const QString &msg, int channel, int timeout) const
{
532
    if (channel == AppOutput || channel == AppError)
533 534 535 536
        const_cast<QmlEngine*>(this)->filterApplicationMessage(msg, channel);
    DebuggerEngine::showMessage(msg, channel, timeout);
}

537 538 539
void QmlEngine::gotoLocation(const Location &location)
{
    const QString fileName = location.fileName();
540
    if (QUrl(fileName).isLocalFile()) {
541
        // internal file from source files -> show generated .js
Kai Koehne's avatar
Kai Koehne committed
542
        QTC_ASSERT(m_sourceDocuments.contains(fileName), return);
543

Aurindam Jana's avatar
Aurindam Jana committed
544
        QString titlePattern = tr("JS Source for %1").arg(fileName);
545
        //Check if there are open documents with the same title
hjk's avatar
hjk committed
546
        foreach (Core::IDocument *document, Core::DocumentModel::openedDocuments()) {
547
            if (document->displayName() == titlePattern) {
548
                Core::EditorManager::activateEditorForDocument(document);
549
                return;
Aurindam Jana's avatar
Aurindam Jana committed
550 551
            }
        }
552 553 554 555 556 557 558 559 560
        Core::IEditor *editor = Core::EditorManager::openEditorWithContents(
                    QmlJSEditor::Constants::C_QMLJSEDITOR_ID, &titlePattern);
        if (editor) {
            editor->document()->setProperty(Constants::OPENED_BY_DEBUGGER, true);
            QPlainTextEdit *plainTextEdit =
                    qobject_cast<QPlainTextEdit *>(editor->widget());
            if (plainTextEdit)
                plainTextEdit->setReadOnly(true);
            updateDocument(editor->document(), m_sourceDocuments.value(fileName));
561
        }
562 563 564 565 566
    } else {
        DebuggerEngine::gotoLocation(location);
    }
}

567 568
void QmlEngine::closeConnection()
{
hjk's avatar
hjk committed
569
    disconnect(watchModel(),SIGNAL(layoutChanged()),this,SLOT(synchronizeWatchers()));
Kai Koehne's avatar
Kai Koehne committed
570
    m_adapter.closeConnection();
571 572
}

hjk's avatar
hjk committed
573 574 575
void QmlEngine::runEngine()
{
    QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());
Lasse Holmstedt's avatar
Lasse Holmstedt committed
576

577
    if (!isSlaveEngine()) {
578
        if (startParameters().startMode == AttachToRemoteServer)
579 580
            m_noDebugOutputTimer.start();
        else if (startParameters().startMode == AttachToRemoteProcess)
581 582
            beginConnection();
        else
583
            startApplicationLauncher();
584
    } else {
Kai Koehne's avatar
Kai Koehne committed
585
        m_noDebugOutputTimer.start();
586
    }
587 588 589 590
}

void QmlEngine::startApplicationLauncher()
{
Kai Koehne's avatar
Kai Koehne committed
591
    if (!m_applicationLauncher.isRunning()) {
592 593 594 595
        appendMessage(tr("Starting %1 %2").arg(
                          QDir::toNativeSeparators(startParameters().executable),
                          startParameters().processArgs)
                      + QLatin1Char('\n')
con's avatar
con committed
596
                     , Utils::NormalMessageFormat);
Kai Koehne's avatar
Kai Koehne committed
597
        m_applicationLauncher.start(ProjectExplorer::ApplicationLauncher::Gui,
598 599 600
                                    startParameters().executable,
                                    startParameters().processArgs);
    }
601
}
Lasse Holmstedt's avatar
Lasse Holmstedt committed
602

603 604
void QmlEngine::stopApplicationLauncher()
{
Kai Koehne's avatar
Kai Koehne committed
605
    if (m_applicationLauncher.isRunning()) {
606
        disconnect(&m_applicationLauncher, SIGNAL(processExited(int,QProcess::ExitStatus)),
Kai Koehne's avatar
Kai Koehne committed
607 608
                   this, SLOT(disconnected()));
        m_applicationLauncher.stop();
609
    }
610 611
}

612
void QmlEngine::notifyEngineRemoteSetupFinished(const RemoteSetupResult &result)
613
{
614
    DebuggerEngine::notifyEngineRemoteSetupFinished(result);
615

616 617 618
    if (result.success) {
        if (result.qmlServerPort != InvalidPort)
            startParameters().qmlServerPort = result.qmlServerPort;
619

620
        notifyEngineSetupOk();
621

622 623 624 625 626 627 628 629 630 631 632 633
        // The remote setup can take while especialy with mixed debugging.
        // Just waiting for 8 seconds is not enough. Increase the timeout
        // to 60 s
        // In case we get an output the m_outputParser will start the connection.
        m_noDebugOutputTimer.setInterval(60000);
    }
    else {
        if (isMasterEngine())
            QMessageBox::critical(Core::ICore::dialogParent(), tr("Failed to start application"),
                                  tr("Application startup failed: %1").arg(result.reason));
        notifyEngineSetupFailed();
    }
634 635
}

Aurindam Jana's avatar
Aurindam Jana committed
636 637 638 639 640 641 642
void QmlEngine::notifyEngineRemoteServerRunning(const QByteArray &serverChannel, int pid)
{
    bool ok = false;
    quint16 qmlPort = serverChannel.toUInt(&ok);
    if (ok)
        startParameters().qmlServerPort = qmlPort;
    else
Friedemann Kleint's avatar
Friedemann Kleint committed
643
        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
644 645 646 647 648 649 650 651 652 653 654

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

    // The remote setup can take a while especially with mixed debugging.
    // Just waiting for 8 seconds is not enough. Increase the timeout
    // to 60 s
    // In case we get an output the m_outputParser will start the connection.
    m_noDebugOutputTimer.setInterval(60000);
}

hjk's avatar
hjk committed
655
void QmlEngine::shutdownInferior()
656
{
Kai Koehne's avatar
Kai Koehne committed
657 658
    if (m_adapter.activeDebuggerClient())
        m_adapter.activeDebuggerClient()->endSession();
659

660
    if (isSlaveEngine())
661 662
        resetLocation();
    stopApplicationLauncher();
663
    closeConnection();
664

hjk's avatar
hjk committed
665 666 667 668 669
    notifyInferiorShutdownOk();
}

void QmlEngine::shutdownEngine()
{
670 671 672
    if (m_adapter.activeDebuggerClient())
        m_adapter.activeDebuggerClient()->resetSession();

673 674
    if (qmlConsoleManager())
        qmlConsoleManager()->setScriptEvaluator(0);
675 676 677
    m_noDebugOutputTimer.stop();

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

680
    notifyEngineShutdownOk();
681 682
    if (!isSlaveEngine())
        showMessage(QString(), StatusBar);
683 684
}

hjk's avatar
hjk committed
685
void QmlEngine::setupEngine()
686
{
687
    if (startParameters().remoteSetupNeeded) {
688
        // we need to get the port first
689
        notifyEngineRequestRemoteSetup();
690
    } else {
Kai Koehne's avatar
Kai Koehne committed
691 692
        m_applicationLauncher.setEnvironment(startParameters().environment);
        m_applicationLauncher.setWorkingDirectory(startParameters().workingDirectory);
Lasse Holmstedt's avatar
Lasse Holmstedt committed
693

694
        // We can't do this in the constructore because runControl() isn't yet defined
Kai Koehne's avatar
Kai Koehne committed
695
        connect(&m_applicationLauncher, SIGNAL(bringToForegroundRequested(qint64)),
696 697 698 699 700
                runControl(), SLOT(bringApplicationToForeground(qint64)),
                Qt::UniqueConnection);

        notifyEngineSetupOk();
    }
701 702
}

703 704
void QmlEngine::continueInferior()
{
hjk's avatar
hjk committed
705
    QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
706
    if (m_adapter.activeDebuggerClient())
Kai Koehne's avatar
Kai Koehne committed
707
        m_adapter.activeDebuggerClient()->continueInferior();
708
    resetLocation();
hjk's avatar
hjk committed
709 710
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
711 712 713 714
}

void QmlEngine::interruptInferior()
{
715
    if (m_adapter.activeDebuggerClient())
Kai Koehne's avatar
Kai Koehne committed
716
        m_adapter.activeDebuggerClient()->interruptInferior();
717
    notifyInferiorStopOk();
718 719 720 721
}

void QmlEngine::executeStep()
{
722
    if (m_adapter.activeDebuggerClient())
Kai Koehne's avatar
Kai Koehne committed
723
        m_adapter.activeDebuggerClient()->executeStep();
hjk's avatar
hjk committed
724 725
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
726 727 728 729
}

void QmlEngine::executeStepI()
{
730
    if (m_adapter.activeDebuggerClient())
Kai Koehne's avatar
Kai Koehne committed
731
        m_adapter.activeDebuggerClient()->executeStepI();
hjk's avatar
hjk committed
732 733
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
734 735 736 737
}

void QmlEngine::executeStepOut()
{
738
    if (m_adapter.activeDebuggerClient())
Kai Koehne's avatar
Kai Koehne committed
739
        m_adapter.activeDebuggerClient()->executeStepOut();
hjk's avatar
hjk committed
740 741
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
742 743 744 745
}

void QmlEngine::executeNext()
{
746
    if (m_adapter.activeDebuggerClient())
Kai Koehne's avatar
Kai Koehne committed
747
        m_adapter.activeDebuggerClient()->executeNext();
hjk's avatar
hjk committed
748 749
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
750 751 752 753
}

void QmlEngine::executeNextI()
{
754
    executeNext();
755 756
}

757
void QmlEngine::executeRunToLine(const ContextData &data)
758
{
759
    QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
Jarek Kobus's avatar
Jarek Kobus committed
760
    showStatusMessage(tr("Run to line %1 (%2) requested...").arg(data.lineNumber).arg(data.fileName), 5000);
761
    resetLocation();
762 763 764 765 766 767
    ContextData modifiedData = data;
    quint32 line = data.lineNumber;
    quint32 column;
    bool valid;
    if (adjustBreakpointLineAndColumn(data.fileName, &line, &column, &valid))
        modifiedData.lineNumber = line;
Kai Koehne's avatar
Kai Koehne committed
768 769
    if (m_adapter.activeDebuggerClient())
        m_adapter.activeDebuggerClient()->executeRunToLine(modifiedData);
770 771
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
772 773 774 775 776 777 778 779
}

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

780
void QmlEngine::executeJumpToLine(const ContextData &data)
781
{
782
    Q_UNUSED(data)
783 784 785 786 787
    XSDEBUG("FIXME:  QmlEngine::executeJumpToLine()");
}

void QmlEngine::activateFrame(int index)
{
788 789 790
    if (state() != InferiorStopOk && state() != InferiorUnrunnable)
        return;

791
    if (m_adapter.activeDebuggerClient())
Kai Koehne's avatar
Kai Koehne committed
792
        m_adapter.activeDebuggerClient()->activateFrame(index);
793
    gotoLocation(stackHandler()->frames().value(index));
794 795
}

hjk's avatar
hjk committed
796
void QmlEngine::selectThread(ThreadId threadId)
797
{
hjk's avatar
hjk committed
798
    Q_UNUSED(threadId)
799 800
}

801
void QmlEngine::insertBreakpoint(Breakpoint bp)
802
{
803 804 805
    BreakpointState state = bp.state();
    QTC_ASSERT(state == BreakpointInsertRequested, qDebug() << bp << this << state);
    bp.notifyBreakpointInsertProceeding();
806

807
    const BreakpointParameters &params = bp.parameters();
808 809 810 811 812 813
    quint32 line = params.lineNumber;
    quint32 column = 0;
    if (params.type == BreakpointByFileAndLine) {
        bool valid = false;
        if (!adjustBreakpointLineAndColumn(params.fileName, &line, &column,
                                           &valid)) {
814
            pendingBreakpoints.insertMulti(params.fileName, bp);
815 816 817 818 819 820
            return;
        }
        if (!valid)
            return;
    }

Kai Koehne's avatar
Kai Koehne committed
821
    if (m_adapter.activeDebuggerClient()) {
822
        m_adapter.activeDebuggerClient()->insertBreakpoint(bp, line, column);
823
    } else {
Kai Koehne's avatar
Kai Koehne committed
824
        foreach (BaseQmlDebuggerClient *client, m_adapter.debuggerClients()) {
825
            client->insertBreakpoint(bp, line, column);
826 827 828 829
        }
    }
}

830
void QmlEngine::removeBreakpoint(Breakpoint bp)
831
{
832
    const BreakpointParameters &params = bp.parameters();
833
    if (params.type == BreakpointByFileAndLine &&
Kai Koehne's avatar
Kai Koehne committed
834
            pendingBreakpoints.contains(params.fileName)) {
835 836 837 838
        auto it = pendingBreakpoints.find(params.fileName);
        while (it != pendingBreakpoints.end() && it.key() == params.fileName) {
            if (it.value() == bp.id()) {
                pendingBreakpoints.erase(it);
839 840
                return;
            }
841
            ++it;
842 843 844
        }
    }

845 846 847
    BreakpointState state = bp.state();
    QTC_ASSERT(state == BreakpointRemoveRequested, qDebug() << bp << this << state);
    bp.notifyBreakpointRemoveProceeding();
848

Kai Koehne's avatar
Kai Koehne committed
849
    if (m_adapter.activeDebuggerClient()) {
850
        m_adapter.activeDebuggerClient()->removeBreakpoint(bp);
851
    } else {
Kai Koehne's avatar
Kai Koehne committed
852
        foreach (BaseQmlDebuggerClient *client, m_adapter.debuggerClients()) {
853
            client->removeBreakpoint(bp);
854 855 856
        }
    }

857 858
    if (bp.state() == BreakpointRemoveProceeding)
        bp.notifyBreakpointRemoveOk();
859 860
}

861
void QmlEngine::changeBreakpoint(Breakpoint bp)
862
{
863 864 865
    BreakpointState state = bp.state();
    QTC_ASSERT(state == BreakpointChangeRequested, qDebug() << bp << this << state);
    bp.notifyBreakpointChangeProceeding();
866

Kai Koehne's avatar
Kai Koehne committed
867
    if (m_adapter.activeDebuggerClient()) {
868
        m_adapter.activeDebuggerClient()->changeBreakpoint(bp);
869
    } else {
Kai Koehne's avatar