Remove "All rights reserved" line from license headers.
[profile/ivi/qtdeclarative.git] / src / declarative / debugger / qdeclarativedebugserver.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the QtDeclarative module of the Qt Toolkit.
7 **
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.
16 **
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.
20 **
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.
28 **
29 ** Other Usage
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.
32 **
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 pluginVersions
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 pluginVersions
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_sendMessages(const QList<QByteArray> &messages);
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     // used in _q_sendMessages
138     qRegisterMetaType<QList<QByteArray> >("QList<QByteArray>");
139 }
140
141 void QDeclarativeDebugServerPrivate::advertisePlugins()
142 {
143     Q_Q(QDeclarativeDebugServer);
144
145     if (!gotHello)
146         return;
147
148     QByteArray message;
149     {
150         QDataStream out(&message, QIODevice::WriteOnly);
151         QStringList pluginNames;
152         QList<float> pluginVersions;
153         foreach (QDeclarativeDebugService *service, plugins.values()) {
154             pluginNames << service->name();
155             pluginVersions << service->version();
156         }
157         out << QString(QLatin1String("QDeclarativeDebugClient")) << 1 << pluginNames << pluginVersions;
158     }
159
160     QMetaObject::invokeMethod(q, "_q_sendMessages", Qt::QueuedConnection, Q_ARG(QList<QByteArray>, QList<QByteArray>() << message));
161 }
162
163 QDeclarativeDebugServerConnection *QDeclarativeDebugServerPrivate::loadConnectionPlugin(
164         const QString &pluginName)
165 {
166 #ifndef QT_NO_LIBRARY
167     QStringList pluginCandidates;
168     const QStringList paths = QCoreApplication::libraryPaths();
169     foreach (const QString &libPath, paths) {
170         const QDir dir(libPath + QLatin1String("/qmltooling"));
171         if (dir.exists()) {
172             QStringList plugins(dir.entryList(QDir::Files));
173             foreach (const QString &pluginPath, plugins) {
174                 if (QFileInfo(pluginPath).fileName().contains(pluginName))
175                     pluginCandidates << dir.absoluteFilePath(pluginPath);
176             }
177         }
178     }
179
180     foreach (const QString &pluginPath, pluginCandidates) {
181         if (qmlDebugVerbose())
182             qDebug() << "QDeclarativeDebugServer: Trying to load plugin " << pluginPath << "...";
183
184         loader.setFileName(pluginPath);
185         if (!loader.load()) {
186             if (qmlDebugVerbose())
187                 qDebug() << "QDeclarativeDebugServer: Error while loading: " << loader.errorString();
188             continue;
189         }
190         if (QObject *instance = loader.instance())
191             connection = qobject_cast<QDeclarativeDebugServerConnection*>(instance);
192
193         if (connection) {
194             if (qmlDebugVerbose())
195                 qDebug() << "QDeclarativeDebugServer: Plugin successfully loaded.";
196
197             return connection;
198         }
199
200         if (qmlDebugVerbose())
201             qDebug() << "QDeclarativeDebugServer: Plugin does not implement interface QDeclarativeDebugServerConnection.";
202
203         loader.unload();
204     }
205 #endif
206     return 0;
207 }
208
209 void QDeclarativeDebugServerThread::run()
210 {
211     QDeclarativeDebugServer *server = QDeclarativeDebugServer::instance();
212     QDeclarativeDebugServerConnection *connection
213             = server->d_func()->loadConnectionPlugin(m_pluginName);
214     if (connection) {
215         connection->setServer(QDeclarativeDebugServer::instance());
216         connection->setPort(m_port, m_block);
217     } else {
218         QCoreApplicationPrivate *appD = static_cast<QCoreApplicationPrivate*>(QObjectPrivate::get(qApp));
219         qWarning() << QString::fromAscii("QDeclarativeDebugServer: Ignoring \"-qmljsdebugger=%1\". "
220                                          "Remote debugger plugin has not been found.").arg(appD->qmljsDebugArgumentsString());
221     }
222
223     exec();
224 }
225
226 bool QDeclarativeDebugServer::hasDebuggingClient() const
227 {
228     Q_D(const QDeclarativeDebugServer);
229     return d->connection
230             && d->connection->isConnected()
231             && d->gotHello;
232 }
233
234 static QDeclarativeDebugServer *qDeclarativeDebugServer = 0;
235
236
237 static void cleanup()
238 {
239     delete qDeclarativeDebugServer;
240     qDeclarativeDebugServer = 0;
241 }
242
243 QDeclarativeDebugServer *QDeclarativeDebugServer::instance()
244 {
245     static bool commandLineTested = false;
246
247     if (!commandLineTested) {
248         commandLineTested = true;
249
250         QCoreApplicationPrivate *appD = static_cast<QCoreApplicationPrivate*>(QObjectPrivate::get(qApp));
251 #ifndef QDECLARATIVE_NO_DEBUG_PROTOCOL
252         // ### remove port definition when protocol is changed
253         int port = 0;
254         bool block = false;
255         bool ok = false;
256
257         // format: qmljsdebugger=port:3768[,block] OR qmljsdebugger=ost[,block]
258         if (!appD->qmljsDebugArgumentsString().isEmpty()) {
259             if (!QDeclarativeEnginePrivate::qml_debugging_enabled) {
260                 qWarning() << QString::fromLatin1(
261                                   "QDeclarativeDebugServer: Ignoring \"-qmljsdebugger=%1\". "
262                                   "Debugging has not been enabled.").arg(
263                                   appD->qmljsDebugArgumentsString());
264                 return 0;
265             }
266
267             QString pluginName;
268             if (appD->qmljsDebugArgumentsString().indexOf(QLatin1String("port:")) == 0) {
269                 int separatorIndex = appD->qmljsDebugArgumentsString().indexOf(QLatin1Char(','));
270                 port = appD->qmljsDebugArgumentsString().mid(5, separatorIndex - 5).toInt(&ok);
271                 pluginName = QLatin1String("qmldbg_tcp");
272             } else if (appD->qmljsDebugArgumentsString().contains(QLatin1String("ost"))) {
273                 pluginName = QLatin1String("qmldbg_ost");
274                 ok = true;
275             }
276
277             block = appD->qmljsDebugArgumentsString().contains(QLatin1String("block"));
278
279             if (ok) {
280                 qDeclarativeDebugServer = new QDeclarativeDebugServer();
281                 QDeclarativeDebugServerThread *thread = new QDeclarativeDebugServerThread;
282                 qDeclarativeDebugServer->d_func()->thread = thread;
283                 qDeclarativeDebugServer->moveToThread(thread);
284                 thread->setPluginName(pluginName);
285                 thread->setPort(port, block);
286                 thread->start();
287
288                 if (block) {
289                     QDeclarativeDebugServerPrivate *d = qDeclarativeDebugServer->d_func();
290                     d->messageArrivedMutex.lock();
291                     d->messageArrivedCondition.wait(&d->messageArrivedMutex);
292                     d->messageArrivedMutex.unlock();
293                 }
294
295             } else {
296                 qWarning() << QString::fromLatin1(
297                                   "QDeclarativeDebugServer: Ignoring \"-qmljsdebugger=%1\". "
298                                   "Format is -qmljsdebugger=port:<port>[,block]").arg(
299                                   appD->qmljsDebugArgumentsString());
300             }
301         }
302 #else
303         if (!appD->qmljsDebugArgumentsString().isEmpty()) {
304             qWarning() << QString::fromLatin1(
305                          "QDeclarativeDebugServer: Ignoring \"-qmljsdebugger=%1\". "
306                          "QtDeclarative is not configured for debugging.").arg(
307                          appD->qmljsDebugArgumentsString());
308         }
309 #endif
310     }
311
312     return qDeclarativeDebugServer;
313 }
314
315 QDeclarativeDebugServer::QDeclarativeDebugServer()
316     : QObject(*(new QDeclarativeDebugServerPrivate))
317 {
318     qAddPostRoutine(cleanup);
319 }
320
321 QDeclarativeDebugServer::~QDeclarativeDebugServer()
322 {
323     Q_D(QDeclarativeDebugServer);
324
325     QReadLocker(&d->pluginsLock);
326     {
327         foreach (QDeclarativeDebugService *service, d->plugins.values()) {
328             service->d_func()->server = 0;
329             service->d_func()->status = QDeclarativeDebugService::NotConnected;
330             service->statusChanged(QDeclarativeDebugService::NotConnected);
331         }
332     }
333
334     if (d->thread) {
335         d->thread->exit();
336         if (!d->thread->wait(1000))
337             d->thread->terminate();
338         delete d->thread;
339     }
340     delete d->connection;
341 }
342
343 void QDeclarativeDebugServer::receiveMessage(const QByteArray &message)
344 {
345     Q_D(QDeclarativeDebugServer);
346
347     QDataStream in(message);
348
349     QString name;
350
351     in >> name;
352     if (name == QLatin1String("QDeclarativeDebugServer")) {
353         int op = -1;
354         in >> op;
355         if (op == 0) {
356             int version;
357             in >> version >> d->clientPlugins;
358
359             // Send the hello answer immediately, since it needs to arrive before
360             // the plugins below start sending messages.
361             QByteArray helloAnswer;
362             {
363                 QDataStream out(&helloAnswer, QIODevice::WriteOnly);
364                 QStringList pluginNames;
365                 QList<float> pluginVersions;
366                 foreach (QDeclarativeDebugService *service, d->plugins.values()) {
367                     pluginNames << service->name();
368                     pluginVersions << service->version();
369                 }
370
371                 out << QString(QLatin1String("QDeclarativeDebugClient")) << 0 << protocolVersion << pluginNames << pluginVersions;
372             }
373             d->connection->send(QList<QByteArray>() << helloAnswer);
374
375             d->gotHello = true;
376
377             QReadLocker(&d->pluginsLock);
378             QHash<QString, QDeclarativeDebugService*>::ConstIterator iter = d->plugins.constBegin();
379             for (; iter != d->plugins.constEnd(); ++iter) {
380                 QDeclarativeDebugService::Status newStatus = QDeclarativeDebugService::Unavailable;
381                 if (d->clientPlugins.contains(iter.key()))
382                     newStatus = QDeclarativeDebugService::Enabled;
383                 iter.value()->d_func()->status = newStatus;
384                 iter.value()->statusChanged(newStatus);
385             }
386
387             qWarning("QDeclarativeDebugServer: Connection established");
388             d->messageArrivedCondition.wakeAll();
389
390         } else if (op == 1) {
391
392             // Service Discovery
393             QStringList oldClientPlugins = d->clientPlugins;
394             in >> d->clientPlugins;
395
396             QReadLocker(&d->pluginsLock);
397             QHash<QString, QDeclarativeDebugService*>::ConstIterator iter = d->plugins.constBegin();
398             for (; iter != d->plugins.constEnd(); ++iter) {
399                 const QString pluginName = iter.key();
400                 QDeclarativeDebugService::Status newStatus = QDeclarativeDebugService::Unavailable;
401                 if (d->clientPlugins.contains(pluginName))
402                     newStatus = QDeclarativeDebugService::Enabled;
403
404                 if (oldClientPlugins.contains(pluginName)
405                         != d->clientPlugins.contains(pluginName)) {
406                     iter.value()->d_func()->status = newStatus;
407                     iter.value()->statusChanged(newStatus);
408                 }
409             }
410
411         } else {
412             qWarning("QDeclarativeDebugServer: Invalid control message %d", op);
413             d->connection->disconnect();
414             return;
415         }
416
417     } else {
418         if (d->gotHello) {
419             QByteArray message;
420             in >> message;
421
422             QReadLocker(&d->pluginsLock);
423             QHash<QString, QDeclarativeDebugService *>::Iterator iter = d->plugins.find(name);
424             if (iter == d->plugins.end()) {
425                 qWarning() << "QDeclarativeDebugServer: Message received for missing plugin" << name;
426             } else {
427                 (*iter)->messageReceived(message);
428
429                 if (d->waitingForMessageNames.removeOne(name))
430                     d->messageArrivedCondition.wakeAll();
431             }
432         } else {
433             qWarning("QDeclarativeDebugServer: Invalid hello message");
434         }
435
436     }
437 }
438
439 void QDeclarativeDebugServerPrivate::_q_sendMessages(const QList<QByteArray> &messages)
440 {
441     if (connection)
442         connection->send(messages);
443 }
444
445 QList<QDeclarativeDebugService*> QDeclarativeDebugServer::services() const
446 {
447     const Q_D(QDeclarativeDebugServer);
448     QReadLocker(&d->pluginsLock);
449     return d->plugins.values();
450 }
451
452 QStringList QDeclarativeDebugServer::serviceNames() const
453 {
454     const Q_D(QDeclarativeDebugServer);
455     QReadLocker(&d->pluginsLock);
456     return d->plugins.keys();
457 }
458
459 bool QDeclarativeDebugServer::addService(QDeclarativeDebugService *service)
460 {
461     Q_D(QDeclarativeDebugServer);
462     {
463         QWriteLocker(&d->pluginsLock);
464         if (!service || d->plugins.contains(service->name()))
465             return false;
466         d->plugins.insert(service->name(), service);
467     }
468     {
469         QReadLocker(&d->pluginsLock);
470         d->advertisePlugins();
471         QDeclarativeDebugService::Status newStatus = QDeclarativeDebugService::Unavailable;
472         if (d->clientPlugins.contains(service->name()))
473             newStatus = QDeclarativeDebugService::Enabled;
474         service->d_func()->status = newStatus;
475     }
476     return true;
477 }
478
479 bool QDeclarativeDebugServer::removeService(QDeclarativeDebugService *service)
480 {
481     Q_D(QDeclarativeDebugServer);
482     {
483         QWriteLocker(&d->pluginsLock);
484         if (!service || !d->plugins.contains(service->name()))
485             return false;
486         d->plugins.remove(service->name());
487     }
488     {
489         QReadLocker(&d->pluginsLock);
490         d->advertisePlugins();
491         QDeclarativeDebugService::Status newStatus = QDeclarativeDebugService::NotConnected;
492         service->d_func()->server = 0;
493         service->d_func()->status = newStatus;
494         service->statusChanged(newStatus);
495     }
496
497     return true;
498 }
499
500 void QDeclarativeDebugServer::sendMessages(QDeclarativeDebugService *service,
501                                           const QList<QByteArray> &messages)
502 {
503     QList<QByteArray> prefixedMessages;
504     foreach (const QByteArray &message, messages) {
505         QByteArray prefixed;
506         QDataStream out(&prefixed, QIODevice::WriteOnly);
507         out << service->name() << message;
508         prefixedMessages << prefixed;
509     }
510
511     QMetaObject::invokeMethod(this, "_q_sendMessages", Qt::QueuedConnection, Q_ARG(QList<QByteArray>, prefixedMessages));
512 }
513
514 bool QDeclarativeDebugServer::waitForMessage(QDeclarativeDebugService *service)
515 {
516     Q_D(QDeclarativeDebugServer);
517     QReadLocker(&d->pluginsLock);
518
519     if (!service
520             || !d->plugins.contains(service->name()))
521         return false;
522
523     d->messageArrivedMutex.lock();
524     d->waitingForMessageNames << service->name();
525     do {
526         d->messageArrivedCondition.wait(&d->messageArrivedMutex);
527     } while (d->waitingForMessageNames.contains(service->name()));
528     d->messageArrivedMutex.unlock();
529     return true;
530 }
531
532 QT_END_NAMESPACE
533
534 #include "moc_qdeclarativedebugserver_p.cpp"