482847c7a7485a7b73fb1dd29d8db61c89afeef2
[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     // make sure events still waiting are processed
226     QEventLoop eventLoop;
227     eventLoop.processEvents(QEventLoop::AllEvents);
228 }
229
230 bool QDeclarativeDebugServer::hasDebuggingClient() const
231 {
232     Q_D(const QDeclarativeDebugServer);
233     return d->connection
234             && d->connection->isConnected()
235             && d->gotHello;
236 }
237
238 static QDeclarativeDebugServer *qDeclarativeDebugServer = 0;
239
240
241 static void cleanup()
242 {
243     delete qDeclarativeDebugServer;
244     qDeclarativeDebugServer = 0;
245 }
246
247 QDeclarativeDebugServer *QDeclarativeDebugServer::instance()
248 {
249     static bool commandLineTested = false;
250
251     if (!commandLineTested) {
252         commandLineTested = true;
253
254         QCoreApplicationPrivate *appD = static_cast<QCoreApplicationPrivate*>(QObjectPrivate::get(qApp));
255 #ifndef QDECLARATIVE_NO_DEBUG_PROTOCOL
256         // ### remove port definition when protocol is changed
257         int port = 0;
258         bool block = false;
259         bool ok = false;
260
261         // format: qmljsdebugger=port:3768[,block] OR qmljsdebugger=ost[,block]
262         if (!appD->qmljsDebugArgumentsString().isEmpty()) {
263             if (!QDeclarativeEnginePrivate::qml_debugging_enabled) {
264                 qWarning() << QString::fromLatin1(
265                                   "QDeclarativeDebugServer: Ignoring \"-qmljsdebugger=%1\". "
266                                   "Debugging has not been enabled.").arg(
267                                   appD->qmljsDebugArgumentsString());
268                 return 0;
269             }
270
271             QString pluginName;
272             if (appD->qmljsDebugArgumentsString().indexOf(QLatin1String("port:")) == 0) {
273                 int separatorIndex = appD->qmljsDebugArgumentsString().indexOf(QLatin1Char(','));
274                 port = appD->qmljsDebugArgumentsString().mid(5, separatorIndex - 5).toInt(&ok);
275                 pluginName = QLatin1String("qmldbg_tcp");
276             } else if (appD->qmljsDebugArgumentsString().contains(QLatin1String("ost"))) {
277                 pluginName = QLatin1String("qmldbg_ost");
278                 ok = true;
279             }
280
281             block = appD->qmljsDebugArgumentsString().contains(QLatin1String("block"));
282
283             if (ok) {
284                 qDeclarativeDebugServer = new QDeclarativeDebugServer();
285                 QDeclarativeDebugServerThread *thread = new QDeclarativeDebugServerThread;
286                 qDeclarativeDebugServer->d_func()->thread = thread;
287                 qDeclarativeDebugServer->moveToThread(thread);
288                 thread->setPluginName(pluginName);
289                 thread->setPort(port, block);
290                 thread->start();
291
292                 if (block) {
293                     QDeclarativeDebugServerPrivate *d = qDeclarativeDebugServer->d_func();
294                     d->messageArrivedMutex.lock();
295                     d->messageArrivedCondition.wait(&d->messageArrivedMutex);
296                     d->messageArrivedMutex.unlock();
297                 }
298
299             } else {
300                 qWarning() << QString::fromLatin1(
301                                   "QDeclarativeDebugServer: Ignoring \"-qmljsdebugger=%1\". "
302                                   "Format is -qmljsdebugger=port:<port>[,block]").arg(
303                                   appD->qmljsDebugArgumentsString());
304             }
305         }
306 #else
307         if (!appD->qmljsDebugArgumentsString().isEmpty()) {
308             qWarning() << QString::fromLatin1(
309                          "QDeclarativeDebugServer: Ignoring \"-qmljsdebugger=%1\". "
310                          "QtDeclarative is not configured for debugging.").arg(
311                          appD->qmljsDebugArgumentsString());
312         }
313 #endif
314     }
315
316     return qDeclarativeDebugServer;
317 }
318
319 QDeclarativeDebugServer::QDeclarativeDebugServer()
320     : QObject(*(new QDeclarativeDebugServerPrivate))
321 {
322     qAddPostRoutine(cleanup);
323 }
324
325 QDeclarativeDebugServer::~QDeclarativeDebugServer()
326 {
327     Q_D(QDeclarativeDebugServer);
328
329     QReadLocker(&d->pluginsLock);
330     {
331         foreach (QDeclarativeDebugService *service, d->plugins.values()) {
332             service->stateAboutToBeChanged(QDeclarativeDebugService::NotConnected);
333             service->d_func()->server = 0;
334             service->d_func()->state = QDeclarativeDebugService::NotConnected;
335             service->stateChanged(QDeclarativeDebugService::NotConnected);
336         }
337     }
338
339     if (d->thread) {
340         d->thread->exit();
341         d->thread->wait();
342         delete d->thread;
343     }
344     delete d->connection;
345 }
346
347 void QDeclarativeDebugServer::receiveMessage(const QByteArray &message)
348 {
349     Q_D(QDeclarativeDebugServer);
350
351     QDataStream in(message);
352
353     QString name;
354
355     in >> name;
356     if (name == QLatin1String("QDeclarativeDebugServer")) {
357         int op = -1;
358         in >> op;
359         if (op == 0) {
360             int version;
361             in >> version >> d->clientPlugins;
362
363             // Send the hello answer immediately, since it needs to arrive before
364             // the plugins below start sending messages.
365             QByteArray helloAnswer;
366             {
367                 QDataStream out(&helloAnswer, QIODevice::WriteOnly);
368                 QStringList pluginNames;
369                 QList<float> pluginVersions;
370                 foreach (QDeclarativeDebugService *service, d->plugins.values()) {
371                     pluginNames << service->name();
372                     pluginVersions << service->version();
373                 }
374
375                 out << QString(QLatin1String("QDeclarativeDebugClient")) << 0 << protocolVersion << pluginNames << pluginVersions;
376             }
377             d->connection->send(QList<QByteArray>() << helloAnswer);
378
379             d->gotHello = true;
380
381             QReadLocker(&d->pluginsLock);
382             QHash<QString, QDeclarativeDebugService*>::ConstIterator iter = d->plugins.constBegin();
383             for (; iter != d->plugins.constEnd(); ++iter) {
384                 QDeclarativeDebugService::State newState = QDeclarativeDebugService::Unavailable;
385                 if (d->clientPlugins.contains(iter.key()))
386                     newState = QDeclarativeDebugService::Enabled;
387                 iter.value()->d_func()->state = newState;
388                 iter.value()->stateChanged(newState);
389             }
390
391             qWarning("QDeclarativeDebugServer: Connection established");
392             d->messageArrivedCondition.wakeAll();
393
394         } else if (op == 1) {
395
396             // Service Discovery
397             QStringList oldClientPlugins = d->clientPlugins;
398             in >> d->clientPlugins;
399
400             QReadLocker(&d->pluginsLock);
401             QHash<QString, QDeclarativeDebugService*>::ConstIterator iter = d->plugins.constBegin();
402             for (; iter != d->plugins.constEnd(); ++iter) {
403                 const QString pluginName = iter.key();
404                 QDeclarativeDebugService::State newState = QDeclarativeDebugService::Unavailable;
405                 if (d->clientPlugins.contains(pluginName))
406                     newState = QDeclarativeDebugService::Enabled;
407
408                 if (oldClientPlugins.contains(pluginName)
409                         != d->clientPlugins.contains(pluginName)) {
410                     iter.value()->d_func()->state = newState;
411                     iter.value()->stateChanged(newState);
412                 }
413             }
414
415         } else {
416             qWarning("QDeclarativeDebugServer: Invalid control message %d", op);
417             d->connection->disconnect();
418             return;
419         }
420
421     } else {
422         if (d->gotHello) {
423             QByteArray message;
424             in >> message;
425
426             QReadLocker(&d->pluginsLock);
427             QHash<QString, QDeclarativeDebugService *>::Iterator iter = d->plugins.find(name);
428             if (iter == d->plugins.end()) {
429                 qWarning() << "QDeclarativeDebugServer: Message received for missing plugin" << name;
430             } else {
431                 (*iter)->messageReceived(message);
432
433                 if (d->waitingForMessageNames.removeOne(name))
434                     d->messageArrivedCondition.wakeAll();
435             }
436         } else {
437             qWarning("QDeclarativeDebugServer: Invalid hello message");
438         }
439
440     }
441 }
442
443 void QDeclarativeDebugServerPrivate::_q_sendMessages(const QList<QByteArray> &messages)
444 {
445     if (connection)
446         connection->send(messages);
447 }
448
449 QList<QDeclarativeDebugService*> QDeclarativeDebugServer::services() const
450 {
451     const Q_D(QDeclarativeDebugServer);
452     QReadLocker(&d->pluginsLock);
453     return d->plugins.values();
454 }
455
456 QStringList QDeclarativeDebugServer::serviceNames() const
457 {
458     const Q_D(QDeclarativeDebugServer);
459     QReadLocker(&d->pluginsLock);
460     return d->plugins.keys();
461 }
462
463 bool QDeclarativeDebugServer::addService(QDeclarativeDebugService *service)
464 {
465     Q_D(QDeclarativeDebugServer);
466     {
467         QWriteLocker(&d->pluginsLock);
468         if (!service || d->plugins.contains(service->name()))
469             return false;
470         d->plugins.insert(service->name(), service);
471     }
472     {
473         QReadLocker(&d->pluginsLock);
474         d->advertisePlugins();
475         QDeclarativeDebugService::State newState = QDeclarativeDebugService::Unavailable;
476         if (d->clientPlugins.contains(service->name()))
477             newState = QDeclarativeDebugService::Enabled;
478         service->d_func()->state = newState;
479     }
480     return true;
481 }
482
483 bool QDeclarativeDebugServer::removeService(QDeclarativeDebugService *service)
484 {
485     Q_D(QDeclarativeDebugServer);
486     {
487         QWriteLocker(&d->pluginsLock);
488         if (!service || !d->plugins.contains(service->name()))
489             return false;
490         d->plugins.remove(service->name());
491     }
492     {
493         QReadLocker(&d->pluginsLock);
494         QDeclarativeDebugService::State newState = QDeclarativeDebugService::NotConnected;
495         service->stateAboutToBeChanged(newState);
496         d->advertisePlugins();
497         service->d_func()->server = 0;
498         service->d_func()->state = newState;
499         service->stateChanged(newState);
500     }
501
502     return true;
503 }
504
505 void QDeclarativeDebugServer::sendMessages(QDeclarativeDebugService *service,
506                                           const QList<QByteArray> &messages)
507 {
508     QList<QByteArray> prefixedMessages;
509     foreach (const QByteArray &message, messages) {
510         QByteArray prefixed;
511         QDataStream out(&prefixed, QIODevice::WriteOnly);
512         out << service->name() << message;
513         prefixedMessages << prefixed;
514     }
515
516     QMetaObject::invokeMethod(this, "_q_sendMessages", Qt::QueuedConnection, Q_ARG(QList<QByteArray>, prefixedMessages));
517 }
518
519 bool QDeclarativeDebugServer::waitForMessage(QDeclarativeDebugService *service)
520 {
521     Q_D(QDeclarativeDebugServer);
522     QReadLocker(&d->pluginsLock);
523
524     if (!service
525             || !d->plugins.contains(service->name()))
526         return false;
527
528     d->messageArrivedMutex.lock();
529     d->waitingForMessageNames << service->name();
530     do {
531         d->messageArrivedCondition.wait(&d->messageArrivedMutex);
532     } while (d->waitingForMessageNames.contains(service->name()));
533     d->messageArrivedMutex.unlock();
534     return true;
535 }
536
537 QT_END_NAMESPACE
538
539 #include "moc_qdeclarativedebugserver_p.cpp"