Merge branch 'master' into refactor
[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 <QtWidgets/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 <QtWidgets/QFormLayout>
51 #include <QtWidgets/QComboBox>
52 #include <QtWidgets/QCheckBox>
53 #include <QtWidgets/QDialog>
54 #include <QtWidgets/QDialogButtonBox>
55 #include <QtWidgets/QFileDialog>
56 #include <QtWidgets/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 class MyQSGView : public QSGView
147 {
148 public:
149     MyQSGView() : QSGView()
150     {
151         setResizeMode(QSGView::SizeRootObjectToView);
152     }
153 };
154
155 class MyDeclarativeView: public QDeclarativeView
156 {
157 public:
158     MyDeclarativeView(QWidget *parent = 0) : QDeclarativeView(parent)
159     {
160         setResizeMode(QDeclarativeView::SizeRootObjectToView);
161     }
162 };
163
164 #ifndef QT_NO_SCENEGRAPHITEM
165 class MyGraphicsView: public QGraphicsView
166 {
167 public:
168     MyGraphicsView(bool clip, QWidget *parent = 0) : QGraphicsView(parent)
169     {
170         setViewport(new QGLWidget(getFormat()));
171         setScene(&scene);
172         scene.addItem(&item);
173         item.setFlag(QGraphicsItem::ItemClipsToShape, clip);
174         QGraphicsTextItem *text;
175         text = scene.addText(QLatin1String("Scene graph on graphics view."), QFont(QLatin1String("Times"), 10));
176         text->setX(5);
177         text->setY(5);
178         text->setDefaultTextColor(Qt::black);
179         text = scene.addText(QLatin1String("Scene graph on graphics view."), QFont(QLatin1String("Times"), 10));
180         text->setX(4);
181         text->setY(4);
182         text->setDefaultTextColor(Qt::yellow);
183     }
184
185     SceneGraphItem *sceneGraphItem() { return &item; }
186
187 protected:
188     void paintEvent(QPaintEvent *event)
189     {
190         QGraphicsView::paintEvent(event);
191
192 #ifdef QML_RUNTIME_TESTING
193         RenderStatistics::updateStats();
194 #endif
195
196         static bool continuousUpdate = qApp->arguments().contains("--continuous-update");
197         if (continuousUpdate)
198             QGraphicsView::scene()->update();
199     }
200
201     QGraphicsScene scene;
202     SceneGraphItem item;
203 };
204 #endif
205
206 struct Options
207 {
208     Options()
209         : originalQml(false)
210         , originalQmlRaster(false)
211         , maximized(false)
212         , fullscreen(false)
213         , scenegraphOnGraphicsview(false)
214         , clip(false)
215         , versionDetection(true)
216         , vsync(true)
217     {
218     }
219
220     QUrl file;
221     bool originalQml;
222     bool originalQmlRaster;
223     bool maximized;
224     bool fullscreen;
225     bool scenegraphOnGraphicsview;
226     bool clip;
227     bool versionDetection;
228     bool vsync;
229 };
230
231 #if defined(QMLSCENE_BUNDLE)
232 Q_DECLARE_METATYPE(QFileInfo);
233 QFileInfoList findQmlFiles(const QString &dirName)
234 {
235     QDir dir(dirName);
236
237     QFileInfoList ret;
238     if (dir.exists()) {
239         QFileInfoList fileInfos = dir.entryInfoList(QStringList() << "*.qml",
240                                                     QDir::Files | QDir::AllDirs | QDir::NoDotAndDotDot);
241
242         foreach (QFileInfo fileInfo, fileInfos) {
243             if (fileInfo.isDir())
244                 ret += findQmlFiles(fileInfo.filePath());
245             else if (fileInfo.fileName().length() > 0 && fileInfo.fileName().at(0).isLower())
246                 ret.append(fileInfo);
247         }
248     }
249
250     return ret;
251 }
252
253 static int displayOptionsDialog(Options *options)
254 {
255     QDialog dialog;
256
257     QFormLayout *layout = new QFormLayout(&dialog);
258
259     QComboBox *qmlFileComboBox = new QComboBox(&dialog);
260     QFileInfoList fileInfos = findQmlFiles(":/bundle") + findQmlFiles("./qmlscene-resources");
261
262     foreach (QFileInfo fileInfo, fileInfos)
263         qmlFileComboBox->addItem(fileInfo.dir().dirName() + "/" + fileInfo.fileName(), QVariant::fromValue(fileInfo));
264
265     QCheckBox *originalCheckBox = new QCheckBox(&dialog);
266     originalCheckBox->setText("Use original QML viewer");
267     originalCheckBox->setChecked(options->originalQml);
268
269     QCheckBox *fullscreenCheckBox = new QCheckBox(&dialog);
270     fullscreenCheckBox->setText("Start fullscreen");
271     fullscreenCheckBox->setChecked(options->fullscreen);
272
273     QCheckBox *maximizedCheckBox = new QCheckBox(&dialog);
274     maximizedCheckBox->setText("Start maximized");
275     maximizedCheckBox->setChecked(options->maximized);
276
277     QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
278                                                        Qt::Horizontal,
279                                                        &dialog);
280     QObject::connect(buttonBox, SIGNAL(accepted()), &dialog, SLOT(accept()));
281     QObject::connect(buttonBox, SIGNAL(rejected()), &dialog, SLOT(reject()));
282
283     layout->addRow("Qml file:", qmlFileComboBox);
284     layout->addWidget(originalCheckBox);
285     layout->addWidget(maximizedCheckBox);
286     layout->addWidget(fullscreenCheckBox);
287     layout->addWidget(buttonBox);
288
289     int result = dialog.exec();
290     if (result == QDialog::Accepted) {
291         QVariant variant = qmlFileComboBox->itemData(qmlFileComboBox->currentIndex());
292         QFileInfo fileInfo = variant.value<QFileInfo>();
293
294         if (fileInfo.canonicalFilePath().startsWith(":"))
295             options->file = QUrl("qrc" + fileInfo.canonicalFilePath());
296         else
297             options->file = QUrl::fromLocalFile(fileInfo.canonicalFilePath());
298         options->originalQml = originalCheckBox->isChecked();
299         options->maximized = maximizedCheckBox->isChecked();
300         options->fullscreen = fullscreenCheckBox->isChecked();
301     }
302     return result;
303 }
304 #endif
305
306 static void checkAndAdaptVersion(const QUrl &url)
307 {
308     if (!qgetenv("QMLSCENE_IMPORT_NAME").isEmpty()) {
309         return;
310     }
311
312     QString fileName = url.toLocalFile();
313     if (fileName.isEmpty())
314         return;
315
316     QFile f(fileName);
317     if (!f.open(QFile::ReadOnly | QFile::Text)) {
318         qWarning("qmlscene: failed to check version of file '%s', could not open...",
319                  qPrintable(fileName));
320         return;
321     }
322
323     QRegExp quick1("^\\s*import +QtQuick +1\\.");
324     QRegExp qt47("^\\s*import +Qt +4\\.7");
325
326     QString envToWrite;
327     QString compat;
328
329     QTextStream stream(&f);
330     bool codeFound= false;
331     while (!codeFound && envToWrite.isEmpty()) {
332         QString line = stream.readLine();
333         if (line.contains("{"))
334             codeFound = true;
335         if (quick1.indexIn(line) >= 0) {
336             envToWrite = QLatin1String("quick1");
337             compat = QLatin1String("QtQuick 1.0");
338         } else if (qt47.indexIn(line) >= 0) {
339             envToWrite = QLatin1String("qt");
340             compat = QLatin1String("Qt 4.7");
341         }
342     }
343
344     if (!envToWrite.isEmpty()) {
345         qWarning("qmlscene: Autodetecting compatibility import \"%s\"...", qPrintable(compat));
346         if (qgetenv("QMLSCENE_IMPORT_NAME").isEmpty())
347             qputenv("QMLSCENE_IMPORT_NAME", envToWrite.toLatin1().constData());
348     }
349 }
350
351 static void displayFileDialog(Options *options)
352 {
353     QString fileName = QFileDialog::getOpenFileName(0, "Open QML file", QString(), "QML Files (*.qml)");
354     if (!fileName.isEmpty()) {
355         QFileInfo fi(fileName);
356         options->file = QUrl::fromLocalFile(fi.canonicalFilePath());
357     }
358 }
359
360 static void loadDummyDataFiles(QDeclarativeEngine &engine, const QString& directory)
361 {
362     QDir dir(directory+"/dummydata", "*.qml");
363     QStringList list = dir.entryList();
364     for (int i = 0; i < list.size(); ++i) {
365         QString qml = list.at(i);
366         QFile f(dir.filePath(qml));
367         f.open(QIODevice::ReadOnly);
368         QByteArray data = f.readAll();
369         QDeclarativeComponent comp(&engine);
370         comp.setData(data, QUrl());
371         QObject *dummyData = comp.create();
372
373         if(comp.isError()) {
374             QList<QDeclarativeError> errors = comp.errors();
375             foreach (const QDeclarativeError &error, errors) {
376                 qWarning() << error;
377             }
378         }
379
380         if (dummyData) {
381             qWarning() << "Loaded dummy data:" << dir.filePath(qml);
382             qml.truncate(qml.length()-4);
383             engine.rootContext()->setContextProperty(qml, dummyData);
384             dummyData->setParent(&engine);
385         }
386     }
387 }
388
389 static void usage()
390 {
391     qWarning("Usage: qmlscene [options] <filename>");
392     qWarning(" ");
393     qWarning(" options:");
394     qWarning("  --maximized ............................... run maximized");
395     qWarning("  --fullscreen .............................. run fullscreen");
396     qWarning("  --original-qml ............................ run using QGraphicsView instead of scenegraph (OpenGL engine)");
397     qWarning("  --original-qml-raster ..................... run using QGraphicsView instead of scenegraph (Raster engine)");
398     qWarning("  --no-multisample .......................... Disable multisampling (anti-aliasing)");
399     qWarning("  --continuous-update ....................... Continuously render the scene");
400     qWarning("  --nonblocking-swap ........................ Do not wait for v-sync to swap buffers");
401     qWarning("  --stereo .................................. Enable stereo on the GL context");
402 #ifndef QT_NO_SCENEGRAPHITEM
403     qWarning("  --sg-on-gv [--clip] ....................... Scenegraph on graphicsview (and clip to item)");
404 #endif
405     qWarning("  --no-version-detection .................... Do not try to detect the version of the .qml file");
406     qWarning("  --no-vsync-animations ..................... Do not use vsync based animations");
407
408     qWarning(" ");
409     exit(1);
410 }
411
412 int main(int argc, char ** argv)
413 {
414 #ifdef Q_WS_X11
415     QApplication::setAttribute(Qt::AA_X11InitThreads);
416 #endif
417
418     Options options;
419
420     QStringList imports;
421     for (int i = 1; i < argc; ++i) {
422         if (*argv[i] != '-' && QFileInfo(argv[i]).exists())
423             options.file = QUrl::fromLocalFile(argv[i]);
424         else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--original-qml"))
425             options.originalQml = true;
426         else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--original-qml-raster"))
427             options.originalQmlRaster = true;
428         else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--maximized"))
429             options.maximized = true;
430         else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--fullscreen"))
431             options.fullscreen = true;
432         else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--sg-on-gv"))
433             options.scenegraphOnGraphicsview = true;
434         else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--clip"))
435             options.clip = true;
436         else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--no-version-detection"))
437             options.versionDetection = false;
438         else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("-i") && i + 1 < argc)
439             imports.append(QString::fromLatin1(argv[++i]));
440         else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--no-vsync-animations"))
441             options.vsync = false;
442         else if (QString::fromLatin1(argv[i]).toLower() == QLatin1String("--help")
443                  || QString::fromLatin1(argv[i]).toLower() == QLatin1String("-help")
444                  || QString::fromLatin1(argv[i]).toLower() == QLatin1String("--h")
445                  || QString::fromLatin1(argv[i]).toLower() == QLatin1String("-h"))
446             usage();
447     }
448
449     QApplication::setGraphicsSystem("raster");
450
451     QApplication app(argc, argv);
452     app.setApplicationName("QtQmlViewer");
453     app.setOrganizationName("Nokia");
454     app.setOrganizationDomain("nokia.com");
455
456     if (options.file.isEmpty())
457 #if defined(QMLSCENE_BUNDLE)
458         displayOptionsDialog(&options);
459 #else
460         displayFileDialog(&options);
461 #endif
462
463     QWindow *window = 0;
464     QDeclarativeEngine *engine = 0;
465
466     int exitCode = 0;
467
468     if (!options.file.isEmpty()) {
469 #ifndef QT_NO_SCENEGRAPHITEM
470         if (options.scenegraphOnGraphicsview) {
471             MyGraphicsView *gvView = new MyGraphicsView(options.clip);
472             SceneGraphItem *item = gvView->sceneGraphItem();
473             engine = item->engine();
474             for (int i = 0; i < imports.size(); ++i)
475                 engine->addImportPath(imports.at(i));
476             view = gvView;
477             if (options.file.isLocalFile()) {
478                 QFileInfo fi(options.file.toLocalFile());
479                 loadDummyDataFiles(*engine, fi.path());
480             }
481             item->setSource(options.file);
482         } else
483 #endif
484         if (options.versionDetection)
485             checkAndAdaptVersion(options.file);
486         QSGView *qxView = new MyQSGView();
487         qxView->setVSyncAnimations(options.vsync);
488         engine = qxView->engine();
489         for (int i = 0; i < imports.size(); ++i)
490             engine->addImportPath(imports.at(i));
491         window = qxView;
492         if (options.file.isLocalFile()) {
493             QFileInfo fi(options.file.toLocalFile());
494             loadDummyDataFiles(*engine, fi.path());
495         }
496         qxView->setSource(options.file);
497
498         QObject::connect(engine, SIGNAL(quit()), QCoreApplication::instance(), SLOT(quit()));
499
500         if (options.fullscreen)
501             window->showFullScreen();
502         else if (options.maximized)
503             window->showMaximized();
504         else
505             window->show();
506
507
508 #ifdef Q_WS_MAC
509         window->raise();
510 #endif
511
512         exitCode = app.exec();
513
514         delete window;
515
516 #ifdef QML_RUNTIME_TESTING
517         RenderStatistics::printTotalStats();
518 #endif
519     }
520
521     return exitCode;
522 }
523