Add slow animations mode to qmlscene
[profile/ivi/qtdeclarative.git] / tools / qmlscene / main.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 tools applications 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 <QtCore/qdebug.h>
43 #include <QtCore/qabstractanimation.h>
44 #include <QtCore/qdir.h>
45 #include <QtCore/qmath.h>
46 #include <QtCore/qdatetime.h>
47
48 #include <QtGui/QGuiApplication>
49
50 #include <QtDeclarative/qdeclarative.h>
51 #include <QtDeclarative/qdeclarativeengine.h>
52 #include <QtDeclarative/qdeclarativecomponent.h>
53 #include <QtDeclarative/qdeclarativecontext.h>
54
55 #include <QtQuick/qquickitem.h>
56 #include <QtQuick/qquickview.h>
57
58 #include <private/qabstractanimation_p.h>
59
60 #ifdef QT_WIDGETS_LIB
61 #include <QtWidgets/QApplication>
62 #include <QtWidgets/QFileDialog>
63 #endif
64
65
66 #ifdef QML_RUNTIME_TESTING
67 class RenderStatistics
68 {
69 public:
70     static void updateStats();
71     static void printTotalStats();
72 private:
73     static QVector<qreal> timePerFrame;
74     static QVector<int> timesPerFrames;
75 };
76
77 QVector<qreal> RenderStatistics::timePerFrame;
78 QVector<int> RenderStatistics::timesPerFrames;
79
80 void RenderStatistics::updateStats()
81 {
82     static QTime time;
83     static int frames;
84     static int lastTime;
85
86     if (frames == 0) {
87         time.start();
88     } else {
89         int elapsed = time.elapsed();
90         timesPerFrames.append(elapsed - lastTime);
91         lastTime = elapsed;
92
93         if (elapsed > 5000) {
94             qreal avgtime = elapsed / (qreal) frames;
95             qreal var = 0;
96             for (int i = 0; i < timesPerFrames.size(); ++i) {
97                 qreal diff = timesPerFrames.at(i) - avgtime;
98                 var += diff * diff;
99             }
100             var /= timesPerFrames.size();
101
102             qDebug("Average time per frame: %f ms (%i fps), std.dev: %f ms", avgtime, qRound(1000. / avgtime), qSqrt(var));
103
104             timePerFrame.append(avgtime);
105             timesPerFrames.clear();
106             time.start();
107             lastTime = 0;
108             frames = 0;
109         }
110     }
111     ++frames;
112 }
113
114 void RenderStatistics::printTotalStats()
115 {
116     int count = timePerFrame.count();
117     if (count == 0)
118         return;
119
120     qreal minTime = 0;
121     qreal maxTime = 0;
122     qreal avg = 0;
123     for (int i = 0; i < count; ++i) {
124         minTime = minTime == 0 ? timePerFrame.at(i) : qMin(minTime, timePerFrame.at(i));
125         maxTime = qMax(maxTime, timePerFrame.at(i));
126         avg += timePerFrame.at(i);
127     }
128     avg /= count;
129
130     qDebug(" ");
131     qDebug("----- Statistics -----");
132     qDebug("Average time per frame: %f ms (%i fps)", avg, qRound(1000. / avg));
133     qDebug("Best time per frame: %f ms (%i fps)", minTime, int(1000 / minTime));
134     qDebug("Worst time per frame: %f ms (%i fps)", maxTime, int(1000 / maxTime));
135     qDebug("----------------------");
136     qDebug(" ");
137 }
138 #endif
139
140 class MyQQuickView : public QQuickView
141 {
142 public:
143     MyQQuickView() : QQuickView()
144     {
145         setResizeMode(QQuickView::SizeRootObjectToView);
146     }
147 };
148
149 struct Options
150 {
151     Options()
152         : originalQml(false)
153         , originalQmlRaster(false)
154         , maximized(false)
155         , fullscreen(false)
156         , clip(false)
157         , versionDetection(true)
158         , slowAnimations(false)
159     {
160     }
161
162     QUrl file;
163     bool originalQml;
164     bool originalQmlRaster;
165     bool maximized;
166     bool fullscreen;
167     bool scenegraphOnGraphicsview;
168     bool clip;
169     bool versionDetection;
170     bool slowAnimations;
171 };
172
173 #if defined(QMLSCENE_BUNDLE)
174 Q_DECLARE_METATYPE(QFileInfo);
175 QFileInfoList findQmlFiles(const QString &dirName)
176 {
177     QDir dir(dirName);
178
179     QFileInfoList ret;
180     if (dir.exists()) {
181         QFileInfoList fileInfos = dir.entryInfoList(QStringList() << "*.qml",
182                                                     QDir::Files | QDir::AllDirs | QDir::NoDotAndDotDot);
183
184         foreach (QFileInfo fileInfo, fileInfos) {
185             if (fileInfo.isDir())
186                 ret += findQmlFiles(fileInfo.filePath());
187             else if (fileInfo.fileName().length() > 0 && fileInfo.fileName().at(0).isLower())
188                 ret.append(fileInfo);
189         }
190     }
191
192     return ret;
193 }
194
195 static int displayOptionsDialog(Options *options)
196 {
197     QDialog dialog;
198
199     QFormLayout *layout = new QFormLayout(&dialog);
200
201     QComboBox *qmlFileComboBox = new QComboBox(&dialog);
202     QFileInfoList fileInfos = findQmlFiles(":/bundle") + findQmlFiles("./qmlscene-resources");
203
204     foreach (QFileInfo fileInfo, fileInfos)
205         qmlFileComboBox->addItem(fileInfo.dir().dirName() + "/" + fileInfo.fileName(), QVariant::fromValue(fileInfo));
206
207     QCheckBox *originalCheckBox = new QCheckBox(&dialog);
208     originalCheckBox->setText("Use original QML viewer");
209     originalCheckBox->setChecked(options->originalQml);
210
211     QCheckBox *fullscreenCheckBox = new QCheckBox(&dialog);
212     fullscreenCheckBox->setText("Start fullscreen");
213     fullscreenCheckBox->setChecked(options->fullscreen);
214
215     QCheckBox *maximizedCheckBox = new QCheckBox(&dialog);
216     maximizedCheckBox->setText("Start maximized");
217     maximizedCheckBox->setChecked(options->maximized);
218
219     QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
220                                                        Qt::Horizontal,
221                                                        &dialog);
222     QObject::connect(buttonBox, SIGNAL(accepted()), &dialog, SLOT(accept()));
223     QObject::connect(buttonBox, SIGNAL(rejected()), &dialog, SLOT(reject()));
224
225     layout->addRow("Qml file:", qmlFileComboBox);
226     layout->addWidget(originalCheckBox);
227     layout->addWidget(maximizedCheckBox);
228     layout->addWidget(fullscreenCheckBox);
229     layout->addWidget(buttonBox);
230
231     int result = dialog.exec();
232     if (result == QDialog::Accepted) {
233         QVariant variant = qmlFileComboBox->itemData(qmlFileComboBox->currentIndex());
234         QFileInfo fileInfo = variant.value<QFileInfo>();
235
236         if (fileInfo.canonicalFilePath().startsWith(":"))
237             options->file = QUrl("qrc" + fileInfo.canonicalFilePath());
238         else
239             options->file = QUrl::fromLocalFile(fileInfo.canonicalFilePath());
240         options->originalQml = originalCheckBox->isChecked();
241         options->maximized = maximizedCheckBox->isChecked();
242         options->fullscreen = fullscreenCheckBox->isChecked();
243     }
244     return result;
245 }
246 #endif
247
248 static bool checkVersion(const QUrl &url)
249 {
250     if (!qgetenv("QMLSCENE_IMPORT_NAME").isEmpty()) {
251         qWarning("QMLSCENE_IMPORT_NAME is no longer supported.");
252     }
253
254     QString fileName = url.toLocalFile();
255     if (fileName.isEmpty()) {
256         qWarning("qmlscene: filename required.");
257         return false;
258     }
259
260     QFile f(fileName);
261     if (!f.open(QFile::ReadOnly | QFile::Text)) {
262         qWarning("qmlscene: failed to check version of file '%s', could not open...",
263                  qPrintable(fileName));
264         return false;
265     }
266
267     QRegExp quick1("^\\s*import +QtQuick +1\\.\\w*");
268     QRegExp qt47("^\\s*import +Qt +4\\.7");
269
270     QTextStream stream(&f);
271     bool codeFound= false;
272     while (!codeFound) {
273         QString line = stream.readLine();
274         if (line.contains("{")) {
275             codeFound = true;
276         } else {
277             QString import;
278             if (quick1.indexIn(line) >= 0) {
279                 import = quick1.cap(0).trimmed();
280             } else if (qt47.indexIn(line) >= 0) {
281                 import = qt47.cap(0).trimmed();
282             }
283
284             if (!import.isNull()) {
285                 qWarning("qmlscene: '%s' is no longer supported.\n"
286                          "Use qmlviewer to load file '%s'.",
287                          qPrintable(import),
288                          qPrintable(fileName));
289                 return false;
290             }
291         }
292     }
293
294     return true;
295 }
296
297 static void displayFileDialog(Options *options)
298 {
299 #ifdef QT_WIDGETS_LIB
300     QString fileName = QFileDialog::getOpenFileName(0, "Open QML file", QString(), "QML Files (*.qml)");
301     if (!fileName.isEmpty()) {
302         QFileInfo fi(fileName);
303         options->file = QUrl::fromLocalFile(fi.canonicalFilePath());
304     }
305 #else
306     Q_UNUSED(options);
307     qWarning("No filename specified...");
308 #endif
309 }
310
311 static void loadDummyDataFiles(QDeclarativeEngine &engine, const QString& directory)
312 {
313     QDir dir(directory+"/dummydata", "*.qml");
314     QStringList list = dir.entryList();
315     for (int i = 0; i < list.size(); ++i) {
316         QString qml = list.at(i);
317         QFile f(dir.filePath(qml));
318         f.open(QIODevice::ReadOnly);
319         QByteArray data = f.readAll();
320         QDeclarativeComponent comp(&engine);
321         comp.setData(data, QUrl());
322         QObject *dummyData = comp.create();
323
324         if(comp.isError()) {
325             QList<QDeclarativeError> errors = comp.errors();
326             foreach (const QDeclarativeError &error, errors) {
327                 qWarning() << error;
328             }
329         }
330
331         if (dummyData) {
332             qWarning() << "Loaded dummy data:" << dir.filePath(qml);
333             qml.truncate(qml.length()-4);
334             engine.rootContext()->setContextProperty(qml, dummyData);
335             dummyData->setParent(&engine);
336         }
337     }
338 }
339
340 static void usage()
341 {
342     qWarning("Usage: qmlscene [options] <filename>");
343     qWarning(" ");
344     qWarning(" options:");
345     qWarning("  --maximized ............................... run maximized");
346     qWarning("  --fullscreen .............................. run fullscreen");
347     qWarning("  --no-multisample .......................... Disable multisampling (anti-aliasing)");
348     qWarning("  --no-version-detection .................... Do not try to detect the version of the .qml file");
349     qWarning("  --slow-animations ......................... Run all animations in slow motion");
350
351     qWarning(" ");
352     exit(1);
353 }
354
355 int main(int argc, char ** argv)
356 {
357     Options options;
358
359     QStringList imports;
360     for (int i = 1; i < argc; ++i) {
361         if (*argv[i] != '-' && QFileInfo(QFile::decodeName(argv[i])).exists()) {
362             options.file = QUrl::fromLocalFile(argv[i]);
363         } else {
364             const QString lowerArgument = QString::fromLatin1(argv[i]).toLower();
365             if (lowerArgument == QLatin1String("--maximized"))
366                 options.maximized = true;
367             else if (lowerArgument == QLatin1String("--fullscreen"))
368                 options.fullscreen = true;
369             else if (lowerArgument == QLatin1String("--clip"))
370                 options.clip = true;
371             else if (lowerArgument == QLatin1String("--no-version-detection"))
372                 options.versionDetection = false;
373             else if (lowerArgument == QLatin1String("--slow-animations"))
374                 options.slowAnimations = true;
375             else if (lowerArgument == QLatin1String("-i") && i + 1 < argc)
376                 imports.append(QString::fromLatin1(argv[++i]));
377             else if (lowerArgument == QLatin1String("--help")
378                      || lowerArgument == QLatin1String("-help")
379                      || lowerArgument == QLatin1String("--h")
380                      || lowerArgument == QLatin1String("-h"))
381                 usage();
382         }
383     }
384
385 #ifdef QT_WIDGETS_LIB
386     QApplication app(argc, argv);
387 #else
388     QGuiApplication app(argc, argv);
389 #endif
390     app.setApplicationName("QtQmlViewer");
391     app.setOrganizationName("Nokia");
392     app.setOrganizationDomain("nokia.com");
393
394     QUnifiedTimer::instance()->setSlowModeEnabled(options.slowAnimations);
395
396     if (options.file.isEmpty())
397 #if defined(QMLSCENE_BUNDLE)
398         displayOptionsDialog(&options);
399 #else
400         displayFileDialog(&options);
401 #endif
402
403     QWindow *window = 0;
404     QDeclarativeEngine *engine = 0;
405
406     int exitCode = 0;
407
408     if (!options.file.isEmpty()) {
409         if (!options.versionDetection || checkVersion(options.file)) {
410             QQuickView *qxView = new MyQQuickView();
411             engine = qxView->engine();
412             for (int i = 0; i < imports.size(); ++i)
413                 engine->addImportPath(imports.at(i));
414             window = qxView;
415             if (options.file.isLocalFile()) {
416                 QFileInfo fi(options.file.toLocalFile());
417                 loadDummyDataFiles(*engine, fi.path());
418             }
419             qxView->setSource(options.file);
420
421             QObject::connect(engine, SIGNAL(quit()), QCoreApplication::instance(), SLOT(quit()));
422
423             window->setWindowFlags(Qt::Window | Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint);
424             if (options.fullscreen)
425                 window->showFullScreen();
426             else if (options.maximized)
427                 window->showMaximized();
428             else
429                 window->show();
430
431             exitCode = app.exec();
432
433             delete window;
434
435 #ifdef QML_RUNTIME_TESTING
436             RenderStatistics::printTotalStats();
437 #endif
438         }
439     }
440
441     return exitCode;
442 }
443