qmlengine.cpp 45.4 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 44
#include <debugger/debuggerstringutils.h>
#include <debugger/debuggertooltipmanager.h>
#include <debugger/localsandexpressionswindow.h>
#include <debugger/watchwindow.h>
45

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

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

56 57
#include <utils/qtcassert.h>

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

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

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

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

81 82 83
namespace Debugger {
namespace Internal {

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

Kai Koehne's avatar
Kai Koehne committed
89
class ASTWalker : public Visitor
90 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
{
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
117 118 119
        if (!ast->statement)
            return true;

120 121 122 123 124 125 126 127 128 129 130
        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
131 132
            if (!block || !block->statements)
                return true;
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 245 246 247 248 249 250
            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;
};
251

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

257 258 259 260 261 262
///////////////////////////////////////////////////////////////////////
//
// QmlEngine
//
///////////////////////////////////////////////////////////////////////

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

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

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

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

299

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

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

Kai Koehne's avatar
Kai Koehne committed
320 321 322 323 324
    // 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()));
325

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

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

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

Aurindam Jana's avatar
Aurindam Jana committed
354 355 356 357 358 359
void QmlEngine::notifyInferiorSetupOk()
{
    emit aboutToNotifyInferiorSetupOk();
    DebuggerEngine::notifyInferiorSetupOk();
}

hjk's avatar
hjk committed
360
void QmlEngine::setupInferior()
361
{
hjk's avatar
hjk committed
362
    QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
Lasse Holmstedt's avatar
Lasse Holmstedt committed
363

364
    notifyInferiorSetupOk();
365

Kai Koehne's avatar
Kai Koehne committed
366
    if (m_automaticConnect)
367
        beginConnection();
hjk's avatar
hjk committed
368
}
hjk's avatar
hjk committed
369

con's avatar
con committed
370
void QmlEngine::appendMessage(const QString &msg, Utils::OutputFormat /* format */)
hjk's avatar
hjk committed
371
{
372
    showMessage(msg, AppOutput); // FIXME: Redirect to RunControl
hjk's avatar
hjk committed
373 374
}

Lasse Holmstedt's avatar
Lasse Holmstedt committed
375 376 377 378
void QmlEngine::connectionEstablished()
{
    attemptBreakpointSynchronization();

379
    if (!watchHandler()->watcherNames().isEmpty())
380
        synchronizeWatchers();
hjk's avatar
hjk committed
381
    connect(watchModel(),SIGNAL(layoutChanged()),this,SLOT(synchronizeWatchers()));
Christiaan Janssen's avatar
Christiaan Janssen committed
382

383 384
    if (state() == EngineRunRequested)
        notifyEngineRunAndInferiorRunOk();
Lasse Holmstedt's avatar
Lasse Holmstedt committed
385
}
386

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

408
void QmlEngine::beginConnection(quint16 port)
409
{
Kai Koehne's avatar
Kai Koehne committed
410
    m_noDebugOutputTimer.stop();
411

Kai Koehne's avatar
Kai Koehne committed
412
    if (state() != EngineRunRequested && m_retryOnConnectFail)
413 414
        return;

415
    QTC_ASSERT(state() == EngineRunRequested, return);
416

417 418 419 420 421
    QString host =  startParameters().qmlServerAddress;
    // Use localhost as default
    if (host.isEmpty())
        host = QLatin1String("localhost");

422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
    /*
     * 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
437 438
}

439

440
void QmlEngine::connectionStartupFailed()
Lasse Holmstedt's avatar
Lasse Holmstedt committed
441
{
Kai Koehne's avatar
Kai Koehne committed
442
    if (m_retryOnConnectFail) {
443 444
        // retry after 3 seconds ...
        QTimer::singleShot(3000, this, SLOT(beginConnection()));
445 446
        return;
    }
447

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

    connect(infoBox, SIGNAL(finished(int)),
459
            this, SLOT(errorMessageBoxFinished(int)));
460 461 462 463

    infoBox->show();
}

464 465
void QmlEngine::appStartupFailed(const QString &errorMessage)
{
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
    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);
    }
482 483 484 485

    notifyEngineRunFailed();
}

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

508
void QmlEngine::connectionError(QDebugSupport::Error error)
Lasse Holmstedt's avatar
Lasse Holmstedt committed
509
{
510
    if (error == QDebugSupport::RemoteClosedConnectionError)
511
        showMessage(tr("QML Debugger: Remote host closed connection."), StatusBar);
512

513 514 515 516
    if (!isSlaveEngine()) { // normal flow for slave engine when gdb exits
        notifyInferiorSpontaneousStop();
        notifyInferiorIll();
    }
Lasse Holmstedt's avatar
Lasse Holmstedt committed
517 518
}

519 520
void QmlEngine::serviceConnectionError(const QString &serviceName)
{
521
    showMessage(tr("QML Debugger: Could not connect to service \"%1\".")
522
        .arg(serviceName), StatusBar);
523 524
}

525 526 527 528 529
bool QmlEngine::canDisplayTooltip() const
{
    return state() == InferiorRunOk || state() == InferiorStopOk;
}

530
void QmlEngine::filterApplicationMessage(const QString &output, int /*channel*/)
531
{
Kai Koehne's avatar
Kai Koehne committed
532
    m_outputParser.processOutput(output);
533 534 535 536
}

void QmlEngine::showMessage(const QString &msg, int channel, int timeout) const
{
537
    if (channel == AppOutput || channel == AppError)
538 539 540 541
        const_cast<QmlEngine*>(this)->filterApplicationMessage(msg, channel);
    DebuggerEngine::showMessage(msg, channel, timeout);
}

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

Aurindam Jana's avatar
Aurindam Jana committed
549
        QString titlePattern = tr("JS Source for %1").arg(fileName);
550
        //Check if there are open documents with the same title
hjk's avatar
hjk committed
551
        foreach (Core::IDocument *document, Core::DocumentModel::openedDocuments()) {
552
            if (document->displayName() == titlePattern) {
553
                Core::EditorManager::activateEditorForDocument(document);
554
                return;
Aurindam Jana's avatar
Aurindam Jana committed
555 556
            }
        }
557 558 559 560 561 562 563 564 565
        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));
566
        }
567 568 569 570 571
    } else {
        DebuggerEngine::gotoLocation(location);
    }
}

572 573
void QmlEngine::closeConnection()
{
hjk's avatar
hjk committed
574
    disconnect(watchModel(),SIGNAL(layoutChanged()),this,SLOT(synchronizeWatchers()));
Kai Koehne's avatar
Kai Koehne committed
575
    m_adapter.closeConnection();
576 577
}

hjk's avatar
hjk committed
578 579 580
void QmlEngine::runEngine()
{
    QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());
Lasse Holmstedt's avatar
Lasse Holmstedt committed
581

582
    if (!isSlaveEngine()) {
583
        if (startParameters().startMode == AttachToRemoteServer)
584 585
            m_noDebugOutputTimer.start();
        else if (startParameters().startMode == AttachToRemoteProcess)
586 587
            beginConnection();
        else
588
            startApplicationLauncher();
589
    } else {
Kai Koehne's avatar
Kai Koehne committed
590
        m_noDebugOutputTimer.start();
591
    }
592 593 594 595
}

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

608 609
void QmlEngine::stopApplicationLauncher()
{
Kai Koehne's avatar
Kai Koehne committed
610
    if (m_applicationLauncher.isRunning()) {
611
        disconnect(&m_applicationLauncher, SIGNAL(processExited(int,QProcess::ExitStatus)),
Kai Koehne's avatar
Kai Koehne committed
612 613
                   this, SLOT(disconnected()));
        m_applicationLauncher.stop();
614
    }
615 616
}

617
void QmlEngine::notifyEngineRemoteSetupFinished(const RemoteSetupResult &result)
618
{
619
    DebuggerEngine::notifyEngineRemoteSetupFinished(result);
620

621 622 623
    if (result.success) {
        if (result.qmlServerPort != InvalidPort)
            startParameters().qmlServerPort = result.qmlServerPort;
624

625
        notifyEngineSetupOk();
626

627 628 629 630 631 632 633 634 635 636 637 638
        // 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();
    }
639 640
}

Aurindam Jana's avatar
Aurindam Jana committed
641 642 643 644 645 646 647
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
648
        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
649 650 651 652 653 654 655 656 657 658 659

    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
660
void QmlEngine::shutdownInferior()
661
{
Kai Koehne's avatar
Kai Koehne committed
662 663
    if (m_adapter.activeDebuggerClient())
        m_adapter.activeDebuggerClient()->endSession();
664

665
    if (isSlaveEngine())
666 667
        resetLocation();
    stopApplicationLauncher();
668
    closeConnection();
669

hjk's avatar
hjk committed
670 671 672 673 674
    notifyInferiorShutdownOk();
}

void QmlEngine::shutdownEngine()
{
675 676 677
    if (m_adapter.activeDebuggerClient())
        m_adapter.activeDebuggerClient()->resetSession();

678 679
    if (qmlConsoleManager())
        qmlConsoleManager()->setScriptEvaluator(0);
680 681 682
    m_noDebugOutputTimer.stop();

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

685
    notifyEngineShutdownOk();
686 687
    if (!isSlaveEngine())
        showMessage(QString(), StatusBar);
688 689
}

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

699
        // We can't do this in the constructore because runControl() isn't yet defined
Kai Koehne's avatar
Kai Koehne committed
700
        connect(&m_applicationLauncher, SIGNAL(bringToForegroundRequested(qint64)),
701 702 703 704 705
                runControl(), SLOT(bringApplicationToForeground(qint64)),
                Qt::UniqueConnection);

        notifyEngineSetupOk();
    }
706 707
}

708 709
void QmlEngine::continueInferior()
{
hjk's avatar
hjk committed
710
    QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
711
    if (m_adapter.activeDebuggerClient())
Kai Koehne's avatar
Kai Koehne committed
712
        m_adapter.activeDebuggerClient()->continueInferior();
713
    resetLocation();
hjk's avatar
hjk committed
714 715
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
716 717 718 719
}

void QmlEngine::interruptInferior()
{
720
    if (m_adapter.activeDebuggerClient())
Kai Koehne's avatar
Kai Koehne committed
721
        m_adapter.activeDebuggerClient()->interruptInferior();
722
    notifyInferiorStopOk();
723 724 725 726
}

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

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

void QmlEngine::executeStepOut()
{
743
    if (m_adapter.activeDebuggerClient())
Kai Koehne's avatar
Kai Koehne committed
744
        m_adapter.activeDebuggerClient()->executeStepOut();
hjk's avatar
hjk committed
745 746
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
747 748 749 750
}

void QmlEngine::executeNext()
{
751
    if (m_adapter.activeDebuggerClient())
Kai Koehne's avatar
Kai Koehne committed
752
        m_adapter.activeDebuggerClient()->executeNext();
hjk's avatar
hjk committed
753 754
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
755 756 757 758
}

void QmlEngine::executeNextI()
{
759
    executeNext();
760 761
}

762
void QmlEngine::executeRunToLine(const ContextData &data)
763
{
764
    QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
Jarek Kobus's avatar
Jarek Kobus committed
765
    showStatusMessage(tr("Run to line %1 (%2) requested...").arg(data.lineNumber).arg(data.fileName), 5000);
766
    resetLocation();
767 768 769 770 771 772
    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
773 774
    if (m_adapter.activeDebuggerClient())
        m_adapter.activeDebuggerClient()->executeRunToLine(modifiedData);
775 776
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
777 778 779 780 781 782 783 784
}

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

785
void QmlEngine::executeJumpToLine(const ContextData &data)
786
{
787
    Q_UNUSED(data)
788 789 790 791 792
    XSDEBUG("FIXME:  QmlEngine::executeJumpToLine()");
}

void QmlEngine::activateFrame(int index)
{
793 794 795
    if (state() != InferiorStopOk && state() != InferiorUnrunnable)
        return;

796
    if (m_adapter.activeDebuggerClient())
Kai Koehne's avatar
Kai Koehne committed
797
        m_adapter.activeDebuggerClient()->activateFrame(index);
798
    gotoLocation(stackHandler()->frames().value(index));
799 800
}

hjk's avatar
hjk committed
801
void QmlEngine::selectThread(ThreadId threadId)
802
{
hjk's avatar
hjk committed
803
    Q_UNUSED(threadId)
804 805
}

806 807 808 809 810 811 812
void QmlEngine::insertBreakpoint(BreakpointModelId id)
{
    BreakHandler *handler = breakHandler();
    BreakpointState state = handler->state(id);
    QTC_ASSERT(state == BreakpointInsertRequested, qDebug() << id << this << state);
    handler->notifyBreakpointInsertProceeding(id);

813 814 815 816 817 818 819
    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
820
            pendingBreakpoints.insertMulti(params.fileName, id);
821 822 823 824 825 826
            return;
        }
        if (!valid)
            return;
    }

Kai Koehne's avatar
Kai Koehne committed
827 828
    if (m_adapter.activeDebuggerClient()) {
        m_adapter.activeDebuggerClient()->insertBreakpoint(id, line, column);
829
    } else {
Kai Koehne's avatar
Kai Koehne committed
830
        foreach (BaseQmlDebuggerClient *client, m_adapter.debuggerClients()) {
831
            client->insertBreakpoint(id, line, column);
832 833 834 835 836 837 838
        }
    }
}

void QmlEngine::removeBreakpoint(BreakpointModelId id)
{
    BreakHandler *handler = breakHandler();
839 840 841

    const BreakpointParameters &params = handler->breakpointData(id);
    if (params.type == BreakpointByFileAndLine &&
Kai Koehne's avatar
Kai Koehne committed
842
            pendingBreakpoints.contains(params.fileName)) {
843
        QHash<QString, BreakpointModelId>::iterator i =
Kai Koehne's avatar
Kai Koehne committed
844 845
                pendingBreakpoints.find(params.fileName);
        while (i != pendingBreakpoints.end() && i.key() == params.fileName) {
846
            if (i.value() == id) {
Kai Koehne's avatar
Kai Koehne committed
847
                pendingBreakpoints.erase(i);
848 849 850 851 852 853
                return;
            }
            ++i;
        }
    }

854 855 856 857
    BreakpointState state = handler->state(id);
    QTC_ASSERT(state == BreakpointRemoveRequested, qDebug() << id << this << state);
    handler->notifyBreakpointRemoveProceeding(id);

Kai Koehne's avatar
Kai Koehne committed
858 859
    if (m_adapter.activeDebuggerClient()) {
        m_adapter.activeDebuggerClient()->removeBreakpoint(id);
860
    } else {
Kai Koehne's avatar
Kai Koehne committed
861
        foreach (BaseQmlDebuggerClient *client, m_adapter.debuggerClients()) {
862
            client->removeBreakpoint(id);
863 864 865
        }
    }

866
    if (handler->state(id) == BreakpointRemoveProceeding)
867 868 869 870 871 872 873 874 875 876
        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
877 878
    if (m_adapter.activeDebuggerClient()) {
        m_adapter.activeDebuggerClient()->changeBreakpoint(id);
879
    } else {
Kai Koehne's avatar
Kai Koehne committed
880
        foreach (BaseQmlDebuggerClient *client, m_adapter.debuggerClients()) {
881
            client->changeBreakpoint(id);
882 883 884
        }
    }

885
    if (handler->state(id) == BreakpointChangeProceeding)
886 887 888
        handler->notifyBreakpointChangeOk(id);
}

889 890
void QmlEngine::attemptBreakpointSynchronization()
{
891 892 893 894 895
    if (!stateAcceptsBreakpointChanges()) {
        showMessage(_("BREAKPOINT SYNCHRONIZATION NOT POSSIBLE IN CURRENT STATE"));
        return;
    }

hjk's avatar
hjk committed
896
    BreakHandler *handler = breakHandler();
897

898
    DebuggerEngine *bpOwner = isSlaveEngine() ? masterEngine() : this;
899
    foreach (BreakpointModelId id, handler->unclaimedBreakpointIds()) {