OSDN Git Service

Update license.
[qt-creator-jp/qt-creator-jp.git] / src / plugins / debugger / qml / qmlengine.cpp
1 /**************************************************************************
2 **
3 ** This file is part of Qt Creator
4 **
5 ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
6 **
7 ** Contact: Nokia Corporation (info@qt.nokia.com)
8 **
9 **
10 ** GNU Lesser General Public License Usage
11 **
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.
18 **
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.
22 **
23 ** Other Usage
24 **
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.
27 **
28 ** If you have questions regarding the use of this file, please contact
29 ** Nokia at qt-info@nokia.com.
30 **
31 **************************************************************************/
32
33 #include "qmlengine.h"
34 #include "qmladapter.h"
35
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"
45
46 #include "breakhandler.h"
47 #include "moduleshandler.h"
48 #include "registerhandler.h"
49 #include "stackhandler.h"
50 #include "watchhandler.h"
51 #include "watchutils.h"
52
53 #include <extensionsystem/pluginmanager.h>
54 #include <projectexplorer/applicationlauncher.h>
55
56 #include <utils/environment.h>
57 #include <utils/abstractprocess.h>
58 #include <utils/qtcassert.h>
59 #include <utils/fileinprojectfinder.h>
60
61 #include <coreplugin/icore.h>
62 #include <coreplugin/helpmanager.h>
63
64 #include <QtCore/QDateTime>
65 #include <QtCore/QDebug>
66 #include <QtCore/QDir>
67 #include <QtCore/QFileInfo>
68 #include <QtCore/QTimer>
69
70 #include <QtGui/QAction>
71 #include <QtGui/QApplication>
72 #include <QtGui/QMainWindow>
73 #include <QtGui/QMessageBox>
74 #include <QtGui/QToolTip>
75 #include <QtGui/QTextDocument>
76
77 #include <QtNetwork/QTcpSocket>
78 #include <QtNetwork/QHostAddress>
79
80 #define DEBUG_QML 1
81 #if DEBUG_QML
82 #   define SDEBUG(s) qDebug() << s
83 #else
84 #   define SDEBUG(s)
85 #endif
86 # define XSDEBUG(s) qDebug() << s
87
88 using namespace ProjectExplorer;
89
90 namespace Debugger {
91 namespace Internal {
92
93 struct JSAgentBreakpointData
94 {
95     QByteArray functionName;
96     QByteArray fileUrl;
97     qint32 lineNumber;
98 };
99
100 struct JSAgentStackData
101 {
102     QByteArray functionName;
103     QByteArray fileUrl;
104     qint32 lineNumber;
105 };
106
107 uint qHash(const JSAgentBreakpointData &b)
108 {
109     return b.lineNumber ^ qHash(b.fileUrl);
110 }
111
112 QDataStream &operator<<(QDataStream &s, const JSAgentBreakpointData &data)
113 {
114     return s << data.functionName << data.fileUrl << data.lineNumber;
115 }
116
117 QDataStream &operator<<(QDataStream &s, const JSAgentStackData &data)
118 {
119     return s << data.functionName << data.fileUrl << data.lineNumber;
120 }
121
122 QDataStream &operator>>(QDataStream &s, JSAgentBreakpointData &data)
123 {
124     return s >> data.functionName >> data.fileUrl >> data.lineNumber;
125 }
126
127 QDataStream &operator>>(QDataStream &s, JSAgentStackData &data)
128 {
129     return s >> data.functionName >> data.fileUrl >> data.lineNumber;
130 }
131
132 bool operator==(const JSAgentBreakpointData &b1, const JSAgentBreakpointData &b2)
133 {
134     return b1.lineNumber == b2.lineNumber && b1.fileUrl == b2.fileUrl;
135 }
136
137 typedef QSet<JSAgentBreakpointData> JSAgentBreakpoints;
138 typedef QList<JSAgentStackData> JSAgentStackFrames;
139
140
141 static QDataStream &operator>>(QDataStream &s, WatchData &data)
142 {
143     data = WatchData();
144     QByteArray name;
145     QByteArray value;
146     QByteArray type;
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();
154     return s;
155 }
156
157 class QmlEnginePrivate
158 {
159 public:
160     explicit QmlEnginePrivate(QmlEngine *q);
161
162 private:
163     friend class QmlEngine;
164     int m_ping;
165     QmlAdapter m_adapter;
166     ApplicationLauncher m_applicationLauncher;
167     Utils::FileInProjectFinder fileFinder;
168 };
169
170 QmlEnginePrivate::QmlEnginePrivate(QmlEngine *q)
171     : m_ping(0), m_adapter(q)
172 {}
173
174
175 ///////////////////////////////////////////////////////////////////////
176 //
177 // QmlEngine
178 //
179 ///////////////////////////////////////////////////////////////////////
180
181 QmlEngine::QmlEngine(const DebuggerStartParameters &startParameters,
182         DebuggerEngine *masterEngine)
183   : DebuggerEngine(startParameters, masterEngine),
184     d(new QmlEnginePrivate(this))
185 {
186     setObjectName(QLatin1String("QmlEngine"));
187 }
188
189 QmlEngine::~QmlEngine()
190 {}
191
192 void QmlEngine::setupInferior()
193 {
194     QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
195
196     if (startParameters().startMode == AttachToRemote) {
197         emit requestRemoteSetup();
198     } else {
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)),
207             runControl(),
208             SLOT(bringApplicationToForeground(qint64)));
209
210         d->m_applicationLauncher.setEnvironment(startParameters().environment);
211         d->m_applicationLauncher.setWorkingDirectory(startParameters().workingDirectory);
212
213         notifyInferiorSetupOk();
214     }
215 }
216
217 void QmlEngine::appendMessage(const QString &msg, OutputFormat /* format */)
218 {
219     showMessage(msg, AppOutput); // FIXME: Redirect to RunControl
220 }
221
222 void QmlEngine::connectionEstablished()
223 {
224     attemptBreakpointSynchronization();
225
226     ExtensionSystem::PluginManager *pluginManager =
227         ExtensionSystem::PluginManager::instance();
228     pluginManager->addObject(&d->m_adapter);
229     pluginManager->addObject(this);
230
231     showMessage(tr("QML Debugger connected."), StatusBar);
232
233     synchronizeWatchers();
234
235     notifyEngineRunAndInferiorRunOk();
236
237 }
238
239 void QmlEngine::connectionStartupFailed()
240 {
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);
250
251     connect(infoBox, SIGNAL(finished(int)),
252             this, SLOT(retryMessageBoxFinished(int)));
253
254     infoBox->show();
255 }
256
257 void QmlEngine::retryMessageBoxFinished(int result)
258 {
259     switch (result) {
260     case QMessageBox::Retry: {
261         d->m_adapter.beginConnection();
262         break;
263     }
264     case QMessageBox::Help: {
265         Core::HelpManager *helpManager = Core::HelpManager::instance();
266         helpManager->handleHelpRequest("qthelp://com.nokia.qtcreator/doc/creator-debugging-qml.html");
267         // fall through
268     }
269     default:
270         notifyEngineRunFailed();
271         break;
272     }
273 }
274
275 void QmlEngine::connectionError(QAbstractSocket::SocketError socketError)
276 {
277     if (socketError == QAbstractSocket::RemoteHostClosedError)
278         showMessage(tr("QML Debugger: Remote host closed connection."), StatusBar);
279 }
280
281 void QmlEngine::serviceConnectionError(const QString &serviceName)
282 {
283     showMessage(tr("QML Debugger: Could not connect to service '%1'.")
284         .arg(serviceName), StatusBar);
285 }
286
287 bool QmlEngine::canDisplayTooltip() const
288 {
289     return state() == InferiorRunOk || state() == InferiorStopOk;
290 }
291
292 void QmlEngine::filterApplicationMessage(const QString &msg, int /*channel*/)
293 {
294     static const QString qddserver = QLatin1String("QDeclarativeDebugServer: ");
295     static const QString cannotRetrieveDebuggingOutput = Utils::AbstractProcess::msgWinCannotRetrieveDebuggingOutput();
296
297     const int index = msg.indexOf(qddserver);
298     if (index != -1) {
299         QString status = msg;
300         status.remove(0, index + qddserver.length()); // chop of 'QDeclarativeDebugServer: '
301
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");
306
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)) {
317             // nothing to do
318         } else {
319             qWarning() << "Unknown QDeclarativeDebugServer status message: " << status;
320         }
321
322         if (!errorMessage.isEmpty()) {
323             notifyEngineRunFailed();
324
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")
331                              .arg(errorMessage));
332             infoBox->setStandardButtons(QMessageBox::Ok | QMessageBox::Help);
333             infoBox->setDefaultButton(QMessageBox::Ok);
334             infoBox->setModal(true);
335
336             connect(infoBox, SIGNAL(finished(int)),
337                     this, SLOT(wrongSetupMessageBoxFinished(int)));
338
339             infoBox->show();
340         }
341     } else if (msg.contains(cannotRetrieveDebuggingOutput)) {
342         // we won't get debugging output, so just try to connect ...
343         d->m_adapter.beginConnection();
344     }
345 }
346
347 void QmlEngine::showMessage(const QString &msg, int channel, int timeout) const
348 {
349     if (channel == AppOutput || channel == AppError) {
350         const_cast<QmlEngine*>(this)->filterApplicationMessage(msg, channel);
351     }
352     DebuggerEngine::showMessage(msg, channel, timeout);
353 }
354
355 bool QmlEngine::acceptsWatchesWhileRunning() const
356 {
357     return true;
358 }
359
360 void QmlEngine::closeConnection()
361 {
362     disconnect(&d->m_adapter, SIGNAL(connectionStartupFailed()),
363         this, SLOT(connectionStartupFailed()));
364     d->m_adapter.closeConnection();
365
366     ExtensionSystem::PluginManager *pluginManager =
367         ExtensionSystem::PluginManager::instance();
368
369     if (pluginManager->allObjects().contains(this)) {
370         pluginManager->removeObject(&d->m_adapter);
371         pluginManager->removeObject(this);
372     }
373 }
374
375 void QmlEngine::runEngine()
376 {
377     QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());
378
379     if (!isSlaveEngine())
380         startApplicationLauncher();
381 }
382
383 void QmlEngine::startApplicationLauncher()
384 {
385     if (!d->m_applicationLauncher.isRunning()) {
386         appendMessage(tr("Starting %1 %2").arg(
387                           QDir::toNativeSeparators(startParameters().executable),
388                           startParameters().processArgs)
389                       + QLatin1Char('\n')
390                      , NormalMessageFormat);
391         d->m_applicationLauncher.start(ApplicationLauncher::Gui,
392                                     startParameters().executable,
393                                     startParameters().processArgs);
394     }
395 }
396
397 void QmlEngine::stopApplicationLauncher()
398 {
399     if (d->m_applicationLauncher.isRunning()) {
400         disconnect(&d->m_applicationLauncher, SIGNAL(processExited(int)), this, SLOT(disconnected()));
401         d->m_applicationLauncher.stop();
402     }
403 }
404
405 void QmlEngine::handleRemoteSetupDone(int gdbServerPort, int qmlPort)
406 {
407     Q_UNUSED(gdbServerPort);
408     if (qmlPort != -1)
409         startParameters().qmlServerPort = qmlPort;
410     notifyInferiorSetupOk();
411 }
412
413 void QmlEngine::handleRemoteSetupFailed(const QString &message)
414 {
415     QMessageBox::critical(0,tr("Failed to start application"),
416         tr("Application startup failed: %1").arg(message));
417     notifyInferiorSetupFailed();
418 }
419
420 void QmlEngine::shutdownInferior()
421 {
422     if (isSlaveEngine()) {
423         resetLocation();
424     }
425     stopApplicationLauncher();
426     notifyInferiorShutdownOk();
427 }
428
429 void QmlEngine::shutdownEngine()
430 {
431     closeConnection();
432
433     // double check (ill engine?):
434     stopApplicationLauncher();
435
436     notifyEngineShutdownOk();
437     if (!isSlaveEngine())
438         showMessage(QString(), StatusBar);
439 }
440
441 void QmlEngine::setupEngine()
442 {
443     d->m_ping = 0;
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()));
452
453     notifyEngineSetupOk();
454 }
455
456 void QmlEngine::continueInferior()
457 {
458     QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
459     QByteArray reply;
460     QDataStream rs(&reply, QIODevice::WriteOnly);
461     QByteArray cmd = "CONTINUE";
462     rs << cmd;
463     logMessage(LogSend, cmd);
464     sendMessage(reply);
465     resetLocation();
466     notifyInferiorRunRequested();
467     notifyInferiorRunOk();
468 }
469
470 void QmlEngine::interruptInferior()
471 {
472     QByteArray reply;
473     QDataStream rs(&reply, QIODevice::WriteOnly);
474     QByteArray cmd = "INTERRUPT";
475     rs << cmd;
476     logMessage(LogSend, cmd);
477     sendMessage(reply);
478     notifyInferiorStopOk();
479 }
480
481 void QmlEngine::executeStep()
482 {
483     QByteArray reply;
484     QDataStream rs(&reply, QIODevice::WriteOnly);
485     QByteArray cmd = "STEPINTO";
486     rs << cmd;
487     logMessage(LogSend, cmd);
488     sendMessage(reply);
489     notifyInferiorRunRequested();
490     notifyInferiorRunOk();
491 }
492
493 void QmlEngine::executeStepI()
494 {
495     QByteArray reply;
496     QDataStream rs(&reply, QIODevice::WriteOnly);
497     QByteArray cmd = "STEPINTO";
498     rs << cmd;
499     logMessage(LogSend, cmd);
500     sendMessage(reply);
501     notifyInferiorRunRequested();
502     notifyInferiorRunOk();
503 }
504
505 void QmlEngine::executeStepOut()
506 {
507     QByteArray reply;
508     QDataStream rs(&reply, QIODevice::WriteOnly);
509     QByteArray cmd = "STEPOUT";
510     rs << cmd;
511     logMessage(LogSend, cmd);
512     sendMessage(reply);
513     notifyInferiorRunRequested();
514     notifyInferiorRunOk();
515 }
516
517 void QmlEngine::executeNext()
518 {
519     QByteArray reply;
520     QDataStream rs(&reply, QIODevice::WriteOnly);
521     QByteArray cmd = "STEPOVER";
522     rs << cmd;
523     logMessage(LogSend, cmd);
524     sendMessage(reply);
525     notifyInferiorRunRequested();
526     notifyInferiorRunOk();
527 }
528
529 void QmlEngine::executeNextI()
530 {
531     SDEBUG("QmlEngine::executeNextI()");
532 }
533
534 void QmlEngine::executeRunToLine(const ContextData &data)
535 {
536     Q_UNUSED(data)
537     SDEBUG("FIXME:  QmlEngine::executeRunToLine()");
538 }
539
540 void QmlEngine::executeRunToFunction(const QString &functionName)
541 {
542     Q_UNUSED(functionName)
543     XSDEBUG("FIXME:  QmlEngine::executeRunToFunction()");
544 }
545
546 void QmlEngine::executeJumpToLine(const ContextData &data)
547 {
548     Q_UNUSED(data)
549     XSDEBUG("FIXME:  QmlEngine::executeJumpToLine()");
550 }
551
552 void QmlEngine::activateFrame(int index)
553 {
554     QByteArray reply;
555     QDataStream rs(&reply, QIODevice::WriteOnly);
556     QByteArray cmd = "ACTIVATE_FRAME";
557     rs << cmd
558        << index;
559     logMessage(LogSend, QString("%1 %2").arg(QString(cmd), QString::number(index)));
560     sendMessage(reply);
561     gotoLocation(stackHandler()->frames().value(index));
562 }
563
564 void QmlEngine::selectThread(int index)
565 {
566     Q_UNUSED(index)
567 }
568
569 void QmlEngine::attemptBreakpointSynchronization()
570 {
571     BreakHandler *handler = breakHandler();
572
573     foreach (BreakpointId id, handler->unclaimedBreakpointIds()) {
574         // Take ownership of the breakpoint. Requests insertion.
575         if (acceptsBreakpoint(id))
576             handler->setEngine(id, this);
577     }
578
579     JSAgentBreakpoints breakpoints;
580     foreach (BreakpointId id, handler->engineBreakpointIds(this)) {
581         if (handler->state(id) == BreakpointRemoveRequested) {
582             handler->notifyBreakpointRemoveProceeding(id);
583             handler->notifyBreakpointRemoveOk(id);
584         } else {
585             if (handler->state(id) == BreakpointInsertRequested) {
586                 handler->notifyBreakpointInsertProceeding(id);
587             }
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);
595             }
596         }
597     }
598
599     QByteArray reply;
600     QDataStream rs(&reply, QIODevice::WriteOnly);
601     QByteArray cmd = "BREAKPOINTS";
602     rs << cmd
603        << breakpoints;
604
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));
609     }
610     logMessage(LogSend, QString("%1 [%2]").arg(QString(cmd), breakPointsStr.join(", ")));
611
612     sendMessage(reply);
613 }
614
615 bool QmlEngine::acceptsBreakpoint(BreakpointId id) const
616 {
617     return !DebuggerEngine::isCppBreakpoint(breakHandler()->breakpointData(id));
618 }
619
620 void QmlEngine::loadSymbols(const QString &moduleName)
621 {
622     Q_UNUSED(moduleName)
623 }
624
625 void QmlEngine::loadAllSymbols()
626 {
627 }
628
629 void QmlEngine::reloadModules()
630 {
631 }
632
633 void QmlEngine::requestModuleSymbols(const QString &moduleName)
634 {
635     Q_UNUSED(moduleName)
636 }
637
638 //////////////////////////////////////////////////////////////////////
639 //
640 // Tooltip specific stuff
641 //
642 //////////////////////////////////////////////////////////////////////
643
644 bool QmlEngine::setToolTipExpression(const QPoint &mousePos,
645     TextEditor::ITextEditor *editor, const DebuggerToolTipContext &ctx)
646 {
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);
650     return true;
651 }
652
653 //////////////////////////////////////////////////////////////////////
654 //
655 // Watch specific stuff
656 //
657 //////////////////////////////////////////////////////////////////////
658
659 void QmlEngine::assignValueInDebugger(const WatchData *,
660     const QString &expression, const QVariant &valueV)
661 {
662     QRegExp inObject("@([0-9a-fA-F]+)->(.+)");
663     if (inObject.exactMatch(expression)) {
664         bool ok = false;
665         quint64 objectId = inObject.cap(1).toULongLong(&ok, 16);
666         QString property = inObject.cap(2);
667         if (ok && objectId > 0 && !property.isEmpty()) {
668             QByteArray reply;
669             QDataStream rs(&reply, QIODevice::WriteOnly);
670             QByteArray cmd = "SET_PROPERTY";
671             rs << cmd;
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),
675                                  valueV.toString()));
676             sendMessage(reply);
677         }
678     }
679 }
680
681 void QmlEngine::updateWatchData(const WatchData &data,
682     const WatchUpdateFlags &)
683 {
684 //    qDebug() << "UPDATE WATCH DATA" << data.toString();
685     //watchHandler()->rebuildModel();
686     showStatusMessage(tr("Stopped."), 5000);
687
688     if (!data.name.isEmpty() && data.isValueNeeded()) {
689         QByteArray reply;
690         QDataStream rs(&reply, QIODevice::WriteOnly);
691         QByteArray cmd = "EXEC";
692         rs << cmd;
693         rs << data.iname << data.name;
694         logMessage(LogSend, QString("%1 %2 %3").arg(QString(cmd), QString(data.iname),
695                                                           QString(data.name)));
696         sendMessage(reply);
697     }
698
699     if (!data.name.isEmpty() && data.isChildrenNeeded()
700             && watchHandler()->isExpandedIName(data.iname)) {
701         expandObject(data.iname, data.id);
702     }
703
704     synchronizeWatchers();
705
706     if (!data.isSomethingNeeded())
707         watchHandler()->insertData(data);
708 }
709
710 void QmlEngine::synchronizeWatchers()
711 {
712     if (!watchHandler()->watcherNames().isEmpty()) {
713         // send watchers list
714         QByteArray reply;
715         QDataStream rs(&reply, QIODevice::WriteOnly);
716         QByteArray cmd = "WATCH_EXPRESSIONS";
717         rs << cmd;
718         rs << watchHandler()->watchedExpressions();
719         logMessage(LogSend, QString("%1 %2").arg(
720                        QString(cmd), watchHandler()->watchedExpressions().join(", ")));
721         sendMessage(reply);
722     }
723 }
724
725 void QmlEngine::expandObject(const QByteArray &iname, quint64 objectId)
726 {
727     QByteArray reply;
728     QDataStream rs(&reply, QIODevice::WriteOnly);
729     QByteArray cmd = "EXPAND";
730     rs << cmd;
731     rs << iname << objectId;
732     logMessage(LogSend, QString("%1 %2 %3").arg(QString(cmd), QString(iname),
733                                                       QString::number(objectId)));
734     sendMessage(reply);
735 }
736
737 void QmlEngine::sendPing()
738 {
739     d->m_ping++;
740     QByteArray reply;
741     QDataStream rs(&reply, QIODevice::WriteOnly);
742     QByteArray cmd = "PING";
743     rs << cmd;
744     rs << d->m_ping;
745     logMessage(LogSend, QString("%1 %2").arg(QString(cmd), QString::number(d->m_ping)));
746     sendMessage(reply);
747 }
748
749 unsigned QmlEngine::debuggerCapabilities() const
750 {
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;*/
761 }
762
763 QString QmlEngine::toFileInProject(const QString &fileUrl)
764 {
765     if (fileUrl.isEmpty())
766         return fileUrl;
767
768     const QString path = QUrl(fileUrl).toLocalFile();
769     if (path.isEmpty())
770         return fileUrl;
771
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())
776             return sourcePath;
777     }
778
779     // Try whether file is absolute & exists
780     if (QFileInfo(path).isAbsolute()
781             && QFileInfo(path).exists()) {
782         return path;
783     }
784
785     if (d->fileFinder.projectDirectory().isEmpty())
786         d->fileFinder.setProjectDirectory(startParameters().projectDir);
787
788     // Try to find file with biggest common path in source directory
789     bool fileFound = false;
790     QString fileInProject = d->fileFinder.findFile(path, &fileFound);
791     if (fileFound)
792         return fileInProject;
793     return fileUrl;
794 }
795
796 void QmlEngine::messageReceived(const QByteArray &message)
797 {
798     QByteArray rwData = message;
799     QDataStream stream(&rwData, QIODevice::ReadOnly);
800
801     QByteArray command;
802     stream >> command;
803
804     if (command == "STOPPED") {
805         //qDebug() << command << this << state();
806         if (state() == InferiorRunOk)
807             notifyInferiorSpontaneousStop();
808
809         QString logString = QString::fromLatin1(command);
810
811         JSAgentStackFrames stackFrames;
812         QList<WatchData> watches;
813         QList<WatchData> locals;
814         stream >> stackFrames >> watches >> locals;
815
816         logString += QString::fromLatin1(" (%1 stack frames) (%2 watches)  (%3 locals)").
817                      arg(stackFrames.size()).arg(watches.size()).arg(locals.size());
818
819         StackFrames ideStackFrames;
820         for (int i = 0; i != stackFrames.size(); ++i) {
821             StackFrame frame;
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();
826             frame.level = i + 1;
827             ideStackFrames << frame;
828         }
829
830         if (ideStackFrames.size() && ideStackFrames.back().function == "<global>")
831             ideStackFrames.takeLast();
832         stackHandler()->setFrames(ideStackFrames);
833
834         watchHandler()->beginCycle();
835         bool needPing = false;
836
837         foreach (WatchData data, watches) {
838             data.iname = watchHandler()->watcherName(data.exp);
839             watchHandler()->insertData(data);
840
841             if (watchHandler()->expandedINames().contains(data.iname)) {
842                 needPing = true;
843                 expandObject(data.iname, data.id);
844             }
845         }
846
847         foreach (WatchData data, locals) {
848             data.iname = "local." + data.exp;
849             watchHandler()->insertData(data);
850
851             if (watchHandler()->expandedINames().contains(data.iname)) {
852                 needPing = true;
853                 expandObject(data.iname, data.id);
854             }
855         }
856
857         if (needPing) {
858             sendPing();
859         } else {
860             watchHandler()->endCycle();
861         }
862
863         bool becauseOfException;
864         stream >> becauseOfException;
865
866         logString += becauseOfException ? " exception" : " no_exception";
867
868         if (becauseOfException) {
869             QString error;
870             stream >> error;
871
872             logString += QLatin1Char(' ');
873             logString += error;
874             logMessage(LogReceive, logString);
875
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);
882         } else {
883             //
884             // Make breakpoint non-pending
885             //
886             QString file;
887             QString function;
888             int line = -1;
889
890             if (!ideStackFrames.isEmpty()) {
891                 file = ideStackFrames.at(0).file;
892                 line = ideStackFrames.at(0).line;
893                 function = ideStackFrames.at(0).function;
894             }
895
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);
902                     br.fileName = file;
903                     br.lineNumber = line;
904                     br.functionName = function;
905                     handler->setResponse(id, br);
906                 }
907             }
908
909             logMessage(LogReceive, logString);
910         }
911
912         if (!ideStackFrames.isEmpty())
913             gotoLocation(ideStackFrames.value(0));
914
915     } else if (command == "RESULT") {
916         WatchData data;
917         QByteArray iname;
918         stream >> iname >> data;
919
920         logMessage(LogReceive, QString("%1 %2 %3").arg(QString(command),
921                                                              QString(iname), QString(data.value)));
922         data.iname = iname;
923         if (iname.startsWith("watch.")) {
924             watchHandler()->insertData(data);
925         } else if(iname == "console") {
926             showMessage(data.value, ScriptConsoleOutput);
927         } else {
928             qWarning() << "QmlEngine: Unexcpected result: " << iname << data.value;
929         }
930     } else if (command == "EXPANDED") {
931         QList<WatchData> result;
932         QByteArray iname;
933         stream >> iname >> result;
934
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);
941
942             if (watchHandler()->expandedINames().contains(data.iname)) {
943                 needPing = true;
944                 expandObject(data.iname, data.id);
945             }
946         }
947         if (needPing)
948             sendPing();
949     } else if (command == "LOCALS") {
950         QList<WatchData> locals;
951         int frameId;
952         stream >> frameId >> locals;
953
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)) {
963                 needPing = true;
964                 expandObject(data.iname, data.id);
965             }
966         }
967         if (needPing)
968             sendPing();
969         else
970             watchHandler()->endCycle();
971
972     } else if (command == "PONG") {
973         int ping;
974         stream >> ping;
975
976         logMessage(LogReceive, QString("%1 %2").arg(QString(command), QString::number(ping)));
977
978         if (ping == d->m_ping)
979             watchHandler()->endCycle();
980     } else {
981         qDebug() << Q_FUNC_INFO << "Unknown command: " << command;
982         logMessage(LogReceive, QString("%1 UNKNOWN COMMAND!!").arg(QString(command)));
983     }
984 }
985
986 void QmlEngine::disconnected()
987 {
988     showMessage(tr("QML Debugger disconnected."), StatusBar);
989     notifyInferiorExited();
990 }
991
992 void QmlEngine::wrongSetupMessageBoxFinished(int result)
993 {
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"));
998     }
999 }
1000
1001 void QmlEngine::executeDebuggerCommand(const QString& command)
1002 {
1003     QByteArray reply;
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),
1009                                                       QString(command)));
1010     sendMessage(reply);
1011 }
1012
1013 bool QmlEngine::isShadowBuildProject() const
1014 {
1015     return !startParameters().projectBuildDir.isEmpty()
1016         && startParameters().projectDir != startParameters().projectBuildDir;
1017 }
1018
1019 QString QmlEngine::qmlImportPath() const
1020 {
1021     return startParameters().environment.value("QML_IMPORT_PATH");
1022 }
1023
1024 QString QmlEngine::mangleFilenamePaths(const QString &filename,
1025     const QString &oldBasePath, const QString &newBasePath) const
1026 {
1027     QDir oldBaseDir(oldBasePath);
1028     QDir newBaseDir(newBasePath);
1029     QFileInfo fileInfo(filename);
1030
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);
1035
1036             if (projectFile.exists())
1037                 return projectFile.canonicalFilePath();
1038         }
1039     }
1040     return filename;
1041 }
1042
1043 QString QmlEngine::fromShadowBuildFilename(const QString &filename) const
1044 {
1045     QString newFilename = filename;
1046     QString importPath = qmlImportPath();
1047
1048 #ifdef Q_OS_MACX
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);
1054 #endif
1055     newFilename = mangleFilenamePaths(newFilename, startParameters().projectBuildDir, startParameters().projectDir);
1056
1057     if (newFilename == filename && !importPath.isEmpty()) {
1058         newFilename = mangleFilenamePaths(filename, startParameters().projectBuildDir, importPath);
1059     }
1060
1061     return newFilename;
1062 }
1063
1064 void QmlEngine::logMessage(LogDirection direction, const QString &message)
1065 {
1066     QString msg = "JSDebugger";
1067     if (direction == LogSend) {
1068         msg += " sending ";
1069     } else {
1070         msg += " receiving ";
1071     }
1072     msg += message;
1073     showMessage(msg, LogDebug);
1074 }
1075
1076 QmlEngine *createQmlEngine(const DebuggerStartParameters &sp,
1077     DebuggerEngine *masterEngine)
1078 {
1079     return new QmlEngine(sp, masterEngine);
1080 }
1081
1082 } // namespace Internal
1083 } // namespace Debugger
1084