OSDN Git Service

It's 2011 now.
[qt-creator-jp/qt-creator-jp.git] / src / plugins / qmljsinspector / qmljsclientproxy.cpp
1 /**************************************************************************
2 **
3 ** This file is part of Qt Creator
4 **
5 ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
6 **
7 ** Contact: Nokia Corporation (qt-info@nokia.com)
8 **
9 ** No Commercial Usage
10 **
11 ** This file contains pre-release code and may not be distributed.
12 ** You may use this file in accordance with the terms and conditions
13 ** contained in the Technology Preview License Agreement accompanying
14 ** this package.
15 **
16 ** GNU Lesser General Public License Usage
17 **
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file.  Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24 **
25 ** In addition, as a special exception, Nokia gives you certain additional
26 ** rights.  These rights are described in the Nokia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
28 **
29 ** If you have questions regarding the use of this file, please contact
30 ** Nokia at qt-info@nokia.com.
31 **
32 **************************************************************************/
33
34 #include "qmljsclientproxy.h"
35 #include "qmljsprivateapi.h"
36 #include "qmljsobserverclient.h"
37 #include "qmljsinspector.h"
38
39 #include <debugger/debuggerplugin.h>
40 #include <debugger/debuggerrunner.h>
41 #include <debugger/qml/qmlengine.h>
42 #include <debugger/qml/qmladapter.h>
43 #include <extensionsystem/pluginmanager.h>
44 #include <utils/qtcassert.h>
45 #include <projectexplorer/project.h>
46
47 #include <QUrl>
48 #include <QAbstractSocket>
49 #include <QDebug>
50
51 enum {
52     debug = false
53 };
54
55 using namespace QmlJSInspector::Internal;
56
57 ClientProxy::ClientProxy(Debugger::QmlAdapter *adapter, QObject *parent)
58     : QObject(parent)
59     , m_adapter(adapter)
60     , m_engineClient(m_adapter->client())
61     , m_observerClient(0)
62     , m_engineQuery(0)
63     , m_contextQuery(0)
64     , m_isConnected(false)
65 {
66     m_requestObjectsTimer.setSingleShot(true);
67     m_requestObjectsTimer.setInterval(3000);
68     connect(m_engineClient, SIGNAL(newObjects()), this, SLOT(newObjects()));
69     connect(&m_requestObjectsTimer, SIGNAL(timeout()), this, SLOT(refreshObjectTree()));
70     connectToServer();
71 }
72
73 void ClientProxy::connectToServer()
74 {
75     m_observerClient = new QmlJSObserverClient(m_adapter->connection(), this);
76
77     connect(m_observerClient, SIGNAL(connectedStatusChanged(QDeclarativeDebugClient::Status)),
78              this, SLOT(clientStatusChanged(QDeclarativeDebugClient::Status)));
79     connect(m_observerClient, SIGNAL(currentObjectsChanged(QList<int>)),
80         SLOT(onCurrentObjectsChanged(QList<int>)));
81     connect(m_observerClient, SIGNAL(colorPickerActivated()),
82         SIGNAL(colorPickerActivated()));
83     connect(m_observerClient, SIGNAL(zoomToolActivated()),
84         SIGNAL(zoomToolActivated()));
85     connect(m_observerClient, SIGNAL(selectToolActivated()),
86         SIGNAL(selectToolActivated()));
87     connect(m_observerClient, SIGNAL(selectMarqueeToolActivated()),
88         SIGNAL(selectMarqueeToolActivated()));
89     connect(m_observerClient, SIGNAL(animationSpeedChanged(qreal)),
90         SIGNAL(animationSpeedChanged(qreal)));
91     connect(m_observerClient, SIGNAL(designModeBehaviorChanged(bool)),
92         SIGNAL(designModeBehaviorChanged(bool)));
93     connect(m_observerClient, SIGNAL(showAppOnTopChanged(bool)),
94         SIGNAL(showAppOnTopChanged(bool)));
95     connect(m_observerClient, SIGNAL(reloaded()), this,
96         SIGNAL(serverReloaded()));
97     connect(m_observerClient, SIGNAL(selectedColorChanged(QColor)),
98         SIGNAL(selectedColorChanged(QColor)));
99     connect(m_observerClient, SIGNAL(contextPathUpdated(QStringList)),
100         SIGNAL(contextPathUpdated(QStringList)));
101     connect(m_observerClient, SIGNAL(logActivity(QString,QString)),
102             m_adapter, SLOT(logServiceActivity(QString,QString)));
103
104     updateConnected();
105 }
106
107 void ClientProxy::clientStatusChanged(QDeclarativeDebugClient::Status status)
108 {
109     QString serviceName;
110     if (QDeclarativeDebugClient *client = qobject_cast<QDeclarativeDebugClient*>(sender())) {
111         serviceName = client->name();
112     }
113
114     m_adapter->logServiceStatusChange(serviceName, status);
115
116     updateConnected();
117 }
118
119 void ClientProxy::disconnectFromServer()
120 {
121     if (m_observerClient) {
122         disconnect(m_observerClient, SIGNAL(connectedStatusChanged(QDeclarativeDebugClient::Status)),
123                  this, SLOT(clientStatusChanged(QDeclarativeDebugClient::Status)));
124         disconnect(m_observerClient, SIGNAL(currentObjectsChanged(QList<int>)),
125             this, SLOT(onCurrentObjectsChanged(QList<int>)));
126         disconnect(m_observerClient, SIGNAL(colorPickerActivated()),
127             this, SIGNAL(colorPickerActivated()));
128         disconnect(m_observerClient, SIGNAL(zoomToolActivated()),
129             this, SIGNAL(zoomToolActivated()));
130         disconnect(m_observerClient, SIGNAL(selectToolActivated()),
131             this, SIGNAL(selectToolActivated()));
132         disconnect(m_observerClient, SIGNAL(selectMarqueeToolActivated()),
133             this, SIGNAL(selectMarqueeToolActivated()));
134         disconnect(m_observerClient, SIGNAL(animationSpeedChanged(qreal)),
135             this, SIGNAL(animationSpeedChanged(qreal)));
136         disconnect(m_observerClient, SIGNAL(designModeBehaviorChanged(bool)),
137             this, SIGNAL(designModeBehaviorChanged(bool)));
138         disconnect(m_observerClient, SIGNAL(selectedColorChanged(QColor)),
139             this, SIGNAL(selectedColorChanged(QColor)));
140         disconnect(m_observerClient, SIGNAL(contextPathUpdated(QStringList)),
141             this, SIGNAL(contextPathUpdated(QStringList)));
142         disconnect(m_observerClient, SIGNAL(logActivity(QString,QString)),
143                    m_adapter, SLOT(logServiceActivity(QString,QString)));
144
145         delete m_observerClient;
146         m_observerClient = 0;
147     }
148
149     if (m_engineQuery)
150         delete m_engineQuery;
151     m_engineQuery = 0;
152
153     if (m_contextQuery)
154         delete m_contextQuery;
155     m_contextQuery = 0;
156
157     qDeleteAll(m_objectTreeQuery);
158     m_objectTreeQuery.clear();
159
160     updateConnected();
161 }
162
163 void ClientProxy::refreshObjectTree()
164 {
165     if (!m_contextQuery) {
166         m_requestObjectsTimer.stop();
167         qDeleteAll(m_objectTreeQuery);
168         m_objectTreeQuery.clear();
169         queryEngineContext(m_engines.value(0).debugId());
170     }
171 }
172
173 void ClientProxy::onCurrentObjectsChanged(const QList<int> &debugIds, bool requestIfNeeded)
174 {
175     QList<QDeclarativeDebugObjectReference> selectedItems;
176
177     foreach (int debugId, debugIds) {
178         QDeclarativeDebugObjectReference ref = objectReferenceForId(debugId);
179         if (ref.debugId() != -1) {
180             selectedItems << ref;
181         } else if (requestIfNeeded) {
182             // ### FIXME right now, there's no way in the protocol to
183             // a) get some item and know its parent (although that's possible
184             //    by adding it to a separate plugin)
185             // b) add children to part of an existing tree.
186             // So the only choice that remains is to update the complete
187             // tree when we have an unknown debug id.
188             // break;
189         }
190     }
191
192     emit selectedItemsChanged(selectedItems);
193 }
194
195 void ClientProxy::setSelectedItemsByObjectId(const QList<QDeclarativeDebugObjectReference> &objectRefs)
196 {
197     if (isConnected()) {
198         QList<int> debugIds;
199
200         foreach (const QDeclarativeDebugObjectReference &ref, objectRefs) {
201             debugIds << ref.debugId();
202         }
203
204         m_observerClient->setCurrentObjects(debugIds);
205     }
206 }
207
208 QDeclarativeDebugObjectReference ClientProxy::objectReferenceForId(int debugId) const
209 {
210     foreach (const QDeclarativeDebugObjectReference& it, m_rootObjects) {
211         QDeclarativeDebugObjectReference result = objectReferenceForId(debugId, it);
212         if (result.debugId() == debugId)
213             return result;
214     }
215     return QDeclarativeDebugObjectReference();
216 }
217
218 QList<QDeclarativeDebugObjectReference> QmlJSInspector::Internal::ClientProxy::rootObjectReference() const
219 {
220     return m_rootObjects;
221 }
222
223 QDeclarativeDebugObjectReference ClientProxy::objectReferenceForId(int debugId,
224                                                                    const QDeclarativeDebugObjectReference &objectRef) const
225 {
226     if (objectRef.debugId() == debugId)
227         return objectRef;
228
229     foreach(const QDeclarativeDebugObjectReference &child, objectRef.children()) {
230         QDeclarativeDebugObjectReference result = objectReferenceForId(debugId, child);
231         if (result.debugId() == debugId)
232             return result;
233     }
234
235     return QDeclarativeDebugObjectReference();
236 }
237
238 QDeclarativeDebugObjectReference ClientProxy::objectReferenceForId(const QString &objectId) const
239 {
240     if (!objectId.isEmpty() && objectId[0].isLower()) {
241         const QList<QDeclarativeDebugObjectReference> refs = objectReferences();
242         foreach (const QDeclarativeDebugObjectReference &ref, refs) {
243             if (ref.idString() == objectId)
244                 return ref;
245         }
246     }
247     return QDeclarativeDebugObjectReference();
248 }
249
250 QDeclarativeDebugObjectReference ClientProxy::objectReferenceForLocation(const int line, const int column) const
251 {
252     const QList<QDeclarativeDebugObjectReference> refs = objectReferences();
253     foreach (const QDeclarativeDebugObjectReference &ref, refs) {
254         if (ref.source().lineNumber() == line && ref.source().columnNumber() == column)
255             return ref;
256     }
257
258     return QDeclarativeDebugObjectReference();
259 }
260
261 QList<QDeclarativeDebugObjectReference> ClientProxy::objectReferences() const
262 {
263     QList<QDeclarativeDebugObjectReference> result;
264     foreach(const QDeclarativeDebugObjectReference &it, m_rootObjects) {
265         result.append(objectReferences(it));
266     }
267     return result;
268 }
269
270 QList<QDeclarativeDebugObjectReference> ClientProxy::objectReferences(const QDeclarativeDebugObjectReference &objectRef) const
271 {
272     QList<QDeclarativeDebugObjectReference> result;
273     result.append(objectRef);
274
275     foreach(const QDeclarativeDebugObjectReference &child, objectRef.children()) {
276         result.append(objectReferences(child));
277     }
278
279     return result;
280 }
281
282 bool ClientProxy::setBindingForObject(int objectDebugId,
283                                       const QString &propertyName,
284                                       const QVariant &value,
285                                       bool isLiteralValue)
286 {
287     if (debug)
288         qDebug() << "setBindingForObject():" << objectDebugId << propertyName << value;
289     if (objectDebugId == -1)
290         return false;
291
292     if (propertyName == QLatin1String("id"))
293         return false; // Crashes the QMLViewer.
294
295     bool result = m_engineClient->setBindingForObject(objectDebugId, propertyName, value.toString(), isLiteralValue);
296
297     return result;
298 }
299
300 bool ClientProxy::setMethodBodyForObject(int objectDebugId, const QString &methodName, const QString &methodBody)
301 {
302     if (debug)
303         qDebug() << "setMethodBodyForObject():" << objectDebugId << methodName << methodBody;
304     if (objectDebugId == -1)
305         return 0;
306     return m_engineClient->setMethodBody(objectDebugId, methodName, methodBody);
307 }
308
309 bool ClientProxy::resetBindingForObject(int objectDebugId, const QString& propertyName)
310 {
311     if (debug)
312         qDebug() << "resetBindingForObject():" << objectDebugId << propertyName;
313     if (objectDebugId == -1)
314         return false;
315     //    if (propertyName == QLatin1String("id"))  return false;
316     return m_engineClient->resetBindingForObject(objectDebugId, propertyName);
317 }
318
319 QDeclarativeDebugExpressionQuery *ClientProxy::queryExpressionResult(int objectDebugId, const QString &expr, QObject *parent)
320 {
321     if (debug)
322         qDebug() << "queryExpressionResult():" << objectDebugId << expr << parent;
323     if (objectDebugId != -1)
324         return m_engineClient->queryExpressionResult(objectDebugId,expr,parent);
325     return 0;
326 }
327
328 void ClientProxy::clearComponentCache()
329 {
330     if (isConnected())
331         m_observerClient->clearComponentCache();
332 }
333
334 void ClientProxy::queryEngineContext(int id)
335 {
336     if (id < 0)
337         return;
338
339     if (m_contextQuery) {
340         delete m_contextQuery;
341         m_contextQuery = 0;
342     }
343
344     m_contextQuery = m_engineClient->queryRootContexts(QDeclarativeDebugEngineReference(id), this);
345     if (!m_contextQuery->isWaiting())
346         contextChanged();
347     else
348         connect(m_contextQuery, SIGNAL(stateChanged(QDeclarativeDebugQuery::State)),
349                 this, SLOT(contextChanged()));
350 }
351
352 void ClientProxy::contextChanged()
353 {
354     if (m_contextQuery) {
355         m_rootObjects.clear();
356         QDeclarativeDebugContextReference rootContext = m_contextQuery->rootContext();
357         delete m_contextQuery;
358         m_contextQuery = 0;
359
360         qDeleteAll(m_objectTreeQuery);
361         m_objectTreeQuery.clear();
362         m_requestObjectsTimer.stop();
363
364         fetchContextObjectRecursive(rootContext);
365     }
366 }
367
368 void ClientProxy::fetchContextObjectRecursive(const QDeclarativeDebugContextReference& context)
369 {
370     foreach (const QDeclarativeDebugObjectReference & obj, context.objects()) {
371         QDeclarativeDebugObjectQuery* query = m_engineClient->queryObjectRecursive(obj, this);
372         if (!query->isWaiting()) {
373             query->deleteLater(); //ignore errors;
374         } else {
375             m_objectTreeQuery << query;
376             connect(query,
377                     SIGNAL(stateChanged(QDeclarativeDebugQuery::State)),
378                     SLOT(objectTreeFetched(QDeclarativeDebugQuery::State)));
379         }
380     }
381     foreach (const QDeclarativeDebugContextReference& child, context.contexts()) {
382         fetchContextObjectRecursive(child);
383     }
384 }
385
386
387 void ClientProxy::objectTreeFetched(QDeclarativeDebugQuery::State state)
388 {
389     QDeclarativeDebugObjectQuery *query = qobject_cast<QDeclarativeDebugObjectQuery *>(sender());
390     if (!query || state == QDeclarativeDebugQuery::Error) {
391         delete query;
392         return;
393     }
394
395     m_rootObjects.append(query->object());
396
397     int removed = m_objectTreeQuery.removeAll(query);
398     Q_ASSERT(removed == 1);
399     Q_UNUSED(removed);
400     delete query;
401
402     if (m_objectTreeQuery.isEmpty()) {
403         int old_count = m_debugIdHash.count();
404         m_debugIdHash.clear();
405         m_debugIdHash.reserve(old_count + 1);
406         foreach(const QDeclarativeDebugObjectReference &it, m_rootObjects)
407             buildDebugIdHashRecursive(it);
408         emit objectTreeUpdated();
409
410         if (isConnected()) {
411             if (!m_observerClient->currentObjects().isEmpty())
412                 onCurrentObjectsChanged(m_observerClient->currentObjects(), false);
413
414             m_observerClient->setObjectIdList(m_rootObjects);
415         }
416     }
417 }
418
419 void ClientProxy::buildDebugIdHashRecursive(const QDeclarativeDebugObjectReference& ref)
420 {
421     QString filename = ref.source().url().toLocalFile();
422     int lineNum = ref.source().lineNumber();
423     int colNum = ref.source().columnNumber();
424     int rev = 0;
425
426     // handle the case where the url contains the revision number encoded. (for object created by the debugger)
427     static QRegExp rx("(.*)_(\\d+):(\\d+)$");
428     if (rx.exactMatch(filename)) {
429         filename = rx.cap(1);
430         rev = rx.cap(2).toInt();
431         lineNum += rx.cap(3).toInt() - 1;
432     }
433
434     //convert the filename to a canonical filename in case of shadow build.
435     bool isShadowBuild = InspectorUi::instance()->isShadowBuildProject();
436     if (isShadowBuild && rev == 0) {
437         QString shadowBuildDir = InspectorUi::instance()->debugProjectBuildDirectory();
438
439         if (filename.startsWith(shadowBuildDir)) {
440             ProjectExplorer::Project *debugProject = InspectorUi::instance()->debugProject();
441             filename = debugProject->projectDirectory() + filename.mid(shadowBuildDir.length());
442         }
443     }
444
445     // append the debug ids in the hash
446     m_debugIdHash[qMakePair<QString, int>(filename, rev)][qMakePair<int, int>(lineNum, colNum)].append(ref.debugId());
447
448     foreach(const QDeclarativeDebugObjectReference &it, ref.children())
449         buildDebugIdHashRecursive(it);
450 }
451
452
453 void ClientProxy::reloadQmlViewer()
454 {
455     if (isConnected())
456         m_observerClient->reloadViewer();
457 }
458
459 void ClientProxy::setDesignModeBehavior(bool inDesignMode)
460 {
461     if (isConnected())
462         m_observerClient->setDesignModeBehavior(inDesignMode);
463 }
464
465 void ClientProxy::setAnimationSpeed(qreal slowdownFactor)
466 {
467     if (isConnected())
468         m_observerClient->setAnimationSpeed(slowdownFactor);
469 }
470
471 void ClientProxy::changeToColorPickerTool()
472 {
473     if (isConnected())
474         m_observerClient->changeToColorPickerTool();
475 }
476
477 void ClientProxy::changeToZoomTool()
478 {
479     if (isConnected())
480         m_observerClient->changeToZoomTool();
481 }
482 void ClientProxy::changeToSelectTool()
483 {
484     if (isConnected())
485         m_observerClient->changeToSelectTool();
486 }
487
488 void ClientProxy::changeToSelectMarqueeTool()
489 {
490     if (isConnected())
491         m_observerClient->changeToSelectMarqueeTool();
492 }
493
494 void ClientProxy::showAppOnTop(bool showOnTop)
495 {
496     if (isConnected())
497         m_observerClient->showAppOnTop(showOnTop);
498 }
499
500 void ClientProxy::createQmlObject(const QString &qmlText, int parentDebugId,
501                                   const QStringList &imports, const QString &filename)
502 {
503     if (isConnected())
504         m_observerClient->createQmlObject(qmlText, parentDebugId, imports, filename);
505 }
506
507 void ClientProxy::destroyQmlObject(int debugId)
508 {
509     if (isConnected())
510         m_observerClient->destroyQmlObject(debugId);
511 }
512
513 void ClientProxy::reparentQmlObject(int debugId, int newParent)
514 {
515     if (isConnected())
516         m_observerClient->reparentQmlObject(debugId, newParent);
517 }
518
519 void ClientProxy::setContextPathIndex(int contextIndex)
520 {
521     if (isConnected())
522         m_observerClient->setContextPathIndex(contextIndex);
523 }
524
525 void ClientProxy::updateConnected()
526 {
527     bool isConnected = m_observerClient && m_observerClient->status() == QDeclarativeDebugClient::Enabled
528             && m_engineClient && m_engineClient->status() == QDeclarativeEngineDebug::Enabled;
529
530     if (isConnected != m_isConnected) {
531         m_isConnected = isConnected;
532         if (isConnected) {
533             emit connected();
534             reloadEngines();
535         } else {
536             emit disconnected();
537         }
538     }
539 }
540
541 void ClientProxy::reloadEngines()
542 {
543     if (m_engineQuery) {
544         emit connectionStatusMessage("[Inspector] Waiting for response to previous engine query");
545         return;
546     }
547
548     emit aboutToReloadEngines();
549
550     m_engineQuery = m_engineClient->queryAvailableEngines(this);
551     if (!m_engineQuery->isWaiting())
552         updateEngineList();
553     else
554         connect(m_engineQuery, SIGNAL(stateChanged(QDeclarativeDebugQuery::State)),
555                          this, SLOT(updateEngineList()));
556 }
557
558 QList<QDeclarativeDebugEngineReference> ClientProxy::engines() const
559 {
560     return m_engines;
561 }
562
563 void ClientProxy::updateEngineList()
564 {
565     m_engines = m_engineQuery->engines();
566     delete m_engineQuery;
567     m_engineQuery = 0;
568
569     emit enginesChanged();
570 }
571
572 Debugger::QmlAdapter *ClientProxy::qmlAdapter() const
573 {
574     return m_adapter;
575 }
576
577 bool ClientProxy::isConnected() const
578 {
579     return m_isConnected;
580 }
581
582 void ClientProxy::newObjects()
583 {
584     if (!m_requestObjectsTimer.isActive())
585         m_requestObjectsTimer.start();
586 }