QML Debugger: Change prefix of warnings
[profile/ivi/qtdeclarative.git] / src / qml / debugger / qqmldebugserver.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 QtQml 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 "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>
47
48 #include <QtCore/QDir>
49 #include <QtCore/QPluginLoader>
50 #include <QtCore/QStringList>
51 #include <QtCore/qwaitcondition.h>
52
53 #include <private/qobject_p.h>
54 #include <private/qcoreapplication_p.h>
55
56 QT_BEGIN_NAMESPACE
57
58 /*
59   QQmlDebug Protocol (Version 1):
60
61   handshake:
62     1. Client sends
63          "QDeclarativeDebugServer" 0 version pluginNames
64        version: an int representing the highest protocol version the client knows
65        pluginNames: plugins available on client side
66     2. Server sends
67          "QDeclarativeDebugClient" 0 version pluginNames pluginVersions
68        version: an int representing the highest protocol version the client & server know
69        pluginNames: plugins available on server side. plugins both in the client and server message are enabled.
70   client plugin advertisement
71     1. Client sends
72          "QDeclarativeDebugServer" 1 pluginNames
73   server plugin advertisement
74     1. Server sends
75          "QDeclarativeDebugClient" 1 pluginNames pluginVersions
76   plugin communication:
77        Everything send with a header different to "QDeclarativeDebugServer" is sent to the appropriate plugin.
78   */
79
80 const int protocolVersion = 1;
81
82 // print detailed information about loading of plugins
83 DEFINE_BOOL_CONFIG_OPTION(qmlDebugVerbose, QML_DEBUGGER_VERBOSE)
84
85 class QQmlDebugServerThread;
86
87 class QQmlDebugServerPrivate : public QObjectPrivate
88 {
89     Q_DECLARE_PUBLIC(QQmlDebugServer)
90 public:
91     QQmlDebugServerPrivate();
92
93     void advertisePlugins();
94     QQmlDebugServerConnection *loadConnectionPlugin(const QString &pluginName);
95
96     QQmlDebugServerConnection *connection;
97     QHash<QString, QQmlDebugService *> plugins;
98     mutable QReadWriteLock pluginsLock;
99     QStringList clientPlugins;
100     bool gotHello;
101
102     QMutex messageArrivedMutex;
103     QWaitCondition messageArrivedCondition;
104     QStringList waitingForMessageNames;
105     QQmlDebugServerThread *thread;
106     QPluginLoader loader;
107
108 private:
109     // private slot
110     void _q_sendMessages(const QList<QByteArray> &messages);
111 };
112
113 class QQmlDebugServerThread : public QThread
114 {
115 public:
116     void setPluginName(const QString &pluginName) {
117         m_pluginName = pluginName;
118     }
119
120     void setPort(int port, bool block) {
121         m_port = port;
122         m_block = block;
123     }
124
125     void run();
126
127 private:
128     QString m_pluginName;
129     int m_port;
130     bool m_block;
131 };
132
133 QQmlDebugServerPrivate::QQmlDebugServerPrivate() :
134     connection(0),
135     gotHello(false),
136     thread(0)
137 {
138     // used in _q_sendMessages
139     qRegisterMetaType<QList<QByteArray> >("QList<QByteArray>");
140 }
141
142 void QQmlDebugServerPrivate::advertisePlugins()
143 {
144     Q_Q(QQmlDebugServer);
145
146     if (!gotHello)
147         return;
148
149     QByteArray message;
150     {
151         QDataStream out(&message, QIODevice::WriteOnly);
152         QStringList pluginNames;
153         QList<float> pluginVersions;
154         foreach (QQmlDebugService *service, plugins.values()) {
155             pluginNames << service->name();
156             pluginVersions << service->version();
157         }
158         out << QString(QLatin1String("QDeclarativeDebugClient")) << 1 << pluginNames << pluginVersions;
159     }
160
161     QMetaObject::invokeMethod(q, "_q_sendMessages", Qt::QueuedConnection, Q_ARG(QList<QByteArray>, QList<QByteArray>() << message));
162 }
163
164 QQmlDebugServerConnection *QQmlDebugServerPrivate::loadConnectionPlugin(
165         const QString &pluginName)
166 {
167 #ifndef QT_NO_LIBRARY
168     QStringList pluginCandidates;
169     const QStringList paths = QCoreApplication::libraryPaths();
170     foreach (const QString &libPath, paths) {
171         const QDir dir(libPath + QLatin1String("/qmltooling"));
172         if (dir.exists()) {
173             QStringList plugins(dir.entryList(QDir::Files));
174             foreach (const QString &pluginPath, plugins) {
175                 if (QFileInfo(pluginPath).fileName().contains(pluginName))
176                     pluginCandidates << dir.absoluteFilePath(pluginPath);
177             }
178         }
179     }
180
181     foreach (const QString &pluginPath, pluginCandidates) {
182         if (qmlDebugVerbose())
183             qDebug() << "QML Debugger: Trying to load plugin " << pluginPath << "...";
184
185         loader.setFileName(pluginPath);
186         if (!loader.load()) {
187             if (qmlDebugVerbose())
188                 qDebug() << "QML Debugger: Error while loading: " << loader.errorString();
189             continue;
190         }
191         if (QObject *instance = loader.instance())
192             connection = qobject_cast<QQmlDebugServerConnection*>(instance);
193
194         if (connection) {
195             if (qmlDebugVerbose())
196                 qDebug() << "QML Debugger: Plugin successfully loaded.";
197
198             return connection;
199         }
200
201         if (qmlDebugVerbose())
202             qDebug() << "QML Debugger: Plugin does not implement interface QQmlDebugServerConnection.";
203
204         loader.unload();
205     }
206 #endif
207     return 0;
208 }
209
210 void QQmlDebugServerThread::run()
211 {
212     QQmlDebugServer *server = QQmlDebugServer::instance();
213     QQmlDebugServerConnection *connection
214             = server->d_func()->loadConnectionPlugin(m_pluginName);
215     if (connection) {
216         connection->setServer(QQmlDebugServer::instance());
217         connection->setPort(m_port, m_block);
218     } else {
219         QCoreApplicationPrivate *appD = static_cast<QCoreApplicationPrivate*>(QObjectPrivate::get(qApp));
220         qWarning() << QString::fromAscii("QML Debugger: Ignoring \"-qmljsdebugger=%1\". "
221                                          "Remote debugger plugin has not been found.").arg(appD->qmljsDebugArgumentsString());
222     }
223
224     exec();
225
226     // make sure events still waiting are processed
227     QEventLoop eventLoop;
228     eventLoop.processEvents(QEventLoop::AllEvents);
229 }
230
231 bool QQmlDebugServer::hasDebuggingClient() const
232 {
233     Q_D(const QQmlDebugServer);
234     return d->connection
235             && d->connection->isConnected()
236             && d->gotHello;
237 }
238
239 static QQmlDebugServer *qQmlDebugServer = 0;
240
241
242 static void cleanup()
243 {
244     delete qQmlDebugServer;
245     qQmlDebugServer = 0;
246 }
247
248 QQmlDebugServer *QQmlDebugServer::instance()
249 {
250     static bool commandLineTested = false;
251
252     if (!commandLineTested) {
253         commandLineTested = true;
254
255         QCoreApplicationPrivate *appD = static_cast<QCoreApplicationPrivate*>(QObjectPrivate::get(qApp));
256 #ifndef QQML_NO_DEBUG_PROTOCOL
257         // ### remove port definition when protocol is changed
258         int port = 0;
259         bool block = false;
260         bool ok = false;
261
262         // format: qmljsdebugger=port:3768[,block] OR qmljsdebugger=ost[,block]
263         if (!appD->qmljsDebugArgumentsString().isEmpty()) {
264             if (!QQmlEnginePrivate::qml_debugging_enabled) {
265                 qWarning() << QString::fromLatin1(
266                                   "QML Debugger: Ignoring \"-qmljsdebugger=%1\". "
267                                   "Debugging has not been enabled.").arg(
268                                   appD->qmljsDebugArgumentsString());
269                 return 0;
270             }
271
272             QString pluginName;
273             if (appD->qmljsDebugArgumentsString().indexOf(QLatin1String("port:")) == 0) {
274                 int separatorIndex = appD->qmljsDebugArgumentsString().indexOf(QLatin1Char(','));
275                 port = appD->qmljsDebugArgumentsString().mid(5, separatorIndex - 5).toInt(&ok);
276                 pluginName = QLatin1String("qmldbg_tcp");
277             } else if (appD->qmljsDebugArgumentsString().contains(QLatin1String("ost"))) {
278                 pluginName = QLatin1String("qmldbg_ost");
279                 ok = true;
280             }
281
282             block = appD->qmljsDebugArgumentsString().contains(QLatin1String("block"));
283
284             if (ok) {
285                 qQmlDebugServer = new QQmlDebugServer();
286                 QQmlDebugServerThread *thread = new QQmlDebugServerThread;
287                 qQmlDebugServer->d_func()->thread = thread;
288                 qQmlDebugServer->moveToThread(thread);
289                 thread->setPluginName(pluginName);
290                 thread->setPort(port, block);
291                 thread->start();
292
293                 if (block) {
294                     QQmlDebugServerPrivate *d = qQmlDebugServer->d_func();
295                     d->messageArrivedMutex.lock();
296                     d->messageArrivedCondition.wait(&d->messageArrivedMutex);
297                     d->messageArrivedMutex.unlock();
298                 }
299
300             } else {
301                 qWarning() << QString::fromLatin1(
302                                   "QML Debugger: Ignoring \"-qmljsdebugger=%1\". "
303                                   "Format is -qmljsdebugger=port:<port>[,block]").arg(
304                                   appD->qmljsDebugArgumentsString());
305             }
306         }
307 #else
308         if (!appD->qmljsDebugArgumentsString().isEmpty()) {
309             qWarning() << QString::fromLatin1(
310                          "QML Debugger: Ignoring \"-qmljsdebugger=%1\". "
311                          "QtQml is not configured for debugging.").arg(
312                          appD->qmljsDebugArgumentsString());
313         }
314 #endif
315     }
316
317     return qQmlDebugServer;
318 }
319
320 QQmlDebugServer::QQmlDebugServer()
321     : QObject(*(new QQmlDebugServerPrivate))
322 {
323     qAddPostRoutine(cleanup);
324 }
325
326 QQmlDebugServer::~QQmlDebugServer()
327 {
328     Q_D(QQmlDebugServer);
329
330     QReadLocker(&d->pluginsLock);
331     {
332         foreach (QQmlDebugService *service, d->plugins.values()) {
333             service->stateAboutToBeChanged(QQmlDebugService::NotConnected);
334             service->d_func()->server = 0;
335             service->d_func()->state = QQmlDebugService::NotConnected;
336             service->stateChanged(QQmlDebugService::NotConnected);
337         }
338     }
339
340     if (d->thread) {
341         d->thread->exit();
342         d->thread->wait();
343         delete d->thread;
344     }
345     delete d->connection;
346 }
347
348 void QQmlDebugServer::receiveMessage(const QByteArray &message)
349 {
350     Q_D(QQmlDebugServer);
351
352     QDataStream in(message);
353
354     QString name;
355
356     in >> name;
357     if (name == QLatin1String("QDeclarativeDebugServer")) {
358         int op = -1;
359         in >> op;
360         if (op == 0) {
361             int version;
362             in >> version >> d->clientPlugins;
363
364             // Send the hello answer immediately, since it needs to arrive before
365             // the plugins below start sending messages.
366             QByteArray helloAnswer;
367             {
368                 QDataStream out(&helloAnswer, QIODevice::WriteOnly);
369                 QStringList pluginNames;
370                 QList<float> pluginVersions;
371                 foreach (QQmlDebugService *service, d->plugins.values()) {
372                     pluginNames << service->name();
373                     pluginVersions << service->version();
374                 }
375
376                 out << QString(QLatin1String("QDeclarativeDebugClient")) << 0 << protocolVersion << pluginNames << pluginVersions;
377             }
378             d->connection->send(QList<QByteArray>() << helloAnswer);
379
380             d->gotHello = true;
381
382             QReadLocker(&d->pluginsLock);
383             QHash<QString, QQmlDebugService*>::ConstIterator iter = d->plugins.constBegin();
384             for (; iter != d->plugins.constEnd(); ++iter) {
385                 QQmlDebugService::State newState = QQmlDebugService::Unavailable;
386                 if (d->clientPlugins.contains(iter.key()))
387                     newState = QQmlDebugService::Enabled;
388                 iter.value()->d_func()->state = newState;
389                 iter.value()->stateChanged(newState);
390             }
391
392             qWarning("QML Debugger: Connection established.");
393             d->messageArrivedCondition.wakeAll();
394
395         } else if (op == 1) {
396
397             // Service Discovery
398             QStringList oldClientPlugins = d->clientPlugins;
399             in >> d->clientPlugins;
400
401             QReadLocker(&d->pluginsLock);
402             QHash<QString, QQmlDebugService*>::ConstIterator iter = d->plugins.constBegin();
403             for (; iter != d->plugins.constEnd(); ++iter) {
404                 const QString pluginName = iter.key();
405                 QQmlDebugService::State newState = QQmlDebugService::Unavailable;
406                 if (d->clientPlugins.contains(pluginName))
407                     newState = QQmlDebugService::Enabled;
408
409                 if (oldClientPlugins.contains(pluginName)
410                         != d->clientPlugins.contains(pluginName)) {
411                     iter.value()->d_func()->state = newState;
412                     iter.value()->stateChanged(newState);
413                 }
414             }
415
416         } else {
417             qWarning("QML Debugger: Invalid control message %d.", op);
418             d->connection->disconnect();
419             return;
420         }
421
422     } else {
423         if (d->gotHello) {
424             QByteArray message;
425             in >> message;
426
427             QReadLocker(&d->pluginsLock);
428             QHash<QString, QQmlDebugService *>::Iterator iter = d->plugins.find(name);
429             if (iter == d->plugins.end()) {
430                 qWarning() << "QML Debugger: Message received for missing plugin" << name << ".";
431             } else {
432                 (*iter)->messageReceived(message);
433
434                 if (d->waitingForMessageNames.removeOne(name))
435                     d->messageArrivedCondition.wakeAll();
436             }
437         } else {
438             qWarning("QML Debugger: Invalid hello message.");
439         }
440
441     }
442 }
443
444 void QQmlDebugServerPrivate::_q_sendMessages(const QList<QByteArray> &messages)
445 {
446     if (connection)
447         connection->send(messages);
448 }
449
450 QList<QQmlDebugService*> QQmlDebugServer::services() const
451 {
452     const Q_D(QQmlDebugServer);
453     QReadLocker(&d->pluginsLock);
454     return d->plugins.values();
455 }
456
457 QStringList QQmlDebugServer::serviceNames() const
458 {
459     const Q_D(QQmlDebugServer);
460     QReadLocker(&d->pluginsLock);
461     return d->plugins.keys();
462 }
463
464 bool QQmlDebugServer::addService(QQmlDebugService *service)
465 {
466     Q_D(QQmlDebugServer);
467     {
468         QWriteLocker(&d->pluginsLock);
469         if (!service || d->plugins.contains(service->name()))
470             return false;
471         d->plugins.insert(service->name(), service);
472     }
473     {
474         QReadLocker(&d->pluginsLock);
475         d->advertisePlugins();
476         QQmlDebugService::State newState = QQmlDebugService::Unavailable;
477         if (d->clientPlugins.contains(service->name()))
478             newState = QQmlDebugService::Enabled;
479         service->d_func()->state = newState;
480     }
481     return true;
482 }
483
484 bool QQmlDebugServer::removeService(QQmlDebugService *service)
485 {
486     Q_D(QQmlDebugServer);
487     {
488         QWriteLocker(&d->pluginsLock);
489         if (!service || !d->plugins.contains(service->name()))
490             return false;
491         d->plugins.remove(service->name());
492     }
493     {
494         QReadLocker(&d->pluginsLock);
495         QQmlDebugService::State newState = QQmlDebugService::NotConnected;
496         service->stateAboutToBeChanged(newState);
497         d->advertisePlugins();
498         service->d_func()->server = 0;
499         service->d_func()->state = newState;
500         service->stateChanged(newState);
501     }
502
503     return true;
504 }
505
506 void QQmlDebugServer::sendMessages(QQmlDebugService *service,
507                                           const QList<QByteArray> &messages)
508 {
509     QList<QByteArray> prefixedMessages;
510     foreach (const QByteArray &message, messages) {
511         QByteArray prefixed;
512         QDataStream out(&prefixed, QIODevice::WriteOnly);
513         out << service->name() << message;
514         prefixedMessages << prefixed;
515     }
516
517     QMetaObject::invokeMethod(this, "_q_sendMessages", Qt::QueuedConnection, Q_ARG(QList<QByteArray>, prefixedMessages));
518 }
519
520 bool QQmlDebugServer::waitForMessage(QQmlDebugService *service)
521 {
522     Q_D(QQmlDebugServer);
523     QReadLocker(&d->pluginsLock);
524
525     if (!service
526             || !d->plugins.contains(service->name()))
527         return false;
528
529     d->messageArrivedMutex.lock();
530     d->waitingForMessageNames << service->name();
531     do {
532         d->messageArrivedCondition.wait(&d->messageArrivedMutex);
533     } while (d->waitingForMessageNames.contains(service->name()));
534     d->messageArrivedMutex.unlock();
535     return true;
536 }
537
538 QT_END_NAMESPACE
539
540 #include "moc_qqmldebugserver_p.cpp"