Introduced a CONFIG option that enables declarative debug services
[profile/ivi/qtdeclarative.git] / tools / qmlscene / main.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2010 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 tools applications 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 <QtCore/qdebug.h>
43 #include <QtCore/qabstractanimation.h>
44 #include <QtGui/qapplication.h>
45 #include <QtDeclarative/qdeclarative.h>
46 #include <QtDeclarative/qdeclarativeengine.h>
47 #include <QtDeclarative/qdeclarativecomponent.h>
48 #include <QtQuick1/qdeclarativeview.h>
49 #include <QtCore/qdir.h>
50 #include <QtGui/QFormLayout>
51 #include <QtGui/QComboBox>
52 #include <QtGui/QCheckBox>
53 #include <QtGui/QDialog>
54 #include <QtGui/QDialogButtonBox>
55 #include <QtGui/QFileDialog>
56 #include <QtGui/QGraphicsView>
57
58 #include <QtDeclarative/qdeclarativecontext.h>
59
60 // ### This should be private API
61 #include <qsgitem.h>
62 #include <qsgview.h>
63
64 #define QT_NO_SCENEGRAPHITEM
65
66 #ifndef QT_NO_SCENEGRAPHITEM
67 #include "scenegraphitem.h"
68 #endif
69
70 #include <QtCore/qmath.h>
71
72 #ifdef QML_RUNTIME_TESTING
73 class RenderStatistics
74 {
75 public:
76     static void updateStats();
77     static void printTotalStats();
78 private:
79     static QVector<qreal> timePerFrame;
80     static QVector<int> timesPerFrames;
81 };
82
83 QVector<qreal> RenderStatistics::timePerFrame;
84 QVector<int> RenderStatistics::timesPerFrames;
85
86 void RenderStatistics::updateStats()
87 {
88     static QTime time;
89     static int frames;
90     static int lastTime;
91
92     if (frames == 0) {
93         time.start();
94     } else {
95         int elapsed = time.elapsed();
96         timesPerFrames.append(elapsed - lastTime);
97         lastTime = elapsed;
98
99         if (elapsed > 5000) {
100             qreal avgtime = elapsed / (qreal) frames;
101             qreal var = 0;
102             for (int i = 0; i < timesPerFrames.size(); ++i) {
103                 qreal diff = timesPerFrames.at(i) - avgtime;
104                 var += diff * diff;
105             }
106             var /= timesPerFrames.size();
107
108             qDebug("Average time per frame: %f ms (%i fps), std.dev: %f ms", avgtime, qRound(1000. / avgtime), qSqrt(var));
109
110             timePerFrame.append(avgtime);
111             timesPerFrames.clear();
112             time.start();
113             lastTime = 0;
114             frames = 0;
115         }
116     }
117     ++frames;
118 }
119
120 void RenderStatistics::printTotalStats()
121 {
122     int count = timePerFrame.count();
123     if (count == 0)
124         return;
125
126     qreal minTime = 0;
127     qreal maxTime = 0;
128     qreal avg = 0;
129     for (int i = 0; i < count; ++i) {
130         minTime = minTime == 0 ? timePerFrame.at(i) : qMin(minTime, timePerFrame.at(i));
131         maxTime = qMax(maxTime, timePerFrame.at(i));
132         avg += timePerFrame.at(i);
133     }
134     avg /= count;
135
136     qDebug(" ");
137     qDebug("----- Statistics -----");
138     qDebug("Average time per frame: %f ms (%i fps)", avg, qRound(1000. / avg));
139     qDebug("Best time per frame: %f ms (%i fps)", minTime, int(1000 / minTime));
140     qDebug("Worst time per frame: %f ms (%i fps)", maxTime, int(1000 / maxTime));
141     qDebug("----------------------");
142     qDebug(" ");
143 }
144 #endif
145
146
147 static QGLFormat getFormat()
148 {
149     QGLFormat f = QGLFormat::defaultFormat();
150     f.setSampleBuffers(!qApp->arguments().contains("--no-multisample"));
151     f.setSwapInterval(qApp->arguments().contains("--nonblocking-swap") ? 0 : 1);
152     f.setStereo(qApp->arguments().contains("--stereo"));
153     return f;
154 }
155
156 class MyQSGView : public QSGView
157 {
158 public:
159     MyQSGView() : QSGView(getFormat())
160     {
161         setResizeMode(QSGView::SizeRootObjectToView);
162     }
163
164 protected:
165     void paintEvent(QPaintEvent *e) {
166         QSGView::paintEvent(e);
167
168 #ifdef QML_RUNTIME_TESTING
169 //        RenderStatistics::updateStats();
170 #endif
171
172         static bool continuousUpdate = qApp->arguments().contains("--continuous-update");
173         if (continuousUpdate)
174             update();
175     }
176 };
177
178 class MyDeclarativeView: public QDeclarativeView
179 {
180 public:
181     MyDeclarativeView(QWidget *parent = 0) : QDeclarativeView(parent)
182     {
183         setResizeMode(QDeclarativeView::SizeRootObjectToView);
184     }
185
186 protected:
187     void paintEvent(QPaintEvent *event)
188     {
189         QDeclarativeView::paintEvent(event);
190
191 #ifdef QML_RUNTIME_TESTING
192         RenderStatistics::updateStats();
193 #endif
194
195         static bool continuousUpdate = qApp->arguments().contains("--continuous-update");
196         if (continuousUpdate)
197             scene()->update();
198     }
199 };
200
201 #ifndef QT_NO_SCENEGRAPHITEM
202 class MyGraphicsView: public QGraphicsView
203 {
204 public:
205     MyGraphicsView(bool clip, QWidget *parent = 0) : QGraphicsView(parent)
206     {
207         setViewport(new QGLWidget(getFormat()));
208         setScene(&scene);
209         scene.addItem(&item);
210         item.setFlag(QGraphicsItem::ItemClipsToShape, clip);
211         QGraphicsTextItem *text;
212         text = scene.addText(QLatin1String("Scene graph on graphics view."), QFont(QLatin1String("Times"), 10));
213         text->setX(5);
214         text->setY(5);
215         text->setDefaultTextColor(Qt::black);
216         text = scene.addText(QLatin1String("Scene graph on graphics view."), QFont(QLatin1String("Times"), 10));
217         text->setX(4);
218         text->setY(4);
219         text->setDefaultTextColor(Qt::yellow);
220     }
221
222     SceneGraphItem *sceneGraphItem() { return &item; }
223
224 protected:
225     void paintEvent(QPaintEvent *event)
226     {
227         QGraphicsView::paintEvent(event);
228
229 #ifdef QML_RUNTIME_TESTING
230         RenderStatistics::updateStats();
231 #endif
232
233         static bool continuousUpdate = qApp->arguments().contains("--continuous-update");
234         if (continuousUpdate)
235             QGraphicsView::scene()->update();
236     }
237
238     QGraphicsScene scene;
239     SceneGraphItem item;
240 };
241 #endif
242
243 struct Options
244 {
245     Options()
246         : originalQml(false)
247         , originalQmlRaster(false)
248         , maximized(false)
249         , fullscreen(false)
250         , scenegraphOnGraphicsview(false)
251         , clip(false)
252         , versionDetection(true)
253         , vsync(true)
254     {
255     }
256
257     QUrl file;
258     bool originalQml;
259     bool originalQmlRaster;
260     bool maximized;
261     bool fullscreen;
262     bool scenegraphOnGraphicsview;
263     bool clip;
264     bool versionDetection;
265     bool vsync;
266 };
267
268 #if defined(QMLSCENE_BUNDLE)
269 Q_DECLARE_METATYPE(QFileInfo);
270 QFileInfoList findQmlFiles(const QString &dirName)
271 {
272     QDir dir(dirName);
273
274     QFileInfoList ret;
275     if (dir.exists()) {
276         QFileInfoList fileInfos = dir.entryInfoList(QStringList() << "*.qml",
277                                                     QDir::Files | QDir::AllDirs | QDir::NoDotAndDotDot);
278
279         foreach (QFileInfo fileInfo, fileInfos) {
280             if (fileInfo.isDir())
281                 ret += findQmlFiles(fileInfo.filePath());
282             else if (fileInfo.fileName().length() > 0 && fileInfo.fileName().at(0).isLower())
283                 ret.append(fileInfo);
284         }
285     }
286
287     return ret;
288 }
289
290 static int displayOptionsDialog(Options *options)
291 {
292     QDialog dialog;
293
294     QFormLayout *layout = new QFormLayout(&dialog);
295
296     QComboBox *qmlFileComboBox = new QComboBox(&dialog);
297     QFileInfoList fileInfos = findQmlFiles(":/bundle") + findQmlFiles("./qmlscene-resources");
298
299     foreach (QFileInfo fileInfo, fileInfos)
300         qmlFileComboBox->addItem(fileInfo.dir().dirName() + "/" + fileInfo.fileName(), QVariant::fromValue(fileInfo));
301
302     QCheckBox *originalCheckBox = new QCheckBox(&dialog);
303     originalCheckBox->setText("Use original QML viewer");
304     originalCheckBox->setChecked(options->originalQml);
305
306     QCheckBox *fullscreenCheckBox = new QCheckBox(&dialog);
307     fullscreenCheckBox->setText("Start fullscreen");
308     fullscreenCheckBox->setChecked(options->fullscreen);
309
310     QCheckBox *maximizedCheckBox = new QCheckBox(&dialog);
311     maximizedCheckBox->setText("Start maximized");
312     maximizedCheckBox->setChecked(options->maximized);
313
314     QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
315                                                        Qt::Horizontal,
316                                                        &dialog);
317     QObject::connect(buttonBox, SIGNAL(accepted()), &dialog, SLOT(accept()));
318     QObject::connect(buttonBox, SIGNAL(rejected()), &dialog, SLOT(reject()));
319
320     layout->addRow("Qml file:", qmlFileComboBox);
321     layout->addWidget(originalCheckBox);
322     layout->addWidget(maximizedCheckBox);
323     layout->addWidget(fullscreenCheckBox);
324     layout->addWidget(buttonBox);
325
326     int result = dialog.exec();
327     if (result == QDialog::Accepted) {
328         QVariant variant = qmlFileComboBox->itemData(qmlFileComboBox->currentIndex());
329         QFileInfo fileInfo = variant.value<QFileInfo>();
330
331         if (fileInfo.canonicalFilePath().startsWith(":"))
332             options->file = QUrl("qrc" + fileInfo.canonicalFilePath());
333         else
334             options->file = QUrl::fromLocalFile(fileInfo.canonicalFilePath());
335         options->originalQml = originalCheckBox->isChecked();
336         options->maximized = maximizedCheckBox->isChecked();
337         options->fullscreen = fullscreenCheckBox->isChecked();
338     }
339     return result;
340 }
341 #endif
342
343 static void checkAndAdaptVersion(const QUrl &url)
344 {
345     if (!qgetenv("QMLSCENE_IMPORT_NAME").isEmpty()) {
346         return;
347     }
348
349     QString fileName = url.toLocalFile();
350     if (fileName.isEmpty())
351         return;
352
353     QFile f(fileName);
354     if (!f.open(QFile::ReadOnly | QFile::Text)) {
355         qWarning("qmlscene: failed to check version of file '%s', could not open...",
356                  qPrintable(fileName));
357         return;
358     }
359
360     QRegExp quick1("^\\s*import +QtQuick +1\\.");
361     QRegExp qt47("^\\s*import +Qt +4\\.7");
362
363     QString envToWrite;
364     QString compat;
365
366     QTextStream stream(&f);
367     bool codeFound= false;
368     while (!codeFound && envToWrite.isEmpty()) {
369         QString line = stream.readLine();
370         if (line.contains("{"))
371             codeFound = true;
372         if (quick1.indexIn(line) >= 0) {
373             envToWrite = QLatin1String("quick1");
374             compat = QLatin1String("QtQuick 1.0");
375         } else if (qt47.indexIn(line) >= 0) {
376             envToWrite = QLatin1String("qt");
377             compat = QLatin1String("Qt 4.7");
378         }
379     }
380
381     if (!envToWrite.isEmpty()) {
382         qWarning("qmlscene: Autodetecting compatibility import \"%s\"...", qPrintable(compat));
383         if (qgetenv("QMLSCENE_IMPORT_NAME").isEmpty())
384             qputenv("QMLSCENE_IMPORT_NAME", envToWrite.toLatin1().constData());
385     }
386 }
387
388 static void displayFileDialog(Options *options)
389 {
390     QString fileName = QFileDialog::getOpenFileName(0, "Open QML file", QString(), "QML Files (*.qml)");
391     if (!fileName.isEmpty()) {
392         QFileInfo fi(fileName);
393         options->file = QUrl::fromLocalFile(fi.canonicalFilePath());
394     }
395 }
396
397 static void loadDummyDataFiles(QDeclarativeEngine &engine, const QString& directory)
398 {
399     QDir dir(directory+"/dummydata", "*.qml");
400     QStringList list = dir.entryList();
401     for (int i = 0; i < list.size(); ++i) {
402         QString qml = list.at(i);
403         QFile f(dir.filePath(qml));
404         f.open(QIODevice::ReadOnly);
405         QByteArray data = f.readAll();
406         QDeclarativeComponent comp(&engine);
407         comp.setData(data, QUrl());
408         QObject *dummyData = comp.create();
409
410         if(comp.isError()) {
411             QList<QDeclarativeError> errors = comp.errors();
412             foreach (const QDeclarativeError &error, errors) {
413                 qWarning() << error;
414             }
415         }
416
417         if (dummyData) {
418             qWarning() << "Loaded dummy data:" << dir.filePath(qml);
419             qml.truncate(qml.length()-4);
420             engine.rootContext()->setContextProperty(qml, dummyData);
421             dummyData->setParent(&engine);
422         }
423     }
424 }
425
426 static void usage()
427 {
428     qWarning("Usage: qmlscene [options] <filename>");
429     qWarning(" ");
430     qWarning(" options:");
431     qWarning("  --maximized ............................... run maximized");
432     qWarning("  --fullscreen .............................. run fullscreen");
433     qWarning("  --original-qml ............................ run using QGraphicsView instead of scenegraph (OpenGL engine)");
434     qWarning("  --original-qml-raster ..................... run using QGraphicsView instead of scenegraph (Raster engine)");
435     qWarning("  --no-multisample .......................... Disable multisampling (anti-aliasing)");
436     qWarning("  --continuous-update ....................... Continuously render the scene");
437     qWarning("  --nonblocking-swap ........................ Do not wait for v-sync to swap buffers");
438     qWarning("  --stereo .................................. Enable stereo on the GL context");
439 #ifndef QT_NO_SCENEGRAPHITEM
440     qWarning("  --sg-on-gv [--clip] ....................... Scenegraph on graphicsview (and clip to item)");
441 #endif
442     qWarning("  --no-version-detection .................... Do not try to detect the version of the .qml file");
443     qWarning("  --no-vsync-animations ..................... Do not use vsync based animations");
444
445     qWarning(" ");
446     exit(1);
447 }
448
449 int main(int argc, char ** argv)
450 {
451 #ifdef Q_WS_X11
452     QApplication::setAttribute(Qt::AA_X11InitThreads);
453 #endif
454
455     Options options;
456
457     QStringList imports;
458     for (int i = 1; i < argc; ++i) {
459         if (*argv[i] != '-' && QFileInfo(argv[i]).exists())
460             options.file = QUrl::fromLocalFile(argv[i]);
461         else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--original-qml"))
462             options.originalQml = true;
463         else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--original-qml-raster"))
464             options.originalQmlRaster = true;
465         else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--maximized"))
466             options.maximized = true;
467         else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--fullscreen"))
468             options.fullscreen = true;
469         else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--sg-on-gv"))
470             options.scenegraphOnGraphicsview = true;
471         else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--clip"))
472             options.clip = true;
473         else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--no-version-detection"))
474             options.versionDetection = false;
475         else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("-i") && i + 1 < argc)
476             imports.append(QString::fromLatin1(argv[++i]));
477         else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--no-vsync-animations"))
478             options.vsync = false;
479         else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--help")
480                  || QString::fromLatin1(argv[i]).toLower() == QLatin1String("-help")
481                  || QString::fromLatin1(argv[i]).toLower() == QLatin1String("--h")
482                  || QString::fromLatin1(argv[i]).toLower() == QLatin1String("-h"))
483             usage();
484     }
485
486     QApplication::setGraphicsSystem("raster");
487
488     QApplication app(argc, argv);
489     app.setApplicationName("QtQmlViewer");
490     app.setOrganizationName("Nokia");
491     app.setOrganizationDomain("nokia.com");
492
493     if (options.file.isEmpty())
494 #if defined(QMLSCENE_BUNDLE)
495         displayOptionsDialog(&options);
496 #else
497         displayFileDialog(&options);
498 #endif
499
500     QWidget *view = 0;
501     QDeclarativeEngine *engine = 0;
502
503     int exitCode = 0;
504
505     if (!options.file.isEmpty()) {
506 #ifndef QT_NO_SCENEGRAPHITEM
507         if (options.scenegraphOnGraphicsview) {
508             MyGraphicsView *gvView = new MyGraphicsView(options.clip);
509             SceneGraphItem *item = gvView->sceneGraphItem();
510             engine = item->engine();
511             for (int i = 0; i < imports.size(); ++i)
512                 engine->addImportPath(imports.at(i));
513             view = gvView;
514             if (options.file.isLocalFile()) {
515                 QFileInfo fi(options.file.toLocalFile());
516                 loadDummyDataFiles(*engine, fi.path());
517             }
518             item->setSource(options.file);
519         } else
520 #endif
521         if (!options.originalQml && !options.originalQmlRaster) {
522             if (options.versionDetection)
523                 checkAndAdaptVersion(options.file);
524             QSGView *qxView = new MyQSGView();
525             qxView->setVSyncAnimations(options.vsync);
526             engine = qxView->engine();
527             for (int i = 0; i < imports.size(); ++i)
528                 engine->addImportPath(imports.at(i));
529             view = qxView;
530             if (options.file.isLocalFile()) {
531                 QFileInfo fi(options.file.toLocalFile());
532                 loadDummyDataFiles(*engine, fi.path());
533             }
534             qxView->setSource(options.file);
535
536         } else {
537             MyDeclarativeView *gvView = new MyDeclarativeView();
538             engine = gvView->engine();
539             for (int i = 0; i < imports.size(); ++i)
540                 engine->addImportPath(imports.at(i));
541             view = gvView;
542             if (options.file.isLocalFile()) {
543                 QFileInfo fi(options.file.toLocalFile());
544                 loadDummyDataFiles(*engine, fi.path());
545             }
546             gvView->setSource(options.file);
547             if (!options.originalQmlRaster) {
548                 QGLWidget *viewport = new QGLWidget(getFormat());
549                 gvView->setViewport(viewport);
550             }
551         }
552
553         QObject::connect(engine, SIGNAL(quit()), QCoreApplication::instance(), SLOT(quit()));
554
555         if (options.fullscreen)
556             view->showFullScreen();
557         else if (options.maximized)
558             view->showMaximized();
559         else
560             view->show();
561
562 #ifdef Q_WS_MAC
563         view->raise();
564 #endif
565
566         exitCode = app.exec();
567
568         delete view;
569
570 #ifdef QML_RUNTIME_TESTING
571         RenderStatistics::printTotalStats();
572 #endif
573     }
574
575     return exitCode;
576 }
577