1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtQml module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
42 #include "qqmldebugserver_p.h"
43 #include "qqmldebugservice_p.h"
44 #include "qqmldebugservice_p_p.h"
45 #include <private/qqmlengine_p.h>
46 #include <private/qqmlglobal_p.h>
48 #include <QtCore/QAtomicInt>
49 #include <QtCore/QDir>
50 #include <QtCore/QPluginLoader>
51 #include <QtCore/QStringList>
52 #include <QtCore/qwaitcondition.h>
54 #include <private/qobject_p.h>
55 #include <private/qcoreapplication_p.h>
60 QQmlDebug Protocol (Version 1):
64 "QDeclarativeDebugServer" 0 version pluginNames
65 version: an int representing the highest protocol version the client knows
66 pluginNames: plugins available on client side
68 "QDeclarativeDebugClient" 0 version pluginNames pluginVersions
69 version: an int representing the highest protocol version the client & server know
70 pluginNames: plugins available on server side. plugins both in the client and server message are enabled.
71 client plugin advertisement
73 "QDeclarativeDebugServer" 1 pluginNames
74 server plugin advertisement
76 "QDeclarativeDebugClient" 1 pluginNames pluginVersions
78 Everything send with a header different to "QDeclarativeDebugServer" is sent to the appropriate plugin.
81 const int protocolVersion = 1;
83 // print detailed information about loading of plugins
84 DEFINE_BOOL_CONFIG_OPTION(qmlDebugVerbose, QML_DEBUGGER_VERBOSE)
86 class QQmlDebugServerThread;
88 class QQmlDebugServerPrivate : public QObjectPrivate
90 Q_DECLARE_PUBLIC(QQmlDebugServer)
92 QQmlDebugServerPrivate();
94 void advertisePlugins();
95 QQmlDebugServerConnection *loadConnectionPlugin(const QString &pluginName);
97 QQmlDebugServerConnection *connection;
98 QHash<QString, QQmlDebugService *> plugins;
99 mutable QReadWriteLock pluginsLock;
100 QStringList clientPlugins;
103 QMutex messageArrivedMutex;
104 QWaitCondition messageArrivedCondition;
105 QStringList waitingForMessageNames;
106 QQmlDebugServerThread *thread;
107 QPluginLoader loader;
108 QAtomicInt changeServiceStateCalls;
112 void _q_changeServiceState(const QString &serviceName,
113 QQmlDebugService::State newState);
114 void _q_sendMessages(const QList<QByteArray> &messages);
117 class QQmlDebugServerThread : public QThread
120 void setPluginName(const QString &pluginName) {
121 m_pluginName = pluginName;
124 void setPort(int port, bool block, QString &hostAddress) {
127 m_hostAddress = hostAddress;
133 QString m_pluginName;
136 QString m_hostAddress;
139 QQmlDebugServerPrivate::QQmlDebugServerPrivate() :
144 // used in _q_sendMessages
145 qRegisterMetaType<QList<QByteArray> >("QList<QByteArray>");
146 // used in _q_changeServiceState
147 qRegisterMetaType<QQmlDebugService::State>("QQmlDebugService::State");
150 void QQmlDebugServerPrivate::advertisePlugins()
152 Q_Q(QQmlDebugServer);
159 QDataStream out(&message, QIODevice::WriteOnly);
160 QStringList pluginNames;
161 QList<float> pluginVersions;
162 foreach (QQmlDebugService *service, plugins.values()) {
163 pluginNames << service->name();
164 pluginVersions << service->version();
166 out << QString(QStringLiteral("QDeclarativeDebugClient")) << 1 << pluginNames << pluginVersions;
169 QMetaObject::invokeMethod(q, "_q_sendMessages", Qt::QueuedConnection, Q_ARG(QList<QByteArray>, QList<QByteArray>() << message));
172 QQmlDebugServerConnection *QQmlDebugServerPrivate::loadConnectionPlugin(
173 const QString &pluginName)
175 #ifndef QT_NO_LIBRARY
176 QStringList pluginCandidates;
177 const QStringList paths = QCoreApplication::libraryPaths();
178 foreach (const QString &libPath, paths) {
179 const QDir dir(libPath + QLatin1String("/qmltooling"));
181 QStringList plugins(dir.entryList(QDir::Files));
182 foreach (const QString &pluginPath, plugins) {
183 if (QFileInfo(pluginPath).fileName().contains(pluginName))
184 pluginCandidates << dir.absoluteFilePath(pluginPath);
189 foreach (const QString &pluginPath, pluginCandidates) {
190 if (qmlDebugVerbose())
191 qDebug() << "QML Debugger: Trying to load plugin " << pluginPath << "...";
193 loader.setFileName(pluginPath);
194 if (!loader.load()) {
195 if (qmlDebugVerbose())
196 qDebug() << "QML Debugger: Error while loading: " << loader.errorString();
199 if (QObject *instance = loader.instance())
200 connection = qobject_cast<QQmlDebugServerConnection*>(instance);
203 if (qmlDebugVerbose())
204 qDebug() << "QML Debugger: Plugin successfully loaded.";
209 if (qmlDebugVerbose())
210 qDebug() << "QML Debugger: Plugin does not implement interface QQmlDebugServerConnection.";
218 void QQmlDebugServerThread::run()
220 QQmlDebugServer *server = QQmlDebugServer::instance();
221 QQmlDebugServerConnection *connection
222 = server->d_func()->loadConnectionPlugin(m_pluginName);
224 connection->setServer(QQmlDebugServer::instance());
225 connection->setPort(m_port, m_block, m_hostAddress);
227 QCoreApplicationPrivate *appD = static_cast<QCoreApplicationPrivate*>(QObjectPrivate::get(qApp));
228 qWarning() << QString(QLatin1String("QML Debugger: Ignoring \"-qmljsdebugger=%1\". "
229 "Remote debugger plugin has not been found.")).arg(appD->qmljsDebugArgumentsString());
234 // make sure events still waiting are processed
235 QEventLoop eventLoop;
236 eventLoop.processEvents(QEventLoop::AllEvents);
239 bool QQmlDebugServer::hasDebuggingClient() const
241 Q_D(const QQmlDebugServer);
243 && d->connection->isConnected()
247 static QQmlDebugServer *qQmlDebugServer = 0;
250 static void cleanup()
252 delete qQmlDebugServer;
256 QQmlDebugServer *QQmlDebugServer::instance()
258 static bool commandLineTested = false;
260 if (!commandLineTested) {
261 commandLineTested = true;
263 QCoreApplicationPrivate *appD = static_cast<QCoreApplicationPrivate*>(QObjectPrivate::get(qApp));
264 #ifndef QT_QML_NO_DEBUGGER
265 // ### remove port definition when protocol is changed
271 // format: qmljsdebugger=port:3768[,host:<ip address>][,block] OR qmljsdebugger=ost[,block]
272 if (!appD->qmljsDebugArgumentsString().isEmpty()) {
273 if (!QQmlEnginePrivate::qml_debugging_enabled) {
274 qWarning() << QString(QLatin1String(
275 "QML Debugger: Ignoring \"-qmljsdebugger=%1\". "
276 "Debugging has not been enabled.")).arg(
277 appD->qmljsDebugArgumentsString());
282 QStringList lstjsDebugArguments = appD->qmljsDebugArgumentsString()
283 .split(QLatin1Char(','));
284 foreach (const QString &strArgument, lstjsDebugArguments) {
285 if (strArgument.startsWith(QLatin1String("port:"))) {
286 port = strArgument.mid(5).toInt(&ok);
287 pluginName = QLatin1String("qmldbg_tcp");
288 } else if (strArgument.startsWith(QLatin1String("host:"))) {
289 hostAddress = strArgument.mid(5);
290 } else if (strArgument == QLatin1String("block")) {
293 qWarning() << QString::fromLatin1("QML Debugger: Invalid argument '%1' "
294 "detected. Ignoring the same.")
300 qQmlDebugServer = new QQmlDebugServer();
301 QQmlDebugServerThread *thread = new QQmlDebugServerThread;
302 qQmlDebugServer->d_func()->thread = thread;
303 qQmlDebugServer->moveToThread(thread);
304 thread->setPluginName(pluginName);
305 thread->setPort(port, block, hostAddress);
307 QQmlDebugServerPrivate *d = qQmlDebugServer->d_func();
308 QMutexLocker locker(&d->messageArrivedMutex);
312 d->messageArrivedCondition.wait(&d->messageArrivedMutex);
315 qWarning() << QString(QLatin1String(
316 "QML Debugger: Ignoring \"-qmljsdebugger=%1\". "
317 "Format is -qmljsdebugger=port:<port>[,block]")).arg(
318 appD->qmljsDebugArgumentsString());
322 if (!appD->qmljsDebugArgumentsString().isEmpty()) {
323 qWarning() << QString(QLatin1String(
324 "QML Debugger: Ignoring \"-qmljsdebugger=%1\". "
325 "QtQml is not configured for debugging.")).arg(
326 appD->qmljsDebugArgumentsString());
331 return qQmlDebugServer;
334 QQmlDebugServer::QQmlDebugServer()
335 : QObject(*(new QQmlDebugServerPrivate))
337 qAddPostRoutine(cleanup);
340 // called from GUI thread!
341 QQmlDebugServer::~QQmlDebugServer()
343 Q_D(QQmlDebugServer);
346 QReadLocker lock(&d->pluginsLock);
347 foreach (QQmlDebugService *service, d->plugins.values()) {
348 d->changeServiceStateCalls.ref();
349 QMetaObject::invokeMethod(this, "_q_changeServiceState", Qt::QueuedConnection,
350 Q_ARG(QString, service->name()),
351 Q_ARG(QQmlDebugService::State, QQmlDebugService::NotConnected));
355 // Wait for changeServiceState calls to finish
356 // (while running an event loop because some services
357 // might again use slots to execute stuff in the GUI thread)
359 while (!d->changeServiceStateCalls.testAndSetOrdered(0, 0))
360 loop.processEvents();
367 delete d->connection;
370 void QQmlDebugServer::receiveMessage(const QByteArray &message)
372 // to be executed in debugger thread
373 Q_ASSERT(QThread::currentThread() == thread());
375 Q_D(QQmlDebugServer);
377 QDataStream in(message);
382 if (name == QLatin1String("QDeclarativeDebugServer")) {
387 in >> version >> d->clientPlugins;
389 // Send the hello answer immediately, since it needs to arrive before
390 // the plugins below start sending messages.
391 QByteArray helloAnswer;
393 QDataStream out(&helloAnswer, QIODevice::WriteOnly);
394 QStringList pluginNames;
395 QList<float> pluginVersions;
396 foreach (QQmlDebugService *service, d->plugins.values()) {
397 pluginNames << service->name();
398 pluginVersions << service->version();
401 out << QString(QStringLiteral("QDeclarativeDebugClient")) << 0 << protocolVersion << pluginNames << pluginVersions;
403 d->connection->send(QList<QByteArray>() << helloAnswer);
407 QReadLocker lock(&d->pluginsLock);
408 QHash<QString, QQmlDebugService*>::ConstIterator iter = d->plugins.constBegin();
409 for (; iter != d->plugins.constEnd(); ++iter) {
410 QQmlDebugService::State newState = QQmlDebugService::Unavailable;
411 if (d->clientPlugins.contains(iter.key()))
412 newState = QQmlDebugService::Enabled;
413 d->changeServiceStateCalls.ref();
414 d->_q_changeServiceState(iter.value()->name(), newState);
417 d->messageArrivedCondition.wakeAll();
419 } else if (op == 1) {
422 QStringList oldClientPlugins = d->clientPlugins;
423 in >> d->clientPlugins;
425 QReadLocker lock(&d->pluginsLock);
426 QHash<QString, QQmlDebugService*>::ConstIterator iter = d->plugins.constBegin();
427 for (; iter != d->plugins.constEnd(); ++iter) {
428 const QString pluginName = iter.key();
429 QQmlDebugService::State newState = QQmlDebugService::Unavailable;
430 if (d->clientPlugins.contains(pluginName))
431 newState = QQmlDebugService::Enabled;
433 if (oldClientPlugins.contains(pluginName)
434 != d->clientPlugins.contains(pluginName)) {
435 d->changeServiceStateCalls.ref();
436 d->_q_changeServiceState(iter.value()->name(), newState);
441 qWarning("QML Debugger: Invalid control message %d.", op);
442 d->connection->disconnect();
451 QReadLocker lock(&d->pluginsLock);
452 QHash<QString, QQmlDebugService *>::Iterator iter = d->plugins.find(name);
453 if (iter == d->plugins.end()) {
454 qWarning() << "QML Debugger: Message received for missing plugin" << name << ".";
456 (*iter)->messageReceived(message);
458 if (d->waitingForMessageNames.removeOne(name))
459 d->messageArrivedCondition.wakeAll();
462 qWarning("QML Debugger: Invalid hello message.");
468 void QQmlDebugServerPrivate::_q_changeServiceState(const QString &serviceName,
469 QQmlDebugService::State newState)
471 // to be executed in debugger thread
472 Q_ASSERT(QThread::currentThread() == q_func()->thread());
474 QQmlDebugService *service = 0;
476 QReadLocker lock(&pluginsLock);
477 service = plugins.value(serviceName);
480 if (service && (service->d_func()->state != newState)) {
481 service->stateAboutToBeChanged(newState);
482 service->d_func()->state = newState;
483 if (newState == QQmlDebugService::NotConnected)
484 service->d_func()->server = 0;
485 service->stateChanged(newState);
488 changeServiceStateCalls.deref();
491 void QQmlDebugServerPrivate::_q_sendMessages(const QList<QByteArray> &messages)
493 // to be executed in debugger thread
494 Q_ASSERT(QThread::currentThread() == q_func()->thread());
497 connection->send(messages);
500 QList<QQmlDebugService*> QQmlDebugServer::services() const
502 Q_D(const QQmlDebugServer);
503 QReadLocker lock(&d->pluginsLock);
504 return d->plugins.values();
507 QStringList QQmlDebugServer::serviceNames() const
509 Q_D(const QQmlDebugServer);
510 QReadLocker lock(&d->pluginsLock);
511 return d->plugins.keys();
514 bool QQmlDebugServer::addService(QQmlDebugService *service)
516 Q_D(QQmlDebugServer);
518 // to be executed in GUI thread
519 Q_ASSERT(QThread::currentThread() == QCoreApplication::instance()->thread());
522 QWriteLocker lock(&d->pluginsLock);
523 if (!service || d->plugins.contains(service->name()))
525 d->plugins.insert(service->name(), service);
528 QReadLocker lock(&d->pluginsLock);
529 d->advertisePlugins();
530 QQmlDebugService::State newState = QQmlDebugService::Unavailable;
531 if (d->clientPlugins.contains(service->name()))
532 newState = QQmlDebugService::Enabled;
533 service->d_func()->state = newState;
538 bool QQmlDebugServer::removeService(QQmlDebugService *service)
540 Q_D(QQmlDebugServer);
542 // to be executed in GUI thread
543 Q_ASSERT(QThread::currentThread() == QCoreApplication::instance()->thread());
546 QWriteLocker lock(&d->pluginsLock);
547 QQmlDebugService::State newState = QQmlDebugService::NotConnected;
549 d->changeServiceStateCalls.ref();
550 QMetaObject::invokeMethod(this, "_q_changeServiceState", Qt::QueuedConnection,
551 Q_ARG(QString, service->name()),
552 Q_ARG(QQmlDebugService::State, newState));
554 if (!service || !d->plugins.contains(service->name()))
556 d->plugins.remove(service->name());
558 d->advertisePlugins();
564 void QQmlDebugServer::sendMessages(QQmlDebugService *service,
565 const QList<QByteArray> &messages)
567 QList<QByteArray> prefixedMessages;
568 foreach (const QByteArray &message, messages) {
570 QDataStream out(&prefixed, QIODevice::WriteOnly);
571 out << service->name() << message;
572 prefixedMessages << prefixed;
575 QMetaObject::invokeMethod(this, "_q_sendMessages", Qt::QueuedConnection,
576 Q_ARG(QList<QByteArray>, prefixedMessages));
579 bool QQmlDebugServer::waitForMessage(QQmlDebugService *service)
581 // to be executed in GUI thread
582 Q_ASSERT(QThread::currentThread() == QCoreApplication::instance()->thread());
584 Q_D(QQmlDebugServer);
585 QReadLocker lock(&d->pluginsLock);
588 || !d->plugins.contains(service->name()))
591 d->messageArrivedMutex.lock();
592 d->waitingForMessageNames << service->name();
594 d->messageArrivedCondition.wait(&d->messageArrivedMutex);
595 } while (d->waitingForMessageNames.contains(service->name()));
596 d->messageArrivedMutex.unlock();
602 #include "moc_qqmldebugserver_p.cpp"