Debugger: Move server into it's own thread
[profile/ivi/qtdeclarative.git] / src / declarative / debugger / qdeclarativedebugserver.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
6 **
7 ** This file is part of the QtDeclarative module of the Qt Toolkit.
8 **
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 **
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 **
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
29 **
30 ** Other Usage
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** conditions contained in a signed written agreement between you and Nokia.
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "qdeclarativedebugserver_p.h"
43 #include "qdeclarativedebugservice_p.h"
44 #include "qdeclarativedebugservice_p_p.h"
45 #include <private/qdeclarativeengine_p.h>
46
47 #include <QtCore/QDir>
48 #include <QtCore/QPluginLoader>
49 #include <QtCore/QStringList>
50 #include <QtCore/qwaitcondition.h>
51
52 #include <private/qobject_p.h>
53 #include <private/qcoreapplication_p.h>
54
55 QT_BEGIN_NAMESPACE
56
57 /*
58   QDeclarativeDebug Protocol (Version 1):
59
60   handshake:
61     1. Client sends
62          "QDeclarativeDebugServer" 0 version pluginNames
63        version: an int representing the highest protocol version the client knows
64        pluginNames: plugins available on client side
65     2. Server sends
66          "QDeclarativeDebugClient" 0 version pluginNames
67        version: an int representing the highest protocol version the client & server know
68        pluginNames: plugins available on server side. plugins both in the client and server message are enabled.
69   client plugin advertisement
70     1. Client sends
71          "QDeclarativeDebugServer" 1 pluginNames
72   server plugin advertisement
73     1. Server sends
74          "QDeclarativeDebugClient" 1 pluginNames
75   plugin communication:
76        Everything send with a header different to "QDeclarativeDebugServer" is sent to the appropriate plugin.
77   */
78
79 const int protocolVersion = 1;
80
81 // print detailed information about loading of plugins
82 DEFINE_BOOL_CONFIG_OPTION(qmlDebugVerbose, QML_DEBUGGER_VERBOSE)
83
84 class QDeclarativeDebugServerThread;
85
86 class QDeclarativeDebugServerPrivate : public QObjectPrivate
87 {
88     Q_DECLARE_PUBLIC(QDeclarativeDebugServer)
89 public:
90     QDeclarativeDebugServerPrivate();
91
92     void advertisePlugins();
93     QDeclarativeDebugServerConnection *loadConnectionPlugin(const QString &pluginName);
94
95     QDeclarativeDebugServerConnection *connection;
96     QHash<QString, QDeclarativeDebugService *> plugins;
97     mutable QReadWriteLock pluginsLock;
98     QStringList clientPlugins;
99     bool gotHello;
100
101     QMutex messageArrivedMutex;
102     QWaitCondition messageArrivedCondition;
103     QStringList waitingForMessageNames;
104     QDeclarativeDebugServerThread *thread;
105     QPluginLoader loader;
106
107 private:
108     // private slot
109     void _q_sendMessage(const QByteArray &message);
110 };
111
112 class QDeclarativeDebugServerThread : public QThread
113 {
114 public:
115     void setPluginName(const QString &pluginName) {
116         m_pluginName = pluginName;
117     }
118
119     void setPort(int port, bool block) {
120         m_port = port;
121         m_block = block;
122     }
123
124     void run();
125
126 private:
127     QString m_pluginName;
128     int m_port;
129     bool m_block;
130 };
131
132 QDeclarativeDebugServerPrivate::QDeclarativeDebugServerPrivate() :
133     connection(0),
134     gotHello(false),
135     thread(0)
136 {
137 }
138
139 void QDeclarativeDebugServerPrivate::advertisePlugins()
140 {
141     Q_Q(QDeclarativeDebugServer);
142
143     if (!gotHello)
144         return;
145
146     QByteArray message;
147     {
148         QDataStream out(&message, QIODevice::WriteOnly);
149         out << QString(QLatin1String("QDeclarativeDebugClient")) << 1 << plugins.keys();
150     }
151
152     QMetaObject::invokeMethod(q, "_q_sendMessage", Qt::QueuedConnection, Q_ARG(QByteArray, message));
153 }
154
155 QDeclarativeDebugServerConnection *QDeclarativeDebugServerPrivate::loadConnectionPlugin(
156         const QString &pluginName)
157 {
158 #ifndef QT_NO_LIBRARY
159     QStringList pluginCandidates;
160     const QStringList paths = QCoreApplication::libraryPaths();
161     foreach (const QString &libPath, paths) {
162         const QDir dir(libPath + QLatin1String("/qmltooling"));
163         if (dir.exists()) {
164             QStringList plugins(dir.entryList(QDir::Files));
165             foreach (const QString &pluginPath, plugins) {
166                 if (QFileInfo(pluginPath).fileName().contains(pluginName))
167                     pluginCandidates << dir.absoluteFilePath(pluginPath);
168             }
169         }
170     }
171
172     foreach (const QString &pluginPath, pluginCandidates) {
173         if (qmlDebugVerbose())
174             qDebug() << "QDeclarativeDebugServer: Trying to load plugin " << pluginPath << "...";
175
176         loader.setFileName(pluginPath);
177         if (!loader.load()) {
178             if (qmlDebugVerbose())
179                 qDebug() << "QDeclarativeDebugServer: Error while loading: " << loader.errorString();
180             continue;
181         }
182         if (QObject *instance = loader.instance())
183             connection = qobject_cast<QDeclarativeDebugServerConnection*>(instance);
184
185         if (connection) {
186             if (qmlDebugVerbose())
187                 qDebug() << "QDeclarativeDebugServer: Plugin successfully loaded.";
188
189             return connection;
190         }
191
192         if (qmlDebugVerbose())
193             qDebug() << "QDeclarativeDebugServer: Plugin does not implement interface QDeclarativeDebugServerConnection.";
194
195         loader.unload();
196     }
197 #endif
198     return 0;
199 }
200
201 void QDeclarativeDebugServerThread::run()
202 {
203     QDeclarativeDebugServer *server = QDeclarativeDebugServer::instance();
204     QDeclarativeDebugServerConnection *connection
205             = server->d_func()->loadConnectionPlugin(m_pluginName);
206     if (connection) {
207         connection->setServer(QDeclarativeDebugServer::instance());
208         connection->setPort(m_port, m_block);
209     } else {
210         QCoreApplicationPrivate *appD = static_cast<QCoreApplicationPrivate*>(QObjectPrivate::get(qApp));
211         qWarning() << QString::fromAscii("QDeclarativeDebugServer: Ignoring \"-qmljsdebugger=%1\". "
212                                          "Remote debugger plugin has not been found.").arg(appD->qmljsDebugArgumentsString());
213     }
214
215     exec();
216 }
217
218 bool QDeclarativeDebugServer::hasDebuggingClient() const
219 {
220     Q_D(const QDeclarativeDebugServer);
221     return d->connection
222             && d->connection->isConnected()
223             && d->gotHello;
224 }
225
226 static QDeclarativeDebugServer *qDeclarativeDebugServer = 0;
227
228 QDeclarativeDebugServer *QDeclarativeDebugServer::instance()
229 {
230     static bool commandLineTested = false;
231
232     if (!commandLineTested) {
233         commandLineTested = true;
234
235         QCoreApplicationPrivate *appD = static_cast<QCoreApplicationPrivate*>(QObjectPrivate::get(qApp));
236 #ifndef QDECLARATIVE_NO_DEBUG_PROTOCOL
237         // ### remove port definition when protocol is changed
238         int port = 0;
239         bool block = false;
240         bool ok = false;
241
242         // format: qmljsdebugger=port:3768[,block] OR qmljsdebugger=ost[,block]
243         if (!appD->qmljsDebugArgumentsString().isEmpty()) {
244             if (!QDeclarativeEnginePrivate::qml_debugging_enabled) {
245                 qWarning() << QString::fromLatin1(
246                                   "QDeclarativeDebugServer: Ignoring \"-qmljsdebugger=%1\". "
247                                   "Debugging has not been enabled.").arg(
248                                   appD->qmljsDebugArgumentsString());
249                 return 0;
250             }
251
252             QString pluginName;
253             if (appD->qmljsDebugArgumentsString().indexOf(QLatin1String("port:")) == 0) {
254                 int separatorIndex = appD->qmljsDebugArgumentsString().indexOf(QLatin1Char(','));
255                 port = appD->qmljsDebugArgumentsString().mid(5, separatorIndex - 5).toInt(&ok);
256                 pluginName = QLatin1String("qmldbg_tcp");
257             } else if (appD->qmljsDebugArgumentsString().contains(QLatin1String("ost"))) {
258                 pluginName = QLatin1String("qmldbg_ost");
259                 ok = true;
260             }
261
262             block = appD->qmljsDebugArgumentsString().contains(QLatin1String("block"));
263
264             if (ok) {
265                 qDeclarativeDebugServer = new QDeclarativeDebugServer();
266
267                 QDeclarativeDebugServerThread *thread = new QDeclarativeDebugServerThread;
268
269                 qDeclarativeDebugServer = new QDeclarativeDebugServer();
270                 qDeclarativeDebugServer->d_func()->thread = thread;
271                 qDeclarativeDebugServer->moveToThread(thread);
272                 thread->setPluginName(pluginName);
273                 thread->setPort(port, block);
274                 thread->start();
275
276                 if (block) {
277                     QDeclarativeDebugServerPrivate *d = qDeclarativeDebugServer->d_func();
278                     d->messageArrivedMutex.lock();
279                     d->messageArrivedCondition.wait(&d->messageArrivedMutex);
280                     d->messageArrivedMutex.unlock();
281                 }
282
283             } else {
284                 qWarning() << QString::fromLatin1(
285                                   "QDeclarativeDebugServer: Ignoring \"-qmljsdebugger=%1\". "
286                                   "Format is -qmljsdebugger=port:<port>[,block]").arg(
287                                   appD->qmljsDebugArgumentsString());
288             }
289         }
290 #else
291         if (!appD->qmljsDebugArgumentsString().isEmpty()) {
292             qWarning() << QString::fromLatin1(
293                          "QDeclarativeDebugServer: Ignoring \"-qmljsdebugger=%1\". "
294                          "QtDeclarative is not configured for debugging.").arg(
295                          appD->qmljsDebugArgumentsString());
296         }
297 #endif
298     }
299
300     return qDeclarativeDebugServer;
301 }
302
303 QDeclarativeDebugServer::QDeclarativeDebugServer()
304     : QObject(*(new QDeclarativeDebugServerPrivate))
305 {
306 }
307
308 void QDeclarativeDebugServer::receiveMessage(const QByteArray &message)
309 {
310     Q_D(QDeclarativeDebugServer);
311
312     QDataStream in(message);
313
314     QString name;
315
316     in >> name;
317     if (name == QLatin1String("QDeclarativeDebugServer")) {
318         int op = -1;
319         in >> op;
320         if (op == 0) {
321             int version;
322             in >> version >> d->clientPlugins;
323
324             // Send the hello answer immediately, since it needs to arrive before
325             // the plugins below start sending messages.
326             QByteArray helloAnswer;
327             {
328                 QDataStream out(&helloAnswer, QIODevice::WriteOnly);
329                 out << QString(QLatin1String("QDeclarativeDebugClient")) << 0 << protocolVersion << d->plugins.keys();
330             }
331             d->connection->send(helloAnswer);
332
333             d->gotHello = true;
334
335             QReadLocker(&d->pluginsLock);
336             QHash<QString, QDeclarativeDebugService*>::ConstIterator iter = d->plugins.constBegin();
337             for (; iter != d->plugins.constEnd(); ++iter) {
338                 QDeclarativeDebugService::Status newStatus = QDeclarativeDebugService::Unavailable;
339                 if (d->clientPlugins.contains(iter.key()))
340                     newStatus = QDeclarativeDebugService::Enabled;
341                 iter.value()->d_func()->status = newStatus;
342                 iter.value()->statusChanged(newStatus);
343             }
344
345             qWarning("QDeclarativeDebugServer: Connection established");
346             d->messageArrivedCondition.wakeAll();
347
348         } else if (op == 1) {
349
350             // Service Discovery
351             QStringList oldClientPlugins = d->clientPlugins;
352             in >> d->clientPlugins;
353
354             QReadLocker(&d->pluginsLock);
355             QHash<QString, QDeclarativeDebugService*>::ConstIterator iter = d->plugins.constBegin();
356             for (; iter != d->plugins.constEnd(); ++iter) {
357                 const QString pluginName = iter.key();
358                 QDeclarativeDebugService::Status newStatus = QDeclarativeDebugService::Unavailable;
359                 if (d->clientPlugins.contains(pluginName))
360                     newStatus = QDeclarativeDebugService::Enabled;
361
362                 if (oldClientPlugins.contains(pluginName)
363                         != d->clientPlugins.contains(pluginName)) {
364                     iter.value()->d_func()->status = newStatus;
365                     iter.value()->statusChanged(newStatus);
366                 }
367             }
368
369         } else {
370             qWarning("QDeclarativeDebugServer: Invalid control message %d", op);
371             d->connection->disconnect();
372             return;
373         }
374
375     } else {
376         if (d->gotHello) {
377             QByteArray message;
378             in >> message;
379
380             QReadLocker(&d->pluginsLock);
381             QHash<QString, QDeclarativeDebugService *>::Iterator iter = d->plugins.find(name);
382             if (iter == d->plugins.end()) {
383                 qWarning() << "QDeclarativeDebugServer: Message received for missing plugin" << name;
384             } else {
385                 (*iter)->messageReceived(message);
386
387                 if (d->waitingForMessageNames.removeOne(name))
388                     d->messageArrivedCondition.wakeAll();
389             }
390         } else {
391             qWarning("QDeclarativeDebugServer: Invalid hello message");
392         }
393
394     }
395 }
396
397 void QDeclarativeDebugServerPrivate::_q_sendMessage(const QByteArray &message)
398 {
399     if (connection)
400         connection->send(message);
401 }
402
403 QList<QDeclarativeDebugService*> QDeclarativeDebugServer::services() const
404 {
405     const Q_D(QDeclarativeDebugServer);
406     QReadLocker(&d->pluginsLock);
407     return d->plugins.values();
408 }
409
410 QStringList QDeclarativeDebugServer::serviceNames() const
411 {
412     const Q_D(QDeclarativeDebugServer);
413     QReadLocker(&d->pluginsLock);
414     return d->plugins.keys();
415 }
416
417 bool QDeclarativeDebugServer::addService(QDeclarativeDebugService *service)
418 {
419     Q_D(QDeclarativeDebugServer);
420     {
421         QWriteLocker(&d->pluginsLock);
422         if (!service || d->plugins.contains(service->name()))
423             return false;
424         d->plugins.insert(service->name(), service);
425     }
426     {
427         QReadLocker(&d->pluginsLock);
428         d->advertisePlugins();
429         QDeclarativeDebugService::Status newStatus = QDeclarativeDebugService::Unavailable;
430         if (d->clientPlugins.contains(service->name()))
431             newStatus = QDeclarativeDebugService::Enabled;
432         service->d_func()->status = newStatus;
433     }
434     return true;
435 }
436
437 bool QDeclarativeDebugServer::removeService(QDeclarativeDebugService *service)
438 {
439     Q_D(QDeclarativeDebugServer);
440     {
441         QWriteLocker(&d->pluginsLock);
442         if (!service || !d->plugins.contains(service->name()))
443             return false;
444         d->plugins.remove(service->name());
445     }
446     {
447         QReadLocker(&d->pluginsLock);
448         d->advertisePlugins();
449         QDeclarativeDebugService::Status newStatus = QDeclarativeDebugService::NotConnected;
450         service->d_func()->server = 0;
451         service->d_func()->status = newStatus;
452         service->statusChanged(newStatus);
453
454         // Last service? Then stop thread & delete instance
455         if (d->plugins.isEmpty()) {
456             d->thread->exit();
457             d->thread->wait();
458             delete d->thread;
459             delete d->connection;
460
461             qDeclarativeDebugServer = 0;
462             deleteLater();
463         }
464     }
465
466     return true;
467 }
468
469 void QDeclarativeDebugServer::sendMessage(QDeclarativeDebugService *service,
470                                           const QByteArray &message)
471 {
472     QByteArray msg;
473     {
474         QDataStream out(&msg, QIODevice::WriteOnly);
475         out << service->name() << message;
476     }
477
478     QMetaObject::invokeMethod(this, "_q_sendMessage", Qt::QueuedConnection, Q_ARG(QByteArray, msg));
479 }
480
481 bool QDeclarativeDebugServer::waitForMessage(QDeclarativeDebugService *service)
482 {
483     Q_D(QDeclarativeDebugServer);
484     QReadLocker(&d->pluginsLock);
485
486     if (!service
487             || !d->plugins.contains(service->name()))
488         return false;
489
490     d->messageArrivedMutex.lock();
491     d->waitingForMessageNames << service->name();
492     do {
493         d->messageArrivedCondition.wait(&d->messageArrivedMutex);
494     } while (d->waitingForMessageNames.contains(service->name()));
495     d->messageArrivedMutex.unlock();
496     return true;
497 }
498
499 QT_END_NAMESPACE
500
501 #include "moc_qdeclarativedebugserver_p.cpp"