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 qt-info@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/abstractprocess.h>
58 #include <utils/qtcassert.h>
59 #include <utils/fileinprojectfinder.h>
61 #include <coreplugin/icore.h>
62 #include <coreplugin/helpmanager.h>
64 #include <QtCore/QDateTime>
65 #include <QtCore/QDebug>
66 #include <QtCore/QDir>
67 #include <QtCore/QFileInfo>
68 #include <QtCore/QTimer>
70 #include <QtGui/QAction>
71 #include <QtGui/QApplication>
72 #include <QtGui/QMainWindow>
73 #include <QtGui/QMessageBox>
74 #include <QtGui/QToolTip>
75 #include <QtGui/QTextDocument>
77 #include <QtNetwork/QTcpSocket>
78 #include <QtNetwork/QHostAddress>
82 # define SDEBUG(s) qDebug() << s
86 # define XSDEBUG(s) qDebug() << s
88 using namespace ProjectExplorer;
93 struct JSAgentBreakpointData
95 QByteArray functionName;
100 struct JSAgentStackData
102 QByteArray functionName;
107 uint qHash(const JSAgentBreakpointData &b)
109 return b.lineNumber ^ qHash(b.fileUrl);
112 QDataStream &operator<<(QDataStream &s, const JSAgentBreakpointData &data)
114 return s << data.functionName << data.fileUrl << data.lineNumber;
117 QDataStream &operator<<(QDataStream &s, const JSAgentStackData &data)
119 return s << data.functionName << data.fileUrl << data.lineNumber;
122 QDataStream &operator>>(QDataStream &s, JSAgentBreakpointData &data)
124 return s >> data.functionName >> data.fileUrl >> data.lineNumber;
127 QDataStream &operator>>(QDataStream &s, JSAgentStackData &data)
129 return s >> data.functionName >> data.fileUrl >> data.lineNumber;
132 bool operator==(const JSAgentBreakpointData &b1, const JSAgentBreakpointData &b2)
134 return b1.lineNumber == b2.lineNumber && b1.fileUrl == b2.fileUrl;
137 typedef QSet<JSAgentBreakpointData> JSAgentBreakpoints;
138 typedef QList<JSAgentStackData> JSAgentStackFrames;
141 static QDataStream &operator>>(QDataStream &s, WatchData &data)
147 bool hasChildren = false;
148 s >> data.exp >> name >> value >> type >> hasChildren >> data.id;
149 data.name = QString::fromUtf8(name);
150 data.setType(type, false);
151 data.setValue(QString::fromUtf8(value));
152 data.setHasChildren(hasChildren);
153 data.setAllUnneeded();
157 class QmlEnginePrivate
160 explicit QmlEnginePrivate(QmlEngine *q);
163 friend class QmlEngine;
165 QmlAdapter m_adapter;
166 ApplicationLauncher m_applicationLauncher;
167 Utils::FileInProjectFinder fileFinder;
170 QmlEnginePrivate::QmlEnginePrivate(QmlEngine *q)
171 : m_ping(0), m_adapter(q)
175 ///////////////////////////////////////////////////////////////////////
179 ///////////////////////////////////////////////////////////////////////
181 QmlEngine::QmlEngine(const DebuggerStartParameters &startParameters,
182 DebuggerEngine *masterEngine)
183 : DebuggerEngine(startParameters, masterEngine),
184 d(new QmlEnginePrivate(this))
186 setObjectName(QLatin1String("QmlEngine"));
189 QmlEngine::~QmlEngine()
192 void QmlEngine::setupInferior()
194 QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
196 if (startParameters().startMode == AttachToRemote) {
197 emit requestRemoteSetup();
199 connect(&d->m_applicationLauncher,
200 SIGNAL(processExited(int)),
201 SLOT(disconnected()));
202 connect(&d->m_applicationLauncher,
203 SIGNAL(appendMessage(QString,ProjectExplorer::OutputFormat)),
204 SLOT(appendMessage(QString,ProjectExplorer::OutputFormat)));
205 connect(&d->m_applicationLauncher,
206 SIGNAL(bringToForegroundRequested(qint64)),
208 SLOT(bringApplicationToForeground(qint64)));
210 d->m_applicationLauncher.setEnvironment(startParameters().environment);
211 d->m_applicationLauncher.setWorkingDirectory(startParameters().workingDirectory);
213 notifyInferiorSetupOk();
217 void QmlEngine::appendMessage(const QString &msg, OutputFormat /* format */)
219 showMessage(msg, AppOutput); // FIXME: Redirect to RunControl
222 void QmlEngine::connectionEstablished()
224 attemptBreakpointSynchronization();
226 ExtensionSystem::PluginManager *pluginManager =
227 ExtensionSystem::PluginManager::instance();
228 pluginManager->addObject(&d->m_adapter);
229 pluginManager->addObject(this);
231 showMessage(tr("QML Debugger connected."), StatusBar);
233 synchronizeWatchers();
235 notifyEngineRunAndInferiorRunOk();
239 void QmlEngine::connectionStartupFailed()
241 Core::ICore * const core = Core::ICore::instance();
242 QMessageBox *infoBox = new QMessageBox(core->mainWindow());
243 infoBox->setIcon(QMessageBox::Critical);
244 infoBox->setWindowTitle(tr("Qt Creator"));
245 infoBox->setText(tr("Could not connect to the in-process QML debugger.\n"
246 "Do you want to retry?"));
247 infoBox->setStandardButtons(QMessageBox::Retry | QMessageBox::Cancel | QMessageBox::Help);
248 infoBox->setDefaultButton(QMessageBox::Retry);
249 infoBox->setModal(true);
251 connect(infoBox, SIGNAL(finished(int)),
252 this, SLOT(retryMessageBoxFinished(int)));
257 void QmlEngine::retryMessageBoxFinished(int result)
260 case QMessageBox::Retry: {
261 d->m_adapter.beginConnection();
264 case QMessageBox::Help: {
265 Core::HelpManager *helpManager = Core::HelpManager::instance();
266 helpManager->handleHelpRequest("qthelp://com.nokia.qtcreator/doc/creator-debugging-qml.html");
270 notifyEngineRunFailed();
275 void QmlEngine::connectionError(QAbstractSocket::SocketError socketError)
277 if (socketError == QAbstractSocket::RemoteHostClosedError)
278 showMessage(tr("QML Debugger: Remote host closed connection."), StatusBar);
281 void QmlEngine::serviceConnectionError(const QString &serviceName)
283 showMessage(tr("QML Debugger: Could not connect to service '%1'.")
284 .arg(serviceName), StatusBar);
287 bool QmlEngine::canDisplayTooltip() const
289 return state() == InferiorRunOk || state() == InferiorStopOk;
292 void QmlEngine::filterApplicationMessage(const QString &msg, int /*channel*/)
294 static const QString qddserver = QLatin1String("QDeclarativeDebugServer: ");
295 static const QString cannotRetrieveDebuggingOutput = Utils::AbstractProcess::msgWinCannotRetrieveDebuggingOutput();
297 const int index = msg.indexOf(qddserver);
299 QString status = msg;
300 status.remove(0, index + qddserver.length()); // chop of 'QDeclarativeDebugServer: '
302 static QString waitingForConnection = QLatin1String("Waiting for connection on port");
303 static QString unableToListen = QLatin1String("Unable to listen on port");
304 static QString debuggingNotEnabled = QLatin1String("Ignoring \"-qmljsdebugger=port:");
305 static QString connectionEstablished = QLatin1String("Connection established");
307 QString errorMessage;
308 if (status.startsWith(waitingForConnection)) {
309 d->m_adapter.beginConnection();
310 } else if (status.startsWith(unableToListen)) {
311 //: Error message shown after 'Could not connect ... debugger:"
312 errorMessage = tr("The port seems to be in use.");
313 } else if (status.startsWith(debuggingNotEnabled)) {
314 //: Error message shown after 'Could not connect ... debugger:"
315 errorMessage = tr("The application is not set up for QML/JS debugging.");
316 } else if (status.startsWith(connectionEstablished)) {
319 qWarning() << "Unknown QDeclarativeDebugServer status message: " << status;
322 if (!errorMessage.isEmpty()) {
323 notifyEngineRunFailed();
325 Core::ICore * const core = Core::ICore::instance();
326 QMessageBox *infoBox = new QMessageBox(core->mainWindow());
327 infoBox->setIcon(QMessageBox::Critical);
328 infoBox->setWindowTitle(tr("Qt Creator"));
329 //: %1 is detailed error message
330 infoBox->setText(tr("Could not connect to the in-process QML debugger:\n%1")
332 infoBox->setStandardButtons(QMessageBox::Ok | QMessageBox::Help);
333 infoBox->setDefaultButton(QMessageBox::Ok);
334 infoBox->setModal(true);
336 connect(infoBox, SIGNAL(finished(int)),
337 this, SLOT(wrongSetupMessageBoxFinished(int)));
341 } else if (msg.contains(cannotRetrieveDebuggingOutput)) {
342 // we won't get debugging output, so just try to connect ...
343 d->m_adapter.beginConnection();
347 void QmlEngine::showMessage(const QString &msg, int channel, int timeout) const
349 if (channel == AppOutput || channel == AppError) {
350 const_cast<QmlEngine*>(this)->filterApplicationMessage(msg, channel);
352 DebuggerEngine::showMessage(msg, channel, timeout);
355 bool QmlEngine::acceptsWatchesWhileRunning() const
360 void QmlEngine::closeConnection()
362 disconnect(&d->m_adapter, SIGNAL(connectionStartupFailed()),
363 this, SLOT(connectionStartupFailed()));
364 d->m_adapter.closeConnection();
366 ExtensionSystem::PluginManager *pluginManager =
367 ExtensionSystem::PluginManager::instance();
369 if (pluginManager->allObjects().contains(this)) {
370 pluginManager->removeObject(&d->m_adapter);
371 pluginManager->removeObject(this);
375 void QmlEngine::runEngine()
377 QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());
379 if (!isSlaveEngine())
380 startApplicationLauncher();
383 void QmlEngine::startApplicationLauncher()
385 if (!d->m_applicationLauncher.isRunning()) {
386 appendMessage(tr("Starting %1 %2").arg(
387 QDir::toNativeSeparators(startParameters().executable),
388 startParameters().processArgs)
390 , NormalMessageFormat);
391 d->m_applicationLauncher.start(ApplicationLauncher::Gui,
392 startParameters().executable,
393 startParameters().processArgs);
397 void QmlEngine::stopApplicationLauncher()
399 if (d->m_applicationLauncher.isRunning()) {
400 disconnect(&d->m_applicationLauncher, SIGNAL(processExited(int)), this, SLOT(disconnected()));
401 d->m_applicationLauncher.stop();
405 void QmlEngine::handleRemoteSetupDone(int gdbServerPort, int qmlPort)
407 Q_UNUSED(gdbServerPort);
409 startParameters().qmlServerPort = qmlPort;
410 notifyInferiorSetupOk();
413 void QmlEngine::handleRemoteSetupFailed(const QString &message)
415 QMessageBox::critical(0,tr("Failed to start application"),
416 tr("Application startup failed: %1").arg(message));
417 notifyInferiorSetupFailed();
420 void QmlEngine::shutdownInferior()
422 if (isSlaveEngine()) {
425 stopApplicationLauncher();
426 notifyInferiorShutdownOk();
429 void QmlEngine::shutdownEngine()
433 // double check (ill engine?):
434 stopApplicationLauncher();
436 notifyEngineShutdownOk();
437 if (!isSlaveEngine())
438 showMessage(QString(), StatusBar);
441 void QmlEngine::setupEngine()
444 connect(&d->m_adapter, SIGNAL(connectionError(QAbstractSocket::SocketError)),
445 SLOT(connectionError(QAbstractSocket::SocketError)));
446 connect(&d->m_adapter, SIGNAL(serviceConnectionError(QString)),
447 SLOT(serviceConnectionError(QString)));
448 connect(&d->m_adapter, SIGNAL(connected()),
449 SLOT(connectionEstablished()));
450 connect(&d->m_adapter, SIGNAL(connectionStartupFailed()),
451 SLOT(connectionStartupFailed()));
453 notifyEngineSetupOk();
456 void QmlEngine::continueInferior()
458 QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
460 QDataStream rs(&reply, QIODevice::WriteOnly);
461 QByteArray cmd = "CONTINUE";
463 logMessage(LogSend, cmd);
466 notifyInferiorRunRequested();
467 notifyInferiorRunOk();
470 void QmlEngine::interruptInferior()
473 QDataStream rs(&reply, QIODevice::WriteOnly);
474 QByteArray cmd = "INTERRUPT";
476 logMessage(LogSend, cmd);
478 notifyInferiorStopOk();
481 void QmlEngine::executeStep()
484 QDataStream rs(&reply, QIODevice::WriteOnly);
485 QByteArray cmd = "STEPINTO";
487 logMessage(LogSend, cmd);
489 notifyInferiorRunRequested();
490 notifyInferiorRunOk();
493 void QmlEngine::executeStepI()
496 QDataStream rs(&reply, QIODevice::WriteOnly);
497 QByteArray cmd = "STEPINTO";
499 logMessage(LogSend, cmd);
501 notifyInferiorRunRequested();
502 notifyInferiorRunOk();
505 void QmlEngine::executeStepOut()
508 QDataStream rs(&reply, QIODevice::WriteOnly);
509 QByteArray cmd = "STEPOUT";
511 logMessage(LogSend, cmd);
513 notifyInferiorRunRequested();
514 notifyInferiorRunOk();
517 void QmlEngine::executeNext()
520 QDataStream rs(&reply, QIODevice::WriteOnly);
521 QByteArray cmd = "STEPOVER";
523 logMessage(LogSend, cmd);
525 notifyInferiorRunRequested();
526 notifyInferiorRunOk();
529 void QmlEngine::executeNextI()
531 SDEBUG("QmlEngine::executeNextI()");
534 void QmlEngine::executeRunToLine(const ContextData &data)
537 SDEBUG("FIXME: QmlEngine::executeRunToLine()");
540 void QmlEngine::executeRunToFunction(const QString &functionName)
542 Q_UNUSED(functionName)
543 XSDEBUG("FIXME: QmlEngine::executeRunToFunction()");
546 void QmlEngine::executeJumpToLine(const ContextData &data)
549 XSDEBUG("FIXME: QmlEngine::executeJumpToLine()");
552 void QmlEngine::activateFrame(int index)
555 QDataStream rs(&reply, QIODevice::WriteOnly);
556 QByteArray cmd = "ACTIVATE_FRAME";
559 logMessage(LogSend, QString("%1 %2").arg(QString(cmd), QString::number(index)));
561 gotoLocation(stackHandler()->frames().value(index));
564 void QmlEngine::selectThread(int index)
569 void QmlEngine::attemptBreakpointSynchronization()
571 BreakHandler *handler = breakHandler();
573 foreach (BreakpointId id, handler->unclaimedBreakpointIds()) {
574 // Take ownership of the breakpoint. Requests insertion.
575 if (acceptsBreakpoint(id))
576 handler->setEngine(id, this);
579 JSAgentBreakpoints breakpoints;
580 foreach (BreakpointId id, handler->engineBreakpointIds(this)) {
581 if (handler->state(id) == BreakpointRemoveRequested) {
582 handler->notifyBreakpointRemoveProceeding(id);
583 handler->notifyBreakpointRemoveOk(id);
585 if (handler->state(id) == BreakpointInsertRequested) {
586 handler->notifyBreakpointInsertProceeding(id);
588 JSAgentBreakpointData bp;
589 bp.fileUrl = QUrl::fromLocalFile(handler->fileName(id)).toString().toUtf8();
590 bp.lineNumber = handler->lineNumber(id);
591 bp.functionName = handler->functionName(id).toUtf8();
592 breakpoints.insert(bp);
593 if (handler->state(id) == BreakpointInsertProceeding) {
594 handler->notifyBreakpointInsertOk(id);
600 QDataStream rs(&reply, QIODevice::WriteOnly);
601 QByteArray cmd = "BREAKPOINTS";
605 QStringList breakPointsStr;
606 foreach (const JSAgentBreakpointData &bp, breakpoints) {
607 breakPointsStr << QString("('%1' '%2' %3)").arg(QString(bp.functionName),
608 QString(bp.fileUrl), QString::number(bp.lineNumber));
610 logMessage(LogSend, QString("%1 [%2]").arg(QString(cmd), breakPointsStr.join(", ")));
615 bool QmlEngine::acceptsBreakpoint(BreakpointId id) const
617 return !DebuggerEngine::isCppBreakpoint(breakHandler()->breakpointData(id));
620 void QmlEngine::loadSymbols(const QString &moduleName)
625 void QmlEngine::loadAllSymbols()
629 void QmlEngine::reloadModules()
633 void QmlEngine::requestModuleSymbols(const QString &moduleName)
638 //////////////////////////////////////////////////////////////////////
640 // Tooltip specific stuff
642 //////////////////////////////////////////////////////////////////////
644 bool QmlEngine::setToolTipExpression(const QPoint &mousePos,
645 TextEditor::ITextEditor *editor, const DebuggerToolTipContext &ctx)
647 // This is processed by QML inspector, which has dependencies to
648 // the qml js editor. Makes life easier.
649 emit tooltipRequested(mousePos, editor, ctx.position);
653 //////////////////////////////////////////////////////////////////////
655 // Watch specific stuff
657 //////////////////////////////////////////////////////////////////////
659 void QmlEngine::assignValueInDebugger(const WatchData *,
660 const QString &expression, const QVariant &valueV)
662 QRegExp inObject("@([0-9a-fA-F]+)->(.+)");
663 if (inObject.exactMatch(expression)) {
665 quint64 objectId = inObject.cap(1).toULongLong(&ok, 16);
666 QString property = inObject.cap(2);
667 if (ok && objectId > 0 && !property.isEmpty()) {
669 QDataStream rs(&reply, QIODevice::WriteOnly);
670 QByteArray cmd = "SET_PROPERTY";
672 rs << expression.toUtf8() << objectId << property << valueV.toString();
673 logMessage(LogSend, QString("%1 %2 %3 %4 %5").arg(
674 QString(cmd), QString::number(objectId), QString(property),
681 void QmlEngine::updateWatchData(const WatchData &data,
682 const WatchUpdateFlags &)
684 // qDebug() << "UPDATE WATCH DATA" << data.toString();
685 //watchHandler()->rebuildModel();
686 showStatusMessage(tr("Stopped."), 5000);
688 if (!data.name.isEmpty() && data.isValueNeeded()) {
690 QDataStream rs(&reply, QIODevice::WriteOnly);
691 QByteArray cmd = "EXEC";
693 rs << data.iname << data.name;
694 logMessage(LogSend, QString("%1 %2 %3").arg(QString(cmd), QString(data.iname),
695 QString(data.name)));
699 if (!data.name.isEmpty() && data.isChildrenNeeded()
700 && watchHandler()->isExpandedIName(data.iname)) {
701 expandObject(data.iname, data.id);
704 synchronizeWatchers();
706 if (!data.isSomethingNeeded())
707 watchHandler()->insertData(data);
710 void QmlEngine::synchronizeWatchers()
712 if (!watchHandler()->watcherNames().isEmpty()) {
713 // send watchers list
715 QDataStream rs(&reply, QIODevice::WriteOnly);
716 QByteArray cmd = "WATCH_EXPRESSIONS";
718 rs << watchHandler()->watchedExpressions();
719 logMessage(LogSend, QString("%1 %2").arg(
720 QString(cmd), watchHandler()->watchedExpressions().join(", ")));
725 void QmlEngine::expandObject(const QByteArray &iname, quint64 objectId)
728 QDataStream rs(&reply, QIODevice::WriteOnly);
729 QByteArray cmd = "EXPAND";
731 rs << iname << objectId;
732 logMessage(LogSend, QString("%1 %2 %3").arg(QString(cmd), QString(iname),
733 QString::number(objectId)));
737 void QmlEngine::sendPing()
741 QDataStream rs(&reply, QIODevice::WriteOnly);
742 QByteArray cmd = "PING";
745 logMessage(LogSend, QString("%1 %2").arg(QString(cmd), QString::number(d->m_ping)));
749 unsigned QmlEngine::debuggerCapabilities() const
751 return AddWatcherCapability;
752 /*ReverseSteppingCapability | SnapshotCapability
753 | AutoDerefPointersCapability | DisassemblerCapability
754 | RegisterCapability | ShowMemoryCapability
755 | JumpToLineCapability | ReloadModuleCapability
756 | ReloadModuleSymbolsCapability | BreakOnThrowAndCatchCapability
757 | ReturnFromFunctionCapability
758 | CreateFullBacktraceCapability
759 | WatchpointCapability
760 | AddWatcherCapability;*/
763 QString QmlEngine::toFileInProject(const QString &fileUrl)
765 if (fileUrl.isEmpty())
768 const QString path = QUrl(fileUrl).toLocalFile();
772 // Try to find shadow-build file in source dir first
773 if (isShadowBuildProject()) {
774 const QString sourcePath = fromShadowBuildFilename(path);
775 if (QFileInfo(sourcePath).exists())
779 // Try whether file is absolute & exists
780 if (QFileInfo(path).isAbsolute()
781 && QFileInfo(path).exists()) {
785 if (d->fileFinder.projectDirectory().isEmpty())
786 d->fileFinder.setProjectDirectory(startParameters().projectDir);
788 // Try to find file with biggest common path in source directory
789 bool fileFound = false;
790 QString fileInProject = d->fileFinder.findFile(path, &fileFound);
792 return fileInProject;
796 void QmlEngine::messageReceived(const QByteArray &message)
798 QByteArray rwData = message;
799 QDataStream stream(&rwData, QIODevice::ReadOnly);
804 if (command == "STOPPED") {
805 //qDebug() << command << this << state();
806 if (state() == InferiorRunOk)
807 notifyInferiorSpontaneousStop();
809 QString logString = QString::fromLatin1(command);
811 JSAgentStackFrames stackFrames;
812 QList<WatchData> watches;
813 QList<WatchData> locals;
814 stream >> stackFrames >> watches >> locals;
816 logString += QString::fromLatin1(" (%1 stack frames) (%2 watches) (%3 locals)").
817 arg(stackFrames.size()).arg(watches.size()).arg(locals.size());
819 StackFrames ideStackFrames;
820 for (int i = 0; i != stackFrames.size(); ++i) {
822 frame.line = stackFrames.at(i).lineNumber;
823 frame.function = stackFrames.at(i).functionName;
824 frame.file = toFileInProject(stackFrames.at(i).fileUrl);
825 frame.usable = QFileInfo(frame.file).isReadable();
827 ideStackFrames << frame;
830 if (ideStackFrames.size() && ideStackFrames.back().function == "<global>")
831 ideStackFrames.takeLast();
832 stackHandler()->setFrames(ideStackFrames);
834 watchHandler()->beginCycle();
835 bool needPing = false;
837 foreach (WatchData data, watches) {
838 data.iname = watchHandler()->watcherName(data.exp);
839 watchHandler()->insertData(data);
841 if (watchHandler()->expandedINames().contains(data.iname)) {
843 expandObject(data.iname, data.id);
847 foreach (WatchData data, locals) {
848 data.iname = "local." + data.exp;
849 watchHandler()->insertData(data);
851 if (watchHandler()->expandedINames().contains(data.iname)) {
853 expandObject(data.iname, data.id);
860 watchHandler()->endCycle();
863 bool becauseOfException;
864 stream >> becauseOfException;
866 logString += becauseOfException ? " exception" : " no_exception";
868 if (becauseOfException) {
872 logString += QLatin1Char(' ');
874 logMessage(LogReceive, logString);
876 QString msg = stackFrames.isEmpty()
877 ? tr("<p>An uncaught exception occurred:</p><p>%1</p>")
878 .arg(Qt::escape(error))
879 : tr("<p>An uncaught exception occurred in <i>%1</i>:</p><p>%2</p>")
880 .arg(stackFrames.value(0).fileUrl, Qt::escape(error));
881 showMessageBox(QMessageBox::Information, tr("Uncaught Exception"), msg);
884 // Make breakpoint non-pending
890 if (!ideStackFrames.isEmpty()) {
891 file = ideStackFrames.at(0).file;
892 line = ideStackFrames.at(0).line;
893 function = ideStackFrames.at(0).function;
896 BreakHandler *handler = breakHandler();
897 foreach (BreakpointId id, handler->engineBreakpointIds(this)) {
898 QString processedFilename = handler->fileName(id);
899 if (processedFilename == file && handler->lineNumber(id) == line) {
900 QTC_ASSERT(handler->state(id) == BreakpointInserted,/**/);
901 BreakpointResponse br = handler->response(id);
903 br.lineNumber = line;
904 br.functionName = function;
905 handler->setResponse(id, br);
909 logMessage(LogReceive, logString);
912 if (!ideStackFrames.isEmpty())
913 gotoLocation(ideStackFrames.value(0));
915 } else if (command == "RESULT") {
918 stream >> iname >> data;
920 logMessage(LogReceive, QString("%1 %2 %3").arg(QString(command),
921 QString(iname), QString(data.value)));
923 if (iname.startsWith("watch.")) {
924 watchHandler()->insertData(data);
925 } else if(iname == "console") {
926 showMessage(data.value, ScriptConsoleOutput);
928 qWarning() << "QmlEngine: Unexcpected result: " << iname << data.value;
930 } else if (command == "EXPANDED") {
931 QList<WatchData> result;
933 stream >> iname >> result;
935 logMessage(LogReceive, QString("%1 %2 (%3 x watchdata)").arg(
936 QString(command), QString(iname), QString::number(result.size())));
937 bool needPing = false;
938 foreach (WatchData data, result) {
939 data.iname = iname + '.' + data.exp;
940 watchHandler()->insertData(data);
942 if (watchHandler()->expandedINames().contains(data.iname)) {
944 expandObject(data.iname, data.id);
949 } else if (command == "LOCALS") {
950 QList<WatchData> locals;
952 stream >> frameId >> locals;
954 logMessage(LogReceive, QString("%1 %2 (%3 x locals)").arg(
955 QString(command), QString::number(frameId),
956 QString::number(locals.size())));
957 watchHandler()->beginCycle();
958 bool needPing = false;
959 foreach (WatchData data, locals) {
960 data.iname = "local." + data.exp;
961 watchHandler()->insertData(data);
962 if (watchHandler()->expandedINames().contains(data.iname)) {
964 expandObject(data.iname, data.id);
970 watchHandler()->endCycle();
972 } else if (command == "PONG") {
976 logMessage(LogReceive, QString("%1 %2").arg(QString(command), QString::number(ping)));
978 if (ping == d->m_ping)
979 watchHandler()->endCycle();
981 qDebug() << Q_FUNC_INFO << "Unknown command: " << command;
982 logMessage(LogReceive, QString("%1 UNKNOWN COMMAND!!").arg(QString(command)));
986 void QmlEngine::disconnected()
988 showMessage(tr("QML Debugger disconnected."), StatusBar);
989 notifyInferiorExited();
992 void QmlEngine::wrongSetupMessageBoxFinished(int result)
994 if (result == QMessageBox::Help) {
995 Core::HelpManager *helpManager = Core::HelpManager::instance();
996 helpManager->handleHelpRequest(
997 QLatin1String("qthelp://com.nokia.qtcreator/doc/creator-debugging-qml.html"));
1001 void QmlEngine::executeDebuggerCommand(const QString& command)
1004 QDataStream rs(&reply, QIODevice::WriteOnly);
1005 QByteArray cmd = "EXEC";
1006 QByteArray console = "console";
1007 rs << cmd << console << command;
1008 logMessage(LogSend, QString("%1 %2 %3").arg(QString(cmd), QString(console),
1013 bool QmlEngine::isShadowBuildProject() const
1015 return !startParameters().projectBuildDir.isEmpty()
1016 && startParameters().projectDir != startParameters().projectBuildDir;
1019 QString QmlEngine::qmlImportPath() const
1021 return startParameters().environment.value("QML_IMPORT_PATH");
1024 QString QmlEngine::mangleFilenamePaths(const QString &filename,
1025 const QString &oldBasePath, const QString &newBasePath) const
1027 QDir oldBaseDir(oldBasePath);
1028 QDir newBaseDir(newBasePath);
1029 QFileInfo fileInfo(filename);
1031 if (oldBaseDir.exists() && newBaseDir.exists() && fileInfo.exists()) {
1032 if (fileInfo.absoluteFilePath().startsWith(oldBaseDir.canonicalPath())) {
1033 QString fileRelativePath = fileInfo.canonicalFilePath().mid(oldBaseDir.canonicalPath().length());
1034 QFileInfo projectFile(newBaseDir.canonicalPath() + QLatin1Char('/') + fileRelativePath);
1036 if (projectFile.exists())
1037 return projectFile.canonicalFilePath();
1043 QString QmlEngine::fromShadowBuildFilename(const QString &filename) const
1045 QString newFilename = filename;
1046 QString importPath = qmlImportPath();
1049 // Qt Quick Applications by default copy the qml directory
1050 // to buildDir()/X.app/Contents/Resources.
1051 const QString applicationBundleDir
1052 = QFileInfo(startParameters().executable).absolutePath() + "/../..";
1053 newFilename = mangleFilenamePaths(newFilename, applicationBundleDir + "/Contents/Resources", startParameters().projectDir);
1055 newFilename = mangleFilenamePaths(newFilename, startParameters().projectBuildDir, startParameters().projectDir);
1057 if (newFilename == filename && !importPath.isEmpty()) {
1058 newFilename = mangleFilenamePaths(filename, startParameters().projectBuildDir, importPath);
1064 void QmlEngine::logMessage(LogDirection direction, const QString &message)
1066 QString msg = "JSDebugger";
1067 if (direction == LogSend) {
1070 msg += " receiving ";
1073 showMessage(msg, LogDebug);
1076 QmlEngine *createQmlEngine(const DebuggerStartParameters &sp,
1077 DebuggerEngine *masterEngine)
1079 return new QmlEngine(sp, masterEngine);
1082 } // namespace Internal
1083 } // namespace Debugger