1 /**************************************************************************
3 ** This file is part of Qt Creator
5 ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
7 ** Contact: Nokia Corporation (info@qt.nokia.com)
10 ** GNU Lesser General Public License Usage
12 ** This file may be used under the terms of the GNU Lesser General Public
13 ** License version 2.1 as published by the Free Software Foundation and
14 ** appearing in the file LICENSE.LGPL included in the packaging of this file.
15 ** Please review the following information to ensure the GNU Lesser General
16 ** Public License version 2.1 requirements will be met:
17 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
19 ** In addition, as a special exception, Nokia gives you certain additional
20 ** rights. These rights are described in the Nokia Qt LGPL Exception
21 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
25 ** Alternatively, this file may be used in accordance with the terms and
26 ** conditions contained in a signed written agreement between you and Nokia.
28 ** If you have questions regarding the use of this file, please contact
29 ** Nokia at info@qt.nokia.com.
31 **************************************************************************/
33 #include "qmlengine.h"
34 #include "qmladapter.h"
36 #include "debuggerstartparameters.h"
37 #include "debuggeractions.h"
38 #include "debuggerconstants.h"
39 #include "debuggercore.h"
40 #include "debuggerdialogs.h"
41 #include "debuggermainwindow.h"
42 #include "debuggerrunner.h"
43 #include "debuggerstringutils.h"
44 #include "debuggertooltipmanager.h"
46 #include "breakhandler.h"
47 #include "moduleshandler.h"
48 #include "registerhandler.h"
49 #include "stackhandler.h"
50 #include "watchhandler.h"
51 #include "watchutils.h"
53 #include <extensionsystem/pluginmanager.h>
54 #include <projectexplorer/applicationlauncher.h>
56 #include <utils/environment.h>
57 #include <utils/qtcassert.h>
58 #include <utils/fileinprojectfinder.h>
60 #include <coreplugin/icore.h>
61 #include <coreplugin/helpmanager.h>
63 #include <QtCore/QDateTime>
64 #include <QtCore/QDebug>
65 #include <QtCore/QDir>
66 #include <QtCore/QFileInfo>
67 #include <QtCore/QTimer>
69 #include <QtGui/QAction>
70 #include <QtGui/QApplication>
71 #include <QtGui/QMainWindow>
72 #include <QtGui/QMessageBox>
73 #include <QtGui/QToolTip>
74 #include <QtGui/QTextDocument>
76 #include <QtNetwork/QTcpSocket>
77 #include <QtNetwork/QHostAddress>
81 # define SDEBUG(s) qDebug() << s
85 # define XSDEBUG(s) qDebug() << s
87 using namespace ProjectExplorer;
92 class QmlEnginePrivate
95 explicit QmlEnginePrivate(QmlEngine *q);
98 friend class QmlEngine;
100 ApplicationLauncher m_applicationLauncher;
101 Utils::FileInProjectFinder fileFinder;
102 QTimer m_noDebugOutputTimer;
105 QmlEnginePrivate::QmlEnginePrivate(QmlEngine *q)
110 ///////////////////////////////////////////////////////////////////////
114 ///////////////////////////////////////////////////////////////////////
116 QmlEngine::QmlEngine(const DebuggerStartParameters &startParameters,
117 DebuggerEngine *masterEngine)
118 : DebuggerEngine(startParameters, masterEngine),
119 d(new QmlEnginePrivate(this))
121 setObjectName(QLatin1String("QmlEngine"));
123 ExtensionSystem::PluginManager *pluginManager =
124 ExtensionSystem::PluginManager::instance();
125 pluginManager->addObject(this);
127 connect(&d->m_adapter, SIGNAL(connectionError(QAbstractSocket::SocketError)),
128 SLOT(connectionError(QAbstractSocket::SocketError)));
129 connect(&d->m_adapter, SIGNAL(serviceConnectionError(QString)),
130 SLOT(serviceConnectionError(QString)));
131 connect(&d->m_adapter, SIGNAL(connected()),
132 SLOT(connectionEstablished()));
133 connect(&d->m_adapter, SIGNAL(connectionStartupFailed()),
134 SLOT(connectionStartupFailed()));
136 connect(&d->m_applicationLauncher,
137 SIGNAL(processExited(int)),
138 SLOT(disconnected()));
139 connect(&d->m_applicationLauncher,
140 SIGNAL(appendMessage(QString,Utils::OutputFormat)),
141 SLOT(appendMessage(QString,Utils::OutputFormat)));
143 // Only wait 8 seconds for the 'Waiting for connection' on application ouput, then just try to connect
144 // (application output might be redirected / blocked)
145 d->m_noDebugOutputTimer.setSingleShot(true);
146 d->m_noDebugOutputTimer.setInterval(8000);
147 connect(&d->m_noDebugOutputTimer, SIGNAL(timeout()), this, SLOT(beginConnection()));
150 QmlEngine::~QmlEngine()
152 ExtensionSystem::PluginManager *pluginManager =
153 ExtensionSystem::PluginManager::instance();
155 if (pluginManager->allObjects().contains(this)) {
156 pluginManager->removeObject(this);
162 void QmlEngine::setupInferior()
164 QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
166 if (startParameters().startMode == AttachToRemote) {
167 if (startParameters().qmlServerPort != quint16(-1))
168 notifyInferiorSetupOk();
170 emit requestRemoteSetup();
172 d->m_applicationLauncher.setEnvironment(startParameters().environment);
173 d->m_applicationLauncher.setWorkingDirectory(startParameters().workingDirectory);
175 notifyInferiorSetupOk();
179 void QmlEngine::appendMessage(const QString &msg, Utils::OutputFormat /* format */)
181 showMessage(msg, AppOutput); // FIXME: Redirect to RunControl
184 void QmlEngine::connectionEstablished()
186 attemptBreakpointSynchronization();
188 showMessage(tr("QML Debugger connected."), StatusBar);
190 if (!watchHandler()->watcherNames().isEmpty()) {
191 synchronizeWatchers();
193 connect(watchersModel(),SIGNAL(layoutChanged()),this,SLOT(synchronizeWatchers()));
195 notifyEngineRunAndInferiorRunOk();
198 void QmlEngine::beginConnection()
200 d->m_noDebugOutputTimer.stop();
201 d->m_adapter.beginConnection();
204 void QmlEngine::connectionStartupFailed()
206 Core::ICore * const core = Core::ICore::instance();
207 QMessageBox *infoBox = new QMessageBox(core->mainWindow());
208 infoBox->setIcon(QMessageBox::Critical);
209 infoBox->setWindowTitle(tr("Qt Creator"));
210 infoBox->setText(tr("Could not connect to the in-process QML debugger.\n"
211 "Do you want to retry?"));
212 infoBox->setStandardButtons(QMessageBox::Retry | QMessageBox::Cancel | QMessageBox::Help);
213 infoBox->setDefaultButton(QMessageBox::Retry);
214 infoBox->setModal(true);
216 connect(infoBox, SIGNAL(finished(int)),
217 this, SLOT(retryMessageBoxFinished(int)));
222 void QmlEngine::retryMessageBoxFinished(int result)
225 case QMessageBox::Retry: {
229 case QMessageBox::Help: {
230 Core::HelpManager *helpManager = Core::HelpManager::instance();
231 helpManager->handleHelpRequest("qthelp://com.nokia.qtcreator/doc/creator-debugging-qml.html");
235 notifyEngineRunFailed();
240 void QmlEngine::connectionError(QAbstractSocket::SocketError socketError)
242 if (socketError == QAbstractSocket::RemoteHostClosedError)
243 showMessage(tr("QML Debugger: Remote host closed connection."), StatusBar);
246 void QmlEngine::serviceConnectionError(const QString &serviceName)
248 showMessage(tr("QML Debugger: Could not connect to service '%1'.")
249 .arg(serviceName), StatusBar);
252 bool QmlEngine::canDisplayTooltip() const
254 return state() == InferiorRunOk || state() == InferiorStopOk;
257 void QmlEngine::filterApplicationMessage(const QString &msg, int /*channel*/)
259 static const QString qddserver = QLatin1String("QDeclarativeDebugServer: ");
260 static const QString cannotRetrieveDebuggingOutput = ApplicationLauncher::msgWinCannotRetrieveDebuggingOutput();
262 const int index = msg.indexOf(qddserver);
264 // we're actually getting debug output
265 d->m_noDebugOutputTimer.stop();
267 QString status = msg;
268 status.remove(0, index + qddserver.length()); // chop of 'QDeclarativeDebugServer: '
270 static QString waitingForConnection = QLatin1String("Waiting for connection ");
271 static QString unableToListen = QLatin1String("Unable to listen ");
272 static QString debuggingNotEnabled = QLatin1String("Ignoring \"-qmljsdebugger=");
273 static QString debuggingNotEnabled2 = QLatin1String("Ignoring\"-qmljsdebugger="); // There is (was?) a bug in one of the error strings - safest to handle both
274 static QString connectionEstablished = QLatin1String("Connection established");
276 QString errorMessage;
277 if (status.startsWith(waitingForConnection)) {
279 } else if (status.startsWith(unableToListen)) {
280 //: Error message shown after 'Could not connect ... debugger:"
281 errorMessage = tr("The port seems to be in use.");
282 } else if (status.startsWith(debuggingNotEnabled) || status.startsWith(debuggingNotEnabled2)) {
283 //: Error message shown after 'Could not connect ... debugger:"
284 errorMessage = tr("The application is not set up for QML/JS debugging.");
285 } else if (status.startsWith(connectionEstablished)) {
288 qWarning() << "Unknown QDeclarativeDebugServer status message: " << status;
291 if (!errorMessage.isEmpty()) {
292 notifyEngineRunFailed();
294 Core::ICore * const core = Core::ICore::instance();
295 QMessageBox *infoBox = new QMessageBox(core->mainWindow());
296 infoBox->setIcon(QMessageBox::Critical);
297 infoBox->setWindowTitle(tr("Qt Creator"));
298 //: %1 is detailed error message
299 infoBox->setText(tr("Could not connect to the in-process QML debugger:\n%1")
301 infoBox->setStandardButtons(QMessageBox::Ok | QMessageBox::Help);
302 infoBox->setDefaultButton(QMessageBox::Ok);
303 infoBox->setModal(true);
305 connect(infoBox, SIGNAL(finished(int)),
306 this, SLOT(wrongSetupMessageBoxFinished(int)));
310 } else if (msg.contains(cannotRetrieveDebuggingOutput)) {
311 // we won't get debugging output, so just try to connect ...
316 void QmlEngine::showMessage(const QString &msg, int channel, int timeout) const
318 if (channel == AppOutput || channel == AppError) {
319 const_cast<QmlEngine*>(this)->filterApplicationMessage(msg, channel);
321 DebuggerEngine::showMessage(msg, channel, timeout);
324 void QmlEngine::closeConnection()
326 disconnect(watchersModel(),SIGNAL(layoutChanged()),this,SLOT(synchronizeWatchers()));
327 d->m_adapter.closeConnection();
330 void QmlEngine::runEngine()
332 QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());
334 if (!isSlaveEngine() && startParameters().startMode != AttachToRemote)
335 startApplicationLauncher();
336 d->m_noDebugOutputTimer.start();
339 void QmlEngine::startApplicationLauncher()
341 if (!d->m_applicationLauncher.isRunning()) {
342 appendMessage(tr("Starting %1 %2").arg(
343 QDir::toNativeSeparators(startParameters().executable),
344 startParameters().processArgs)
346 , Utils::NormalMessageFormat);
347 d->m_applicationLauncher.start(ApplicationLauncher::Gui,
348 startParameters().executable,
349 startParameters().processArgs);
353 void QmlEngine::stopApplicationLauncher()
355 if (d->m_applicationLauncher.isRunning()) {
356 disconnect(&d->m_applicationLauncher, SIGNAL(processExited(int)), this, SLOT(disconnected()));
357 d->m_applicationLauncher.stop();
361 void QmlEngine::handleRemoteSetupDone(int gdbServerPort, int qmlPort)
363 Q_UNUSED(gdbServerPort);
365 startParameters().qmlServerPort = qmlPort;
366 notifyInferiorSetupOk();
369 void QmlEngine::handleRemoteSetupFailed(const QString &message)
371 QMessageBox::critical(0,tr("Failed to start application"),
372 tr("Application startup failed: %1").arg(message));
373 notifyInferiorSetupFailed();
376 void QmlEngine::shutdownInferior()
378 d->m_adapter.activeDebuggerClient()->disconnect();
380 if (isSlaveEngine()) {
383 stopApplicationLauncher();
385 notifyInferiorShutdownOk();
388 void QmlEngine::shutdownEngine()
392 // double check (ill engine?):
393 stopApplicationLauncher();
395 notifyEngineShutdownOk();
396 if (!isSlaveEngine())
397 showMessage(QString(), StatusBar);
400 void QmlEngine::setupEngine()
402 connect(&d->m_applicationLauncher, SIGNAL(bringToForegroundRequested(qint64)),
403 runControl(), SLOT(bringApplicationToForeground(qint64)),
404 Qt::UniqueConnection);
406 notifyEngineSetupOk();
409 void QmlEngine::continueInferior()
411 QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
412 logMessage(LogSend, "CONTINUE");
413 d->m_adapter.activeDebuggerClient()->continueInferior();
415 notifyInferiorRunRequested();
416 notifyInferiorRunOk();
419 void QmlEngine::interruptInferior()
421 logMessage(LogSend, "INTERRUPT");
422 d->m_adapter.activeDebuggerClient()->interruptInferior();
423 notifyInferiorStopOk();
426 void QmlEngine::executeStep()
428 logMessage(LogSend, "STEPINTO");
429 d->m_adapter.activeDebuggerClient()->executeStep();
431 notifyInferiorRunRequested();
432 notifyInferiorRunOk();
435 void QmlEngine::executeStepI()
437 logMessage(LogSend, "STEPINTO");
438 d->m_adapter.activeDebuggerClient()->executeStepI();
440 notifyInferiorRunRequested();
441 notifyInferiorRunOk();
444 void QmlEngine::executeStepOut()
446 logMessage(LogSend, "STEPOUT");
447 d->m_adapter.activeDebuggerClient()->executeStepOut();
449 notifyInferiorRunRequested();
450 notifyInferiorRunOk();
453 void QmlEngine::executeNext()
455 logMessage(LogSend, "STEPOVER");
456 d->m_adapter.activeDebuggerClient()->executeNext();
458 notifyInferiorRunRequested();
459 notifyInferiorRunOk();
462 void QmlEngine::executeNextI()
464 SDEBUG("QmlEngine::executeNextI()");
467 void QmlEngine::executeRunToLine(const ContextData &data)
470 SDEBUG("FIXME: QmlEngine::executeRunToLine()");
473 void QmlEngine::executeRunToFunction(const QString &functionName)
475 Q_UNUSED(functionName)
476 XSDEBUG("FIXME: QmlEngine::executeRunToFunction()");
479 void QmlEngine::executeJumpToLine(const ContextData &data)
482 XSDEBUG("FIXME: QmlEngine::executeJumpToLine()");
485 void QmlEngine::activateFrame(int index)
487 logMessage(LogSend, QString("%1 %2").arg(QString("ACTIVATE_FRAME"), QString::number(index)));
488 d->m_adapter.activeDebuggerClient()->activateFrame(index);
489 gotoLocation(stackHandler()->frames().value(index));
492 void QmlEngine::selectThread(int index)
497 void QmlEngine::insertBreakpoint(BreakpointModelId id)
499 BreakHandler *handler = breakHandler();
500 BreakpointState state = handler->state(id);
501 QTC_ASSERT(state == BreakpointInsertRequested, qDebug() << id << this << state);
502 handler->notifyBreakpointInsertProceeding(id);
504 if (d->m_adapter.activeDebuggerClient()) {
505 d->m_adapter.activeDebuggerClient()->insertBreakpoint(id,handler);
507 foreach (QmlDebuggerClient *client, d->m_adapter.debuggerClients()) {
508 client->insertBreakpoint(id,handler);
512 if (handler->state(id) == BreakpointInsertProceeding) {
513 handler->notifyBreakpointInsertOk(id);
517 void QmlEngine::removeBreakpoint(BreakpointModelId id)
519 BreakHandler *handler = breakHandler();
520 BreakpointState state = handler->state(id);
521 QTC_ASSERT(state == BreakpointRemoveRequested, qDebug() << id << this << state);
522 handler->notifyBreakpointRemoveProceeding(id);
524 if (d->m_adapter.activeDebuggerClient()) {
525 d->m_adapter.activeDebuggerClient()->removeBreakpoint(id,handler);
527 foreach (QmlDebuggerClient *client, d->m_adapter.debuggerClients()) {
528 client->removeBreakpoint(id,handler);
532 if (handler->state(id) == BreakpointRemoveProceeding) {
533 handler->notifyBreakpointRemoveOk(id);
537 void QmlEngine::changeBreakpoint(BreakpointModelId id)
539 BreakHandler *handler = breakHandler();
540 BreakpointState state = handler->state(id);
541 QTC_ASSERT(state == BreakpointChangeRequested, qDebug() << id << this << state);
542 handler->notifyBreakpointChangeProceeding(id);
544 if (d->m_adapter.activeDebuggerClient()) {
545 d->m_adapter.activeDebuggerClient()->changeBreakpoint(id,handler);
547 foreach (QmlDebuggerClient *client, d->m_adapter.debuggerClients()) {
548 client->changeBreakpoint(id,handler);
552 if (handler->state(id) == BreakpointChangeProceeding) {
553 handler->notifyBreakpointChangeOk(id);
557 void QmlEngine::attemptBreakpointSynchronization()
559 if (!stateAcceptsBreakpointChanges()) {
560 showMessage(_("BREAKPOINT SYNCHRONIZATION NOT POSSIBLE IN CURRENT STATE"));
564 BreakHandler *handler = breakHandler();
566 foreach (BreakpointModelId id, handler->unclaimedBreakpointIds()) {
567 // Take ownership of the breakpoint. Requests insertion.
568 if (acceptsBreakpoint(id))
569 handler->setEngine(id, this);
572 foreach (BreakpointModelId id, handler->engineBreakpointIds(this)) {
573 switch (handler->state(id)) {
575 // Should not happen once claimed.
578 case BreakpointInsertRequested:
579 insertBreakpoint(id);
581 case BreakpointChangeRequested:
582 changeBreakpoint(id);
584 case BreakpointRemoveRequested:
585 removeBreakpoint(id);
587 case BreakpointChangeProceeding:
588 case BreakpointInsertProceeding:
589 case BreakpointRemoveProceeding:
590 case BreakpointInserted:
594 QTC_ASSERT(false, qDebug() << "UNKNOWN STATE" << id << state());
597 DebuggerEngine::attemptBreakpointSynchronization();
599 if (d->m_adapter.activeDebuggerClient()) {
600 d->m_adapter.activeDebuggerClient()->updateBreakpoints();
602 foreach (QmlDebuggerClient *client, d->m_adapter.debuggerClients()) {
603 client->updateBreakpoints();
608 bool QmlEngine::acceptsBreakpoint(BreakpointModelId id) const
610 return !DebuggerEngine::isCppBreakpoint(breakHandler()->breakpointData(id));
613 void QmlEngine::loadSymbols(const QString &moduleName)
618 void QmlEngine::loadAllSymbols()
622 void QmlEngine::reloadModules()
626 void QmlEngine::requestModuleSymbols(const QString &moduleName)
631 //////////////////////////////////////////////////////////////////////
633 // Tooltip specific stuff
635 //////////////////////////////////////////////////////////////////////
637 bool QmlEngine::setToolTipExpression(const QPoint &mousePos,
638 TextEditor::ITextEditor *editor, const DebuggerToolTipContext &ctx)
640 // This is processed by QML inspector, which has dependencies to
641 // the qml js editor. Makes life easier.
642 emit tooltipRequested(mousePos, editor, ctx.position);
646 //////////////////////////////////////////////////////////////////////
648 // Watch specific stuff
650 //////////////////////////////////////////////////////////////////////
652 void QmlEngine::assignValueInDebugger(const WatchData *data,
653 const QString &expression, const QVariant &valueV)
655 quint64 objectId = data->id;
656 if (objectId > 0 && !expression.isEmpty()) {
657 logMessage(LogSend, QString("%1 %2 %3 %4 %5").arg(
658 QString("SET_PROPERTY"), QString::number(objectId), QString(expression),
660 d->m_adapter.activeDebuggerClient()->assignValueInDebugger(expression.toUtf8(), objectId, expression, valueV.toString());
664 void QmlEngine::updateWatchData(const WatchData &data,
665 const WatchUpdateFlags &)
667 // qDebug() << "UPDATE WATCH DATA" << data.toString();
668 //watchHandler()->rebuildModel();
669 showStatusMessage(tr("Stopped."), 5000);
671 if (!data.name.isEmpty() && data.isValueNeeded()) {
672 logMessage(LogSend, QString("%1 %2 %3").arg(QString("EXEC"), QString(data.iname),
673 QString(data.name)));
674 d->m_adapter.activeDebuggerClient()->updateWatchData(&data);
677 if (!data.name.isEmpty() && data.isChildrenNeeded()
678 && watchHandler()->isExpandedIName(data.iname)) {
679 d->m_adapter.activeDebuggerClient()->expandObject(data.iname, data.id);
682 synchronizeWatchers();
684 if (!data.isSomethingNeeded())
685 watchHandler()->insertData(data);
688 void QmlEngine::synchronizeWatchers()
690 QStringList watchedExpressions = watchHandler()->watchedExpressions();
691 // send watchers list
692 logMessage(LogSend, QString("%1 %2").arg(
693 QString("WATCH_EXPRESSIONS"), watchedExpressions.join(", ")));
694 if (d->m_adapter.activeDebuggerClient()) {
695 d->m_adapter.activeDebuggerClient()->synchronizeWatchers(watchedExpressions);
697 foreach (QmlDebuggerClient *client, d->m_adapter.debuggerClients())
698 client->synchronizeWatchers(watchedExpressions);
702 unsigned QmlEngine::debuggerCapabilities() const
704 return AddWatcherCapability|AddWatcherWhileRunningCapability;
705 /*ReverseSteppingCapability | SnapshotCapability
706 | AutoDerefPointersCapability | DisassemblerCapability
707 | RegisterCapability | ShowMemoryCapability
708 | JumpToLineCapability | ReloadModuleCapability
709 | ReloadModuleSymbolsCapability | BreakOnThrowAndCatchCapability
710 | ReturnFromFunctionCapability
711 | CreateFullBacktraceCapability
712 | WatchpointCapability
713 | AddWatcherCapability;*/
716 QString QmlEngine::toFileInProject(const QUrl &fileUrl)
718 if (d->fileFinder.projectDirectory().isEmpty()) {
719 d->fileFinder.setProjectDirectory(startParameters().projectSourceDirectory);
720 d->fileFinder.setProjectFiles(startParameters().projectSourceFiles);
723 return d->fileFinder.findFile(fileUrl);
726 void QmlEngine::inferiorSpontaneousStop()
728 if (state() == InferiorRunOk)
729 notifyInferiorSpontaneousStop();
732 void QmlEngine::disconnected()
734 showMessage(tr("QML Debugger disconnected."), StatusBar);
735 notifyInferiorExited();
738 void QmlEngine::wrongSetupMessageBoxFinished(int result)
740 if (result == QMessageBox::Help) {
741 Core::HelpManager *helpManager = Core::HelpManager::instance();
742 helpManager->handleHelpRequest(
743 QLatin1String("qthelp://com.nokia.qtcreator/doc/creator-debugging-qml.html"));
747 void QmlEngine::executeDebuggerCommand(const QString& command)
749 logMessage(LogSend, QString("%1 %2 %3").arg(QString("EXEC"), QString("console"),
751 d->m_adapter.activeDebuggerClient()->executeDebuggerCommand(command);
755 QString QmlEngine::qmlImportPath() const
757 return startParameters().environment.value("QML_IMPORT_PATH");
760 void QmlEngine::logMessage(LogDirection direction, const QString &message)
762 QString msg = "QmlDebugger";
763 if (direction == LogSend) {
766 msg += " receiving ";
769 showMessage(msg, LogDebug);
772 QmlEngine *createQmlEngine(const DebuggerStartParameters &sp,
773 DebuggerEngine *masterEngine)
775 return new QmlEngine(sp, masterEngine);
778 } // namespace Internal
779 } // namespace Debugger