OSDN Git Service

QmlCppDebugger: Decouple states of engines
[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 info@qt.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/qtcassert.h>
58 #include <utils/fileinprojectfinder.h>
59
60 #include <coreplugin/icore.h>
61 #include <coreplugin/helpmanager.h>
62
63 #include <QtCore/QDateTime>
64 #include <QtCore/QDebug>
65 #include <QtCore/QDir>
66 #include <QtCore/QFileInfo>
67 #include <QtCore/QTimer>
68
69 #include <QtGui/QAction>
70 #include <QtGui/QApplication>
71 #include <QtGui/QMainWindow>
72 #include <QtGui/QMessageBox>
73 #include <QtGui/QToolTip>
74 #include <QtGui/QTextDocument>
75
76 #include <QtNetwork/QTcpSocket>
77 #include <QtNetwork/QHostAddress>
78
79 #define DEBUG_QML 1
80 #if DEBUG_QML
81 #   define SDEBUG(s) qDebug() << s
82 #else
83 #   define SDEBUG(s)
84 #endif
85 # define XSDEBUG(s) qDebug() << s
86
87 using namespace ProjectExplorer;
88
89 namespace Debugger {
90 namespace Internal {
91
92 class QmlEnginePrivate
93 {
94 public:
95     explicit QmlEnginePrivate(QmlEngine *q);
96
97 private:
98     friend class QmlEngine;
99     QmlAdapter m_adapter;
100     ApplicationLauncher m_applicationLauncher;
101     Utils::FileInProjectFinder fileFinder;
102     QTimer m_noDebugOutputTimer;
103 };
104
105 QmlEnginePrivate::QmlEnginePrivate(QmlEngine *q)
106     : m_adapter(q)
107 {}
108
109
110 ///////////////////////////////////////////////////////////////////////
111 //
112 // QmlEngine
113 //
114 ///////////////////////////////////////////////////////////////////////
115
116 QmlEngine::QmlEngine(const DebuggerStartParameters &startParameters,
117         DebuggerEngine *masterEngine)
118   : DebuggerEngine(startParameters, masterEngine),
119     d(new QmlEnginePrivate(this))
120 {
121     setObjectName(QLatin1String("QmlEngine"));
122
123     ExtensionSystem::PluginManager *pluginManager =
124         ExtensionSystem::PluginManager::instance();
125     pluginManager->addObject(this);
126
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()));
135
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)));
142     connect(&d->m_applicationLauncher,
143             SIGNAL(processStarted()),
144             &d->m_noDebugOutputTimer,
145             SLOT(start()));
146
147     // Only wait 8 seconds for the 'Waiting for connection' on application ouput, then just try to connect
148     // (application output might be redirected / blocked)
149     d->m_noDebugOutputTimer.setSingleShot(true);
150     d->m_noDebugOutputTimer.setInterval(8000);
151     connect(&d->m_noDebugOutputTimer, SIGNAL(timeout()), this, SLOT(beginConnection()));
152 }
153
154 QmlEngine::~QmlEngine()
155 {
156     ExtensionSystem::PluginManager *pluginManager =
157         ExtensionSystem::PluginManager::instance();
158
159     if (pluginManager->allObjects().contains(this)) {
160         pluginManager->removeObject(this);
161     }
162
163     delete d;
164 }
165
166 void QmlEngine::setupInferior()
167 {
168     QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
169
170     if (startParameters().startMode == AttachToRemoteServer) {
171         emit requestRemoteSetup();
172         if (startParameters().qmlServerPort != quint16(-1))
173             notifyInferiorSetupOk();
174     } if (startParameters().startMode == AttachToQmlPort) {
175             notifyInferiorSetupOk();
176
177     } else {
178         d->m_applicationLauncher.setEnvironment(startParameters().environment);
179         d->m_applicationLauncher.setWorkingDirectory(startParameters().workingDirectory);
180
181         notifyInferiorSetupOk();
182     }
183 }
184
185 void QmlEngine::appendMessage(const QString &msg, Utils::OutputFormat /* format */)
186 {
187     showMessage(msg, AppOutput); // FIXME: Redirect to RunControl
188 }
189
190 void QmlEngine::connectionEstablished()
191 {
192     attemptBreakpointSynchronization();
193
194     showMessage(tr("QML Debugger connected."), StatusBar);
195
196     if (!watchHandler()->watcherNames().isEmpty()) {
197         synchronizeWatchers();
198     }
199     connect(watchersModel(),SIGNAL(layoutChanged()),this,SLOT(synchronizeWatchers()));
200
201     notifyEngineRunAndInferiorRunOk();
202 }
203
204 void QmlEngine::beginConnection()
205 {
206     d->m_noDebugOutputTimer.stop();
207     showMessage(tr("QML Debugger connecting..."), StatusBar);
208     d->m_adapter.beginConnection();
209 }
210
211 void QmlEngine::connectionStartupFailed()
212 {
213     Core::ICore * const core = Core::ICore::instance();
214     QMessageBox *infoBox = new QMessageBox(core->mainWindow());
215     infoBox->setIcon(QMessageBox::Critical);
216     infoBox->setWindowTitle(tr("Qt Creator"));
217     infoBox->setText(tr("Could not connect to the in-process QML debugger.\n"
218                         "Do you want to retry?"));
219     infoBox->setStandardButtons(QMessageBox::Retry | QMessageBox::Cancel | QMessageBox::Help);
220     infoBox->setDefaultButton(QMessageBox::Retry);
221     infoBox->setModal(true);
222
223     connect(infoBox, SIGNAL(finished(int)),
224             this, SLOT(retryMessageBoxFinished(int)));
225
226     infoBox->show();
227 }
228
229 void QmlEngine::retryMessageBoxFinished(int result)
230 {
231     switch (result) {
232     case QMessageBox::Retry: {
233         beginConnection();
234         break;
235     }
236     case QMessageBox::Help: {
237         Core::HelpManager *helpManager = Core::HelpManager::instance();
238         helpManager->handleHelpRequest("qthelp://com.nokia.qtcreator/doc/creator-debugging-qml.html");
239         // fall through
240     }
241     default:
242         notifyEngineRunFailed();
243         break;
244     }
245 }
246
247 void QmlEngine::connectionError(QAbstractSocket::SocketError socketError)
248 {
249     if (socketError == QAbstractSocket::RemoteHostClosedError)
250         showMessage(tr("QML Debugger: Remote host closed connection."), StatusBar);
251
252     if (!isSlaveEngine()) { // normal flow for slave engine when gdb exits
253         notifyInferiorSpontaneousStop();
254         notifyInferiorIll();
255     }
256 }
257
258 void QmlEngine::serviceConnectionError(const QString &serviceName)
259 {
260     showMessage(tr("QML Debugger: Could not connect to service '%1'.")
261         .arg(serviceName), StatusBar);
262 }
263
264 bool QmlEngine::canDisplayTooltip() const
265 {
266     return state() == InferiorRunOk || state() == InferiorStopOk;
267 }
268
269 void QmlEngine::filterApplicationMessage(const QString &msg, int /*channel*/)
270 {
271     static const QString qddserver = QLatin1String("QDeclarativeDebugServer: ");
272     static const QString cannotRetrieveDebuggingOutput = ApplicationLauncher::msgWinCannotRetrieveDebuggingOutput();
273
274     const int index = msg.indexOf(qddserver);
275     if (index != -1) {
276         // we're actually getting debug output
277         d->m_noDebugOutputTimer.stop();
278
279         QString status = msg;
280         status.remove(0, index + qddserver.length()); // chop of 'QDeclarativeDebugServer: '
281
282         static QString waitingForConnection = QLatin1String("Waiting for connection ");
283         static QString unableToListen = QLatin1String("Unable to listen ");
284         static QString debuggingNotEnabled = QLatin1String("Ignoring \"-qmljsdebugger=");
285         static QString debuggingNotEnabled2 = QLatin1String("Ignoring\"-qmljsdebugger="); // There is (was?) a bug in one of the error strings - safest to handle both
286         static QString connectionEstablished = QLatin1String("Connection established");
287
288         QString errorMessage;
289         if (status.startsWith(waitingForConnection)) {
290             beginConnection();
291         } else if (status.startsWith(unableToListen)) {
292             //: Error message shown after 'Could not connect ... debugger:"
293             errorMessage = tr("The port seems to be in use.");
294         } else if (status.startsWith(debuggingNotEnabled) || status.startsWith(debuggingNotEnabled2)) {
295             //: Error message shown after 'Could not connect ... debugger:"
296             errorMessage = tr("The application is not set up for QML/JS debugging.");
297         } else if (status.startsWith(connectionEstablished)) {
298             // nothing to do
299         } else {
300             qWarning() << "Unknown QDeclarativeDebugServer status message: " << status;
301         }
302
303         if (!errorMessage.isEmpty()) {
304             notifyEngineRunFailed();
305
306             Core::ICore * const core = Core::ICore::instance();
307             QMessageBox *infoBox = new QMessageBox(core->mainWindow());
308             infoBox->setIcon(QMessageBox::Critical);
309             infoBox->setWindowTitle(tr("Qt Creator"));
310             //: %1 is detailed error message
311             infoBox->setText(tr("Could not connect to the in-process QML debugger:\n%1")
312                              .arg(errorMessage));
313             infoBox->setStandardButtons(QMessageBox::Ok | QMessageBox::Help);
314             infoBox->setDefaultButton(QMessageBox::Ok);
315             infoBox->setModal(true);
316
317             connect(infoBox, SIGNAL(finished(int)),
318                     this, SLOT(wrongSetupMessageBoxFinished(int)));
319
320             infoBox->show();
321         }
322     } else if (msg.contains(cannotRetrieveDebuggingOutput)) {
323         // we won't get debugging output, so just try to connect ...
324         beginConnection();
325     }
326 }
327
328 void QmlEngine::showMessage(const QString &msg, int channel, int timeout) const
329 {
330     if (channel == AppOutput || channel == AppError) {
331         const_cast<QmlEngine*>(this)->filterApplicationMessage(msg, channel);
332     }
333     DebuggerEngine::showMessage(msg, channel, timeout);
334 }
335
336 void QmlEngine::closeConnection()
337 {
338     disconnect(watchersModel(),SIGNAL(layoutChanged()),this,SLOT(synchronizeWatchers()));
339     d->m_adapter.closeConnection();
340 }
341
342 void QmlEngine::runEngine()
343 {
344     QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());
345
346     if (!isSlaveEngine() && startParameters().startMode != AttachToRemoteServer
347             && startParameters().startMode != AttachToQmlPort)
348         startApplicationLauncher();
349
350     if (startParameters().startMode == AttachToQmlPort)
351         beginConnection();
352 }
353
354 void QmlEngine::startApplicationLauncher()
355 {
356     if (!d->m_applicationLauncher.isRunning()) {
357         appendMessage(tr("Starting %1 %2").arg(
358                           QDir::toNativeSeparators(startParameters().executable),
359                           startParameters().processArgs)
360                       + QLatin1Char('\n')
361                      , Utils::NormalMessageFormat);
362         d->m_applicationLauncher.start(ApplicationLauncher::Gui,
363                                     startParameters().executable,
364                                     startParameters().processArgs);
365     }
366 }
367
368 void QmlEngine::stopApplicationLauncher()
369 {
370     if (d->m_applicationLauncher.isRunning()) {
371         disconnect(&d->m_applicationLauncher, SIGNAL(processExited(int)), this, SLOT(disconnected()));
372         d->m_applicationLauncher.stop();
373     }
374 }
375
376 void QmlEngine::handleRemoteSetupDone(int gdbServerPort, int qmlPort)
377 {
378     Q_UNUSED(gdbServerPort);
379     if (qmlPort != -1)
380         startParameters().qmlServerPort = qmlPort;
381     notifyInferiorSetupOk();
382 }
383
384 void QmlEngine::handleRemoteSetupFailed(const QString &message)
385 {
386     QMessageBox::critical(0,tr("Failed to start application"),
387         tr("Application startup failed: %1").arg(message));
388     notifyInferiorSetupFailed();
389 }
390
391 void QmlEngine::shutdownInferior()
392 {
393     d->m_noDebugOutputTimer.stop();
394
395     if (d->m_adapter.activeDebuggerClient())
396         d->m_adapter.activeDebuggerClient()->endSession();
397
398     if (isSlaveEngine()) {
399         resetLocation();
400     }
401     stopApplicationLauncher();
402
403     notifyInferiorShutdownOk();
404 }
405
406 void QmlEngine::shutdownEngine()
407 {
408     closeConnection();
409
410     // double check (ill engine?):
411     stopApplicationLauncher();
412
413     notifyEngineShutdownOk();
414     if (!isSlaveEngine())
415         showMessage(QString(), StatusBar);
416 }
417
418 void QmlEngine::setupEngine()
419 {
420     connect(&d->m_applicationLauncher, SIGNAL(bringToForegroundRequested(qint64)),
421             runControl(), SLOT(bringApplicationToForeground(qint64)),
422             Qt::UniqueConnection);
423
424     notifyEngineSetupOk();
425 }
426
427 void QmlEngine::continueInferior()
428 {
429     QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
430     if (d->m_adapter.activeDebuggerClient()) {
431         logMessage(LogSend, "CONTINUE");
432         d->m_adapter.activeDebuggerClient()->continueInferior();
433     }
434     resetLocation();
435     notifyInferiorRunRequested();
436     notifyInferiorRunOk();
437 }
438
439 void QmlEngine::interruptInferior()
440 {
441     if (d->m_adapter.activeDebuggerClient()) {
442         logMessage(LogSend, "INTERRUPT");
443         d->m_adapter.activeDebuggerClient()->interruptInferior();
444     }
445     notifyInferiorStopOk();
446 }
447
448 void QmlEngine::executeStep()
449 {
450     if (d->m_adapter.activeDebuggerClient()) {
451         logMessage(LogSend, "STEPINTO");
452         d->m_adapter.activeDebuggerClient()->executeStep();
453     }
454     resetLocation();
455     notifyInferiorRunRequested();
456     notifyInferiorRunOk();
457 }
458
459 void QmlEngine::executeStepI()
460 {
461     if (d->m_adapter.activeDebuggerClient()) {
462         logMessage(LogSend, "STEPINTO");
463         d->m_adapter.activeDebuggerClient()->executeStepI();
464     }
465     resetLocation();
466     notifyInferiorRunRequested();
467     notifyInferiorRunOk();
468 }
469
470 void QmlEngine::executeStepOut()
471 {
472     if (d->m_adapter.activeDebuggerClient()) {
473         logMessage(LogSend, "STEPOUT");
474         d->m_adapter.activeDebuggerClient()->executeStepOut();
475     }
476     resetLocation();
477     notifyInferiorRunRequested();
478     notifyInferiorRunOk();
479 }
480
481 void QmlEngine::executeNext()
482 {
483     if (d->m_adapter.activeDebuggerClient()) {
484         logMessage(LogSend, "STEPOVER");
485         d->m_adapter.activeDebuggerClient()->executeNext();
486     }
487     resetLocation();
488     notifyInferiorRunRequested();
489     notifyInferiorRunOk();
490 }
491
492 void QmlEngine::executeNextI()
493 {
494     SDEBUG("QmlEngine::executeNextI()");
495 }
496
497 void QmlEngine::executeRunToLine(const ContextData &data)
498 {
499     Q_UNUSED(data)
500     SDEBUG("FIXME:  QmlEngine::executeRunToLine()");
501 }
502
503 void QmlEngine::executeRunToFunction(const QString &functionName)
504 {
505     Q_UNUSED(functionName)
506     XSDEBUG("FIXME:  QmlEngine::executeRunToFunction()");
507 }
508
509 void QmlEngine::executeJumpToLine(const ContextData &data)
510 {
511     Q_UNUSED(data)
512     XSDEBUG("FIXME:  QmlEngine::executeJumpToLine()");
513 }
514
515 void QmlEngine::activateFrame(int index)
516 {
517     if (d->m_adapter.activeDebuggerClient()) {
518         logMessage(LogSend, QString("%1 %2").arg(QString("ACTIVATE_FRAME"), QString::number(index)));
519         d->m_adapter.activeDebuggerClient()->activateFrame(index);
520     }
521     gotoLocation(stackHandler()->frames().value(index));
522 }
523
524 void QmlEngine::selectThread(int index)
525 {
526     Q_UNUSED(index)
527 }
528
529 void QmlEngine::insertBreakpoint(BreakpointModelId id)
530 {
531     BreakHandler *handler = breakHandler();
532     BreakpointState state = handler->state(id);
533     QTC_ASSERT(state == BreakpointInsertRequested, qDebug() << id << this << state);
534     handler->notifyBreakpointInsertProceeding(id);
535
536     if (d->m_adapter.activeDebuggerClient()) {
537         d->m_adapter.activeDebuggerClient()->insertBreakpoint(id);
538     } else {
539         foreach (QmlDebuggerClient *client, d->m_adapter.debuggerClients()) {
540             client->insertBreakpoint(id);
541         }
542     }
543 }
544
545 void QmlEngine::removeBreakpoint(BreakpointModelId id)
546 {
547     BreakHandler *handler = breakHandler();
548     BreakpointState state = handler->state(id);
549     QTC_ASSERT(state == BreakpointRemoveRequested, qDebug() << id << this << state);
550     handler->notifyBreakpointRemoveProceeding(id);
551
552     if (d->m_adapter.activeDebuggerClient()) {
553         d->m_adapter.activeDebuggerClient()->removeBreakpoint(id);
554     } else {
555         foreach (QmlDebuggerClient *client, d->m_adapter.debuggerClients()) {
556             client->removeBreakpoint(id);
557         }
558     }
559
560     if (handler->state(id) == BreakpointRemoveProceeding) {
561         handler->notifyBreakpointRemoveOk(id);
562     }
563 }
564
565 void QmlEngine::changeBreakpoint(BreakpointModelId id)
566 {
567     BreakHandler *handler = breakHandler();
568     BreakpointState state = handler->state(id);
569     QTC_ASSERT(state == BreakpointChangeRequested, qDebug() << id << this << state);
570     handler->notifyBreakpointChangeProceeding(id);
571
572     if (d->m_adapter.activeDebuggerClient()) {
573         d->m_adapter.activeDebuggerClient()->changeBreakpoint(id);
574     } else {
575         foreach (QmlDebuggerClient *client, d->m_adapter.debuggerClients()) {
576             client->changeBreakpoint(id);
577         }
578     }
579
580     if (handler->state(id) == BreakpointChangeProceeding) {
581         handler->notifyBreakpointChangeOk(id);
582     }
583 }
584
585 void QmlEngine::attemptBreakpointSynchronization()
586 {
587     if (!stateAcceptsBreakpointChanges()) {
588         showMessage(_("BREAKPOINT SYNCHRONIZATION NOT POSSIBLE IN CURRENT STATE"));
589         return;
590     }
591
592     BreakHandler *handler = breakHandler();
593
594     foreach (BreakpointModelId id, handler->unclaimedBreakpointIds()) {
595         // Take ownership of the breakpoint. Requests insertion.
596         if (acceptsBreakpoint(id))
597             handler->setEngine(id, this);
598     }
599
600     foreach (BreakpointModelId id, handler->engineBreakpointIds(this)) {
601         switch (handler->state(id)) {
602         case BreakpointNew:
603             // Should not happen once claimed.
604             QTC_CHECK(false);
605             continue;
606         case BreakpointInsertRequested:
607             insertBreakpoint(id);
608             continue;
609         case BreakpointChangeRequested:
610             changeBreakpoint(id);
611             continue;
612         case BreakpointRemoveRequested:
613             removeBreakpoint(id);
614             continue;
615         case BreakpointChangeProceeding:
616         case BreakpointInsertProceeding:
617         case BreakpointRemoveProceeding:
618         case BreakpointInserted:
619         case BreakpointDead:
620             continue;
621         }
622         QTC_ASSERT(false, qDebug() << "UNKNOWN STATE"  << id << state());
623     }
624
625     DebuggerEngine::attemptBreakpointSynchronization();
626
627     if (d->m_adapter.activeDebuggerClient()) {
628         d->m_adapter.activeDebuggerClient()->updateBreakpoints();
629     } else {
630         foreach (QmlDebuggerClient *client, d->m_adapter.debuggerClients()) {
631             client->updateBreakpoints();
632         }
633     }
634 }
635
636 bool QmlEngine::acceptsBreakpoint(BreakpointModelId id) const
637 {
638     if (!DebuggerEngine::isCppBreakpoint(breakHandler()->breakpointData(id)))
639             return true;
640
641     //If it is a Cpp Breakpoint query if the type can be also handled by the debugger client
642     //TODO: enable setting of breakpoints before start of debug session
643     //For now, the event breakpoint can be set after the activeDebuggerClient is known
644     //This is because the older client does not support BreakpointOnQmlSignalHandler
645     bool acceptBreakpoint = false;
646     if (d->m_adapter.activeDebuggerClient()) {
647         acceptBreakpoint = d->m_adapter.activeDebuggerClient()->acceptsBreakpoint(id);
648     }
649     return acceptBreakpoint;
650 }
651
652 void QmlEngine::loadSymbols(const QString &moduleName)
653 {
654     Q_UNUSED(moduleName)
655 }
656
657 void QmlEngine::loadAllSymbols()
658 {
659 }
660
661 void QmlEngine::reloadModules()
662 {
663 }
664
665 void QmlEngine::requestModuleSymbols(const QString &moduleName)
666 {
667     Q_UNUSED(moduleName)
668 }
669
670 //////////////////////////////////////////////////////////////////////
671 //
672 // Tooltip specific stuff
673 //
674 //////////////////////////////////////////////////////////////////////
675
676 bool QmlEngine::setToolTipExpression(const QPoint &mousePos,
677     TextEditor::ITextEditor *editor, const DebuggerToolTipContext &ctx)
678 {
679     // This is processed by QML inspector, which has dependencies to 
680     // the qml js editor. Makes life easier.
681     emit tooltipRequested(mousePos, editor, ctx.position);
682     return true;
683 }
684
685 //////////////////////////////////////////////////////////////////////
686 //
687 // Watch specific stuff
688 //
689 //////////////////////////////////////////////////////////////////////
690
691 void QmlEngine::assignValueInDebugger(const WatchData *data,
692     const QString &expression, const QVariant &valueV)
693 {
694     quint64 objectId =  data->id;
695     if (objectId > 0 && !expression.isEmpty() && d->m_adapter.activeDebuggerClient()) {
696         logMessage(LogSend, QString("%1 %2 %3 %4 %5").arg(
697                        QString("SET_PROPERTY"), QString::number(objectId), QString(expression),
698                        valueV.toString()));
699         d->m_adapter.activeDebuggerClient()->assignValueInDebugger(expression.toUtf8(), objectId, expression, valueV.toString());
700     }
701 }
702
703 void QmlEngine::updateWatchData(const WatchData &data,
704     const WatchUpdateFlags &)
705 {
706 //    qDebug() << "UPDATE WATCH DATA" << data.toString();
707     //watchHandler()->rebuildModel();
708     showStatusMessage(tr("Stopped."), 5000);
709
710     if (!data.name.isEmpty() && d->m_adapter.activeDebuggerClient()) {
711         if (data.isValueNeeded()) {
712             logMessage(LogSend, QString("%1 %2 %3").arg(QString("EXEC"), QString(data.iname),
713                                                         QString(data.name)));
714             d->m_adapter.activeDebuggerClient()->updateWatchData(&data);
715         }
716         if (data.isChildrenNeeded()
717                 && watchHandler()->isExpandedIName(data.iname)) {
718             d->m_adapter.activeDebuggerClient()->expandObject(data.iname, data.id);
719         }
720     }
721
722     synchronizeWatchers();
723
724     if (!data.isSomethingNeeded())
725         watchHandler()->insertData(data);
726 }
727
728 void QmlEngine::synchronizeWatchers()
729 {
730     QStringList watchedExpressions = watchHandler()->watchedExpressions();
731     // send watchers list
732     logMessage(LogSend, QString("%1 %2").arg(
733                    QString("WATCH_EXPRESSIONS"), watchedExpressions.join(", ")));
734     if (d->m_adapter.activeDebuggerClient()) {
735         d->m_adapter.activeDebuggerClient()->synchronizeWatchers(watchedExpressions);
736     } else {
737         foreach (QmlDebuggerClient *client, d->m_adapter.debuggerClients())
738             client->synchronizeWatchers(watchedExpressions);
739     }
740 }
741
742 unsigned QmlEngine::debuggerCapabilities() const
743 {
744     return AddWatcherCapability|AddWatcherWhileRunningCapability;
745     /*ReverseSteppingCapability | SnapshotCapability
746         | AutoDerefPointersCapability | DisassemblerCapability
747         | RegisterCapability | ShowMemoryCapability
748         | JumpToLineCapability | ReloadModuleCapability
749         | ReloadModuleSymbolsCapability | BreakOnThrowAndCatchCapability
750         | ReturnFromFunctionCapability
751         | CreateFullBacktraceCapability
752         | WatchpointCapability
753         | AddWatcherCapability;*/
754 }
755
756 QString QmlEngine::toFileInProject(const QUrl &fileUrl)
757 {
758     if (startParameters().startMode != AttachToQmlPort) {
759         if (d->fileFinder.projectDirectory().isEmpty()) {
760             d->fileFinder.setProjectDirectory(startParameters().projectSourceDirectory);
761             d->fileFinder.setProjectFiles(startParameters().projectSourceFiles);
762         }
763     }
764
765     return d->fileFinder.findFile(fileUrl);
766 }
767
768 void QmlEngine::inferiorSpontaneousStop()
769 {
770     if (state() == InferiorRunOk)
771         notifyInferiorSpontaneousStop();
772 }
773
774 void QmlEngine::disconnected()
775 {
776     showMessage(tr("QML Debugger disconnected."), StatusBar);
777     notifyInferiorExited();
778 }
779
780 void QmlEngine::wrongSetupMessageBoxFinished(int result)
781 {
782     if (result == QMessageBox::Help) {
783         Core::HelpManager *helpManager = Core::HelpManager::instance();
784         helpManager->handleHelpRequest(
785                     QLatin1String("qthelp://com.nokia.qtcreator/doc/creator-debugging-qml.html"));
786     }
787 }
788
789 void QmlEngine::executeDebuggerCommand(const QString& command)
790 {
791     if (d->m_adapter.activeDebuggerClient()) {
792         logMessage(LogSend, QString("%1 %2 %3").arg(QString("EXEC"), QString("console"),
793                                                           QString(command)));
794         d->m_adapter.activeDebuggerClient()->executeDebuggerCommand(command);
795     }
796 }
797
798
799 QString QmlEngine::qmlImportPath() const
800 {
801     return startParameters().environment.value("QML_IMPORT_PATH");
802 }
803
804 void QmlEngine::logMessage(LogDirection direction, const QString &message)
805 {
806     QString msg = "QmlDebugger";
807     if (direction == LogSend) {
808         msg += " sending ";
809     } else {
810         msg += " receiving ";
811     }
812     msg += message;
813     showMessage(msg, LogDebug);
814 }
815
816 QmlEngine *createQmlEngine(const DebuggerStartParameters &sp,
817     DebuggerEngine *masterEngine)
818 {
819     return new QmlEngine(sp, masterEngine);
820 }
821
822 } // namespace Internal
823 } // namespace Debugger
824