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);
309 QQmlDebugServerPrivate *d = qQmlDebugServer->d_func();
310 d->messageArrivedMutex.lock();
311 d->messageArrivedCondition.wait(&d->messageArrivedMutex);
312 d->messageArrivedMutex.unlock();
316 qWarning() << QString(QLatin1String(
317 "QML Debugger: Ignoring \"-qmljsdebugger=%1\". "
318 "Format is -qmljsdebugger=port:<port>[,block]")).arg(
319 appD->qmljsDebugArgumentsString());
323 if (!appD->qmljsDebugArgumentsString().isEmpty()) {
324 qWarning() << QString(QLatin1String(
325 "QML Debugger: Ignoring \"-qmljsdebugger=%1\". "
326 "QtQml is not configured for debugging.")).arg(
327 appD->qmljsDebugArgumentsString());
332 return qQmlDebugServer;
335 QQmlDebugServer::QQmlDebugServer()
336 : QObject(*(new QQmlDebugServerPrivate))
338 qAddPostRoutine(cleanup);
341 // called from GUI thread!
342 QQmlDebugServer::~QQmlDebugServer()
344 Q_D(QQmlDebugServer);
346 QReadLocker(&d->pluginsLock);
348 foreach (QQmlDebugService *service, d->plugins.values()) {
349 d->changeServiceStateCalls.ref();
350 QMetaObject::invokeMethod(this, "_q_changeServiceState", Qt::QueuedConnection,
351 Q_ARG(QString, service->name()),
352 Q_ARG(QQmlDebugService::State, QQmlDebugService::NotConnected));
356 // Wait for changeServiceState calls to finish
357 // (while running an event loop because some services
358 // might again use slots to execute stuff in the GUI thread)
360 while (!d->changeServiceStateCalls.testAndSetOrdered(0, 0))
361 loop.processEvents();
368 delete d->connection;
371 void QQmlDebugServer::receiveMessage(const QByteArray &message)
373 // to be executed in debugger thread
374 Q_ASSERT(QThread::currentThread() == thread());
376 Q_D(QQmlDebugServer);
378 QDataStream in(message);
383 if (name == QLatin1String("QDeclarativeDebugServer")) {
388 in >> version >> d->clientPlugins;
390 // Send the hello answer immediately, since it needs to arrive before
391 // the plugins below start sending messages.
392 QByteArray helloAnswer;
394 QDataStream out(&helloAnswer, QIODevice::WriteOnly);
395 QStringList pluginNames;
396 QList<float> pluginVersions;
397 foreach (QQmlDebugService *service, d->plugins.values()) {
398 pluginNames << service->name();
399 pluginVersions << service->version();
402 out << QString(QStringLiteral("QDeclarativeDebugClient")) << 0 << protocolVersion << pluginNames << pluginVersions;
404 d->connection->send(QList<QByteArray>() << helloAnswer);
408 QReadLocker(&d->pluginsLock);
409 QHash<QString, QQmlDebugService*>::ConstIterator iter = d->plugins.constBegin();
410 for (; iter != d->plugins.constEnd(); ++iter) {
411 QQmlDebugService::State newState = QQmlDebugService::Unavailable;
412 if (d->clientPlugins.contains(iter.key()))
413 newState = QQmlDebugService::Enabled;
414 d->changeServiceStateCalls.ref();
415 d->_q_changeServiceState(iter.value()->name(), newState);
418 d->messageArrivedCondition.wakeAll();
420 } else if (op == 1) {
423 QStringList oldClientPlugins = d->clientPlugins;
424 in >> d->clientPlugins;
426 QReadLocker(&d->pluginsLock);
427 QHash<QString, QQmlDebugService*>::ConstIterator iter = d->plugins.constBegin();
428 for (; iter != d->plugins.constEnd(); ++iter) {
429 const QString pluginName = iter.key();
430 QQmlDebugService::State newState = QQmlDebugService::Unavailable;
431 if (d->clientPlugins.contains(pluginName))
432 newState = QQmlDebugService::Enabled;
434 if (oldClientPlugins.contains(pluginName)
435 != d->clientPlugins.contains(pluginName)) {
436 d->changeServiceStateCalls.ref();
437 d->_q_changeServiceState(iter.value()->name(), newState);
442 qWarning("QML Debugger: Invalid control message %d.", op);
443 d->connection->disconnect();
452 QReadLocker(&d->pluginsLock);
453 QHash<QString, QQmlDebugService *>::Iterator iter = d->plugins.find(name);
454 if (iter == d->plugins.end()) {
455 qWarning() << "QML Debugger: Message received for missing plugin" << name << ".";
457 (*iter)->messageReceived(message);
459 if (d->waitingForMessageNames.removeOne(name))
460 d->messageArrivedCondition.wakeAll();
463 qWarning("QML Debugger: Invalid hello message.");
469 void QQmlDebugServerPrivate::_q_changeServiceState(const QString &serviceName,
470 QQmlDebugService::State newState)
472 // to be executed in debugger thread
473 Q_ASSERT(QThread::currentThread() == q_func()->thread());
475 QQmlDebugService *service = 0;
477 QReadLocker lock(&pluginsLock);
478 service = plugins.value(serviceName);
481 if (service && (service->d_func()->state != newState)) {
482 service->stateAboutToBeChanged(newState);
483 service->d_func()->state = newState;
484 if (newState == QQmlDebugService::NotConnected)
485 service->d_func()->server = 0;
486 service->stateChanged(newState);
489 changeServiceStateCalls.deref();
492 void QQmlDebugServerPrivate::_q_sendMessages(const QList<QByteArray> &messages)
494 // to be executed in debugger thread
495 Q_ASSERT(QThread::currentThread() == q_func()->thread());
498 connection->send(messages);
501 QList<QQmlDebugService*> QQmlDebugServer::services() const
503 Q_D(const QQmlDebugServer);
504 QReadLocker(&d->pluginsLock);
505 return d->plugins.values();
508 QStringList QQmlDebugServer::serviceNames() const
510 Q_D(const QQmlDebugServer);
511 QReadLocker(&d->pluginsLock);
512 return d->plugins.keys();
515 bool QQmlDebugServer::addService(QQmlDebugService *service)
517 Q_D(QQmlDebugServer);
519 // to be executed in GUI thread
520 Q_ASSERT(QThread::currentThread() == QCoreApplication::instance()->thread());
523 QWriteLocker(&d->pluginsLock);
524 if (!service || d->plugins.contains(service->name()))
526 d->plugins.insert(service->name(), service);
529 QReadLocker(&d->pluginsLock);
530 d->advertisePlugins();
531 QQmlDebugService::State newState = QQmlDebugService::Unavailable;
532 if (d->clientPlugins.contains(service->name()))
533 newState = QQmlDebugService::Enabled;
534 service->d_func()->state = newState;
539 bool QQmlDebugServer::removeService(QQmlDebugService *service)
541 Q_D(QQmlDebugServer);
543 // to be executed in GUI thread
544 Q_ASSERT(QThread::currentThread() == QCoreApplication::instance()->thread());
547 QWriteLocker(&d->pluginsLock);
548 QQmlDebugService::State newState = QQmlDebugService::NotConnected;
550 d->changeServiceStateCalls.ref();
551 QMetaObject::invokeMethod(this, "_q_changeServiceState", Qt::QueuedConnection,
552 Q_ARG(QString, service->name()),
553 Q_ARG(QQmlDebugService::State, newState));
555 if (!service || !d->plugins.contains(service->name()))
557 d->plugins.remove(service->name());
559 d->advertisePlugins();
565 void QQmlDebugServer::sendMessages(QQmlDebugService *service,
566 const QList<QByteArray> &messages)
568 QList<QByteArray> prefixedMessages;
569 foreach (const QByteArray &message, messages) {
571 QDataStream out(&prefixed, QIODevice::WriteOnly);
572 out << service->name() << message;
573 prefixedMessages << prefixed;
576 QMetaObject::invokeMethod(this, "_q_sendMessages", Qt::QueuedConnection,
577 Q_ARG(QList<QByteArray>, prefixedMessages));
580 bool QQmlDebugServer::waitForMessage(QQmlDebugService *service)
582 // to be executed in GUI thread
583 Q_ASSERT(QThread::currentThread() == QCoreApplication::instance()->thread());
585 Q_D(QQmlDebugServer);
586 QReadLocker(&d->pluginsLock);
589 || !d->plugins.contains(service->name()))
592 d->messageArrivedMutex.lock();
593 d->waitingForMessageNames << service->name();
595 d->messageArrivedCondition.wait(&d->messageArrivedMutex);
596 } while (d->waitingForMessageNames.contains(service->name()));
597 d->messageArrivedMutex.unlock();
603 #include "moc_qqmldebugserver_p.cpp"