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