Small cleanup: remove braces from single line conditionals.
[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 <QtQml/qqml.h>
51 #include <QtQml/qqmlengine.h>
52 #include <QtQml/qqmlcomponent.h>
53 #include <QtQml/qqmlcontext.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 struct Options
141 {
142     Options()
143         : originalQml(false)
144         , originalQmlRaster(false)
145         , maximized(false)
146         , fullscreen(false)
147         , clip(false)
148         , versionDetection(true)
149         , slowAnimations(false)
150         , quitImmediately(false)
151         , resizeViewToRootItem(false)
152     {
153     }
154
155     QUrl file;
156     bool originalQml;
157     bool originalQmlRaster;
158     bool maximized;
159     bool fullscreen;
160     bool scenegraphOnGraphicsview;
161     bool clip;
162     bool versionDetection;
163     bool slowAnimations;
164     bool quitImmediately;
165     bool resizeViewToRootItem;
166 };
167
168 #if defined(QMLSCENE_BUNDLE)
169 Q_DECLARE_METATYPE(QFileInfo);
170 QFileInfoList findQmlFiles(const QString &dirName)
171 {
172     QDir dir(dirName);
173
174     QFileInfoList ret;
175     if (dir.exists()) {
176         QFileInfoList fileInfos = dir.entryInfoList(QStringList() << "*.qml",
177                                                     QDir::Files | QDir::AllDirs | QDir::NoDotAndDotDot);
178
179         foreach (QFileInfo fileInfo, fileInfos) {
180             if (fileInfo.isDir())
181                 ret += findQmlFiles(fileInfo.filePath());
182             else if (fileInfo.fileName().length() > 0 && fileInfo.fileName().at(0).isLower())
183                 ret.append(fileInfo);
184         }
185     }
186
187     return ret;
188 }
189
190 static int displayOptionsDialog(Options *options)
191 {
192     QDialog dialog;
193
194     QFormLayout *layout = new QFormLayout(&dialog);
195
196     QComboBox *qmlFileComboBox = new QComboBox(&dialog);
197     QFileInfoList fileInfos = findQmlFiles(":/bundle") + findQmlFiles("./qmlscene-resources");
198
199     foreach (QFileInfo fileInfo, fileInfos)
200         qmlFileComboBox->addItem(fileInfo.dir().dirName() + "/" + fileInfo.fileName(), QVariant::fromValue(fileInfo));
201
202     QCheckBox *originalCheckBox = new QCheckBox(&dialog);
203     originalCheckBox->setText("Use original QML viewer");
204     originalCheckBox->setChecked(options->originalQml);
205
206     QCheckBox *fullscreenCheckBox = new QCheckBox(&dialog);
207     fullscreenCheckBox->setText("Start fullscreen");
208     fullscreenCheckBox->setChecked(options->fullscreen);
209
210     QCheckBox *maximizedCheckBox = new QCheckBox(&dialog);
211     maximizedCheckBox->setText("Start maximized");
212     maximizedCheckBox->setChecked(options->maximized);
213
214     QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
215                                                        Qt::Horizontal,
216                                                        &dialog);
217     QObject::connect(buttonBox, SIGNAL(accepted()), &dialog, SLOT(accept()));
218     QObject::connect(buttonBox, SIGNAL(rejected()), &dialog, SLOT(reject()));
219
220     layout->addRow("Qml file:", qmlFileComboBox);
221     layout->addWidget(originalCheckBox);
222     layout->addWidget(maximizedCheckBox);
223     layout->addWidget(fullscreenCheckBox);
224     layout->addWidget(buttonBox);
225
226     int result = dialog.exec();
227     if (result == QDialog::Accepted) {
228         QVariant variant = qmlFileComboBox->itemData(qmlFileComboBox->currentIndex());
229         QFileInfo fileInfo = variant.value<QFileInfo>();
230
231         if (fileInfo.canonicalFilePath().startsWith(":"))
232             options->file = QUrl("qrc" + fileInfo.canonicalFilePath());
233         else
234             options->file = QUrl::fromLocalFile(fileInfo.canonicalFilePath());
235         options->originalQml = originalCheckBox->isChecked();
236         options->maximized = maximizedCheckBox->isChecked();
237         options->fullscreen = fullscreenCheckBox->isChecked();
238     }
239     return result;
240 }
241 #endif
242
243 static bool checkVersion(const QUrl &url)
244 {
245     if (!qgetenv("QMLSCENE_IMPORT_NAME").isEmpty())
246         qWarning("QMLSCENE_IMPORT_NAME is no longer supported.");
247
248     QString fileName = url.toLocalFile();
249     if (fileName.isEmpty()) {
250         qWarning("qmlscene: filename required.");
251         return false;
252     }
253
254     QFile f(fileName);
255     if (!f.open(QFile::ReadOnly | QFile::Text)) {
256         qWarning("qmlscene: failed to check version of file '%s', could not open...",
257                  qPrintable(fileName));
258         return false;
259     }
260
261     QRegExp quick1("^\\s*import +QtQuick +1\\.\\w*");
262     QRegExp qt47("^\\s*import +Qt +4\\.7");
263
264     QTextStream stream(&f);
265     bool codeFound= false;
266     while (!codeFound) {
267         QString line = stream.readLine();
268         if (line.contains("{")) {
269             codeFound = true;
270         } else {
271             QString import;
272             if (quick1.indexIn(line) >= 0)
273                 import = quick1.cap(0).trimmed();
274             else if (qt47.indexIn(line) >= 0)
275                 import = qt47.cap(0).trimmed();
276
277             if (!import.isNull()) {
278                 qWarning("qmlscene: '%s' is no longer supported.\n"
279                          "Use qmlviewer to load file '%s'.",
280                          qPrintable(import),
281                          qPrintable(fileName));
282                 return false;
283             }
284         }
285     }
286
287     return true;
288 }
289
290 static void displayFileDialog(Options *options)
291 {
292 #if defined(QT_WIDGETS_LIB) && !defined(QT_NO_FILEDIALOG)
293     QString fileName = QFileDialog::getOpenFileName(0, "Open QML file", QString(), "QML Files (*.qml)");
294     if (!fileName.isEmpty()) {
295         QFileInfo fi(fileName);
296         options->file = QUrl::fromLocalFile(fi.canonicalFilePath());
297     }
298 #else
299     Q_UNUSED(options);
300     qWarning("No filename specified...");
301 #endif
302 }
303
304 static void loadDummyDataFiles(QQmlEngine &engine, const QString& directory)
305 {
306     QDir dir(directory+"/dummydata", "*.qml");
307     QStringList list = dir.entryList();
308     for (int i = 0; i < list.size(); ++i) {
309         QString qml = list.at(i);
310         QFile f(dir.filePath(qml));
311         f.open(QIODevice::ReadOnly);
312         QByteArray data = f.readAll();
313         QQmlComponent comp(&engine);
314         comp.setData(data, QUrl());
315         QObject *dummyData = comp.create();
316
317         if(comp.isError()) {
318             QList<QQmlError> errors = comp.errors();
319             foreach (const QQmlError &error, errors)
320                 qWarning() << error;
321         }
322
323         if (dummyData) {
324             qWarning() << "Loaded dummy data:" << dir.filePath(qml);
325             qml.truncate(qml.length()-4);
326             engine.rootContext()->setContextProperty(qml, dummyData);
327             dummyData->setParent(&engine);
328         }
329     }
330 }
331
332 static void usage()
333 {
334     qWarning("Usage: qmlscene [options] <filename>");
335     qWarning(" ");
336     qWarning(" options:");
337     qWarning("  --maximized ............................... run maximized");
338     qWarning("  --fullscreen .............................. run fullscreen");
339     qWarning("  --no-multisample .......................... Disable multisampling (anti-aliasing)");
340     qWarning("  --no-version-detection .................... Do not try to detect the version of the .qml file");
341     qWarning("  --slow-animations ......................... Run all animations in slow motion");
342     qWarning("  --resize-to-root .......................... Resize the window to the size of the root item");
343     qWarning("  --quit .................................... Quit immediately after starting");
344     qWarning("  -I <path> ................................. Add <path> to the list of import paths");
345     qWarning("  -B <name> <file> .......................... Add a named bundle");
346
347     qWarning(" ");
348     exit(1);
349 }
350
351 int main(int argc, char ** argv)
352 {
353     Options options;
354
355     QStringList imports;
356     QList<QPair<QString, QString> > bundles;
357     for (int i = 1; i < argc; ++i) {
358         if (*argv[i] != '-' && QFileInfo(QFile::decodeName(argv[i])).exists()) {
359             options.file = QUrl::fromLocalFile(argv[i]);
360         } else {
361             const QString lowerArgument = QString::fromLatin1(argv[i]).toLower();
362             if (lowerArgument == QLatin1String("--maximized"))
363                 options.maximized = true;
364             else if (lowerArgument == QLatin1String("--fullscreen"))
365                 options.fullscreen = true;
366             else if (lowerArgument == QLatin1String("--clip"))
367                 options.clip = true;
368             else if (lowerArgument == QLatin1String("--no-version-detection"))
369                 options.versionDetection = false;
370             else if (lowerArgument == QLatin1String("--slow-animations"))
371                 options.slowAnimations = true;
372             else if (lowerArgument == QLatin1String("--quit"))
373                 options.quitImmediately = true;
374             else if (lowerArgument == QLatin1String("--resize-to-root"))
375                 options.resizeViewToRootItem = true;
376             else if (lowerArgument == QLatin1String("-i") && i + 1 < argc)
377                 imports.append(QString::fromLatin1(argv[++i]));
378             else if (lowerArgument == QLatin1String("-b") && i + 2 < argc) {
379                 QString name = QString::fromLatin1(argv[++i]);
380                 QString file = QString::fromLatin1(argv[++i]);
381                 bundles.append(qMakePair(name, file));
382             } else if (lowerArgument == QLatin1String("--help")
383                      || lowerArgument == QLatin1String("-help")
384                      || lowerArgument == QLatin1String("--h")
385                      || lowerArgument == QLatin1String("-h"))
386                 usage();
387         }
388     }
389
390 #ifdef QT_WIDGETS_LIB
391     QApplication app(argc, argv);
392 #else
393     QGuiApplication app(argc, argv);
394 #endif
395     app.setApplicationName("QtQmlViewer");
396     app.setOrganizationName("Nokia");
397     app.setOrganizationDomain("nokia.com");
398
399     QUnifiedTimer::instance()->setSlowModeEnabled(options.slowAnimations);
400
401     if (options.file.isEmpty())
402 #if defined(QMLSCENE_BUNDLE)
403         displayOptionsDialog(&options);
404 #else
405         displayFileDialog(&options);
406 #endif
407
408     QWindow *window = 0;
409     QQmlEngine *engine = 0;
410
411     int exitCode = 0;
412
413     if (!options.file.isEmpty()) {
414         if (!options.versionDetection || checkVersion(options.file)) {
415             QQuickView *qxView = new QQuickView();
416             engine = qxView->engine();
417             for (int i = 0; i < imports.size(); ++i)
418                 engine->addImportPath(imports.at(i));
419             for (int i = 0; i < bundles.size(); ++i)
420                 engine->addNamedBundle(bundles.at(i).first, bundles.at(i).second);
421             window = qxView;
422             if (options.file.isLocalFile()) {
423                 QFileInfo fi(options.file.toLocalFile());
424                 loadDummyDataFiles(*engine, fi.path());
425             }
426             qxView->setSource(options.file);
427
428             QObject::connect(engine, SIGNAL(quit()), QCoreApplication::instance(), SLOT(quit()));
429
430             if (options.resizeViewToRootItem)
431                 qxView->setResizeMode(QQuickView::SizeViewToRootObject);
432             else
433                 qxView->setResizeMode(QQuickView::SizeRootObjectToView);
434
435             window->setWindowFlags(Qt::Window | Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint);
436             if (options.fullscreen)
437                 window->showFullScreen();
438             else if (options.maximized)
439                 window->showMaximized();
440             else
441                 window->show();
442
443             if (options.quitImmediately)
444                 QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
445
446             exitCode = app.exec();
447
448             delete window;
449
450 #ifdef QML_RUNTIME_TESTING
451             RenderStatistics::printTotalStats();
452 #endif
453         }
454     }
455
456     return exitCode;
457 }
458