qmlengine.cpp 45.1 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
2
**
3
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
7
**
hjk's avatar
hjk committed
8 9 10 11 12 13 14
** 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
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
15 16
**
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17 18 19 20 21 22 23 24 25
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
con's avatar
con committed
26 27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
29 30

#include "qmlengine.h"
31
#include "baseqmldebuggerclient.h"
32
#include "qmlinspectoragent.h"
33

Friedemann Kleint's avatar
Friedemann Kleint committed
34
#include "debuggerstartparameters.h"
35
#include "debuggeractions.h"
hjk's avatar
hjk committed
36
#include "debuggercore.h"
37
#include "debuggerinternalconstants.h"
38
#include "debuggermainwindow.h"
hjk's avatar
hjk committed
39
#include "debuggerrunner.h"
40
#include "debuggerstringutils.h"
41
#include "debuggertooltipmanager.h"
42 43
#include "localsandexpressionswindow.h"
#include "watchwindow.h"
44

45 46 47
#include "breakhandler.h"
#include "stackhandler.h"
#include "watchhandler.h"
48 49
#include "sourcefileshandler.h"
#include <qmljseditor/qmljseditorconstants.h>
50 51
#include <qmljs/parser/qmljsast_p.h>
#include <qmljs/qmljsmodelmanagerinterface.h>
52
#include <qmljs/consolemanagerinterface.h>
53

54 55
#include <utils/qtcassert.h>

56
#include <texteditor/itexteditor.h>
57
#include <coreplugin/editormanager/editormanager.h>
58
#include <coreplugin/helpmanager.h>
59 60
#include <coreplugin/icore.h>

61 62
#include <QDebug>
#include <QDir>
63

64 65
#include <QMessageBox>
#include <QPlainTextEdit>
66

67 68
#include <QDockWidget>

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

77 78
using namespace QmlJS;
using namespace AST;
hjk's avatar
hjk committed
79

80 81 82
namespace Debugger {
namespace Internal {

Kai Koehne's avatar
Kai Koehne committed
83
class ASTWalker : public Visitor
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
{
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
111 112 113
        if (!ast->statement)
            return true;

114 115 116 117 118 119 120 121 122 123 124
        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
125 126
            if (!block || !block->statements)
                return true;
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 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
            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;
};
245

246 247 248 249 250
QmlJS::ConsoleManagerInterface *qmlConsoleManager()
{
    return QmlJS::ConsoleManagerInterface::instance();
}

251 252 253 254 255 256
///////////////////////////////////////////////////////////////////////
//
// QmlEngine
//
///////////////////////////////////////////////////////////////////////

Aurindam Jana's avatar
Aurindam Jana committed
257
QmlEngine::QmlEngine(const DebuggerStartParameters &startParameters, DebuggerEngine *masterEngine)
258
  : DebuggerEngine(startParameters)
Kai Koehne's avatar
Kai Koehne committed
259 260 261 262
  , m_adapter(this)
  , m_inspectorAdapter(&m_adapter, this)
  , m_retryOnConnectFail(false)
  , m_automaticConnect(false)
263
{
Friedemann Kleint's avatar
Friedemann Kleint committed
264
    setObjectName(QLatin1String("QmlEngine"));
265

Aurindam Jana's avatar
Aurindam Jana committed
266 267 268
    if (masterEngine)
        setMasterEngine(masterEngine);

Kai Koehne's avatar
Kai Koehne committed
269
    connect(&m_adapter, SIGNAL(connectionError(QAbstractSocket::SocketError)),
270
        SLOT(connectionError(QAbstractSocket::SocketError)));
Kai Koehne's avatar
Kai Koehne committed
271
    connect(&m_adapter, SIGNAL(serviceConnectionError(QString)),
272
        SLOT(serviceConnectionError(QString)));
Kai Koehne's avatar
Kai Koehne committed
273
    connect(&m_adapter, SIGNAL(connected()),
274
        SLOT(connectionEstablished()));
Kai Koehne's avatar
Kai Koehne committed
275
    connect(&m_adapter, SIGNAL(connectionStartupFailed()),
276 277
        SLOT(connectionStartupFailed()));

Aurindam Jana's avatar
Aurindam Jana committed
278
    connect(stackHandler(), SIGNAL(stackChanged()),
279
            SLOT(updateCurrentContext()));
Aurindam Jana's avatar
Aurindam Jana committed
280
    connect(stackHandler(), SIGNAL(currentIndexChanged()),
281
            SLOT(updateCurrentContext()));
282
    connect(inspectorTreeView(), SIGNAL(currentIndexChanged(QModelIndex)),
283
            SLOT(updateCurrentContext()));
Kai Koehne's avatar
Kai Koehne committed
284
    connect(m_inspectorAdapter.agent(), SIGNAL(
285 286
                expressionResult(quint32,QVariant)),
            SLOT(expressionEvaluated(quint32,QVariant)));
Kai Koehne's avatar
Kai Koehne committed
287
    connect(m_adapter.messageClient(),
288
            SIGNAL(message(QtMsgType,QString,
289
                           QmlDebug::QDebugContextInfo)),
290
            SLOT(appendDebugOutput(QtMsgType,QString,
291
                                   QmlDebug::QDebugContextInfo)));
292

293

Kai Koehne's avatar
Kai Koehne committed
294
    connect(&m_applicationLauncher,
295 296
        SIGNAL(processExited(int)),
        SLOT(disconnected()));
Kai Koehne's avatar
Kai Koehne committed
297
    connect(&m_applicationLauncher,
Robert Loehning's avatar
Robert Loehning committed
298 299
        SIGNAL(appendMessage(QString,Utils::OutputFormat)),
        SLOT(appendMessage(QString,Utils::OutputFormat)));
Kai Koehne's avatar
Kai Koehne committed
300
    connect(&m_applicationLauncher,
301
            SIGNAL(processStarted()),
Kai Koehne's avatar
Kai Koehne committed
302
            &m_noDebugOutputTimer,
303
            SLOT(start()));
304

Kai Koehne's avatar
Kai Koehne committed
305 306 307
    m_outputParser.setNoOutputText(ProjectExplorer::ApplicationLauncher
                                   ::msgWinCannotRetrieveDebuggingOutput());
    connect(&m_outputParser, SIGNAL(waitingForConnectionOnPort(quint16)),
308
            this, SLOT(beginConnection(quint16)));
Kai Koehne's avatar
Kai Koehne committed
309
    connect(&m_outputParser, SIGNAL(noOutputMessage()),
310
            this, SLOT(tryToConnect()));
Kai Koehne's avatar
Kai Koehne committed
311
    connect(&m_outputParser, SIGNAL(errorMessage(QString)),
312
            this, SLOT(appStartupFailed(QString)));
313

Kai Koehne's avatar
Kai Koehne committed
314 315 316 317 318
    // 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()));
319

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

QmlEngine::~QmlEngine()
hjk's avatar
hjk committed
336
{
337 338 339
    QList<Core::IEditor *> editorsToClose;

    QHash<QString, QWeakPointer<TextEditor::ITextEditor> >::iterator iter;
Kai Koehne's avatar
Kai Koehne committed
340
    for (iter = m_sourceEditors.begin(); iter != m_sourceEditors.end(); ++iter) {
341 342 343 344 345
        QWeakPointer<TextEditor::ITextEditor> textEditPtr = iter.value();
        if (textEditPtr)
            editorsToClose << textEditPtr.data();
    }
    Core::EditorManager::instance()->closeEditors(editorsToClose);
hjk's avatar
hjk committed
346
}
347

Aurindam Jana's avatar
Aurindam Jana committed
348 349 350 351 352 353
void QmlEngine::notifyInferiorSetupOk()
{
    emit aboutToNotifyInferiorSetupOk();
    DebuggerEngine::notifyInferiorSetupOk();
}

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

358
    notifyInferiorSetupOk();
359

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

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

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

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

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

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

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

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

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

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

416 417 418 419
    if (port > 0) {
        QTC_ASSERT(startParameters().connParams.port == 0
                   || startParameters().connParams.port == port,
                   qWarning() << "Port " << port << "from application output does not match"
420
                   << startParameters().connParams.port << "from start parameters.");
421
        m_adapter.beginConnectionTcp(host, port);
422 423
        return;
    }
424
    // no port from application output, use the one from start parameters ...
425
    m_adapter.beginConnectionTcp(host, startParameters().qmlServerPort);
Lasse Holmstedt's avatar
Lasse Holmstedt committed
426 427
}

428
void QmlEngine::connectionStartupFailed()
Lasse Holmstedt's avatar
Lasse Holmstedt committed
429
{
Kai Koehne's avatar
Kai Koehne committed
430
    if (m_retryOnConnectFail) {
431 432
        // retry after 3 seconds ...
        QTimer::singleShot(3000, this, SLOT(beginConnection()));
433 434
        return;
    }
435

hjk's avatar
hjk committed
436
    QMessageBox *infoBox = new QMessageBox(Core::ICore::mainWindow());
437 438
    infoBox->setIcon(QMessageBox::Critical);
    infoBox->setWindowTitle(tr("Qt Creator"));
439 440 441 442 443
    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);
444 445 446
    infoBox->setModal(true);

    connect(infoBox, SIGNAL(finished(int)),
447
            this, SLOT(errorMessageBoxFinished(int)));
448 449 450 451

    infoBox->show();
}

452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
void QmlEngine::appStartupFailed(const QString &errorMessage)
{
    QMessageBox *infoBox = new QMessageBox(Core::ICore::mainWindow());
    infoBox->setIcon(QMessageBox::Critical);
    infoBox->setWindowTitle(tr("Qt Creator"));
    infoBox->setText(tr("Could not connect to the in-process QML debugger."
                        "\n%1").arg(errorMessage));
    infoBox->setStandardButtons(QMessageBox::Ok | QMessageBox::Help);
    infoBox->setDefaultButton(QMessageBox::Ok);
    connect(infoBox, SIGNAL(finished(int)),
            this, SLOT(errorMessageBoxFinished(int)));
    infoBox->show();

    notifyEngineRunFailed();
}

468
void QmlEngine::errorMessageBoxFinished(int result)
469 470
{
    switch (result) {
471
    case QMessageBox::Retry: {
472
        beginConnection();
473 474 475 476
        break;
    }
    case QMessageBox::Help: {
        Core::HelpManager *helpManager = Core::HelpManager::instance();
477
        helpManager->handleHelpRequest(QLatin1String("qthelp://org.qt-project.qtcreator/doc/creator-debugging-qml.html"));
478
        // fall through
479 480
    }
    default:
481 482 483
        if (state() == InferiorRunOk) {
            notifyInferiorSpontaneousStop();
            notifyInferiorIll();
484
        } else if (state() == EngineRunRequested) {
485
            notifyEngineRunFailed();
486
        }
Kai Koehne's avatar
Kai Koehne committed
487
        break;
488
    }
Lasse Holmstedt's avatar
Lasse Holmstedt committed
489 490
}

491
void QmlEngine::connectionError(QAbstractSocket::SocketError socketError)
Lasse Holmstedt's avatar
Lasse Holmstedt committed
492
{
hjk's avatar
hjk committed
493
    if (socketError == QAbstractSocket::RemoteHostClosedError)
494
        showMessage(tr("QML Debugger: Remote host closed connection."), StatusBar);
495

496 497 498 499
    if (!isSlaveEngine()) { // normal flow for slave engine when gdb exits
        notifyInferiorSpontaneousStop();
        notifyInferiorIll();
    }
Lasse Holmstedt's avatar
Lasse Holmstedt committed
500 501
}

502 503
void QmlEngine::serviceConnectionError(const QString &serviceName)
{
504 505
    showMessage(tr("QML Debugger: Could not connect to service '%1'.")
        .arg(serviceName), StatusBar);
506 507
}

508 509 510 511 512
bool QmlEngine::canDisplayTooltip() const
{
    return state() == InferiorRunOk || state() == InferiorStopOk;
}

513
void QmlEngine::filterApplicationMessage(const QString &output, int /*channel*/)
514
{
Kai Koehne's avatar
Kai Koehne committed
515
    m_outputParser.processOutput(output);
516 517 518 519
}

void QmlEngine::showMessage(const QString &msg, int channel, int timeout) const
{
520
    if (channel == AppOutput || channel == AppError)
521 522 523 524
        const_cast<QmlEngine*>(this)->filterApplicationMessage(msg, channel);
    DebuggerEngine::showMessage(msg, channel, timeout);
}

525 526 527
void QmlEngine::gotoLocation(const Location &location)
{
    const QString fileName = location.fileName();
528
    if (QUrl(fileName).isLocalFile()) {
529
        // internal file from source files -> show generated .js
Kai Koehne's avatar
Kai Koehne committed
530
        QTC_ASSERT(m_sourceDocuments.contains(fileName), return);
531 532 533
        Core::IEditor *editor = 0;

        Core::EditorManager *editorManager = Core::EditorManager::instance();
Aurindam Jana's avatar
Aurindam Jana committed
534 535 536 537
        QString titlePattern = tr("JS Source for %1").arg(fileName);
        //Check if there are open editors with the same title
        QList<Core::IEditor *> editors = editorManager->openedEditors();
        foreach (Core::IEditor *ed, editors) {
538
            if (ed->document()->displayName() == titlePattern) {
Aurindam Jana's avatar
Aurindam Jana committed
539 540 541 542 543
                editor = ed;
                break;
            }
        }
        if (!editor) {
hjk's avatar
hjk committed
544
            editor = Core::EditorManager::openEditorWithContents(QmlJSEditor::Constants::C_QMLJSEDITOR_ID,
545
                                                           &titlePattern);
546
            if (editor)
547 548
                editor->setProperty(Constants::OPENED_BY_DEBUGGER, true);

Kai Koehne's avatar
Kai Koehne committed
549
            updateEditor(editor, m_sourceDocuments.value(fileName));
550
        }
hjk's avatar
hjk committed
551
        Core::EditorManager::activateEditor(editor);
552

553 554 555 556 557
    } else {
        DebuggerEngine::gotoLocation(location);
    }
}

558 559
void QmlEngine::closeConnection()
{
560
    disconnect(watchersModel(),SIGNAL(layoutChanged()),this,SLOT(synchronizeWatchers()));
Kai Koehne's avatar
Kai Koehne committed
561
    m_adapter.closeConnection();
562 563
}

hjk's avatar
hjk committed
564 565 566
void QmlEngine::runEngine()
{
    QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());
Lasse Holmstedt's avatar
Lasse Holmstedt committed
567

568
    if (!isSlaveEngine()) {
569
        if (startParameters().startMode == AttachToRemoteServer)
570 571
            m_noDebugOutputTimer.start();
        else if (startParameters().startMode == AttachToRemoteProcess)
572 573
            beginConnection();
        else
574
            startApplicationLauncher();
575
    } else {
Kai Koehne's avatar
Kai Koehne committed
576
        m_noDebugOutputTimer.start();
577
    }
578 579 580 581
}

void QmlEngine::startApplicationLauncher()
{
Kai Koehne's avatar
Kai Koehne committed
582
    if (!m_applicationLauncher.isRunning()) {
583 584 585 586
        appendMessage(tr("Starting %1 %2").arg(
                          QDir::toNativeSeparators(startParameters().executable),
                          startParameters().processArgs)
                      + QLatin1Char('\n')
con's avatar
con committed
587
                     , Utils::NormalMessageFormat);
Kai Koehne's avatar
Kai Koehne committed
588
        m_applicationLauncher.start(ProjectExplorer::ApplicationLauncher::Gui,
589 590 591
                                    startParameters().executable,
                                    startParameters().processArgs);
    }
592
}
Lasse Holmstedt's avatar
Lasse Holmstedt committed
593

594 595
void QmlEngine::stopApplicationLauncher()
{
Kai Koehne's avatar
Kai Koehne committed
596 597 598 599
    if (m_applicationLauncher.isRunning()) {
        disconnect(&m_applicationLauncher, SIGNAL(processExited(int)),
                   this, SLOT(disconnected()));
        m_applicationLauncher.stop();
600
    }
601 602
}

603
void QmlEngine::notifyEngineRemoteSetupDone(int gdbServerPort, int qmlPort)
604
{
Christian Kandeler's avatar
Christian Kandeler committed
605 606
    if (qmlPort != -1)
        startParameters().qmlServerPort = qmlPort;
607

608
    DebuggerEngine::notifyEngineRemoteSetupDone(gdbServerPort, qmlPort);
609
    notifyEngineSetupOk();
610 611 612 613 614 615

    // 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);
616 617
}

618
void QmlEngine::notifyEngineRemoteSetupFailed(const QString &message)
619
{
620
    DebuggerEngine::notifyEngineRemoteSetupFailed(message);
621 622 623
    if (isMasterEngine())
        QMessageBox::critical(0,tr("Failed to start application"),
            tr("Application startup failed: %1").arg(message));
624

625
    notifyEngineSetupFailed();
626 627
}

Aurindam Jana's avatar
Aurindam Jana committed
628 629 630 631 632 633 634
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
635
        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
636 637 638 639 640 641 642 643 644 645 646

    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
647
void QmlEngine::shutdownInferior()
648
{
Kai Koehne's avatar
Kai Koehne committed
649 650
    if (m_adapter.activeDebuggerClient())
        m_adapter.activeDebuggerClient()->endSession();
651

652
    if (isSlaveEngine())
653 654
        resetLocation();
    stopApplicationLauncher();
655
    closeConnection();
656

hjk's avatar
hjk committed
657 658 659 660 661
    notifyInferiorShutdownOk();
}

void QmlEngine::shutdownEngine()
{
662 663
    if (qmlConsoleManager())
        qmlConsoleManager()->setScriptEvaluator(0);
664 665 666
    m_noDebugOutputTimer.stop();

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

669
    notifyEngineShutdownOk();
670 671
    if (!isSlaveEngine())
        showMessage(QString(), StatusBar);
672 673
}

hjk's avatar
hjk committed
674
void QmlEngine::setupEngine()
675
{
676
    if (startParameters().remoteSetupNeeded) {
677
        // we need to get the port first
678
        notifyEngineRequestRemoteSetup();
679
    } else {
Kai Koehne's avatar
Kai Koehne committed
680 681
        m_applicationLauncher.setEnvironment(startParameters().environment);
        m_applicationLauncher.setWorkingDirectory(startParameters().workingDirectory);
Lasse Holmstedt's avatar
Lasse Holmstedt committed
682

683
        // We can't do this in the constructore because runControl() isn't yet defined
Kai Koehne's avatar
Kai Koehne committed
684
        connect(&m_applicationLauncher, SIGNAL(bringToForegroundRequested(qint64)),
685 686 687 688 689
                runControl(), SLOT(bringApplicationToForeground(qint64)),
                Qt::UniqueConnection);

        notifyEngineSetupOk();
    }
690 691
}

692 693
void QmlEngine::continueInferior()
{
hjk's avatar
hjk committed
694
    QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
695
    if (m_adapter.activeDebuggerClient())
Kai Koehne's avatar
Kai Koehne committed
696
        m_adapter.activeDebuggerClient()->continueInferior();
697
    resetLocation();
hjk's avatar
hjk committed
698 699
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
700 701 702 703
}

void QmlEngine::interruptInferior()
{
704
    if (m_adapter.activeDebuggerClient())
Kai Koehne's avatar
Kai Koehne committed
705
        m_adapter.activeDebuggerClient()->interruptInferior();
706
    notifyInferiorStopOk();
707 708 709 710
}

void QmlEngine::executeStep()
{
711
    if (m_adapter.activeDebuggerClient())
Kai Koehne's avatar
Kai Koehne committed
712
        m_adapter.activeDebuggerClient()->executeStep();
hjk's avatar
hjk committed
713 714
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
715 716 717 718
}

void QmlEngine::executeStepI()
{
719
    if (m_adapter.activeDebuggerClient())
Kai Koehne's avatar
Kai Koehne committed
720
        m_adapter.activeDebuggerClient()->executeStepI();
hjk's avatar
hjk committed
721 722
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
723 724 725 726
}

void QmlEngine::executeStepOut()
{
727
    if (m_adapter.activeDebuggerClient())
Kai Koehne's avatar
Kai Koehne committed
728
        m_adapter.activeDebuggerClient()->executeStepOut();
hjk's avatar
hjk committed
729 730
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
731 732 733 734
}

void QmlEngine::executeNext()
{
735
    if (m_adapter.activeDebuggerClient())
Kai Koehne's avatar
Kai Koehne committed
736
        m_adapter.activeDebuggerClient()->executeNext();
hjk's avatar
hjk committed
737 738
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
739 740 741 742
}

void QmlEngine::executeNextI()
{
743
    executeNext();
744 745
}

746
void QmlEngine::executeRunToLine(const ContextData &data)
747
{
748
    QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
Jarek Kobus's avatar
Jarek Kobus committed
749
    showStatusMessage(tr("Run to line %1 (%2) requested...").arg(data.lineNumber).arg(data.fileName), 5000);
750
    resetLocation();
751 752 753 754 755 756
    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
757 758
    if (m_adapter.activeDebuggerClient())
        m_adapter.activeDebuggerClient()->executeRunToLine(modifiedData);
759 760
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
761 762 763 764 765 766 767 768
}

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

769
void QmlEngine::executeJumpToLine(const ContextData &data)
770
{
771
    Q_UNUSED(data)
772 773 774 775 776
    XSDEBUG("FIXME:  QmlEngine::executeJumpToLine()");
}

void QmlEngine::activateFrame(int index)
{
777 778 779
    if (state() != InferiorStopOk && state() != InferiorUnrunnable)
        return;

780
    if (m_adapter.activeDebuggerClient())
Kai Koehne's avatar
Kai Koehne committed
781
        m_adapter.activeDebuggerClient()->activateFrame(index);
782
    gotoLocation(stackHandler()->frames().value(index));
783 784
}

hjk's avatar
hjk committed
785
void QmlEngine::selectThread(ThreadId threadId)
786
{
hjk's avatar
hjk committed
787
    Q_UNUSED(threadId)
788 789
}

790 791 792 793 794 795 796
void QmlEngine::insertBreakpoint(BreakpointModelId id)
{
    BreakHandler *handler = breakHandler();
    BreakpointState state = handler->state(id);
    QTC_ASSERT(state == BreakpointInsertRequested, qDebug() << id << this << state);
    handler->notifyBreakpointInsertProceeding(id);

797 798 799 800 801 802 803
    const BreakpointParameters &params = handler->breakpointData(id);
    quint32 line = params.lineNumber;
    quint32 column = 0;
    if (params.type == BreakpointByFileAndLine) {
        bool valid = false;
        if (!adjustBreakpointLineAndColumn(params.fileName, &line, &column,
                                           &valid)) {
Kai Koehne's avatar
Kai Koehne committed
804
            pendingBreakpoints.insertMulti(params.fileName, id);
805 806 807 808 809 810
            return;
        }
        if (!valid)
            return;
    }

Kai Koehne's avatar
Kai Koehne committed
811 812
    if (m_adapter.activeDebuggerClient()) {
        m_adapter.activeDebuggerClient()->insertBreakpoint(id, line, column);
813
    } else {
Kai Koehne's avatar
Kai Koehne committed
814
        foreach (BaseQmlDebuggerClient *client, m_adapter.debuggerClients()) {
815
            client->insertBreakpoint(id, line, column);
816 817 818 819 820 821 822
        }
    }
}

void QmlEngine::removeBreakpoint(BreakpointModelId id)
{
    BreakHandler *handler = breakHandler();
823 824 825

    const BreakpointParameters &params = handler->breakpointData(id);
    if (params.type == BreakpointByFileAndLine &&
Kai Koehne's avatar
Kai Koehne committed
826
            pendingBreakpoints.contains(params.fileName)) {
827
        QHash<QString, BreakpointModelId>::iterator i =
Kai Koehne's avatar
Kai Koehne committed
828 829
                pendingBreakpoints.find(params.fileName);
        while (i != pendingBreakpoints.end() && i.key() == params.fileName) {
830
            if (i.value() == id) {
Kai Koehne's avatar
Kai Koehne committed
831
                pendingBreakpoints.erase(i);
832 833 834 835 836 837
                return;
            }
            ++i;
        }
    }

838 839 840 841
    BreakpointState state = handler->state(id);
    QTC_ASSERT(state == BreakpointRemoveRequested, qDebug() << id << this << state);
    handler->notifyBreakpointRemoveProceeding(id);

Kai Koehne's avatar
Kai Koehne committed
842 843
    if (m_adapter.activeDebuggerClient()) {
        m_adapter.activeDebuggerClient()->removeBreakpoint(id);
844
    } else {
Kai Koehne's avatar
Kai Koehne committed
845
        foreach (BaseQmlDebuggerClient *client, m_adapter.debuggerClients()) {
846
            client->removeBreakpoint(id);
847 848 849
        }
    }

850
    if (handler->state(id) == BreakpointRemoveProceeding)
851 852 853 854 855 856 857 858 859 860
        handler->notifyBreakpointRemoveOk(id);
}

void QmlEngine::changeBreakpoint(BreakpointModelId id)
{
    BreakHandler *handler = breakHandler();
    BreakpointState state = handler->state(id);
    QTC_ASSERT(state == BreakpointChangeRequested, qDebug() << id << this << state);
    handler->notifyBreakpointChangeProceeding(id);

Kai Koehne's avatar
Kai Koehne committed
861 862
    if (m_adapter.activeDebuggerClient()) {
        m_adapter.activeDebuggerClient()->changeBreakpoint(id);
863
    } else {
Kai Koehne's avatar
Kai Koehne committed
864